Coverage Report

Created: 2019-07-24 05:18

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/clang/lib/Sema/SemaCodeComplete.cpp
Line
Count
Source (jump to first uncovered line)
1
//===---------------- SemaCodeComplete.cpp - Code Completion ----*- C++ -*-===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
//
9
//  This file defines the code-completion semantic actions.
10
//
11
//===----------------------------------------------------------------------===//
12
#include "clang/AST/Decl.h"
13
#include "clang/AST/DeclBase.h"
14
#include "clang/AST/DeclCXX.h"
15
#include "clang/AST/DeclObjC.h"
16
#include "clang/AST/ExprCXX.h"
17
#include "clang/AST/ExprObjC.h"
18
#include "clang/AST/QualTypeNames.h"
19
#include "clang/AST/Type.h"
20
#include "clang/Basic/CharInfo.h"
21
#include "clang/Basic/Specifiers.h"
22
#include "clang/Lex/HeaderSearch.h"
23
#include "clang/Lex/MacroInfo.h"
24
#include "clang/Lex/Preprocessor.h"
25
#include "clang/Sema/CodeCompleteConsumer.h"
26
#include "clang/Sema/Lookup.h"
27
#include "clang/Sema/Overload.h"
28
#include "clang/Sema/Scope.h"
29
#include "clang/Sema/ScopeInfo.h"
30
#include "clang/Sema/SemaInternal.h"
31
#include "llvm/ADT/DenseSet.h"
32
#include "llvm/ADT/SmallBitVector.h"
33
#include "llvm/ADT/SmallPtrSet.h"
34
#include "llvm/ADT/SmallString.h"
35
#include "llvm/ADT/StringExtras.h"
36
#include "llvm/ADT/StringSwitch.h"
37
#include "llvm/ADT/Twine.h"
38
#include "llvm/ADT/iterator_range.h"
39
#include "llvm/Support/Path.h"
40
#include <list>
41
#include <map>
42
#include <string>
43
#include <vector>
44
45
using namespace clang;
46
using namespace sema;
47
48
namespace {
49
/// A container of code-completion results.
50
class ResultBuilder {
51
public:
52
  /// The type of a name-lookup filter, which can be provided to the
53
  /// name-lookup routines to specify which declarations should be included in
54
  /// the result set (when it returns true) and which declarations should be
55
  /// filtered out (returns false).
56
  typedef bool (ResultBuilder::*LookupFilter)(const NamedDecl *) const;
57
58
  typedef CodeCompletionResult Result;
59
60
private:
61
  /// The actual results we have found.
62
  std::vector<Result> Results;
63
64
  /// A record of all of the declarations we have found and placed
65
  /// into the result set, used to ensure that no declaration ever gets into
66
  /// the result set twice.
67
  llvm::SmallPtrSet<const Decl *, 16> AllDeclsFound;
68
69
  typedef std::pair<const NamedDecl *, unsigned> DeclIndexPair;
70
71
  /// An entry in the shadow map, which is optimized to store
72
  /// a single (declaration, index) mapping (the common case) but
73
  /// can also store a list of (declaration, index) mappings.
74
  class ShadowMapEntry {
75
    typedef SmallVector<DeclIndexPair, 4> DeclIndexPairVector;
76
77
    /// Contains either the solitary NamedDecl * or a vector
78
    /// of (declaration, index) pairs.
79
    llvm::PointerUnion<const NamedDecl *, DeclIndexPairVector *> DeclOrVector;
80
81
    /// When the entry contains a single declaration, this is
82
    /// the index associated with that entry.
83
    unsigned SingleDeclIndex;
84
85
  public:
86
715
    ShadowMapEntry() : DeclOrVector(), SingleDeclIndex(0) {}
87
    ShadowMapEntry(const ShadowMapEntry &) = delete;
88
0
    ShadowMapEntry(ShadowMapEntry &&Move) { *this = std::move(Move); }
89
    ShadowMapEntry &operator=(const ShadowMapEntry &) = delete;
90
0
    ShadowMapEntry &operator=(ShadowMapEntry &&Move) {
91
0
      SingleDeclIndex = Move.SingleDeclIndex;
92
0
      DeclOrVector = Move.DeclOrVector;
93
0
      Move.DeclOrVector = nullptr;
94
0
      return *this;
95
0
    }
96
97
858
    void Add(const NamedDecl *ND, unsigned Index) {
98
858
      if (DeclOrVector.isNull()) {
99
715
        // 0 - > 1 elements: just set the single element information.
100
715
        DeclOrVector = ND;
101
715
        SingleDeclIndex = Index;
102
715
        return;
103
715
      }
104
143
105
143
      if (const NamedDecl *PrevND =
106
80
              DeclOrVector.dyn_cast<const NamedDecl *>()) {
107
80
        // 1 -> 2 elements: create the vector of results and push in the
108
80
        // existing declaration.
109
80
        DeclIndexPairVector *Vec = new DeclIndexPairVector;
110
80
        Vec->push_back(DeclIndexPair(PrevND, SingleDeclIndex));
111
80
        DeclOrVector = Vec;
112
80
      }
113
143
114
143
      // Add the new element to the end of the vector.
115
143
      DeclOrVector.get<DeclIndexPairVector *>()->push_back(
116
143
          DeclIndexPair(ND, Index));
117
143
    }
118
119
715
    ~ShadowMapEntry() {
120
715
      if (DeclIndexPairVector *Vec =
121
80
              DeclOrVector.dyn_cast<DeclIndexPairVector *>()) {
122
80
        delete Vec;
123
80
        DeclOrVector = ((NamedDecl *)nullptr);
124
80
      }
125
715
    }
126
127
    // Iteration.
128
    class iterator;
129
    iterator begin() const;
130
    iterator end() const;
131
  };
132
133
  /// A mapping from declaration names to the declarations that have
134
  /// this name within a particular scope and their index within the list of
135
  /// results.
136
  typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
137
138
  /// The semantic analysis object for which results are being
139
  /// produced.
140
  Sema &SemaRef;
141
142
  /// The allocator used to allocate new code-completion strings.
143
  CodeCompletionAllocator &Allocator;
144
145
  CodeCompletionTUInfo &CCTUInfo;
146
147
  /// If non-NULL, a filter function used to remove any code-completion
148
  /// results that are not desirable.
149
  LookupFilter Filter;
150
151
  /// Whether we should allow declarations as
152
  /// nested-name-specifiers that would otherwise be filtered out.
153
  bool AllowNestedNameSpecifiers;
154
155
  /// If set, the type that we would prefer our resulting value
156
  /// declarations to have.
157
  ///
158
  /// Closely matching the preferred type gives a boost to a result's
159
  /// priority.
160
  CanQualType PreferredType;
161
162
  /// A list of shadow maps, which is used to model name hiding at
163
  /// different levels of, e.g., the inheritance hierarchy.
164
  std::list<ShadowMap> ShadowMaps;
165
166
  /// Overloaded C++ member functions found by SemaLookup.
167
  /// Used to determine when one overload is dominated by another.
168
  llvm::DenseMap<std::pair<DeclContext *, /*Name*/uintptr_t>, ShadowMapEntry>
169
      OverloadMap;
170
171
  /// If we're potentially referring to a C++ member function, the set
172
  /// of qualifiers applied to the object type.
173
  Qualifiers ObjectTypeQualifiers;
174
  /// The kind of the object expression, for rvalue/lvalue overloads.
175
  ExprValueKind ObjectKind;
176
177
  /// Whether the \p ObjectTypeQualifiers field is active.
178
  bool HasObjectTypeQualifiers;
179
180
  /// The selector that we prefer.
181
  Selector PreferredSelector;
182
183
  /// The completion context in which we are gathering results.
184
  CodeCompletionContext CompletionContext;
185
186
  /// If we are in an instance method definition, the \@implementation
187
  /// object.
188
  ObjCImplementationDecl *ObjCImplementation;
189
190
  void AdjustResultPriorityForDecl(Result &R);
191
192
  void MaybeAddConstructorResults(Result R);
193
194
public:
195
  explicit ResultBuilder(Sema &SemaRef, CodeCompletionAllocator &Allocator,
196
                         CodeCompletionTUInfo &CCTUInfo,
197
                         const CodeCompletionContext &CompletionContext,
198
                         LookupFilter Filter = nullptr)
199
      : SemaRef(SemaRef), Allocator(Allocator), CCTUInfo(CCTUInfo),
200
        Filter(Filter), AllowNestedNameSpecifiers(false),
201
        HasObjectTypeQualifiers(false), CompletionContext(CompletionContext),
202
1.14k
        ObjCImplementation(nullptr) {
203
1.14k
    // If this is an Objective-C instance method definition, dig out the
204
1.14k
    // corresponding implementation.
205
1.14k
    switch (CompletionContext.getKind()) {
206
1.14k
    case CodeCompletionContext::CCC_Expression:
207
595
    case CodeCompletionContext::CCC_ObjCMessageReceiver:
208
595
    case CodeCompletionContext::CCC_ParenthesizedExpression:
209
595
    case CodeCompletionContext::CCC_Statement:
210
595
    case CodeCompletionContext::CCC_Recovery:
211
595
      if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl())
212
33
        if (Method->isInstanceMethod())
213
30
          if (ObjCInterfaceDecl *Interface = Method->getClassInterface())
214
30
            ObjCImplementation = Interface->getImplementation();
215
595
      break;
216
595
217
595
    default:
218
549
      break;
219
1.14k
    }
220
1.14k
  }
221
222
  /// Determine the priority for a reference to the given declaration.
223
  unsigned getBasePriority(const NamedDecl *D);
224
225
  /// Whether we should include code patterns in the completion
226
  /// results.
227
514
  bool includeCodePatterns() const {
228
514
    return SemaRef.CodeCompleter &&
229
514
           SemaRef.CodeCompleter->includeCodePatterns();
230
514
  }
231
232
  /// Set the filter used for code-completion results.
233
617
  void setFilter(LookupFilter Filter) { this->Filter = Filter; }
234
235
1.23k
  Result *data() { return Results.empty() ? 
nullptr20
:
&Results.front()1.21k
; }
236
1.14k
  unsigned size() const { return Results.size(); }
237
123
  bool empty() const { return Results.empty(); }
238
239
  /// Specify the preferred type.
240
294
  void setPreferredType(QualType T) {
241
294
    PreferredType = SemaRef.Context.getCanonicalType(T);
242
294
  }
243
244
  /// Set the cv-qualifiers on the object type, for us in filtering
245
  /// calls to member functions.
246
  ///
247
  /// When there are qualifiers in this set, they will be used to filter
248
  /// out member functions that aren't available (because there will be a
249
  /// cv-qualifier mismatch) or prefer functions with an exact qualifier
250
  /// match.
251
100
  void setObjectTypeQualifiers(Qualifiers Quals, ExprValueKind Kind) {
252
100
    ObjectTypeQualifiers = Quals;
253
100
    ObjectKind = Kind;
254
100
    HasObjectTypeQualifiers = true;
255
100
  }
256
257
  /// Set the preferred selector.
258
  ///
259
  /// When an Objective-C method declaration result is added, and that
260
  /// method's selector matches this preferred selector, we give that method
261
  /// a slight priority boost.
262
29
  void setPreferredSelector(Selector Sel) { PreferredSelector = Sel; }
263
264
  /// Retrieve the code-completion context for which results are
265
  /// being collected.
266
1.05k
  const CodeCompletionContext &getCompletionContext() const {
267
1.05k
    return CompletionContext;
268
1.05k
  }
269
270
  /// Specify whether nested-name-specifiers are allowed.
271
104
  void allowNestedNameSpecifiers(bool Allow = true) {
272
104
    AllowNestedNameSpecifiers = Allow;
273
104
  }
274
275
  /// Return the semantic analysis object for which we are collecting
276
  /// code completion results.
277
14.5k
  Sema &getSema() const { return SemaRef; }
278
279
  /// Retrieve the allocator used to allocate code completion strings.
280
4.41k
  CodeCompletionAllocator &getAllocator() const { return Allocator; }
281
282
1.75k
  CodeCompletionTUInfo &getCodeCompletionTUInfo() const { return CCTUInfo; }
283
284
  /// Determine whether the given declaration is at all interesting
285
  /// as a code-completion result.
286
  ///
287
  /// \param ND the declaration that we are inspecting.
288
  ///
289
  /// \param AsNestedNameSpecifier will be set true if this declaration is
290
  /// only interesting when it is a nested-name-specifier.
291
  bool isInterestingDecl(const NamedDecl *ND,
292
                         bool &AsNestedNameSpecifier) const;
293
294
  /// Check whether the result is hidden by the Hiding declaration.
295
  ///
296
  /// \returns true if the result is hidden and cannot be found, false if
297
  /// the hidden result could still be found. When false, \p R may be
298
  /// modified to describe how the result can be found (e.g., via extra
299
  /// qualification).
300
  bool CheckHiddenResult(Result &R, DeclContext *CurContext,
301
                         const NamedDecl *Hiding);
302
303
  /// Add a new result to this result set (if it isn't already in one
304
  /// of the shadow maps), or replace an existing result (for, e.g., a
305
  /// redeclaration).
306
  ///
307
  /// \param R the result to add (if it is unique).
308
  ///
309
  /// \param CurContext the context in which this result will be named.
310
  void MaybeAddResult(Result R, DeclContext *CurContext = nullptr);
311
312
  /// Add a new result to this result set, where we already know
313
  /// the hiding declaration (if any).
314
  ///
315
  /// \param R the result to add (if it is unique).
316
  ///
317
  /// \param CurContext the context in which this result will be named.
318
  ///
319
  /// \param Hiding the declaration that hides the result.
320
  ///
321
  /// \param InBaseClass whether the result was found in a base
322
  /// class of the searched context.
323
  void AddResult(Result R, DeclContext *CurContext, NamedDecl *Hiding,
324
                 bool InBaseClass);
325
326
  /// Add a new non-declaration result to this result set.
327
  void AddResult(Result R);
328
329
  /// Enter into a new scope.
330
  void EnterNewScope();
331
332
  /// Exit from the current scope.
333
  void ExitScope();
334
335
  /// Ignore this declaration, if it is seen again.
336
62
  void Ignore(const Decl *D) { AllDeclsFound.insert(D->getCanonicalDecl()); }
337
338
  /// Add a visited context.
339
895
  void addVisitedContext(DeclContext *Ctx) {
340
895
    CompletionContext.addVisitedContext(Ctx);
341
895
  }
342
343
  /// \name Name lookup predicates
344
  ///
345
  /// These predicates can be passed to the name lookup functions to filter the
346
  /// results of name lookup. All of the predicates have the same type, so that
347
  ///
348
  //@{
349
  bool IsOrdinaryName(const NamedDecl *ND) const;
350
  bool IsOrdinaryNonTypeName(const NamedDecl *ND) const;
351
  bool IsIntegralConstantValue(const NamedDecl *ND) const;
352
  bool IsOrdinaryNonValueName(const NamedDecl *ND) const;
353
  bool IsNestedNameSpecifier(const NamedDecl *ND) const;
354
  bool IsEnum(const NamedDecl *ND) const;
355
  bool IsClassOrStruct(const NamedDecl *ND) const;
356
  bool IsUnion(const NamedDecl *ND) const;
357
  bool IsNamespace(const NamedDecl *ND) const;
358
  bool IsNamespaceOrAlias(const NamedDecl *ND) const;
359
  bool IsType(const NamedDecl *ND) const;
360
  bool IsMember(const NamedDecl *ND) const;
361
  bool IsObjCIvar(const NamedDecl *ND) const;
362
  bool IsObjCMessageReceiver(const NamedDecl *ND) const;
363
  bool IsObjCMessageReceiverOrLambdaCapture(const NamedDecl *ND) const;
364
  bool IsObjCCollection(const NamedDecl *ND) const;
365
  bool IsImpossibleToSatisfy(const NamedDecl *ND) const;
366
  //@}
367
};
368
} // namespace
369
370
2.70M
void PreferredTypeBuilder::enterReturn(Sema &S, SourceLocation Tok) {
371
2.70M
  if (isa<BlockDecl>(S.CurContext)) {
372
601
    if (sema::BlockScopeInfo *BSI = S.getCurBlock()) {
373
601
      ComputeType = nullptr;
374
601
      Type = BSI->ReturnType;
375
601
      ExpectedLoc = Tok;
376
601
    }
377
2.70M
  } else if (const auto *Function = dyn_cast<FunctionDecl>(S.CurContext)) {
378
2.70M
    ComputeType = nullptr;
379
2.70M
    Type = Function->getReturnType();
380
2.70M
    ExpectedLoc = Tok;
381
2.70M
  } else 
if (const auto *2.96k
Method2.96k
= dyn_cast<ObjCMethodDecl>(S.CurContext)) {
382
2.92k
    ComputeType = nullptr;
383
2.92k
    Type = Method->getReturnType();
384
2.92k
    ExpectedLoc = Tok;
385
2.92k
  }
386
2.70M
}
387
388
1.29M
void PreferredTypeBuilder::enterVariableInit(SourceLocation Tok, Decl *D) {
389
1.29M
  auto *VD = llvm::dyn_cast_or_null<ValueDecl>(D);
390
1.29M
  ComputeType = nullptr;
391
1.29M
  Type = VD ? 
VD->getType()1.29M
:
QualType()16
;
392
1.29M
  ExpectedLoc = Tok;
393
1.29M
}
394
395
void PreferredTypeBuilder::enterFunctionArgument(
396
10.1M
    SourceLocation Tok, llvm::function_ref<QualType()> ComputeType) {
397
10.1M
  this->ComputeType = ComputeType;
398
10.1M
  Type = QualType();
399
10.1M
  ExpectedLoc = Tok;
400
10.1M
}
401
402
void PreferredTypeBuilder::enterParenExpr(SourceLocation Tok,
403
6.05M
                                          SourceLocation LParLoc) {
404
6.05M
  // expected type for parenthesized expression does not change.
405
6.05M
  if (ExpectedLoc == LParLoc)
406
5.48M
    ExpectedLoc = Tok;
407
6.05M
}
408
409
static QualType getPreferredTypeOfBinaryRHS(Sema &S, Expr *LHS,
410
5.34M
                                            tok::TokenKind Op) {
411
5.34M
  if (!LHS)
412
1.80k
    return QualType();
413
5.34M
414
5.34M
  QualType LHSType = LHS->getType();
415
5.34M
  if (LHSType->isPointerType()) {
416
366k
    if (Op == tok::plus || 
Op == tok::plusequal308k
||
Op == tok::minusequal300k
)
417
68.0k
      return S.getASTContext().getPointerDiffType();
418
298k
    // Pointer difference is more common than subtracting an int from a pointer.
419
298k
    if (Op == tok::minus)
420
27.1k
      return LHSType;
421
5.24M
  }
422
5.24M
423
5.24M
  switch (Op) {
424
5.24M
  // No way to infer the type of RHS from LHS.
425
5.24M
  case tok::comma:
426
53.0k
    return QualType();
427
5.24M
  // Prefer the type of the left operand for all of these.
428
5.24M
  // Arithmetic operations.
429
5.24M
  case tok::plus:
430
4.10M
  case tok::plusequal:
431
4.10M
  case tok::minus:
432
4.10M
  case tok::minusequal:
433
4.10M
  case tok::percent:
434
4.10M
  case tok::percentequal:
435
4.10M
  case tok::slash:
436
4.10M
  case tok::slashequal:
437
4.10M
  case tok::star:
438
4.10M
  case tok::starequal:
439
4.10M
  // Assignment.
440
4.10M
  case tok::equal:
441
4.10M
  // Comparison operators.
442
4.10M
  case tok::equalequal:
443
4.10M
  case tok::exclaimequal:
444
4.10M
  case tok::less:
445
4.10M
  case tok::lessequal:
446
4.10M
  case tok::greater:
447
4.10M
  case tok::greaterequal:
448
4.10M
  case tok::spaceship:
449
4.10M
    return LHS->getType();
450
4.10M
  // Binary shifts are often overloaded, so don't try to guess those.
451
4.10M
  case tok::greatergreater:
452
275k
  case tok::greatergreaterequal:
453
275k
  case tok::lessless:
454
275k
  case tok::lesslessequal:
455
275k
    if (LHSType->isIntegralOrEnumerationType())
456
207k
      return S.getASTContext().IntTy;
457
67.5k
    return QualType();
458
67.5k
  // Logical operators, assume we want bool.
459
332k
  case tok::ampamp:
460
332k
  case tok::pipepipe:
461
332k
  case tok::caretcaret:
462
332k
    return S.getASTContext().BoolTy;
463
332k
  // Operators often used for bit manipulation are typically used with the type
464
332k
  // of the left argument.
465
332k
  case tok::pipe:
466
325k
  case tok::pipeequal:
467
325k
  case tok::caret:
468
325k
  case tok::caretequal:
469
325k
  case tok::amp:
470
325k
  case tok::ampequal:
471
325k
    if (LHSType->isIntegralOrEnumerationType())
472
209k
      return LHSType;
473
115k
    return QualType();
474
115k
  // RHS should be a pointer to a member of the 'LHS' type, but we can't give
475
115k
  // any particular type here.
476
115k
  case tok::periodstar:
477
26.6k
  case tok::arrowstar:
478
26.6k
    return QualType();
479
131k
  default:
480
131k
    // FIXME(ibiryukov): handle the missing op, re-add the assertion.
481
131k
    // assert(false && "unhandled binary op");
482
131k
    return QualType();
483
5.24M
  }
484
5.24M
}
485
486
/// Get preferred type for an argument of an unary expression. \p ContextType is
487
/// preferred type of the whole unary expression.
488
static QualType getPreferredTypeOfUnaryArg(Sema &S, QualType ContextType,
489
2.11M
                                           tok::TokenKind Op) {
490
2.11M
  switch (Op) {
491
2.11M
  case tok::exclaim:
492
655k
    return S.getASTContext().BoolTy;
493
2.11M
  case tok::amp:
494
263k
    if (!ContextType.isNull() && 
ContextType->isPointerType()41.1k
)
495
37.6k
      return ContextType->getPointeeType();
496
225k
    return QualType();
497
575k
  case tok::star:
498
575k
    if (ContextType.isNull())
499
384k
      return QualType();
500
191k
    return S.getASTContext().getPointerType(ContextType.getNonReferenceType());
501
615k
  case tok::plus:
502
615k
  case tok::minus:
503
615k
  case tok::tilde:
504
615k
  case tok::minusminus:
505
615k
  case tok::plusplus:
506
615k
    if (ContextType.isNull())
507
506k
      return S.getASTContext().IntTy;
508
108k
    // leave as is, these operators typically return the same type.
509
108k
    return ContextType;
510
108k
  case tok::kw___real:
511
1.45k
  case tok::kw___imag:
512
1.45k
    return QualType();
513
1.45k
  default:
514
0
    assert(false && "unhandled unary op");
515
0
    return QualType();
516
2.11M
  }
517
2.11M
}
518
519
void PreferredTypeBuilder::enterBinary(Sema &S, SourceLocation Tok, Expr *LHS,
520
5.34M
                                       tok::TokenKind Op) {
521
5.34M
  ComputeType = nullptr;
522
5.34M
  Type = getPreferredTypeOfBinaryRHS(S, LHS, Op);
523
5.34M
  ExpectedLoc = Tok;
524
5.34M
}
525
526
void PreferredTypeBuilder::enterMemAccess(Sema &S, SourceLocation Tok,
527
2.21M
                                          Expr *Base) {
528
2.21M
  if (!Base)
529
113
    return;
530
2.21M
  // Do we have expected type for Base?
531
2.21M
  if (ExpectedLoc != Base->getBeginLoc())
532
693k
    return;
533
1.52M
  // Keep the expected type, only update the location.
534
1.52M
  ExpectedLoc = Tok;
535
1.52M
  return;
536
1.52M
}
537
538
void PreferredTypeBuilder::enterUnary(Sema &S, SourceLocation Tok,
539
                                      tok::TokenKind OpKind,
540
2.11M
                                      SourceLocation OpLoc) {
541
2.11M
  ComputeType = nullptr;
542
2.11M
  Type = getPreferredTypeOfUnaryArg(S, this->get(OpLoc), OpKind);
543
2.11M
  ExpectedLoc = Tok;
544
2.11M
}
545
546
void PreferredTypeBuilder::enterSubscript(Sema &S, SourceLocation Tok,
547
674k
                                          Expr *LHS) {
548
674k
  ComputeType = nullptr;
549
674k
  Type = S.getASTContext().IntTy;
550
674k
  ExpectedLoc = Tok;
551
674k
}
552
553
void PreferredTypeBuilder::enterTypeCast(SourceLocation Tok,
554
3.99M
                                         QualType CastType) {
555
3.99M
  ComputeType = nullptr;
556
3.99M
  Type = !CastType.isNull() ? 
CastType.getCanonicalType()346k
:
QualType()3.64M
;
557
3.99M
  ExpectedLoc = Tok;
558
3.99M
}
559
560
1.07M
void PreferredTypeBuilder::enterCondition(Sema &S, SourceLocation Tok) {
561
1.07M
  ComputeType = nullptr;
562
1.07M
  Type = S.getASTContext().BoolTy;
563
1.07M
  ExpectedLoc = Tok;
564
1.07M
}
565
566
class ResultBuilder::ShadowMapEntry::iterator {
567
  llvm::PointerUnion<const NamedDecl *, const DeclIndexPair *> DeclOrIterator;
568
  unsigned SingleDeclIndex;
569
570
public:
571
  typedef DeclIndexPair value_type;
572
  typedef value_type reference;
573
  typedef std::ptrdiff_t difference_type;
574
  typedef std::input_iterator_tag iterator_category;
575
576
  class pointer {
577
    DeclIndexPair Value;
578
579
  public:
580
4
    pointer(const DeclIndexPair &Value) : Value(Value) {}
581
582
4
    const DeclIndexPair *operator->() const { return &Value; }
583
  };
584
585
1.53k
  iterator() : DeclOrIterator((NamedDecl *)nullptr), SingleDeclIndex(0) {}
586
587
  iterator(const NamedDecl *SingleDecl, unsigned Index)
588
87
      : DeclOrIterator(SingleDecl), SingleDeclIndex(Index) {}
589
590
  iterator(const DeclIndexPair *Iterator)
591
126
      : DeclOrIterator(Iterator), SingleDeclIndex(0) {}
592
593
287
  iterator &operator++() {
594
287
    if (DeclOrIterator.is<const NamedDecl *>()) {
595
80
      DeclOrIterator = (NamedDecl *)nullptr;
596
80
      SingleDeclIndex = 0;
597
80
      return *this;
598
80
    }
599
207
600
207
    const DeclIndexPair *I = DeclOrIterator.get<const DeclIndexPair *>();
601
207
    ++I;
602
207
    DeclOrIterator = I;
603
207
    return *this;
604
207
  }
605
606
  /*iterator operator++(int) {
607
    iterator tmp(*this);
608
    ++(*this);
609
    return tmp;
610
  }*/
611
612
296
  reference operator*() const {
613
296
    if (const NamedDecl *ND = DeclOrIterator.dyn_cast<const NamedDecl *>())
614
89
      return reference(ND, SingleDeclIndex);
615
207
616
207
    return *DeclOrIterator.get<const DeclIndexPair *>();
617
207
  }
618
619
4
  pointer operator->() const { return pointer(**this); }
620
621
1.16k
  friend bool operator==(const iterator &X, const iterator &Y) {
622
1.16k
    return X.DeclOrIterator.getOpaqueValue() ==
623
1.16k
               Y.DeclOrIterator.getOpaqueValue() &&
624
1.16k
           
X.SingleDeclIndex == Y.SingleDeclIndex867
;
625
1.16k
  }
626
627
1.16k
  friend bool operator!=(const iterator &X, const iterator &Y) {
628
1.16k
    return !(X == Y);
629
1.16k
  }
630
};
631
632
ResultBuilder::ShadowMapEntry::iterator
633
456
ResultBuilder::ShadowMapEntry::begin() const {
634
456
  if (DeclOrVector.isNull())
635
306
    return iterator();
636
150
637
150
  if (const NamedDecl *ND = DeclOrVector.dyn_cast<const NamedDecl *>())
638
87
    return iterator(ND, SingleDeclIndex);
639
63
640
63
  return iterator(DeclOrVector.get<DeclIndexPairVector *>()->begin());
641
63
}
642
643
ResultBuilder::ShadowMapEntry::iterator
644
456
ResultBuilder::ShadowMapEntry::end() const {
645
456
  if (DeclOrVector.is<const NamedDecl *>() || 
DeclOrVector.isNull()63
)
646
393
    return iterator();
647
63
648
63
  return iterator(DeclOrVector.get<DeclIndexPairVector *>()->end());
649
63
}
650
651
/// Compute the qualification required to get from the current context
652
/// (\p CurContext) to the target context (\p TargetContext).
653
///
654
/// \param Context the AST context in which the qualification will be used.
655
///
656
/// \param CurContext the context where an entity is being named, which is
657
/// typically based on the current scope.
658
///
659
/// \param TargetContext the context in which the named entity actually
660
/// resides.
661
///
662
/// \returns a nested name specifier that refers into the target context, or
663
/// NULL if no qualification is needed.
664
static NestedNameSpecifier *
665
getRequiredQualification(ASTContext &Context, const DeclContext *CurContext,
666
138
                         const DeclContext *TargetContext) {
667
138
  SmallVector<const DeclContext *, 4> TargetParents;
668
138
669
138
  for (const DeclContext *CommonAncestor = TargetContext;
670
241
       CommonAncestor && !CommonAncestor->Encloses(CurContext);
671
138
       
CommonAncestor = CommonAncestor->getLookupParent()103
) {
672
103
    if (CommonAncestor->isTransparentContext() ||
673
103
        
CommonAncestor->isFunctionOrMethod()96
)
674
7
      continue;
675
96
676
96
    TargetParents.push_back(CommonAncestor);
677
96
  }
678
138
679
138
  NestedNameSpecifier *Result = nullptr;
680
234
  while (!TargetParents.empty()) {
681
96
    const DeclContext *Parent = TargetParents.pop_back_val();
682
96
683
96
    if (const auto *Namespace = dyn_cast<NamespaceDecl>(Parent)) {
684
8
      if (!Namespace->getIdentifier())
685
0
        continue;
686
8
687
8
      Result = NestedNameSpecifier::Create(Context, Result, Namespace);
688
88
    } else if (const auto *TD = dyn_cast<TagDecl>(Parent))
689
88
      Result = NestedNameSpecifier::Create(
690
88
          Context, Result, false, Context.getTypeDeclType(TD).getTypePtr());
691
96
  }
692
138
  return Result;
693
138
}
694
695
/// Determine whether \p Id is a name reserved for the implementation (C99
696
/// 7.1.3, C++ [lib.global.names]).
697
static bool isReservedName(const IdentifierInfo *Id,
698
20.5k
                           bool doubleUnderscoreOnly = false) {
699
20.5k
  if (Id->getLength() < 2)
700
2.63k
    return false;
701
17.8k
  const char *Name = Id->getNameStart();
702
17.8k
  return Name[0] == '_' &&
703
17.8k
         
(5.29k
Name[1] == '_'5.29k
||
704
5.29k
          
(172
Name[1] >= 'A'172
&&
Name[1] <= 'Z'172
&&
!doubleUnderscoreOnly8
));
705
17.8k
}
706
707
// Some declarations have reserved names that we don't want to ever show.
708
// Filter out names reserved for the implementation if they come from a
709
// system header.
710
14.0k
static bool shouldIgnoreDueToReservedName(const NamedDecl *ND, Sema &SemaRef) {
711
14.0k
  const IdentifierInfo *Id = ND->getIdentifier();
712
14.0k
  if (!Id)
713
1.25k
    return false;
714
12.8k
715
12.8k
  // Ignore reserved names for compiler provided decls.
716
12.8k
  if (isReservedName(Id) && 
ND->getLocation().isInvalid()5.12k
)
717
5.11k
    return true;
718
7.69k
719
7.69k
  // For system headers ignore only double-underscore names.
720
7.69k
  // This allows for system headers providing private symbols with a single
721
7.69k
  // underscore.
722
7.69k
  if (isReservedName(Id, /*doubleUnderscoreOnly=*/true) &&
723
7.69k
      SemaRef.SourceMgr.isInSystemHeader(
724
2
          SemaRef.SourceMgr.getSpellingLoc(ND->getLocation())))
725
2
    return true;
726
7.69k
727
7.69k
  return false;
728
7.69k
}
729
730
bool ResultBuilder::isInterestingDecl(const NamedDecl *ND,
731
14.0k
                                      bool &AsNestedNameSpecifier) const {
732
14.0k
  AsNestedNameSpecifier = false;
733
14.0k
734
14.0k
  auto *Named = ND;
735
14.0k
  ND = ND->getUnderlyingDecl();
736
14.0k
737
14.0k
  // Skip unnamed entities.
738
14.0k
  if (!ND->getDeclName())
739
0
    return false;
740
14.0k
741
14.0k
  // Friend declarations and declarations introduced due to friends are never
742
14.0k
  // added as results.
743
14.0k
  if (ND->getFriendObjectKind() == Decl::FOK_Undeclared)
744
0
    return false;
745
14.0k
746
14.0k
  // Class template (partial) specializations are never added as results.
747
14.0k
  if (isa<ClassTemplateSpecializationDecl>(ND) ||
748
14.0k
      isa<ClassTemplatePartialSpecializationDecl>(ND))
749
0
    return false;
750
14.0k
751
14.0k
  // Using declarations themselves are never added as results.
752
14.0k
  if (isa<UsingDecl>(ND))
753
2
    return false;
754
14.0k
755
14.0k
  if (shouldIgnoreDueToReservedName(ND, SemaRef))
756
5.11k
    return false;
757
8.94k
758
8.94k
  if (Filter == &ResultBuilder::IsNestedNameSpecifier ||
759
8.94k
      
(8.88k
isa<NamespaceDecl>(ND)8.88k
&&
Filter != &ResultBuilder::IsNamespace80
&&
760
8.88k
       
Filter != &ResultBuilder::IsNamespaceOrAlias78
&&
Filter != nullptr64
))
761
103
    AsNestedNameSpecifier = true;
762
8.94k
763
8.94k
  // Filter out any unwanted results.
764
8.94k
  if (Filter && 
!(this->*Filter)(Named)7.70k
) {
765
525
    // Check whether it is interesting as a nested-name-specifier.
766
525
    if (AllowNestedNameSpecifiers && 
SemaRef.getLangOpts().CPlusPlus139
&&
767
525
        
IsNestedNameSpecifier(ND)139
&&
768
525
        
(135
Filter != &ResultBuilder::IsMember135
||
769
135
         
(107
isa<CXXRecordDecl>(ND)107
&&
770
126
          
cast<CXXRecordDecl>(ND)->isInjectedClassName()101
))) {
771
126
      AsNestedNameSpecifier = true;
772
126
      return true;
773
126
    }
774
399
775
399
    return false;
776
399
  }
777
8.41k
  // ... then it must be interesting!
778
8.41k
  return true;
779
8.41k
}
780
781
bool ResultBuilder::CheckHiddenResult(Result &R, DeclContext *CurContext,
782
987
                                      const NamedDecl *Hiding) {
783
987
  // In C, there is no way to refer to a hidden name.
784
987
  // FIXME: This isn't true; we can find a tag name hidden by an ordinary
785
987
  // name if we introduce the tag type.
786
987
  if (!SemaRef.getLangOpts().CPlusPlus)
787
406
    return true;
788
581
789
581
  const DeclContext *HiddenCtx =
790
581
      R.Declaration->getDeclContext()->getRedeclContext();
791
581
792
581
  // There is no way to qualify a name declared in a function or method.
793
581
  if (HiddenCtx->isFunctionOrMethod())
794
0
    return true;
795
581
796
581
  if (HiddenCtx == Hiding->getDeclContext()->getRedeclContext())
797
455
    return true;
798
126
799
126
  // We can refer to the result with the appropriate qualification. Do it.
800
126
  R.Hidden = true;
801
126
  R.QualifierIsInformative = false;
802
126
803
126
  if (!R.Qualifier)
804
126
    R.Qualifier = getRequiredQualification(SemaRef.Context, CurContext,
805
126
                                           R.Declaration->getDeclContext());
806
126
  return false;
807
126
}
808
809
/// A simplified classification of types used to determine whether two
810
/// types are "similar enough" when adjusting priorities.
811
3.36k
SimplifiedTypeClass clang::getSimplifiedTypeClass(CanQualType T) {
812
3.36k
  switch (T->getTypeClass()) {
813
3.36k
  case Type::Builtin:
814
2.12k
    switch (cast<BuiltinType>(T)->getKind()) {
815
2.12k
    case BuiltinType::Void:
816
1.14k
      return STC_Void;
817
2.12k
818
2.12k
    case BuiltinType::NullPtr:
819
0
      return STC_Pointer;
820
2.12k
821
2.12k
    case BuiltinType::Overload:
822
0
    case BuiltinType::Dependent:
823
0
      return STC_Other;
824
0
825
0
    case BuiltinType::ObjCId:
826
0
    case BuiltinType::ObjCClass:
827
0
    case BuiltinType::ObjCSel:
828
0
      return STC_ObjectiveC;
829
0
830
984
    default:
831
984
      return STC_Arithmetic;
832
0
    }
833
0
834
0
  case Type::Complex:
835
0
    return STC_Arithmetic;
836
0
837
394
  case Type::Pointer:
838
394
    return STC_Pointer;
839
0
840
0
  case Type::BlockPointer:
841
0
    return STC_Block;
842
0
843
0
  case Type::LValueReference:
844
0
  case Type::RValueReference:
845
0
    return getSimplifiedTypeClass(T->getAs<ReferenceType>()->getPointeeType());
846
0
847
0
  case Type::ConstantArray:
848
0
  case Type::IncompleteArray:
849
0
  case Type::VariableArray:
850
0
  case Type::DependentSizedArray:
851
0
    return STC_Array;
852
0
853
0
  case Type::DependentSizedExtVector:
854
0
  case Type::Vector:
855
0
  case Type::ExtVector:
856
0
    return STC_Arithmetic;
857
0
858
0
  case Type::FunctionProto:
859
0
  case Type::FunctionNoProto:
860
0
    return STC_Function;
861
0
862
262
  case Type::Record:
863
262
    return STC_Record;
864
0
865
126
  case Type::Enum:
866
126
    return STC_Arithmetic;
867
0
868
136
  case Type::ObjCObject:
869
136
  case Type::ObjCInterface:
870
136
  case Type::ObjCObjectPointer:
871
136
    return STC_ObjectiveC;
872
136
873
317
  default:
874
317
    return STC_Other;
875
3.36k
  }
876
3.36k
}
877
878
/// Get the type that a given expression will have if this declaration
879
/// is used as an expression in its "typical" code-completion form.
880
2.44k
QualType clang::getDeclUsageType(ASTContext &C, const NamedDecl *ND) {
881
2.44k
  ND = ND->getUnderlyingDecl();
882
2.44k
883
2.44k
  if (const auto *Type = dyn_cast<TypeDecl>(ND))
884
326
    return C.getTypeDeclType(Type);
885
2.11k
  if (const auto *Iface = dyn_cast<ObjCInterfaceDecl>(ND))
886
115
    return C.getObjCInterfaceType(Iface);
887
1.99k
888
1.99k
  QualType T;
889
1.99k
  if (const FunctionDecl *Function = ND->getAsFunction())
890
1.32k
    T = Function->getCallResultType();
891
671
  else if (const auto *Method = dyn_cast<ObjCMethodDecl>(ND))
892
18
    T = Method->getSendResultType();
893
653
  else if (const auto *Enumerator = dyn_cast<EnumConstantDecl>(ND))
894
64
    T = C.getTypeDeclType(cast<EnumDecl>(Enumerator->getDeclContext()));
895
589
  else if (const auto *Property = dyn_cast<ObjCPropertyDecl>(ND))
896
0
    T = Property->getType();
897
589
  else if (const auto *Value = dyn_cast<ValueDecl>(ND))
898
478
    T = Value->getType();
899
1.99k
900
1.99k
  if (T.isNull())
901
111
    return QualType();
902
1.88k
903
1.88k
  // Dig through references, function pointers, and block pointers to
904
1.88k
  // get down to the likely type of an expression when the entity is
905
1.88k
  // used.
906
1.90k
  
do 1.88k
{
907
1.90k
    if (const auto *Ref = T->getAs<ReferenceType>()) {
908
1
      T = Ref->getPointeeType();
909
1
      continue;
910
1
    }
911
1.90k
912
1.90k
    if (const auto *Pointer = T->getAs<PointerType>()) {
913
112
      if (Pointer->getPointeeType()->isFunctionType()) {
914
3
        T = Pointer->getPointeeType();
915
3
        continue;
916
3
      }
917
109
918
109
      break;
919
109
    }
920
1.79k
921
1.79k
    if (const auto *Block = T->getAs<BlockPointerType>()) {
922
4
      T = Block->getPointeeType();
923
4
      continue;
924
4
    }
925
1.78k
926
1.78k
    if (const auto *Function = T->getAs<FunctionType>()) {
927
7
      T = Function->getReturnType();
928
7
      continue;
929
7
    }
930
1.77k
931
1.77k
    break;
932
1.77k
  } while (
true15
);
933
1.88k
934
1.88k
  return T;
935
1.88k
}
936
937
14.0k
unsigned ResultBuilder::getBasePriority(const NamedDecl *ND) {
938
14.0k
  if (!ND)
939
0
    return CCP_Unlikely;
940
14.0k
941
14.0k
  // Context-based decisions.
942
14.0k
  const DeclContext *LexicalDC = ND->getLexicalDeclContext();
943
14.0k
  if (LexicalDC->isFunctionOrMethod()) {
944
641
    // _cmd is relatively rare
945
641
    if (const auto *ImplicitParam = dyn_cast<ImplicitParamDecl>(ND))
946
68
      if (ImplicitParam->getIdentifier() &&
947
68
          ImplicitParam->getIdentifier()->isStr("_cmd"))
948
34
        return CCP_ObjC_cmd;
949
607
950
607
    return CCP_LocalDeclaration;
951
607
  }
952
13.4k
953
13.4k
  const DeclContext *DC = ND->getDeclContext()->getRedeclContext();
954
13.4k
  if (DC->isRecord() || 
isa<ObjCContainerDecl>(DC)11.8k
) {
955
2.10k
    // Explicit destructor calls are very rare.
956
2.10k
    if (isa<CXXDestructorDecl>(ND))
957
152
      return CCP_Unlikely;
958
1.94k
    // Explicit operator and conversion function calls are also very rare.
959
1.94k
    auto DeclNameKind = ND->getDeclName().getNameKind();
960
1.94k
    if (DeclNameKind == DeclarationName::CXXOperatorName ||
961
1.94k
        
DeclNameKind == DeclarationName::CXXLiteralOperatorName1.64k
||
962
1.94k
        
DeclNameKind == DeclarationName::CXXConversionFunctionName1.64k
)
963
306
      return CCP_Unlikely;
964
1.64k
    return CCP_MemberDeclaration;
965
1.64k
  }
966
11.3k
967
11.3k
  // Content-based decisions.
968
11.3k
  if (isa<EnumConstantDecl>(ND))
969
124
    return CCP_Constant;
970
11.1k
971
11.1k
  // Use CCP_Type for type declarations unless we're in a statement, Objective-C
972
11.1k
  // message receiver, or parenthesized expression context. There, it's as
973
11.1k
  // likely that the user will want to write a type as other declarations.
974
11.1k
  if ((isa<TypeDecl>(ND) || 
isa<ObjCInterfaceDecl>(ND)4.86k
) &&
975
11.1k
      
!(6.76k
CompletionContext.getKind() == CodeCompletionContext::CCC_Statement6.76k
||
976
6.76k
        CompletionContext.getKind() ==
977
5.92k
            CodeCompletionContext::CCC_ObjCMessageReceiver ||
978
6.76k
        CompletionContext.getKind() ==
979
5.75k
            CodeCompletionContext::CCC_ParenthesizedExpression))
980
5.40k
    return CCP_Type;
981
5.78k
982
5.78k
  return CCP_Declaration;
983
5.78k
}
984
985
5.32k
void ResultBuilder::AdjustResultPriorityForDecl(Result &R) {
986
5.32k
  // If this is an Objective-C method declaration whose selector matches our
987
5.32k
  // preferred selector, give it a priority boost.
988
5.32k
  if (!PreferredSelector.isNull())
989
83
    if (const auto *Method = dyn_cast<ObjCMethodDecl>(R.Declaration))
990
83
      if (PreferredSelector == Method->getSelector())
991
14
        R.Priority += CCD_SelectorMatch;
992
5.32k
993
5.32k
  // If we have a preferred type, adjust the priority for results with exactly-
994
5.32k
  // matching or nearly-matching types.
995
5.32k
  if (!PreferredType.isNull()) {
996
1.75k
    QualType T = getDeclUsageType(SemaRef.Context, R.Declaration);
997
1.75k
    if (!T.isNull()) {
998
1.67k
      CanQualType TC = SemaRef.Context.getCanonicalType(T);
999
1.67k
      // Check for exactly-matching types (modulo qualifiers).
1000
1.67k
      if (SemaRef.Context.hasSameUnqualifiedType(PreferredType, TC))
1001
322
        R.Priority /= CCF_ExactTypeMatch;
1002
1.34k
      // Check for nearly-matching types, based on classification of each.
1003
1.34k
      else if ((getSimplifiedTypeClass(PreferredType) ==
1004
1.34k
                getSimplifiedTypeClass(TC)) &&
1005
1.34k
               
!(90
PreferredType->isEnumeralType()90
&&
TC->isEnumeralType()42
))
1006
61
        R.Priority /= CCF_SimilarTypeMatch;
1007
1.67k
    }
1008
1.75k
  }
1009
5.32k
}
1010
1011
static DeclContext::lookup_result getConstructors(ASTContext &Context,
1012
389
                                                  const CXXRecordDecl *Record) {
1013
389
  QualType RecordTy = Context.getTypeDeclType(Record);
1014
389
  DeclarationName ConstructorName =
1015
389
      Context.DeclarationNames.getCXXConstructorName(
1016
389
          Context.getCanonicalType(RecordTy));
1017
389
  return Record->lookup(ConstructorName);
1018
389
}
1019
1020
5.12k
void ResultBuilder::MaybeAddConstructorResults(Result R) {
1021
5.12k
  if (!SemaRef.getLangOpts().CPlusPlus || 
!R.Declaration3.45k
||
1022
5.12k
      
!CompletionContext.wantConstructorResults()3.45k
)
1023
2.22k
    return;
1024
2.90k
1025
2.90k
  const NamedDecl *D = R.Declaration;
1026
2.90k
  const CXXRecordDecl *Record = nullptr;
1027
2.90k
  if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D))
1028
134
    Record = ClassTemplate->getTemplatedDecl();
1029
2.76k
  else if ((Record = dyn_cast<CXXRecordDecl>(D))) {
1030
316
    // Skip specializations and partial specializations.
1031
316
    if (isa<ClassTemplateSpecializationDecl>(Record))
1032
0
      return;
1033
2.45k
  } else {
1034
2.45k
    // There are no constructors here.
1035
2.45k
    return;
1036
2.45k
  }
1037
450
1038
450
  Record = Record->getDefinition();
1039
450
  if (!Record)
1040
75
    return;
1041
375
1042
381
  
for (NamedDecl *Ctor : getConstructors(SemaRef.Context, Record))375
{
1043
381
    R.Declaration = Ctor;
1044
381
    R.CursorKind = getCursorKindForDecl(R.Declaration);
1045
381
    Results.push_back(R);
1046
381
  }
1047
375
}
1048
1049
13.7k
static bool isConstructor(const Decl *ND) {
1050
13.7k
  if (const auto *Tmpl = dyn_cast<FunctionTemplateDecl>(ND))
1051
1.87k
    ND = Tmpl->getTemplatedDecl();
1052
13.7k
  return isa<CXXConstructorDecl>(ND);
1053
13.7k
}
1054
1055
491
void ResultBuilder::MaybeAddResult(Result R, DeclContext *CurContext) {
1056
491
  assert(!ShadowMaps.empty() && "Must enter into a results scope");
1057
491
1058
491
  if (R.Kind != Result::RK_Declaration) {
1059
71
    // For non-declaration results, just add the result.
1060
71
    Results.push_back(R);
1061
71
    return;
1062
71
  }
1063
420
1064
420
  // Look through using declarations.
1065
420
  if (const UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
1066
0
    CodeCompletionResult Result(Using->getTargetDecl(),
1067
0
                                getBasePriority(Using->getTargetDecl()),
1068
0
                                R.Qualifier);
1069
0
    Result.ShadowDecl = Using;
1070
0
    MaybeAddResult(Result, CurContext);
1071
0
    return;
1072
0
  }
1073
420
1074
420
  const Decl *CanonDecl = R.Declaration->getCanonicalDecl();
1075
420
  unsigned IDNS = CanonDecl->getIdentifierNamespace();
1076
420
1077
420
  bool AsNestedNameSpecifier = false;
1078
420
  if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
1079
0
    return;
1080
420
1081
420
  // C++ constructors are never found by name lookup.
1082
420
  if (isConstructor(R.Declaration))
1083
0
    return;
1084
420
1085
420
  ShadowMap &SMap = ShadowMaps.back();
1086
420
  ShadowMapEntry::iterator I, IEnd;
1087
420
  ShadowMap::iterator NamePos = SMap.find(R.Declaration->getDeclName());
1088
420
  if (NamePos != SMap.end()) {
1089
2
    I = NamePos->second.begin();
1090
2
    IEnd = NamePos->second.end();
1091
2
  }
1092
420
1093
422
  for (; I != IEnd; 
++I2
) {
1094
2
    const NamedDecl *ND = I->first;
1095
2
    unsigned Index = I->second;
1096
2
    if (ND->getCanonicalDecl() == CanonDecl) {
1097
0
      // This is a redeclaration. Always pick the newer declaration.
1098
0
      Results[Index].Declaration = R.Declaration;
1099
0
1100
0
      // We're done.
1101
0
      return;
1102
0
    }
1103
2
  }
1104
420
1105
420
  // This is a new declaration in this scope. However, check whether this
1106
420
  // declaration name is hidden by a similarly-named declaration in an outer
1107
420
  // scope.
1108
420
  std::list<ShadowMap>::iterator SM, SMEnd = ShadowMaps.end();
1109
420
  --SMEnd;
1110
420
  for (SM = ShadowMaps.begin(); SM != SMEnd; 
++SM0
) {
1111
0
    ShadowMapEntry::iterator I, IEnd;
1112
0
    ShadowMap::iterator NamePos = SM->find(R.Declaration->getDeclName());
1113
0
    if (NamePos != SM->end()) {
1114
0
      I = NamePos->second.begin();
1115
0
      IEnd = NamePos->second.end();
1116
0
    }
1117
0
    for (; I != IEnd; ++I) {
1118
0
      // A tag declaration does not hide a non-tag declaration.
1119
0
      if (I->first->hasTagIdentifierNamespace() &&
1120
0
          (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
1121
0
                   Decl::IDNS_LocalExtern | Decl::IDNS_ObjCProtocol)))
1122
0
        continue;
1123
0
1124
0
      // Protocols are in distinct namespaces from everything else.
1125
0
      if (((I->first->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol) ||
1126
0
           (IDNS & Decl::IDNS_ObjCProtocol)) &&
1127
0
          I->first->getIdentifierNamespace() != IDNS)
1128
0
        continue;
1129
0
1130
0
      // The newly-added result is hidden by an entry in the shadow map.
1131
0
      if (CheckHiddenResult(R, CurContext, I->first))
1132
0
        return;
1133
0
1134
0
      break;
1135
0
    }
1136
0
  }
1137
420
1138
420
  // Make sure that any given declaration only shows up in the result set once.
1139
420
  if (!AllDeclsFound.insert(CanonDecl).second)
1140
9
    return;
1141
411
1142
411
  // If the filter is for nested-name-specifiers, then this result starts a
1143
411
  // nested-name-specifier.
1144
411
  if (AsNestedNameSpecifier) {
1145
0
    R.StartsNestedNameSpecifier = true;
1146
0
    R.Priority = CCP_NestedNameSpecifier;
1147
0
  } else
1148
411
    AdjustResultPriorityForDecl(R);
1149
411
1150
411
  // If this result is supposed to have an informative qualifier, add one.
1151
411
  if (R.QualifierIsInformative && 
!R.Qualifier0
&&
1152
411
      
!R.StartsNestedNameSpecifier0
) {
1153
0
    const DeclContext *Ctx = R.Declaration->getDeclContext();
1154
0
    if (const NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
1155
0
      R.Qualifier =
1156
0
          NestedNameSpecifier::Create(SemaRef.Context, nullptr, Namespace);
1157
0
    else if (const TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
1158
0
      R.Qualifier = NestedNameSpecifier::Create(
1159
0
          SemaRef.Context, nullptr, false,
1160
0
          SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
1161
0
    else
1162
0
      R.QualifierIsInformative = false;
1163
0
  }
1164
411
1165
411
  // Insert this result into the set of results and into the current shadow
1166
411
  // map.
1167
411
  SMap[R.Declaration->getDeclName()].Add(R.Declaration, Results.size());
1168
411
  Results.push_back(R);
1169
411
1170
411
  if (!AsNestedNameSpecifier)
1171
411
    MaybeAddConstructorResults(R);
1172
411
}
1173
1174
382
static void setInBaseClass(ResultBuilder::Result &R) {
1175
382
  R.Priority += CCD_InBaseClass;
1176
382
  R.InBaseClass = true;
1177
382
}
1178
1179
enum class OverloadCompare { BothViable, Dominates, Dominated };
1180
// Will Candidate ever be called on the object, when overloaded with Incumbent?
1181
// Returns Dominates if Candidate is always called, Dominated if Incumbent is
1182
// always called, BothViable if either may be called dependending on arguments.
1183
// Precondition: must actually be overloads!
1184
static OverloadCompare compareOverloads(const CXXMethodDecl &Candidate,
1185
                                        const CXXMethodDecl &Incumbent,
1186
                                        const Qualifiers &ObjectQuals,
1187
292
                                        ExprValueKind ObjectKind) {
1188
292
  if (Candidate.isVariadic() != Incumbent.isVariadic() ||
1189
292
      Candidate.getNumParams() != Incumbent.getNumParams() ||
1190
292
      Candidate.getMinRequiredArguments() !=
1191
292
          Incumbent.getMinRequiredArguments())
1192
0
    return OverloadCompare::BothViable;
1193
302
  
for (unsigned I = 0, E = Candidate.getNumParams(); 292
I != E;
++I10
)
1194
293
    if (Candidate.parameters()[I]->getType().getCanonicalType() !=
1195
293
        Incumbent.parameters()[I]->getType().getCanonicalType())
1196
283
      return OverloadCompare::BothViable;
1197
292
  
if (9
!llvm::empty(Candidate.specific_attrs<EnableIfAttr>())9
||
1198
9
      !llvm::empty(Incumbent.specific_attrs<EnableIfAttr>()))
1199
0
    return OverloadCompare::BothViable;
1200
9
  // At this point, we know calls can't pick one or the other based on
1201
9
  // arguments, so one of the two must win. (Or both fail, handled elsewhere).
1202
9
  RefQualifierKind CandidateRef = Candidate.getRefQualifier();
1203
9
  RefQualifierKind IncumbentRef = Incumbent.getRefQualifier();
1204
9
  if (CandidateRef != IncumbentRef) {
1205
2
    // If the object kind is LValue/RValue, there's one acceptable ref-qualifier
1206
2
    // and it can't be mixed with ref-unqualified overloads (in valid code).
1207
2
1208
2
    // For xvalue objects, we prefer the rvalue overload even if we have to
1209
2
    // add qualifiers (which is rare, because const&& is rare).
1210
2
    if (ObjectKind == clang::VK_XValue)
1211
1
      return CandidateRef == RQ_RValue ? OverloadCompare::Dominates
1212
1
                                       : 
OverloadCompare::Dominated0
;
1213
8
  }
1214
8
  // Now the ref qualifiers are the same (or we're in some invalid state).
1215
8
  // So make some decision based on the qualifiers.
1216
8
  Qualifiers CandidateQual = Candidate.getMethodQualifiers();
1217
8
  Qualifiers IncumbentQual = Incumbent.getMethodQualifiers();
1218
8
  bool CandidateSuperset = CandidateQual.compatiblyIncludes(IncumbentQual);
1219
8
  bool IncumbentSuperset = IncumbentQual.compatiblyIncludes(CandidateQual);
1220
8
  if (CandidateSuperset == IncumbentSuperset)
1221
2
    return OverloadCompare::BothViable;
1222
6
  return IncumbentSuperset ? 
OverloadCompare::Dominates2
1223
6
                           : 
OverloadCompare::Dominated4
;
1224
6
}
1225
1226
void ResultBuilder::AddResult(Result R, DeclContext *CurContext,
1227
13.6k
                              NamedDecl *Hiding, bool InBaseClass = false) {
1228
13.6k
  if (R.Kind != Result::RK_Declaration) {
1229
0
    // For non-declaration results, just add the result.
1230
0
    Results.push_back(R);
1231
0
    return;
1232
0
  }
1233
13.6k
1234
13.6k
  // Look through using declarations.
1235
13.6k
  if (const auto *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
1236
13
    CodeCompletionResult Result(Using->getTargetDecl(),
1237
13
                                getBasePriority(Using->getTargetDecl()),
1238
13
                                R.Qualifier);
1239
13
    Result.ShadowDecl = Using;
1240
13
    AddResult(Result, CurContext, Hiding);
1241
13
    return;
1242
13
  }
1243
13.6k
1244
13.6k
  bool AsNestedNameSpecifier = false;
1245
13.6k
  if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
1246
5.51k
    return;
1247
8.12k
1248
8.12k
  // C++ constructors are never found by name lookup.
1249
8.12k
  if (isConstructor(R.Declaration))
1250
442
    return;
1251
7.68k
1252
7.68k
  if (Hiding && 
CheckHiddenResult(R, CurContext, Hiding)987
)
1253
861
    return;
1254
6.82k
1255
6.82k
  // Make sure that any given declaration only shows up in the result set once.
1256
6.82k
  if (!AllDeclsFound.insert(R.Declaration->getCanonicalDecl()).second)
1257
1.90k
    return;
1258
4.91k
1259
4.91k
  // If the filter is for nested-name-specifiers, then this result starts a
1260
4.91k
  // nested-name-specifier.
1261
4.91k
  if (AsNestedNameSpecifier) {
1262
145
    R.StartsNestedNameSpecifier = true;
1263
145
    R.Priority = CCP_NestedNameSpecifier;
1264
4.77k
  } else if (Filter == &ResultBuilder::IsMember && 
!R.Qualifier538
&&
1265
4.77k
             
InBaseClass487
&&
1266
4.77k
             isa<CXXRecordDecl>(
1267
83
                 R.Declaration->getDeclContext()->getRedeclContext()))
1268
83
    R.QualifierIsInformative = true;
1269
4.91k
1270
4.91k
  // If this result is supposed to have an informative qualifier, add one.
1271
4.91k
  if (R.QualifierIsInformative && 
!R.Qualifier83
&&
1272
4.91k
      
!R.StartsNestedNameSpecifier83
) {
1273
83
    const DeclContext *Ctx = R.Declaration->getDeclContext();
1274
83
    if (const auto *Namespace = dyn_cast<NamespaceDecl>(Ctx))
1275
0
      R.Qualifier =
1276
0
          NestedNameSpecifier::Create(SemaRef.Context, nullptr, Namespace);
1277
83
    else if (const auto *Tag = dyn_cast<TagDecl>(Ctx))
1278
83
      R.Qualifier = NestedNameSpecifier::Create(
1279
83
          SemaRef.Context, nullptr, false,
1280
83
          SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
1281
0
    else
1282
0
      R.QualifierIsInformative = false;
1283
83
  }
1284
4.91k
1285
4.91k
  // Adjust the priority if this result comes from a base class.
1286
4.91k
  if (InBaseClass)
1287
252
    setInBaseClass(R);
1288
4.91k
1289
4.91k
  AdjustResultPriorityForDecl(R);
1290
4.91k
1291
4.91k
  if (HasObjectTypeQualifiers)
1292
792
    if (const auto *Method = dyn_cast<CXXMethodDecl>(R.Declaration))
1293
509
      if (Method->isInstance()) {
1294
506
        Qualifiers MethodQuals = Method->getMethodQualifiers();
1295
506
        if (ObjectTypeQualifiers == MethodQuals)
1296
417
          R.Priority += CCD_ObjectQualifierMatch;
1297
89
        else if (ObjectTypeQualifiers - MethodQuals) {
1298
49
          // The method cannot be invoked, because doing so would drop
1299
49
          // qualifiers.
1300
49
          return;
1301
49
        }
1302
457
        // Detect cases where a ref-qualified method cannot be invoked.
1303
457
        switch (Method->getRefQualifier()) {
1304
457
          case RQ_LValue:
1305
7
            if (ObjectKind != VK_LValue && 
!MethodQuals.hasConst()4
)
1306
2
              return;
1307
5
            break;
1308
5
          case RQ_RValue:
1309
3
            if (ObjectKind == VK_LValue)
1310
1
              return;
1311
2
            break;
1312
447
          case RQ_None:
1313
447
            break;
1314
454
        }
1315
454
1316
454
        /// Check whether this dominates another overloaded method, which should
1317
454
        /// be suppressed (or vice versa).
1318
454
        /// Motivating case is const_iterator begin() const vs iterator begin().
1319
454
        auto &OverloadSet = OverloadMap[std::make_pair(
1320
454
            CurContext, Method->getDeclName().getAsOpaqueInteger())];
1321
454
        for (const DeclIndexPair& Entry : OverloadSet) {
1322
292
          Result &Incumbent = Results[Entry.second];
1323
292
          switch (compareOverloads(*Method,
1324
292
                                   *cast<CXXMethodDecl>(Incumbent.Declaration),
1325
292
                                   ObjectTypeQualifiers, ObjectKind)) {
1326
292
          case OverloadCompare::Dominates:
1327
3
            // Replace the dominated overload with this one.
1328
3
            // FIXME: if the overload dominates multiple incumbents then we
1329
3
            // should remove all. But two overloads is by far the common case.
1330
3
            Incumbent = std::move(R);
1331
3
            return;
1332
292
          case OverloadCompare::Dominated:
1333
4
            // This overload can't be called, drop it.
1334
4
            return;
1335
292
          case OverloadCompare::BothViable:
1336
285
            break;
1337
292
          }
1338
292
        }
1339
454
        OverloadSet.Add(Method, Results.size());
1340
447
      }
1341
4.91k
1342
4.91k
  // Insert this result into the set of results.
1343
4.91k
  Results.push_back(R);
1344
4.85k
1345
4.85k
  if (!AsNestedNameSpecifier)
1346
4.71k
    MaybeAddConstructorResults(R);
1347
4.85k
}
1348
1349
152k
void ResultBuilder::AddResult(Result R) {
1350
152k
  assert(R.Kind != Result::RK_Declaration &&
1351
152k
         "Declaration results need more context");
1352
152k
  Results.push_back(R);
1353
152k
}
1354
1355
/// Enter into a new scope.
1356
1.81k
void ResultBuilder::EnterNewScope() { ShadowMaps.emplace_back(); }
1357
1358
/// Exit from the current scope.
1359
1.81k
void ResultBuilder::ExitScope() {
1360
1.81k
  ShadowMaps.pop_back();
1361
1.81k
}
1362
1363
/// Determines whether this given declaration will be found by
1364
/// ordinary name lookup.
1365
5.15k
bool ResultBuilder::IsOrdinaryName(const NamedDecl *ND) const {
1366
5.15k
  ND = ND->getUnderlyingDecl();
1367
5.15k
1368
5.15k
  // If name lookup finds a local extern declaration, then we are in a
1369
5.15k
  // context where it behaves like an ordinary name.
1370
5.15k
  unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_LocalExtern;
1371
5.15k
  if (SemaRef.getLangOpts().CPlusPlus)
1372
4.74k
    IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
1373
410
  else if (SemaRef.getLangOpts().ObjC) {
1374
285
    if (isa<ObjCIvarDecl>(ND))
1375
36
      return true;
1376
5.12k
  }
1377
5.12k
1378
5.12k
  return ND->getIdentifierNamespace() & IDNS;
1379
5.12k
}
1380
1381
/// Determines whether this given declaration will be found by
1382
/// ordinary name lookup but is not a type name.
1383
772
bool ResultBuilder::IsOrdinaryNonTypeName(const NamedDecl *ND) const {
1384
772
  ND = ND->getUnderlyingDecl();
1385
772
  if (isa<TypeDecl>(ND))
1386
152
    return false;
1387
620
  // Objective-C interfaces names are not filtered by this method because they
1388
620
  // can be used in a class property expression. We can still filter out
1389
620
  // @class declarations though.
1390
620
  if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND)) {
1391
92
    if (!ID->getDefinition())
1392
56
      return false;
1393
564
  }
1394
564
1395
564
  unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_LocalExtern;
1396
564
  if (SemaRef.getLangOpts().CPlusPlus)
1397
0
    IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
1398
564
  else if (SemaRef.getLangOpts().ObjC) {
1399
377
    if (isa<ObjCIvarDecl>(ND))
1400
10
      return true;
1401
554
  }
1402
554
1403
554
  return ND->getIdentifierNamespace() & IDNS;
1404
554
}
1405
1406
18
bool ResultBuilder::IsIntegralConstantValue(const NamedDecl *ND) const {
1407
18
  if (!IsOrdinaryNonTypeName(ND))
1408
0
    return 0;
1409
18
1410
18
  if (const auto *VD = dyn_cast<ValueDecl>(ND->getUnderlyingDecl()))
1411
18
    if (VD->getType()->isIntegralOrEnumerationType())
1412
16
      return true;
1413
2
1414
2
  return false;
1415
2
}
1416
1417
/// Determines whether this given declaration will be found by
1418
/// ordinary name lookup.
1419
419
bool ResultBuilder::IsOrdinaryNonValueName(const NamedDecl *ND) const {
1420
419
  ND = ND->getUnderlyingDecl();
1421
419
1422
419
  unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_LocalExtern;
1423
419
  if (SemaRef.getLangOpts().CPlusPlus)
1424
139
    IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace;
1425
419
1426
419
  return (ND->getIdentifierNamespace() & IDNS) && 
!isa<ValueDecl>(ND)415
&&
1427
419
         
!isa<FunctionTemplateDecl>(ND)334
&&
!isa<ObjCPropertyDecl>(ND)334
;
1428
419
}
1429
1430
/// Determines whether the given declaration is suitable as the
1431
/// start of a C++ nested-name-specifier, e.g., a class or namespace.
1432
194
bool ResultBuilder::IsNestedNameSpecifier(const NamedDecl *ND) const {
1433
194
  // Allow us to find class templates, too.
1434
194
  if (const auto *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
1435
1
    ND = ClassTemplate->getTemplatedDecl();
1436
194
1437
194
  return SemaRef.isAcceptableNestedNameSpecifier(ND);
1438
194
}
1439
1440
/// Determines whether the given declaration is an enumeration.
1441
11
bool ResultBuilder::IsEnum(const NamedDecl *ND) const {
1442
11
  return isa<EnumDecl>(ND);
1443
11
}
1444
1445
/// Determines whether the given declaration is a class or struct.
1446
34
bool ResultBuilder::IsClassOrStruct(const NamedDecl *ND) const {
1447
34
  // Allow us to find class templates, too.
1448
34
  if (const auto *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
1449
1
    ND = ClassTemplate->getTemplatedDecl();
1450
34
1451
34
  // For purposes of this check, interfaces match too.
1452
34
  if (const auto *RD = dyn_cast<RecordDecl>(ND))
1453
34
    return RD->getTagKind() == TTK_Class || 
RD->getTagKind() == TTK_Struct24
||
1454
34
           
RD->getTagKind() == TTK_Interface0
;
1455
0
1456
0
  return false;
1457
0
}
1458
1459
/// Determines whether the given declaration is a union.
1460
0
bool ResultBuilder::IsUnion(const NamedDecl *ND) const {
1461
0
  // Allow us to find class templates, too.
1462
0
  if (const auto *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
1463
0
    ND = ClassTemplate->getTemplatedDecl();
1464
0
1465
0
  if (const auto *RD = dyn_cast<RecordDecl>(ND))
1466
0
    return RD->getTagKind() == TTK_Union;
1467
0
1468
0
  return false;
1469
0
}
1470
1471
/// Determines whether the given declaration is a namespace.
1472
2
bool ResultBuilder::IsNamespace(const NamedDecl *ND) const {
1473
2
  return isa<NamespaceDecl>(ND);
1474
2
}
1475
1476
/// Determines whether the given declaration is a namespace or
1477
/// namespace alias.
1478
19
bool ResultBuilder::IsNamespaceOrAlias(const NamedDecl *ND) const {
1479
19
  return isa<NamespaceDecl>(ND->getUnderlyingDecl());
1480
19
}
1481
1482
/// Determines whether the given declaration is a type.
1483
9
bool ResultBuilder::IsType(const NamedDecl *ND) const {
1484
9
  ND = ND->getUnderlyingDecl();
1485
9
  return isa<TypeDecl>(ND) || 
isa<ObjCInterfaceDecl>(ND)4
;
1486
9
}
1487
1488
/// Determines which members of a class should be visible via
1489
/// "." or "->".  Only value declarations, nested name specifiers, and
1490
/// using declarations thereof should show up.
1491
1.00k
bool ResultBuilder::IsMember(const NamedDecl *ND) const {
1492
1.00k
  ND = ND->getUnderlyingDecl();
1493
1.00k
  return isa<ValueDecl>(ND) || 
isa<FunctionTemplateDecl>(ND)190
||
1494
1.00k
         
isa<ObjCPropertyDecl>(ND)184
;
1495
1.00k
}
1496
1497
175
static bool isObjCReceiverType(ASTContext &C, QualType T) {
1498
175
  T = C.getCanonicalType(T);
1499
175
  switch (T->getTypeClass()) {
1500
175
  case Type::ObjCObject:
1501
101
  case Type::ObjCInterface:
1502
101
  case Type::ObjCObjectPointer:
1503
101
    return true;
1504
101
1505
101
  case Type::Builtin:
1506
50
    switch (cast<BuiltinType>(T)->getKind()) {
1507
50
    case BuiltinType::ObjCId:
1508
0
    case BuiltinType::ObjCClass:
1509
0
    case BuiltinType::ObjCSel:
1510
0
      return true;
1511
0
1512
50
    default:
1513
50
      break;
1514
50
    }
1515
50
    return false;
1516
50
1517
50
  default:
1518
24
    break;
1519
24
  }
1520
24
1521
24
  if (!C.getLangOpts().CPlusPlus)
1522
14
    return false;
1523
10
1524
10
  // FIXME: We could perform more analysis here to determine whether a
1525
10
  // particular class type has any conversions to Objective-C types. For now,
1526
10
  // just accept all class types.
1527
10
  return T->isDependentType() || T->isRecordType();
1528
10
}
1529
1530
175
bool ResultBuilder::IsObjCMessageReceiver(const NamedDecl *ND) const {
1531
175
  QualType T = getDeclUsageType(SemaRef.Context, ND);
1532
175
  if (T.isNull())
1533
0
    return false;
1534
175
1535
175
  T = SemaRef.Context.getBaseElementType(T);
1536
175
  return isObjCReceiverType(SemaRef.Context, T);
1537
175
}
1538
1539
bool ResultBuilder::IsObjCMessageReceiverOrLambdaCapture(
1540
43
    const NamedDecl *ND) const {
1541
43
  if (IsObjCMessageReceiver(ND))
1542
26
    return true;
1543
17
1544
17
  const auto *Var = dyn_cast<VarDecl>(ND);
1545
17
  if (!Var)
1546
9
    return false;
1547
8
1548
8
  return Var->hasLocalStorage() && 
!Var->hasAttr<BlocksAttr>()4
;
1549
8
}
1550
1551
34
bool ResultBuilder::IsObjCCollection(const NamedDecl *ND) const {
1552
34
  if ((SemaRef.getLangOpts().CPlusPlus && 
!IsOrdinaryName(ND)0
) ||
1553
34
      (!SemaRef.getLangOpts().CPlusPlus && !IsOrdinaryNonTypeName(ND)))
1554
16
    return false;
1555
18
1556
18
  QualType T = getDeclUsageType(SemaRef.Context, ND);
1557
18
  if (T.isNull())
1558
0
    return false;
1559
18
1560
18
  T = SemaRef.Context.getBaseElementType(T);
1561
18
  return T->isObjCObjectType() || 
T->isObjCObjectPointerType()14
||
1562
18
         
T->isObjCIdType()8
||
1563
18
         
(8
SemaRef.getLangOpts().CPlusPlus8
&&
T->isRecordType()0
);
1564
18
}
1565
1566
26
bool ResultBuilder::IsImpossibleToSatisfy(const NamedDecl *ND) const {
1567
26
  return false;
1568
26
}
1569
1570
/// Determines whether the given declaration is an Objective-C
1571
/// instance variable.
1572
28
bool ResultBuilder::IsObjCIvar(const NamedDecl *ND) const {
1573
28
  return isa<ObjCIvarDecl>(ND);
1574
28
}
1575
1576
namespace {
1577
1578
/// Visible declaration consumer that adds a code-completion result
1579
/// for each visible declaration.
1580
class CodeCompletionDeclConsumer : public VisibleDeclConsumer {
1581
  ResultBuilder &Results;
1582
  DeclContext *InitialLookupCtx;
1583
  // NamingClass and BaseType are used for access-checking. See
1584
  // Sema::IsSimplyAccessible for details.
1585
  CXXRecordDecl *NamingClass;
1586
  QualType BaseType;
1587
  std::vector<FixItHint> FixIts;
1588
1589
public:
1590
  CodeCompletionDeclConsumer(
1591
      ResultBuilder &Results, DeclContext *InitialLookupCtx,
1592
      QualType BaseType = QualType(),
1593
      std::vector<FixItHint> FixIts = std::vector<FixItHint>())
1594
      : Results(Results), InitialLookupCtx(InitialLookupCtx),
1595
838
        FixIts(std::move(FixIts)) {
1596
838
    NamingClass = llvm::dyn_cast<CXXRecordDecl>(InitialLookupCtx);
1597
838
    // If BaseType was not provided explicitly, emulate implicit 'this->'.
1598
838
    if (BaseType.isNull()) {
1599
738
      auto ThisType = Results.getSema().getCurrentThisType();
1600
738
      if (!ThisType.isNull()) {
1601
26
        assert(ThisType->isPointerType());
1602
26
        BaseType = ThisType->getPointeeType();
1603
26
        if (!NamingClass)
1604
22
          NamingClass = BaseType->getAsCXXRecordDecl();
1605
26
      }
1606
738
    }
1607
838
    this->BaseType = BaseType;
1608
838
  }
1609
1610
  void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
1611
13.5k
                 bool InBaseClass) override {
1612
13.5k
    ResultBuilder::Result Result(ND, Results.getBasePriority(ND), nullptr,
1613
13.5k
                                 false, IsAccessible(ND, Ctx), FixIts);
1614
13.5k
    Results.AddResult(Result, InitialLookupCtx, Hiding, InBaseClass);
1615
13.5k
  }
1616
1617
895
  void EnteredContext(DeclContext *Ctx) override {
1618
895
    Results.addVisitedContext(Ctx);
1619
895
  }
1620
1621
private:
1622
13.5k
  bool IsAccessible(NamedDecl *ND, DeclContext *Ctx) {
1623
13.5k
    // Naming class to use for access check. In most cases it was provided
1624
13.5k
    // explicitly (e.g. member access (lhs.foo) or qualified lookup (X::)),
1625
13.5k
    // for unqualified lookup we fallback to the \p Ctx in which we found the
1626
13.5k
    // member.
1627
13.5k
    auto *NamingClass = this->NamingClass;
1628
13.5k
    QualType BaseType = this->BaseType;
1629
13.5k
    if (auto *Cls = llvm::dyn_cast_or_null<CXXRecordDecl>(Ctx)) {
1630
1.49k
      if (!NamingClass)
1631
0
        NamingClass = Cls;
1632
1.49k
      // When we emulate implicit 'this->' in an unqualified lookup, we might
1633
1.49k
      // end up with an invalid naming class. In that case, we avoid emulating
1634
1.49k
      // 'this->' qualifier to satisfy preconditions of the access checking.
1635
1.49k
      if (NamingClass->getCanonicalDecl() != Cls->getCanonicalDecl() &&
1636
1.49k
          
!NamingClass->isDerivedFrom(Cls)398
) {
1637
17
        NamingClass = Cls;
1638
17
        BaseType = QualType();
1639
17
      }
1640
12.0k
    } else {
1641
12.0k
      // The decl was found outside the C++ class, so only ObjC access checks
1642
12.0k
      // apply. Those do not rely on NamingClass and BaseType, so we clear them
1643
12.0k
      // out.
1644
12.0k
      NamingClass = nullptr;
1645
12.0k
      BaseType = QualType();
1646
12.0k
    }
1647
13.5k
    return Results.getSema().IsSimplyAccessible(ND, NamingClass, BaseType);
1648
13.5k
  }
1649
};
1650
} // namespace
1651
1652
/// Add type specifiers for the current language as keyword results.
1653
static void AddTypeSpecifierResults(const LangOptions &LangOpts,
1654
477
                                    ResultBuilder &Results) {
1655
477
  typedef CodeCompletionResult Result;
1656
477
  Results.AddResult(Result("short", CCP_Type));
1657
477
  Results.AddResult(Result("long", CCP_Type));
1658
477
  Results.AddResult(Result("signed", CCP_Type));
1659
477
  Results.AddResult(Result("unsigned", CCP_Type));
1660
477
  Results.AddResult(Result("void", CCP_Type));
1661
477
  Results.AddResult(Result("char", CCP_Type));
1662
477
  Results.AddResult(Result("int", CCP_Type));
1663
477
  Results.AddResult(Result("float", CCP_Type));
1664
477
  Results.AddResult(Result("double", CCP_Type));
1665
477
  Results.AddResult(Result("enum", CCP_Type));
1666
477
  Results.AddResult(Result("struct", CCP_Type));
1667
477
  Results.AddResult(Result("union", CCP_Type));
1668
477
  Results.AddResult(Result("const", CCP_Type));
1669
477
  Results.AddResult(Result("volatile", CCP_Type));
1670
477
1671
477
  if (LangOpts.C99) {
1672
97
    // C99-specific
1673
97
    Results.AddResult(Result("_Complex", CCP_Type));
1674
97
    Results.AddResult(Result("_Imaginary", CCP_Type));
1675
97
    Results.AddResult(Result("_Bool", CCP_Type));
1676
97
    Results.AddResult(Result("restrict", CCP_Type));
1677
97
  }
1678
477
1679
477
  CodeCompletionBuilder Builder(Results.getAllocator(),
1680
477
                                Results.getCodeCompletionTUInfo());
1681
477
  if (LangOpts.CPlusPlus) {
1682
380
    // C++-specific
1683
380
    Results.AddResult(
1684
380
        Result("bool", CCP_Type + (LangOpts.ObjC ? 
CCD_bool_in_ObjC2
:
0378
)));
1685
380
    Results.AddResult(Result("class", CCP_Type));
1686
380
    Results.AddResult(Result("wchar_t", CCP_Type));
1687
380
1688
380
    // typename qualified-id
1689
380
    Builder.AddTypedTextChunk("typename");
1690
380
    Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1691
380
    Builder.AddPlaceholderChunk("qualifier");
1692
380
    Builder.AddTextChunk("::");
1693
380
    Builder.AddPlaceholderChunk("name");
1694
380
    Results.AddResult(Result(Builder.TakeString()));
1695
380
1696
380
    if (LangOpts.CPlusPlus11) {
1697
373
      Results.AddResult(Result("auto", CCP_Type));
1698
373
      Results.AddResult(Result("char16_t", CCP_Type));
1699
373
      Results.AddResult(Result("char32_t", CCP_Type));
1700
373
1701
373
      Builder.AddTypedTextChunk("decltype");
1702
373
      Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1703
373
      Builder.AddPlaceholderChunk("expression");
1704
373
      Builder.AddChunk(CodeCompletionString::CK_RightParen);
1705
373
      Results.AddResult(Result(Builder.TakeString()));
1706
373
    }
1707
380
  } else
1708
97
    Results.AddResult(Result("__auto_type", CCP_Type));
1709
477
1710
477
  // GNU keywords
1711
477
  if (LangOpts.GNUKeywords) {
1712
315
    // FIXME: Enable when we actually support decimal floating point.
1713
315
    //    Results.AddResult(Result("_Decimal32"));
1714
315
    //    Results.AddResult(Result("_Decimal64"));
1715
315
    //    Results.AddResult(Result("_Decimal128"));
1716
315
1717
315
    Builder.AddTypedTextChunk("typeof");
1718
315
    Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1719
315
    Builder.AddPlaceholderChunk("expression");
1720
315
    Results.AddResult(Result(Builder.TakeString()));
1721
315
1722
315
    Builder.AddTypedTextChunk("typeof");
1723
315
    Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1724
315
    Builder.AddPlaceholderChunk("type");
1725
315
    Builder.AddChunk(CodeCompletionString::CK_RightParen);
1726
315
    Results.AddResult(Result(Builder.TakeString()));
1727
315
  }
1728
477
1729
477
  // Nullability
1730
477
  Results.AddResult(Result("_Nonnull", CCP_Type));
1731
477
  Results.AddResult(Result("_Null_unspecified", CCP_Type));
1732
477
  Results.AddResult(Result("_Nullable", CCP_Type));
1733
477
}
1734
1735
static void AddStorageSpecifiers(Sema::ParserCompletionContext CCC,
1736
                                 const LangOptions &LangOpts,
1737
180
                                 ResultBuilder &Results) {
1738
180
  typedef CodeCompletionResult Result;
1739
180
  // Note: we don't suggest either "auto" or "register", because both
1740
180
  // are pointless as storage specifiers. Elsewhere, we suggest "auto"
1741
180
  // in C++0x as a type specifier.
1742
180
  Results.AddResult(Result("extern"));
1743
180
  Results.AddResult(Result("static"));
1744
180
1745
180
  if (LangOpts.CPlusPlus11) {
1746
94
    CodeCompletionAllocator &Allocator = Results.getAllocator();
1747
94
    CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
1748
94
1749
94
    // alignas
1750
94
    Builder.AddTypedTextChunk("alignas");
1751
94
    Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1752
94
    Builder.AddPlaceholderChunk("expression");
1753
94
    Builder.AddChunk(CodeCompletionString::CK_RightParen);
1754
94
    Results.AddResult(Result(Builder.TakeString()));
1755
94
1756
94
    Results.AddResult(Result("constexpr"));
1757
94
    Results.AddResult(Result("thread_local"));
1758
94
  }
1759
180
}
1760
1761
static void AddFunctionSpecifiers(Sema::ParserCompletionContext CCC,
1762
                                  const LangOptions &LangOpts,
1763
62
                                  ResultBuilder &Results) {
1764
62
  typedef CodeCompletionResult Result;
1765
62
  switch (CCC) {
1766
62
  case Sema::PCC_Class:
1767
9
  case Sema::PCC_MemberTemplate:
1768
9
    if (LangOpts.CPlusPlus) {
1769
9
      Results.AddResult(Result("explicit"));
1770
9
      Results.AddResult(Result("friend"));
1771
9
      Results.AddResult(Result("mutable"));
1772
9
      Results.AddResult(Result("virtual"));
1773
9
    }
1774
9
    LLVM_FALLTHROUGH;
1775
9
1776
62
  case Sema::PCC_ObjCInterface:
1777
62
  case Sema::PCC_ObjCImplementation:
1778
62
  case Sema::PCC_Namespace:
1779
62
  case Sema::PCC_Template:
1780
62
    if (LangOpts.CPlusPlus || 
LangOpts.C9927
)
1781
62
      Results.AddResult(Result("inline"));
1782
62
    break;
1783
62
1784
62
  case Sema::PCC_ObjCInstanceVariableList:
1785
0
  case Sema::PCC_Expression:
1786
0
  case Sema::PCC_Statement:
1787
0
  case Sema::PCC_ForInit:
1788
0
  case Sema::PCC_Condition:
1789
0
  case Sema::PCC_RecoveryInFunction:
1790
0
  case Sema::PCC_Type:
1791
0
  case Sema::PCC_ParenthesizedExpression:
1792
0
  case Sema::PCC_LocalDeclarationSpecifiers:
1793
0
    break;
1794
62
  }
1795
62
}
1796
1797
static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt);
1798
static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt);
1799
static void AddObjCVisibilityResults(const LangOptions &LangOpts,
1800
                                     ResultBuilder &Results, bool NeedAt);
1801
static void AddObjCImplementationResults(const LangOptions &LangOpts,
1802
                                         ResultBuilder &Results, bool NeedAt);
1803
static void AddObjCInterfaceResults(const LangOptions &LangOpts,
1804
                                    ResultBuilder &Results, bool NeedAt);
1805
static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt);
1806
1807
166
static void AddTypedefResult(ResultBuilder &Results) {
1808
166
  CodeCompletionBuilder Builder(Results.getAllocator(),
1809
166
                                Results.getCodeCompletionTUInfo());
1810
166
  Builder.AddTypedTextChunk("typedef");
1811
166
  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1812
166
  Builder.AddPlaceholderChunk("type");
1813
166
  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1814
166
  Builder.AddPlaceholderChunk("name");
1815
166
  Builder.AddChunk(CodeCompletionString::CK_SemiColon);
1816
166
  Results.AddResult(CodeCompletionResult(Builder.TakeString()));
1817
166
}
1818
1819
static bool WantTypesInContext(Sema::ParserCompletionContext CCC,
1820
1.04k
                               const LangOptions &LangOpts) {
1821
1.04k
  switch (CCC) {
1822
1.04k
  case Sema::PCC_Namespace:
1823
337
  case Sema::PCC_Class:
1824
337
  case Sema::PCC_ObjCInstanceVariableList:
1825
337
  case Sema::PCC_Template:
1826
337
  case Sema::PCC_MemberTemplate:
1827
337
  case Sema::PCC_Statement:
1828
337
  case Sema::PCC_RecoveryInFunction:
1829
337
  case Sema::PCC_Type:
1830
337
  case Sema::PCC_ParenthesizedExpression:
1831
337
  case Sema::PCC_LocalDeclarationSpecifiers:
1832
337
    return true;
1833
337
1834
693
  case Sema::PCC_Expression:
1835
693
  case Sema::PCC_Condition:
1836
693
    return LangOpts.CPlusPlus;
1837
693
1838
693
  case Sema::PCC_ObjCInterface:
1839
2
  case Sema::PCC_ObjCImplementation:
1840
2
    return false;
1841
2
1842
12
  case Sema::PCC_ForInit:
1843
12
    return LangOpts.CPlusPlus || LangOpts.ObjC || 
LangOpts.C990
;
1844
0
  }
1845
0
1846
0
  llvm_unreachable("Invalid ParserCompletionContext!");
1847
0
}
1848
1849
static PrintingPolicy getCompletionPrintingPolicy(const ASTContext &Context,
1850
71.2k
                                                  const Preprocessor &PP) {
1851
71.2k
  PrintingPolicy Policy = Sema::getPrintingPolicy(Context, PP);
1852
71.2k
  Policy.AnonymousTagLocations = false;
1853
71.2k
  Policy.SuppressStrongLifetime = true;
1854
71.2k
  Policy.SuppressUnwrittenScope = true;
1855
71.2k
  Policy.SuppressScope = true;
1856
71.2k
  return Policy;
1857
71.2k
}
1858
1859
/// Retrieve a printing policy suitable for code completion.
1860
454
static PrintingPolicy getCompletionPrintingPolicy(Sema &S) {
1861
454
  return getCompletionPrintingPolicy(S.Context, S.PP);
1862
454
}
1863
1864
/// Retrieve the string representation of the given type as a string
1865
/// that has the appropriate lifetime for code completion.
1866
///
1867
/// This routine provides a fast path where we provide constant strings for
1868
/// common type names.
1869
static const char *GetCompletionTypeString(QualType T, ASTContext &Context,
1870
                                           const PrintingPolicy &Policy,
1871
4.07k
                                           CodeCompletionAllocator &Allocator) {
1872
4.07k
  if (!T.getLocalQualifiers()) {
1873
4.04k
    // Built-in type names are constant strings.
1874
4.04k
    if (const BuiltinType *BT = dyn_cast<BuiltinType>(T))
1875
2.97k
      return BT->getNameAsCString(Policy);
1876
1.06k
1877
1.06k
    // Anonymous tag types are constant strings.
1878
1.06k
    if (const TagType *TagT = dyn_cast<TagType>(T))
1879
121
      if (TagDecl *Tag = TagT->getDecl())
1880
121
        if (!Tag->hasNameForLinkage()) {
1881
4
          switch (Tag->getTagKind()) {
1882
4
          case TTK_Struct:
1883
0
            return "struct <anonymous>";
1884
4
          case TTK_Interface:
1885
0
            return "__interface <anonymous>";
1886
4
          case TTK_Class:
1887
0
            return "class <anonymous>";
1888
4
          case TTK_Union:
1889
0
            return "union <anonymous>";
1890
4
          case TTK_Enum:
1891
4
            return "enum <anonymous>";
1892
1.09k
          }
1893
1.09k
        }
1894
1.06k
  }
1895
1.09k
1896
1.09k
  // Slow path: format the type as a string.
1897
1.09k
  std::string Result;
1898
1.09k
  T.getAsStringInternal(Result, Policy);
1899
1.09k
  return Allocator.CopyString(Result);
1900
1.09k
}
1901
1902
/// Add a completion for "this", if we're in a member function.
1903
350
static void addThisCompletion(Sema &S, ResultBuilder &Results) {
1904
350
  QualType ThisTy = S.getCurrentThisType();
1905
350
  if (ThisTy.isNull())
1906
325
    return;
1907
25
1908
25
  CodeCompletionAllocator &Allocator = Results.getAllocator();
1909
25
  CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
1910
25
  PrintingPolicy Policy = getCompletionPrintingPolicy(S);
1911
25
  Builder.AddResultTypeChunk(
1912
25
      GetCompletionTypeString(ThisTy, S.Context, Policy, Allocator));
1913
25
  Builder.AddTypedTextChunk("this");
1914
25
  Results.AddResult(CodeCompletionResult(Builder.TakeString()));
1915
25
}
1916
1917
static void AddStaticAssertResult(CodeCompletionBuilder &Builder,
1918
                                  ResultBuilder &Results,
1919
141
                                  const LangOptions &LangOpts) {
1920
141
  if (!LangOpts.CPlusPlus11)
1921
53
    return;
1922
88
1923
88
  Builder.AddTypedTextChunk("static_assert");
1924
88
  Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1925
88
  Builder.AddPlaceholderChunk("expression");
1926
88
  Builder.AddChunk(CodeCompletionString::CK_Comma);
1927
88
  Builder.AddPlaceholderChunk("message");
1928
88
  Builder.AddChunk(CodeCompletionString::CK_RightParen);
1929
88
  Builder.AddChunk(CodeCompletionString::CK_SemiColon);
1930
88
  Results.AddResult(CodeCompletionResult(Builder.TakeString()));
1931
88
}
1932
1933
static void AddOverrideResults(ResultBuilder &Results,
1934
                               const CodeCompletionContext &CCContext,
1935
9
                               CodeCompletionBuilder &Builder) {
1936
9
  Sema &S = Results.getSema();
1937
9
  const auto *CR = llvm::dyn_cast<CXXRecordDecl>(S.CurContext);
1938
9
  // If not inside a class/struct/union return empty.
1939
9
  if (!CR)
1940
0
    return;
1941
9
  // First store overrides within current class.
1942
9
  // These are stored by name to make querying fast in the later step.
1943
9
  llvm::StringMap<std::vector<FunctionDecl *>> Overrides;
1944
9
  for (auto *Method : CR->methods()) {
1945
7
    if (!Method->isVirtual() || 
!Method->getIdentifier()3
)
1946
4
      continue;
1947
3
    Overrides[Method->getName()].push_back(Method);
1948
3
  }
1949
9
1950
9
  for (const auto &Base : CR->bases()) {
1951
2
    const auto *BR = Base.getType().getTypePtr()->getAsCXXRecordDecl();
1952
2
    if (!BR)
1953
0
      continue;
1954
16
    
for (auto *Method : BR->methods())2
{
1955
16
      if (!Method->isVirtual() || 
!Method->getIdentifier()4
)
1956
12
        continue;
1957
4
      const auto it = Overrides.find(Method->getName());
1958
4
      bool IsOverriden = false;
1959
4
      if (it != Overrides.end()) {
1960
2
        for (auto *MD : it->second) {
1961
2
          // If the method in current body is not an overload of this virtual
1962
2
          // function, then it overrides this one.
1963
2
          if (!S.IsOverload(MD, Method, false)) {
1964
0
            IsOverriden = true;
1965
0
            break;
1966
0
          }
1967
2
        }
1968
2
      }
1969
4
      if (!IsOverriden) {
1970
4
        // Generates a new CodeCompletionResult by taking this function and
1971
4
        // converting it into an override declaration with only one chunk in the
1972
4
        // final CodeCompletionString as a TypedTextChunk.
1973
4
        std::string OverrideSignature;
1974
4
        llvm::raw_string_ostream OS(OverrideSignature);
1975
4
        CodeCompletionResult CCR(Method, 0);
1976
4
        PrintingPolicy Policy =
1977
4
            getCompletionPrintingPolicy(S.getASTContext(), S.getPreprocessor());
1978
4
        auto *CCS = CCR.createCodeCompletionStringForOverride(
1979
4
            S.getPreprocessor(), S.getASTContext(), Builder,
1980
4
            /*IncludeBriefComments=*/false, CCContext, Policy);
1981
4
        Results.AddResult(CodeCompletionResult(CCS, Method, CCP_CodePattern));
1982
4
      }
1983
4
    }
1984
2
  }
1985
9
}
1986
1987
/// Add language constructs that show up for "ordinary" names.
1988
static void AddOrdinaryNameResults(Sema::ParserCompletionContext CCC, Scope *S,
1989
562
                                   Sema &SemaRef, ResultBuilder &Results) {
1990
562
  CodeCompletionAllocator &Allocator = Results.getAllocator();
1991
562
  CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
1992
562
1993
562
  typedef CodeCompletionResult Result;
1994
562
  switch (CCC) {
1995
562
  case Sema::PCC_Namespace:
1996
51
    if (SemaRef.getLangOpts().CPlusPlus) {
1997
26
      if (Results.includeCodePatterns()) {
1998
3
        // namespace <identifier> { declarations }
1999
3
        Builder.AddTypedTextChunk("namespace");
2000
3
        Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2001
3
        Builder.AddPlaceholderChunk("identifier");
2002
3
        Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2003
3
        Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
2004
3
        Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2005
3
        Builder.AddPlaceholderChunk("declarations");
2006
3
        Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2007
3
        Builder.AddChunk(CodeCompletionString::CK_RightBrace);
2008
3
        Results.AddResult(Result(Builder.TakeString()));
2009
3
      }
2010
26
2011
26
      // namespace identifier = identifier ;
2012
26
      Builder.AddTypedTextChunk("namespace");
2013
26
      Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2014
26
      Builder.AddPlaceholderChunk("name");
2015
26
      Builder.AddChunk(CodeCompletionString::CK_Equal);
2016
26
      Builder.AddPlaceholderChunk("namespace");
2017
26
      Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2018
26
      Results.AddResult(Result(Builder.TakeString()));
2019
26
2020
26
      // Using directives
2021
26
      Builder.AddTypedTextChunk("using namespace");
2022
26
      Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2023
26
      Builder.AddPlaceholderChunk("identifier");
2024
26
      Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2025
26
      Results.AddResult(Result(Builder.TakeString()));
2026
26
2027
26
      // asm(string-literal)
2028
26
      Builder.AddTypedTextChunk("asm");
2029
26
      Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2030
26
      Builder.AddPlaceholderChunk("string-literal");
2031
26
      Builder.AddChunk(CodeCompletionString::CK_RightParen);
2032
26
      Results.AddResult(Result(Builder.TakeString()));
2033
26
2034
26
      if (Results.includeCodePatterns()) {
2035
3
        // Explicit template instantiation
2036
3
        Builder.AddTypedTextChunk("template");
2037
3
        Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2038
3
        Builder.AddPlaceholderChunk("declaration");
2039
3
        Results.AddResult(Result(Builder.TakeString()));
2040
23
      } else {
2041
23
        Results.AddResult(Result("template", CodeCompletionResult::RK_Keyword));
2042
23
      }
2043
26
    }
2044
51
2045
51
    if (SemaRef.getLangOpts().ObjC)
2046
13
      AddObjCTopLevelResults(Results, true);
2047
51
2048
51
    AddTypedefResult(Results);
2049
51
    LLVM_FALLTHROUGH;
2050
51
2051
60
  case Sema::PCC_Class:
2052
60
    if (SemaRef.getLangOpts().CPlusPlus) {
2053
35
      // Using declaration
2054
35
      Builder.AddTypedTextChunk("using");
2055
35
      Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2056
35
      Builder.AddPlaceholderChunk("qualifier");
2057
35
      Builder.AddTextChunk("::");
2058
35
      Builder.AddPlaceholderChunk("name");
2059
35
      Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2060
35
      Results.AddResult(Result(Builder.TakeString()));
2061
35
2062
35
      // using typename qualifier::name (only in a dependent context)
2063
35
      if (SemaRef.CurContext->isDependentContext()) {
2064
0
        Builder.AddTypedTextChunk("using typename");
2065
0
        Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2066
0
        Builder.AddPlaceholderChunk("qualifier");
2067
0
        Builder.AddTextChunk("::");
2068
0
        Builder.AddPlaceholderChunk("name");
2069
0
        Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2070
0
        Results.AddResult(Result(Builder.TakeString()));
2071
0
      }
2072
35
2073
35
      AddStaticAssertResult(Builder, Results, SemaRef.getLangOpts());
2074
35
2075
35
      if (CCC == Sema::PCC_Class) {
2076
9
        AddTypedefResult(Results);
2077
9
2078
9
        bool IsNotInheritanceScope =
2079
9
            !(S->getFlags() & Scope::ClassInheritanceScope);
2080
9
        // public:
2081
9
        Builder.AddTypedTextChunk("public");
2082
9
        if (IsNotInheritanceScope && 
Results.includeCodePatterns()8
)
2083
3
          Builder.AddChunk(CodeCompletionString::CK_Colon);
2084
9
        Results.AddResult(Result(Builder.TakeString()));
2085
9
2086
9
        // protected:
2087
9
        Builder.AddTypedTextChunk("protected");
2088
9
        if (IsNotInheritanceScope && 
Results.includeCodePatterns()8
)
2089
3
          Builder.AddChunk(CodeCompletionString::CK_Colon);
2090
9
        Results.AddResult(Result(Builder.TakeString()));
2091
9
2092
9
        // private:
2093
9
        Builder.AddTypedTextChunk("private");
2094
9
        if (IsNotInheritanceScope && 
Results.includeCodePatterns()8
)
2095
3
          Builder.AddChunk(CodeCompletionString::CK_Colon);
2096
9
        Results.AddResult(Result(Builder.TakeString()));
2097
9
2098
9
        // FIXME: This adds override results only if we are at the first word of
2099
9
        // the declaration/definition. Also call this from other sides to have
2100
9
        // more use-cases.
2101
9
        AddOverrideResults(Results, CodeCompletionContext::CCC_ClassStructUnion,
2102
9
                           Builder);
2103
9
      }
2104
35
    }
2105
60
    LLVM_FALLTHROUGH;
2106
60
2107
60
  case Sema::PCC_Template:
2108
60
  case Sema::PCC_MemberTemplate:
2109
60
    if (SemaRef.getLangOpts().CPlusPlus && 
Results.includeCodePatterns()35
) {
2110
7
      // template < parameters >
2111
7
      Builder.AddTypedTextChunk("template");
2112
7
      Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
2113
7
      Builder.AddPlaceholderChunk("parameters");
2114
7
      Builder.AddChunk(CodeCompletionString::CK_RightAngle);
2115
7
      Results.AddResult(Result(Builder.TakeString()));
2116
53
    } else {
2117
53
      Results.AddResult(Result("template", CodeCompletionResult::RK_Keyword));
2118
53
    }
2119
60
2120
60
    AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
2121
60
    AddFunctionSpecifiers(CCC, SemaRef.getLangOpts(), Results);
2122
60
    break;
2123
60
2124
60
  case Sema::PCC_ObjCInterface:
2125
1
    AddObjCInterfaceResults(SemaRef.getLangOpts(), Results, true);
2126
1
    AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
2127
1
    AddFunctionSpecifiers(CCC, SemaRef.getLangOpts(), Results);
2128
1
    break;
2129
60
2130
60
  case Sema::PCC_ObjCImplementation:
2131
1
    AddObjCImplementationResults(SemaRef.getLangOpts(), Results, true);
2132
1
    AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
2133
1
    AddFunctionSpecifiers(CCC, SemaRef.getLangOpts(), Results);
2134
1
    break;
2135
60
2136
60
  case Sema::PCC_ObjCInstanceVariableList:
2137
1
    AddObjCVisibilityResults(SemaRef.getLangOpts(), Results, true);
2138
1
    break;
2139
60
2140
106
  case Sema::PCC_RecoveryInFunction:
2141
106
  case Sema::PCC_Statement: {
2142
106
    AddTypedefResult(Results);
2143
106
2144
106
    if (SemaRef.getLangOpts().CPlusPlus && 
Results.includeCodePatterns()57
&&
2145
106
        
SemaRef.getLangOpts().CXXExceptions11
) {
2146
2
      Builder.AddTypedTextChunk("try");
2147
2
      Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2148
2
      Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
2149
2
      Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2150
2
      Builder.AddPlaceholderChunk("statements");
2151
2
      Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2152
2
      Builder.AddChunk(CodeCompletionString::CK_RightBrace);
2153
2
      Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2154
2
      Builder.AddTextChunk("catch");
2155
2
      Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2156
2
      Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2157
2
      Builder.AddPlaceholderChunk("declaration");
2158
2
      Builder.AddChunk(CodeCompletionString::CK_RightParen);
2159
2
      Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2160
2
      Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
2161
2
      Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2162
2
      Builder.AddPlaceholderChunk("statements");
2163
2
      Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2164
2
      Builder.AddChunk(CodeCompletionString::CK_RightBrace);
2165
2
      Results.AddResult(Result(Builder.TakeString()));
2166
2
    }
2167
106
    if (SemaRef.getLangOpts().ObjC)
2168
16
      AddObjCStatementResults(Results, true);
2169
106
2170
106
    if (Results.includeCodePatterns()) {
2171
14
      // if (condition) { statements }
2172
14
      Builder.AddTypedTextChunk("if");
2173
14
      Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2174
14
      Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2175
14
      if (SemaRef.getLangOpts().CPlusPlus)
2176
11
        Builder.AddPlaceholderChunk("condition");
2177
3
      else
2178
3
        Builder.AddPlaceholderChunk("expression");
2179
14
      Builder.AddChunk(CodeCompletionString::CK_RightParen);
2180
14
      Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2181
14
      Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
2182
14
      Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2183
14
      Builder.AddPlaceholderChunk("statements");
2184
14
      Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2185
14
      Builder.AddChunk(CodeCompletionString::CK_RightBrace);
2186
14
      Results.AddResult(Result(Builder.TakeString()));
2187
14
2188
14
      // switch (condition) { }
2189
14
      Builder.AddTypedTextChunk("switch");
2190
14
      Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2191
14
      Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2192
14
      if (SemaRef.getLangOpts().CPlusPlus)
2193
11
        Builder.AddPlaceholderChunk("condition");
2194
3
      else
2195
3
        Builder.AddPlaceholderChunk("expression");
2196
14
      Builder.AddChunk(CodeCompletionString::CK_RightParen);
2197
14
      Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2198
14
      Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
2199
14
      Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2200
14
      Builder.AddPlaceholderChunk("cases");
2201
14
      Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2202
14
      Builder.AddChunk(CodeCompletionString::CK_RightBrace);
2203
14
      Results.AddResult(Result(Builder.TakeString()));
2204
14
    }
2205
106
2206
106
    // Switch-specific statements.
2207
106
    if (SemaRef.getCurFunction() &&
2208
106
        !SemaRef.getCurFunction()->SwitchStack.empty()) {
2209
0
      // case expression:
2210
0
      Builder.AddTypedTextChunk("case");
2211
0
      Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2212
0
      Builder.AddPlaceholderChunk("expression");
2213
0
      Builder.AddChunk(CodeCompletionString::CK_Colon);
2214
0
      Results.AddResult(Result(Builder.TakeString()));
2215
0
2216
0
      // default:
2217
0
      Builder.AddTypedTextChunk("default");
2218
0
      Builder.AddChunk(CodeCompletionString::CK_Colon);
2219
0
      Results.AddResult(Result(Builder.TakeString()));
2220
0
    }
2221
106
2222
106
    if (Results.includeCodePatterns()) {
2223
14
      /// while (condition) { statements }
2224
14
      Builder.AddTypedTextChunk("while");
2225
14
      Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2226
14
      Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2227
14
      if (SemaRef.getLangOpts().CPlusPlus)
2228
11
        Builder.AddPlaceholderChunk("condition");
2229
3
      else
2230
3
        Builder.AddPlaceholderChunk("expression");
2231
14
      Builder.AddChunk(CodeCompletionString::CK_RightParen);
2232
14
      Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2233
14
      Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
2234
14
      Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2235
14
      Builder.AddPlaceholderChunk("statements");
2236
14
      Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2237
14
      Builder.AddChunk(CodeCompletionString::CK_RightBrace);
2238
14
      Results.AddResult(Result(Builder.TakeString()));
2239
14
2240
14
      // do { statements } while ( expression );
2241
14
      Builder.AddTypedTextChunk("do");
2242
14
      Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2243
14
      Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
2244
14
      Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2245
14
      Builder.AddPlaceholderChunk("statements");
2246
14
      Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2247
14
      Builder.AddChunk(CodeCompletionString::CK_RightBrace);
2248
14
      Builder.AddTextChunk("while");
2249
14
      Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2250
14
      Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2251
14
      Builder.AddPlaceholderChunk("expression");
2252
14
      Builder.AddChunk(CodeCompletionString::CK_RightParen);
2253
14
      Results.AddResult(Result(Builder.TakeString()));
2254
14
2255
14
      // for ( for-init-statement ; condition ; expression ) { statements }
2256
14
      Builder.AddTypedTextChunk("for");
2257
14
      Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2258
14
      Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2259
14
      if (SemaRef.getLangOpts().CPlusPlus || 
SemaRef.getLangOpts().C993
)
2260
14
        Builder.AddPlaceholderChunk("init-statement");
2261
0
      else
2262
0
        Builder.AddPlaceholderChunk("init-expression");
2263
14
      Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2264
14
      Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2265
14
      Builder.AddPlaceholderChunk("condition");
2266
14
      Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2267
14
      Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2268
14
      Builder.AddPlaceholderChunk("inc-expression");
2269
14
      Builder.AddChunk(CodeCompletionString::CK_RightParen);
2270
14
      Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2271
14
      Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
2272
14
      Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2273
14
      Builder.AddPlaceholderChunk("statements");
2274
14
      Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2275
14
      Builder.AddChunk(CodeCompletionString::CK_RightBrace);
2276
14
      Results.AddResult(Result(Builder.TakeString()));
2277
14
    }
2278
106
2279
106
    if (S->getContinueParent()) {
2280
4
      // continue ;
2281
4
      Builder.AddTypedTextChunk("continue");
2282
4
      Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2283
4
      Results.AddResult(Result(Builder.TakeString()));
2284
4
    }
2285
106
2286
106
    if (S->getBreakParent()) {
2287
4
      // break ;
2288
4
      Builder.AddTypedTextChunk("break");
2289
4
      Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2290
4
      Results.AddResult(Result(Builder.TakeString()));
2291
4
    }
2292
106
2293
106
    // "return expression ;" or "return ;", depending on the return type.
2294
106
    QualType ReturnType;
2295
106
    if (const auto *Function = dyn_cast<FunctionDecl>(SemaRef.CurContext))
2296
92
      ReturnType = Function->getReturnType();
2297
14
    else if (const auto *Method = dyn_cast<ObjCMethodDecl>(SemaRef.CurContext))
2298
14
      ReturnType = Method->getReturnType();
2299
0
    else if (SemaRef.getCurBlock() &&
2300
0
             !SemaRef.getCurBlock()->ReturnType.isNull())
2301
0
      ReturnType = SemaRef.getCurBlock()->ReturnType;;
2302
106
    if (ReturnType.isNull() || ReturnType->isVoidType()) {
2303
83
      Builder.AddTypedTextChunk("return");
2304
83
      Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2305
83
      Results.AddResult(Result(Builder.TakeString()));
2306
83
    } else {
2307
23
      assert(!ReturnType.isNull());
2308
23
      // "return expression ;"
2309
23
      Builder.AddTypedTextChunk("return");
2310
23
      Builder.AddChunk(clang::CodeCompletionString::CK_HorizontalSpace);
2311
23
      Builder.AddPlaceholderChunk("expression");
2312
23
      Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2313
23
      Results.AddResult(Result(Builder.TakeString()));
2314
23
      // When boolean, also add 'return true;' and 'return false;'.
2315
23
      if (ReturnType->isBooleanType()) {
2316
1
        Builder.AddTypedTextChunk("return true");
2317
1
        Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2318
1
        Results.AddResult(Result(Builder.TakeString()));
2319
1
2320
1
        Builder.AddTypedTextChunk("return false");
2321
1
        Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2322
1
        Results.AddResult(Result(Builder.TakeString()));
2323
1
      }
2324
23
    }
2325
106
2326
106
    // goto identifier ;
2327
106
    Builder.AddTypedTextChunk("goto");
2328
106
    Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2329
106
    Builder.AddPlaceholderChunk("label");
2330
106
    Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2331
106
    Results.AddResult(Result(Builder.TakeString()));
2332
106
2333
106
    // Using directives
2334
106
    Builder.AddTypedTextChunk("using namespace");
2335
106
    Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2336
106
    Builder.AddPlaceholderChunk("identifier");
2337
106
    Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2338
106
    Results.AddResult(Result(Builder.TakeString()));
2339
106
2340
106
    AddStaticAssertResult(Builder, Results, SemaRef.getLangOpts());
2341
106
  }
2342
106
    LLVM_FALLTHROUGH;
2343
106
2344
106
  // Fall through (for statement expressions).
2345
118
  case Sema::PCC_ForInit:
2346
118
  case Sema::PCC_Condition:
2347
118
    AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
2348
118
    // Fall through: conditions and statements can have expressions.
2349
118
    LLVM_FALLTHROUGH;
2350
118
2351
148
  case Sema::PCC_ParenthesizedExpression:
2352
148
    if (SemaRef.getLangOpts().ObjCAutoRefCount &&
2353
148
        
CCC == Sema::PCC_ParenthesizedExpression7
) {
2354
1
      // (__bridge <type>)<expression>
2355
1
      Builder.AddTypedTextChunk("__bridge");
2356
1
      Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2357
1
      Builder.AddPlaceholderChunk("type");
2358
1
      Builder.AddChunk(CodeCompletionString::CK_RightParen);
2359
1
      Builder.AddPlaceholderChunk("expression");
2360
1
      Results.AddResult(Result(Builder.TakeString()));
2361
1
2362
1
      // (__bridge_transfer <Objective-C type>)<expression>
2363
1
      Builder.AddTypedTextChunk("__bridge_transfer");
2364
1
      Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2365
1
      Builder.AddPlaceholderChunk("Objective-C type");
2366
1
      Builder.AddChunk(CodeCompletionString::CK_RightParen);
2367
1
      Builder.AddPlaceholderChunk("expression");
2368
1
      Results.AddResult(Result(Builder.TakeString()));
2369
1
2370
1
      // (__bridge_retained <CF type>)<expression>
2371
1
      Builder.AddTypedTextChunk("__bridge_retained");
2372
1
      Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2373
1
      Builder.AddPlaceholderChunk("CF type");
2374
1
      Builder.AddChunk(CodeCompletionString::CK_RightParen);
2375
1
      Builder.AddPlaceholderChunk("expression");
2376
1
      Results.AddResult(Result(Builder.TakeString()));
2377
1
    }
2378
148
    // Fall through
2379
148
    LLVM_FALLTHROUGH;
2380
148
2381
490
  case Sema::PCC_Expression: {
2382
490
    if (SemaRef.getLangOpts().CPlusPlus) {
2383
344
      // 'this', if we're in a non-static member function.
2384
344
      addThisCompletion(SemaRef, Results);
2385
344
2386
344
      // true
2387
344
      Builder.AddResultTypeChunk("bool");
2388
344
      Builder.AddTypedTextChunk("true");
2389
344
      Results.AddResult(Result(Builder.TakeString()));
2390
344
2391
344
      // false
2392
344
      Builder.AddResultTypeChunk("bool");
2393
344
      Builder.AddTypedTextChunk("false");
2394
344
      Results.AddResult(Result(Builder.TakeString()));
2395
344
2396
344
      if (SemaRef.getLangOpts().RTTI) {
2397
342
        // dynamic_cast < type-id > ( expression )
2398
342
        Builder.AddTypedTextChunk("dynamic_cast");
2399
342
        Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
2400
342
        Builder.AddPlaceholderChunk("type");
2401
342
        Builder.AddChunk(CodeCompletionString::CK_RightAngle);
2402
342
        Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2403
342
        Builder.AddPlaceholderChunk("expression");
2404
342
        Builder.AddChunk(CodeCompletionString::CK_RightParen);
2405
342
        Results.AddResult(Result(Builder.TakeString()));
2406
342
      }
2407
344
2408
344
      // static_cast < type-id > ( expression )
2409
344
      Builder.AddTypedTextChunk("static_cast");
2410
344
      Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
2411
344
      Builder.AddPlaceholderChunk("type");
2412
344
      Builder.AddChunk(CodeCompletionString::CK_RightAngle);
2413
344
      Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2414
344
      Builder.AddPlaceholderChunk("expression");
2415
344
      Builder.AddChunk(CodeCompletionString::CK_RightParen);
2416
344
      Results.AddResult(Result(Builder.TakeString()));
2417
344
2418
344
      // reinterpret_cast < type-id > ( expression )
2419
344
      Builder.AddTypedTextChunk("reinterpret_cast");
2420
344
      Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
2421
344
      Builder.AddPlaceholderChunk("type");
2422
344
      Builder.AddChunk(CodeCompletionString::CK_RightAngle);
2423
344
      Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2424
344
      Builder.AddPlaceholderChunk("expression");
2425
344
      Builder.AddChunk(CodeCompletionString::CK_RightParen);
2426
344
      Results.AddResult(Result(Builder.TakeString()));
2427
344
2428
344
      // const_cast < type-id > ( expression )
2429
344
      Builder.AddTypedTextChunk("const_cast");
2430
344
      Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
2431
344
      Builder.AddPlaceholderChunk("type");
2432
344
      Builder.AddChunk(CodeCompletionString::CK_RightAngle);
2433
344
      Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2434
344
      Builder.AddPlaceholderChunk("expression");
2435
344
      Builder.AddChunk(CodeCompletionString::CK_RightParen);
2436
344
      Results.AddResult(Result(Builder.TakeString()));
2437
344
2438
344
      if (SemaRef.getLangOpts().RTTI) {
2439
342
        // typeid ( expression-or-type )
2440
342
        Builder.AddResultTypeChunk("std::type_info");
2441
342
        Builder.AddTypedTextChunk("typeid");
2442
342
        Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2443
342
        Builder.AddPlaceholderChunk("expression-or-type");
2444
342
        Builder.AddChunk(CodeCompletionString::CK_RightParen);
2445
342
        Results.AddResult(Result(Builder.TakeString()));
2446
342
      }
2447
344
2448
344
      // new T ( ... )
2449
344
      Builder.AddTypedTextChunk("new");
2450
344
      Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2451
344
      Builder.AddPlaceholderChunk("type");
2452
344
      Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2453
344
      Builder.AddPlaceholderChunk("expressions");
2454
344
      Builder.AddChunk(CodeCompletionString::CK_RightParen);
2455
344
      Results.AddResult(Result(Builder.TakeString()));
2456
344
2457
344
      // new T [ ] ( ... )
2458
344
      Builder.AddTypedTextChunk("new");
2459
344
      Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2460
344
      Builder.AddPlaceholderChunk("type");
2461
344
      Builder.AddChunk(CodeCompletionString::CK_LeftBracket);
2462
344
      Builder.AddPlaceholderChunk("size");
2463
344
      Builder.AddChunk(CodeCompletionString::CK_RightBracket);
2464
344
      Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2465
344
      Builder.AddPlaceholderChunk("expressions");
2466
344
      Builder.AddChunk(CodeCompletionString::CK_RightParen);
2467
344
      Results.AddResult(Result(Builder.TakeString()));
2468
344
2469
344
      // delete expression
2470
344
      Builder.AddResultTypeChunk("void");
2471
344
      Builder.AddTypedTextChunk("delete");
2472
344
      Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2473
344
      Builder.AddPlaceholderChunk("expression");
2474
344
      Results.AddResult(Result(Builder.TakeString()));
2475
344
2476
344
      // delete [] expression
2477
344
      Builder.AddResultTypeChunk("void");
2478
344
      Builder.AddTypedTextChunk("delete");
2479
344
      Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2480
344
      Builder.AddChunk(CodeCompletionString::CK_LeftBracket);
2481
344
      Builder.AddChunk(CodeCompletionString::CK_RightBracket);
2482
344
      Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2483
344
      Builder.AddPlaceholderChunk("expression");
2484
344
      Results.AddResult(Result(Builder.TakeString()));
2485
344
2486
344
      if (SemaRef.getLangOpts().CXXExceptions) {
2487
279
        // throw expression
2488
279
        Builder.AddResultTypeChunk("void");
2489
279
        Builder.AddTypedTextChunk("throw");
2490
279
        Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2491
279
        Builder.AddPlaceholderChunk("expression");
2492
279
        Results.AddResult(Result(Builder.TakeString()));
2493
279
      }
2494
344
2495
344
      // FIXME: Rethrow?
2496
344
2497
344
      if (SemaRef.getLangOpts().CPlusPlus11) {
2498
339
        // nullptr
2499
339
        Builder.AddResultTypeChunk("std::nullptr_t");
2500
339
        Builder.AddTypedTextChunk("nullptr");
2501
339
        Results.AddResult(Result(Builder.TakeString()));
2502
339
2503
339
        // alignof
2504
339
        Builder.AddResultTypeChunk("size_t");
2505
339
        Builder.AddTypedTextChunk("alignof");
2506
339
        Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2507
339
        Builder.AddPlaceholderChunk("type");
2508
339
        Builder.AddChunk(CodeCompletionString::CK_RightParen);
2509
339
        Results.AddResult(Result(Builder.TakeString()));
2510
339
2511
339
        // noexcept
2512
339
        Builder.AddResultTypeChunk("bool");
2513
339
        Builder.AddTypedTextChunk("noexcept");
2514
339
        Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2515
339
        Builder.AddPlaceholderChunk("expression");
2516
339
        Builder.AddChunk(CodeCompletionString::CK_RightParen);
2517
339
        Results.AddResult(Result(Builder.TakeString()));
2518
339
2519
339
        // sizeof... expression
2520
339
        Builder.AddResultTypeChunk("size_t");
2521
339
        Builder.AddTypedTextChunk("sizeof...");
2522
339
        Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2523
339
        Builder.AddPlaceholderChunk("parameter-pack");
2524
339
        Builder.AddChunk(CodeCompletionString::CK_RightParen);
2525
339
        Results.AddResult(Result(Builder.TakeString()));
2526
339
      }
2527
344
    }
2528
490
2529
490
    if (SemaRef.getLangOpts().ObjC) {
2530
63
      // Add "super", if we're in an Objective-C class with a superclass.
2531
63
      if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
2532
28
        // The interface can be NULL.
2533
28
        if (ObjCInterfaceDecl *ID = Method->getClassInterface())
2534
28
          if (ID->getSuperClass()) {
2535
5
            std::string SuperType;
2536
5
            SuperType = ID->getSuperClass()->getNameAsString();
2537
5
            if (Method->isInstanceMethod())
2538
5
              SuperType += " *";
2539
5
2540
5
            Builder.AddResultTypeChunk(Allocator.CopyString(SuperType));
2541
5
            Builder.AddTypedTextChunk("super");
2542
5
            Results.AddResult(Result(Builder.TakeString()));
2543
5
          }
2544
28
      }
2545
63
2546
63
      AddObjCExpressionResults(Results, true);
2547
63
    }
2548
490
2549
490
    if (SemaRef.getLangOpts().C11) {
2550
143
      // _Alignof
2551
143
      Builder.AddResultTypeChunk("size_t");
2552
143
      if (SemaRef.PP.isMacroDefined("alignof"))
2553
0
        Builder.AddTypedTextChunk("alignof");
2554
143
      else
2555
143
        Builder.AddTypedTextChunk("_Alignof");
2556
143
      Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2557
143
      Builder.AddPlaceholderChunk("type");
2558
143
      Builder.AddChunk(CodeCompletionString::CK_RightParen);
2559
143
      Results.AddResult(Result(Builder.TakeString()));
2560
143
    }
2561
490
2562
490
    // sizeof expression
2563
490
    Builder.AddResultTypeChunk("size_t");
2564
490
    Builder.AddTypedTextChunk("sizeof");
2565
490
    Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2566
490
    Builder.AddPlaceholderChunk("expression-or-type");
2567
490
    Builder.AddChunk(CodeCompletionString::CK_RightParen);
2568
490
    Results.AddResult(Result(Builder.TakeString()));
2569
490
    break;
2570
148
  }
2571
148
2572
148
  case Sema::PCC_Type:
2573
9
  case Sema::PCC_LocalDeclarationSpecifiers:
2574
9
    break;
2575
562
  }
2576
562
2577
562
  if (WantTypesInContext(CCC, SemaRef.getLangOpts()))
2578
476
    AddTypeSpecifierResults(SemaRef.getLangOpts(), Results);
2579
562
2580
562
  if (SemaRef.getLangOpts().CPlusPlus && 
CCC != Sema::PCC_Type379
)
2581
379
    Results.AddResult(Result("operator"));
2582
562
}
2583
2584
/// If the given declaration has an associated type, add it as a result
2585
/// type chunk.
2586
static void AddResultTypeChunk(ASTContext &Context,
2587
                               const PrintingPolicy &Policy,
2588
                               const NamedDecl *ND, QualType BaseType,
2589
5.25k
                               CodeCompletionBuilder &Result) {
2590
5.25k
  if (!ND)
2591
0
    return;
2592
5.25k
2593
5.25k
  // Skip constructors and conversion functions, which have their return types
2594
5.25k
  // built into their names.
2595
5.25k
  if (isConstructor(ND) || 
isa<CXXConversionDecl>(ND)4.90k
)
2596
354
    return;
2597
4.89k
2598
4.89k
  // Determine the type of the declaration (if it has a type).
2599
4.89k
  QualType T;
2600
4.89k
  if (const FunctionDecl *Function = ND->getAsFunction())
2601
2.52k
    T = Function->getReturnType();
2602
2.37k
  else if (const auto *Method = dyn_cast<ObjCMethodDecl>(ND)) {
2603
357
    if (!BaseType.isNull())
2604
296
      T = Method->getSendResultType(BaseType);
2605
61
    else
2606
61
      T = Method->getReturnType();
2607
2.01k
  } else if (const auto *Enumerator = dyn_cast<EnumConstantDecl>(ND)) {
2608
115
    T = Context.getTypeDeclType(cast<TypeDecl>(Enumerator->getDeclContext()));
2609
115
    T = clang::TypeName::getFullyQualifiedType(T, Context);
2610
1.90k
  } else if (isa<UnresolvedUsingValueDecl>(ND)) {
2611
0
    /* Do nothing: ignore unresolved using declarations*/
2612
1.90k
  } else if (const auto *Ivar = dyn_cast<ObjCIvarDecl>(ND)) {
2613
61
    if (!BaseType.isNull())
2614
28
      T = Ivar->getUsageType(BaseType);
2615
33
    else
2616
33
      T = Ivar->getType();
2617
1.84k
  } else if (const auto *Value = dyn_cast<ValueDecl>(ND)) {
2618
730
    T = Value->getType();
2619
1.11k
  } else if (const auto *Property = dyn_cast<ObjCPropertyDecl>(ND)) {
2620
111
    if (!BaseType.isNull())
2621
87
      T = Property->getUsageType(BaseType);
2622
24
    else
2623
24
      T = Property->getType();
2624
111
  }
2625
4.89k
2626
4.89k
  if (T.isNull() || 
Context.hasSameType(T, Context.DependentTy)3.89k
)
2627
1.00k
    return;
2628
3.89k
2629
3.89k
  Result.AddResultTypeChunk(
2630
3.89k
      GetCompletionTypeString(T, Context, Policy, Result.getAllocator()));
2631
3.89k
}
2632
2633
static void MaybeAddSentinel(Preprocessor &PP,
2634
                             const NamedDecl *FunctionOrMethod,
2635
27
                             CodeCompletionBuilder &Result) {
2636
27
  if (SentinelAttr *Sentinel = FunctionOrMethod->getAttr<SentinelAttr>())
2637
9
    if (Sentinel->getSentinel() == 0) {
2638
9
      if (PP.getLangOpts().ObjC && 
PP.isMacroDefined("nil")3
)
2639
3
        Result.AddTextChunk(", nil");
2640
6
      else if (PP.isMacroDefined("NULL"))
2641
6
        Result.AddTextChunk(", NULL");
2642
0
      else
2643
0
        Result.AddTextChunk(", (void*)0");
2644
9
    }
2645
27
}
2646
2647
static std::string formatObjCParamQualifiers(unsigned ObjCQuals,
2648
381
                                             QualType &Type) {
2649
381
  std::string Result;
2650
381
  if (ObjCQuals & Decl::OBJC_TQ_In)
2651
2
    Result += "in ";
2652
379
  else if (ObjCQuals & Decl::OBJC_TQ_Inout)
2653
6
    Result += "inout ";
2654
373
  else if (ObjCQuals & Decl::OBJC_TQ_Out)
2655
1
    Result += "out ";
2656
381
  if (ObjCQuals & Decl::OBJC_TQ_Bycopy)
2657
1
    Result += "bycopy ";
2658
380
  else if (ObjCQuals & Decl::OBJC_TQ_Byref)
2659
1
    Result += "byref ";
2660
381
  if (ObjCQuals & Decl::OBJC_TQ_Oneway)
2661
1
    Result += "oneway ";
2662
381
  if (ObjCQuals & Decl::OBJC_TQ_CSNullability) {
2663
6
    if (auto nullability = AttributedType::stripOuterNullability(Type)) {
2664
1
      switch (*nullability) {
2665
1
      case NullabilityKind::NonNull:
2666
0
        Result += "nonnull ";
2667
0
        break;
2668
1
2669
1
      case NullabilityKind::Nullable:
2670
1
        Result += "nullable ";
2671
1
        break;
2672
1
2673
1
      case NullabilityKind::Unspecified:
2674
0
        Result += "null_unspecified ";
2675
0
        break;
2676
381
      }
2677
381
    }
2678
6
  }
2679
381
  return Result;
2680
381
}
2681
2682
/// Tries to find the most appropriate type location for an Objective-C
2683
/// block placeholder.
2684
///
2685
/// This function ignores things like typedefs and qualifiers in order to
2686
/// present the most relevant and accurate block placeholders in code completion
2687
/// results.
2688
static void findTypeLocationForBlockDecl(const TypeSourceInfo *TSInfo,
2689
                                         FunctionTypeLoc &Block,
2690
                                         FunctionProtoTypeLoc &BlockProto,
2691
87
                                         bool SuppressBlock = false) {
2692
87
  if (!TSInfo)
2693
4
    return;
2694
83
  TypeLoc TL = TSInfo->getTypeLoc().getUnqualifiedLoc();
2695
105
  while (true) {
2696
105
    // Look through typedefs.
2697
105
    if (!SuppressBlock) {
2698
100
      if (TypedefTypeLoc TypedefTL = TL.getAs<TypedefTypeLoc>()) {
2699
18
        if (TypeSourceInfo *InnerTSInfo =
2700
18
                TypedefTL.getTypedefNameDecl()->getTypeSourceInfo()) {
2701
18
          TL = InnerTSInfo->getTypeLoc().getUnqualifiedLoc();
2702
18
          continue;
2703
18
        }
2704
82
      }
2705
82
2706
82
      // Look through qualified types
2707
82
      if (QualifiedTypeLoc QualifiedTL = TL.getAs<QualifiedTypeLoc>()) {
2708
0
        TL = QualifiedTL.getUnqualifiedLoc();
2709
0
        continue;
2710
0
      }
2711
82
2712
82
      if (AttributedTypeLoc AttrTL = TL.getAs<AttributedTypeLoc>()) {
2713
4
        TL = AttrTL.getModifiedLoc();
2714
4
        continue;
2715
4
      }
2716
83
    }
2717
83
2718
83
    // Try to get the function prototype behind the block pointer type,
2719
83
    // then we're done.
2720
83
    if (BlockPointerTypeLoc BlockPtr = TL.getAs<BlockPointerTypeLoc>()) {
2721
78
      TL = BlockPtr.getPointeeLoc().IgnoreParens();
2722
78
      Block = TL.getAs<FunctionTypeLoc>();
2723
78
      BlockProto = TL.getAs<FunctionProtoTypeLoc>();
2724
78
    }
2725
83
    break;
2726
83
  }
2727
83
}
2728
2729
static std::string
2730
formatBlockPlaceholder(const PrintingPolicy &Policy, const NamedDecl *BlockDecl,
2731
                       FunctionTypeLoc &Block, FunctionProtoTypeLoc &BlockProto,
2732
                       bool SuppressBlockName = false,
2733
                       bool SuppressBlock = false,
2734
                       Optional<ArrayRef<QualType>> ObjCSubsts = None);
2735
2736
static std::string
2737
FormatFunctionParameter(const PrintingPolicy &Policy, const ParmVarDecl *Param,
2738
                        bool SuppressName = false, bool SuppressBlock = false,
2739
3.60k
                        Optional<ArrayRef<QualType>> ObjCSubsts = None) {
2740
3.60k
  // Params are unavailable in FunctionTypeLoc if the FunctionType is invalid.
2741
3.60k
  // It would be better to pass in the param Type, which is usually avaliable.
2742
3.60k
  // But this case is rare, so just pretend we fell back to int as elsewhere.
2743
3.60k
  if (!Param)
2744
1
    return "int";
2745
3.60k
  bool ObjCMethodParam = isa<ObjCMethodDecl>(Param->getDeclContext());
2746
3.60k
  if (Param->getType()->isDependentType() ||
2747
3.60k
      
!Param->getType()->isBlockPointerType()2.70k
) {
2748
3.56k
    // The argument for a dependent or non-block parameter is a placeholder
2749
3.56k
    // containing that parameter's type.
2750
3.56k
    std::string Result;
2751
3.56k
2752
3.56k
    if (Param->getIdentifier() && 
!ObjCMethodParam621
&&
!SuppressName621
)
2753
621
      Result = Param->getIdentifier()->getName();
2754
3.56k
2755
3.56k
    QualType Type = Param->getType();
2756
3.56k
    if (ObjCSubsts)
2757
8
      Type = Type.substObjCTypeArgs(Param->getASTContext(), *ObjCSubsts,
2758
8
                                    ObjCSubstitutionContext::Parameter);
2759
3.56k
    if (ObjCMethodParam) {
2760
0
      Result =
2761
0
          "(" + formatObjCParamQualifiers(Param->getObjCDeclQualifier(), Type);
2762
0
      Result += Type.getAsString(Policy) + ")";
2763
0
      if (Param->getIdentifier() && !SuppressName)
2764
0
        Result += Param->getIdentifier()->getName();
2765
3.56k
    } else {
2766
3.56k
      Type.getAsStringInternal(Result, Policy);
2767
3.56k
    }
2768
3.56k
    return Result;
2769
3.56k
  }
2770
44
2771
44
  // The argument for a block pointer parameter is a block literal with
2772
44
  // the appropriate type.
2773
44
  FunctionTypeLoc Block;
2774
44
  FunctionProtoTypeLoc BlockProto;
2775
44
  findTypeLocationForBlockDecl(Param->getTypeSourceInfo(), Block, BlockProto,
2776
44
                               SuppressBlock);
2777
44
  // Try to retrieve the block type information from the property if this is a
2778
44
  // parameter in a setter.
2779
44
  if (!Block && 
ObjCMethodParam9
&&
2780
44
      
cast<ObjCMethodDecl>(Param->getDeclContext())->isPropertyAccessor()4
) {
2781
4
    if (const auto *PD = cast<ObjCMethodDecl>(Param->getDeclContext())
2782
4
                             ->findPropertyDecl(/*CheckOverrides=*/false))
2783
4
      findTypeLocationForBlockDecl(PD->getTypeSourceInfo(), Block, BlockProto,
2784
4
                                   SuppressBlock);
2785
4
  }
2786
44
2787
44
  if (!Block) {
2788
5
    // We were unable to find a FunctionProtoTypeLoc with parameter names
2789
5
    // for the block; just use the parameter type as a placeholder.
2790
5
    std::string Result;
2791
5
    if (!ObjCMethodParam && Param->getIdentifier())
2792
5
      Result = Param->getIdentifier()->getName();
2793
5
2794
5
    QualType Type = Param->getType().getUnqualifiedType();
2795
5
2796
5
    if (ObjCMethodParam) {
2797
0
      Result = Type.getAsString(Policy);
2798
0
      std::string Quals =
2799
0
          formatObjCParamQualifiers(Param->getObjCDeclQualifier(), Type);
2800
0
      if (!Quals.empty())
2801
0
        Result = "(" + Quals + " " + Result + ")";
2802
0
      if (Result.back() != ')')
2803
0
        Result += " ";
2804
0
      if (Param->getIdentifier())
2805
0
        Result += Param->getIdentifier()->getName();
2806
5
    } else {
2807
5
      Type.getAsStringInternal(Result, Policy);
2808
5
    }
2809
5
2810
5
    return Result;
2811
5
  }
2812
39
2813
39
  // We have the function prototype behind the block pointer type, as it was
2814
39
  // written in the source.
2815
39
  return formatBlockPlaceholder(Policy, Param, Block, BlockProto,
2816
39
                                /*SuppressBlockName=*/false, SuppressBlock,
2817
39
                                ObjCSubsts);
2818
39
}
2819
2820
/// Returns a placeholder string that corresponds to an Objective-C block
2821
/// declaration.
2822
///
2823
/// \param BlockDecl A declaration with an Objective-C block type.
2824
///
2825
/// \param Block The most relevant type location for that block type.
2826
///
2827
/// \param SuppressBlockName Determines whether or not the name of the block
2828
/// declaration is included in the resulting string.
2829
static std::string
2830
formatBlockPlaceholder(const PrintingPolicy &Policy, const NamedDecl *BlockDecl,
2831
                       FunctionTypeLoc &Block, FunctionProtoTypeLoc &BlockProto,
2832
                       bool SuppressBlockName, bool SuppressBlock,
2833
58
                       Optional<ArrayRef<QualType>> ObjCSubsts) {
2834
58
  std::string Result;
2835
58
  QualType ResultType = Block.getTypePtr()->getReturnType();
2836
58
  if (ObjCSubsts)
2837
4
    ResultType =
2838
4
        ResultType.substObjCTypeArgs(BlockDecl->getASTContext(), *ObjCSubsts,
2839
4
                                     ObjCSubstitutionContext::Result);
2840
58
  if (!ResultType->isVoidType() || 
SuppressBlock27
)
2841
31
    ResultType.getAsStringInternal(Result, Policy);
2842
58
2843
58
  // Format the parameter list.
2844
58
  std::string Params;
2845
58
  if (!BlockProto || 
Block.getNumParams() == 052
) {
2846
9
    if (BlockProto && 
BlockProto.getTypePtr()->isVariadic()3
)
2847
0
      Params = "(...)";
2848
9
    else
2849
9
      Params = "(void)";
2850
49
  } else {
2851
49
    Params += "(";
2852
133
    for (unsigned I = 0, N = Block.getNumParams(); I != N; 
++I84
) {
2853
84
      if (I)
2854
35
        Params += ", ";
2855
84
      Params += FormatFunctionParameter(Policy, Block.getParam(I),
2856
84
                                        /*SuppressName=*/false,
2857
84
                                        /*SuppressBlock=*/true, ObjCSubsts);
2858
84
2859
84
      if (I == N - 1 && 
BlockProto.getTypePtr()->isVariadic()49
)
2860
0
        Params += ", ...";
2861
84
    }
2862
49
    Params += ")";
2863
49
  }
2864
58
2865
58
  if (SuppressBlock) {
2866
0
    // Format as a parameter.
2867
0
    Result = Result + " (^";
2868
0
    if (!SuppressBlockName && BlockDecl->getIdentifier())
2869
0
      Result += BlockDecl->getIdentifier()->getName();
2870
0
    Result += ")";
2871
0
    Result += Params;
2872
58
  } else {
2873
58
    // Format as a block literal argument.
2874
58
    Result = '^' + Result;
2875
58
    Result += Params;
2876
58
2877
58
    if (!SuppressBlockName && 
BlockDecl->getIdentifier()39
)
2878
39
      Result += BlockDecl->getIdentifier()->getName();
2879
58
  }
2880
58
2881
58
  return Result;
2882
58
}
2883
2884
static std::string GetDefaultValueString(const ParmVarDecl *Param,
2885
                                         const SourceManager &SM,
2886
82
                                         const LangOptions &LangOpts) {
2887
82
  const SourceRange SrcRange = Param->getDefaultArgRange();
2888
82
  CharSourceRange CharSrcRange = CharSourceRange::getTokenRange(SrcRange);
2889
82
  bool Invalid = CharSrcRange.isInvalid();
2890
82
  if (Invalid)
2891
0
    return "";
2892
82
  StringRef srcText =
2893
82
      Lexer::getSourceText(CharSrcRange, SM, LangOpts, &Invalid);
2894
82
  if (Invalid)
2895
0
    return "";
2896
82
2897
82
  if (srcText.empty() || srcText == "=") {
2898
6
    // Lexer can't determine the value.
2899
6
    // This happens if the code is incorrect (for example class is forward
2900
6
    // declared).
2901
6
    return "";
2902
6
  }
2903
76
  std::string DefValue(srcText.str());
2904
76
  // FIXME: remove this check if the Lexer::getSourceText value is fixed and
2905
76
  // this value always has (or always does not have) '=' in front of it
2906
76
  if (DefValue.at(0) != '=') {
2907
70
    // If we don't have '=' in front of value.
2908
70
    // Lexer returns built-in types values without '=' and user-defined types
2909
70
    // values with it.
2910
70
    return " = " + DefValue;
2911
70
  }
2912
6
  return " " + DefValue;
2913
6
}
2914
2915
/// Add function parameter chunks to the given code completion string.
2916
static void AddFunctionParameterChunks(Preprocessor &PP,
2917
                                       const PrintingPolicy &Policy,
2918
                                       const FunctionDecl *Function,
2919
                                       CodeCompletionBuilder &Result,
2920
                                       unsigned Start = 0,
2921
2.76k
                                       bool InOptional = false) {
2922
2.76k
  bool FirstParameter = true;
2923
2.76k
2924
5.88k
  for (unsigned P = Start, N = Function->getNumParams(); P != N; 
++P3.11k
) {
2925
3.18k
    const ParmVarDecl *Param = Function->getParamDecl(P);
2926
3.18k
2927
3.18k
    if (Param->hasDefaultArg() && 
!InOptional138
) {
2928
69
      // When we see an optional default argument, put that argument and
2929
69
      // the remaining default arguments into a new, optional string.
2930
69
      CodeCompletionBuilder Opt(Result.getAllocator(),
2931
69
                                Result.getCodeCompletionTUInfo());
2932
69
      if (!FirstParameter)
2933
42
        Opt.AddChunk(CodeCompletionString::CK_Comma);
2934
69
      AddFunctionParameterChunks(PP, Policy, Function, Opt, P, true);
2935
69
      Result.AddOptionalChunk(Opt.TakeString());
2936
69
      break;
2937
69
    }
2938
3.11k
2939
3.11k
    if (FirstParameter)
2940
1.94k
      FirstParameter = false;
2941
1.17k
    else
2942
1.17k
      Result.AddChunk(CodeCompletionString::CK_Comma);
2943
3.11k
2944
3.11k
    InOptional = false;
2945
3.11k
2946
3.11k
    // Format the placeholder string.
2947
3.11k
    std::string PlaceholderStr = FormatFunctionParameter(Policy, Param);
2948
3.11k
    if (Param->hasDefaultArg())
2949
69
      PlaceholderStr +=
2950
69
          GetDefaultValueString(Param, PP.getSourceManager(), PP.getLangOpts());
2951
3.11k
2952
3.11k
    if (Function->isVariadic() && 
P == N - 122
)
2953
17
      PlaceholderStr += ", ...";
2954
3.11k
2955
3.11k
    // Add the placeholder string.
2956
3.11k
    Result.AddPlaceholderChunk(
2957
3.11k
        Result.getAllocator().CopyString(PlaceholderStr));
2958
3.11k
  }
2959
2.76k
2960
2.76k
  if (const auto *Proto = Function->getType()->getAs<FunctionProtoType>())
2961
2.69k
    if (Proto->isVariadic()) {
2962
23
      if (Proto->getNumParams() == 0)
2963
0
        Result.AddPlaceholderChunk("...");
2964
23
2965
23
      MaybeAddSentinel(PP, Function, Result);
2966
23
    }
2967
2.76k
}
2968
2969
/// Add template parameter chunks to the given code completion string.
2970
static void AddTemplateParameterChunks(
2971
    ASTContext &Context, const PrintingPolicy &Policy,
2972
    const TemplateDecl *Template, CodeCompletionBuilder &Result,
2973
241
    unsigned MaxParameters = 0, unsigned Start = 0, bool InDefaultArg = false) {
2974
241
  bool FirstParameter = true;
2975
241
2976
241
  // Prefer to take the template parameter names from the first declaration of
2977
241
  // the template.
2978
241
  Template = cast<TemplateDecl>(Template->getCanonicalDecl());
2979
241
2980
241
  TemplateParameterList *Params = Template->getTemplateParameters();
2981
241
  TemplateParameterList::iterator PEnd = Params->end();
2982
241
  if (MaxParameters)
2983
72
    PEnd = Params->begin() + MaxParameters;
2984
486
  for (TemplateParameterList::iterator P = Params->begin() + Start; P != PEnd;
2985
252
       
++P245
) {
2986
252
    bool HasDefaultArg = false;
2987
252
    std::string PlaceholderStr;
2988
252
    if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
2989
252
      if (TTP->wasDeclaredWithTypename())
2990
40
        PlaceholderStr = "typename";
2991
212
      else
2992
212
        PlaceholderStr = "class";
2993
252
2994
252
      if (TTP->getIdentifier()) {
2995
251
        PlaceholderStr += ' ';
2996
251
        PlaceholderStr += TTP->getIdentifier()->getName();
2997
251
      }
2998
252
2999
252
      HasDefaultArg = TTP->hasDefaultArgument();
3000
252
    } else 
if (NonTypeTemplateParmDecl *0
NTTP0
=
3001
0
                   dyn_cast<NonTypeTemplateParmDecl>(*P)) {
3002
0
      if (NTTP->getIdentifier())
3003
0
        PlaceholderStr = NTTP->getIdentifier()->getName();
3004
0
      NTTP->getType().getAsStringInternal(PlaceholderStr, Policy);
3005
0
      HasDefaultArg = NTTP->hasDefaultArgument();
3006
0
    } else {
3007
0
      assert(isa<TemplateTemplateParmDecl>(*P));
3008
0
      TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
3009
0
3010
0
      // Since putting the template argument list into the placeholder would
3011
0
      // be very, very long, we just use an abbreviation.
3012
0
      PlaceholderStr = "template<...> class";
3013
0
      if (TTP->getIdentifier()) {
3014
0
        PlaceholderStr += ' ';
3015
0
        PlaceholderStr += TTP->getIdentifier()->getName();
3016
0
      }
3017
0
3018
0
      HasDefaultArg = TTP->hasDefaultArgument();
3019
0
    }
3020
252
3021
252
    if (HasDefaultArg && 
!InDefaultArg14
) {
3022
7
      // When we see an optional default argument, put that argument and
3023
7
      // the remaining default arguments into a new, optional string.
3024
7
      CodeCompletionBuilder Opt(Result.getAllocator(),
3025
7
                                Result.getCodeCompletionTUInfo());
3026
7
      if (!FirstParameter)
3027
7
        Opt.AddChunk(CodeCompletionString::CK_Comma);
3028
7
      AddTemplateParameterChunks(Context, Policy, Template, Opt, MaxParameters,
3029
7
                                 P - Params->begin(), true);
3030
7
      Result.AddOptionalChunk(Opt.TakeString());
3031
7
      break;
3032
7
    }
3033
245
3034
245
    InDefaultArg = false;
3035
245
3036
245
    if (FirstParameter)
3037
241
      FirstParameter = false;
3038
4
    else
3039
4
      Result.AddChunk(CodeCompletionString::CK_Comma);
3040
245
3041
245
    // Add the placeholder string.
3042
245
    Result.AddPlaceholderChunk(
3043
245
        Result.getAllocator().CopyString(PlaceholderStr));
3044
245
  }
3045
241
}
3046
3047
/// Add a qualifier to the given code-completion string, if the
3048
/// provided nested-name-specifier is non-NULL.
3049
static void AddQualifierToCompletionString(CodeCompletionBuilder &Result,
3050
                                           NestedNameSpecifier *Qualifier,
3051
                                           bool QualifierIsInformative,
3052
                                           ASTContext &Context,
3053
2.87k
                                           const PrintingPolicy &Policy) {
3054
2.87k
  if (!Qualifier)
3055
2.68k
    return;
3056
191
3057
191
  std::string PrintedNNS;
3058
191
  {
3059
191
    llvm::raw_string_ostream OS(PrintedNNS);
3060
191
    Qualifier->print(OS, Policy);
3061
191
  }
3062
191
  if (QualifierIsInformative)
3063
83
    Result.AddInformativeChunk(Result.getAllocator().CopyString(PrintedNNS));
3064
108
  else
3065
108
    Result.AddTextChunk(Result.getAllocator().CopyString(PrintedNNS));
3066
191
}
3067
3068
static void
3069
AddFunctionTypeQualsToCompletionString(CodeCompletionBuilder &Result,
3070
2.67k
                                       const FunctionDecl *Function) {
3071
2.67k
  const auto *Proto = Function->getType()->getAs<FunctionProtoType>();
3072
2.67k
  if (!Proto || 
!Proto->getMethodQuals()2.59k
)
3073
2.59k
    return;
3074
74
3075
74
  // FIXME: Add ref-qualifier!
3076
74
3077
74
  // Handle single qualifiers without copying
3078
74
  if (Proto->getMethodQuals().hasOnlyConst()) {
3079
48
    Result.AddInformativeChunk(" const");
3080
48
    return;
3081
48
  }
3082
26
3083
26
  if (Proto->getMethodQuals().hasOnlyVolatile()) {
3084
6
    Result.AddInformativeChunk(" volatile");
3085
6
    return;
3086
6
  }
3087
20
3088
20
  if (Proto->getMethodQuals().hasOnlyRestrict()) {
3089
0
    Result.AddInformativeChunk(" restrict");
3090
0
    return;
3091
0
  }
3092
20
3093
20
  // Handle multiple qualifiers.
3094
20
  std::string QualsStr;
3095
20
  if (Proto->isConst())
3096
20
    QualsStr += " const";
3097
20
  if (Proto->isVolatile())
3098
20
    QualsStr += " volatile";
3099
20
  if (Proto->isRestrict())
3100
0
    QualsStr += " restrict";
3101
20
  Result.AddInformativeChunk(Result.getAllocator().CopyString(QualsStr));
3102
20
}
3103
3104
/// Add the name of the given declaration
3105
static void AddTypedNameChunk(ASTContext &Context, const PrintingPolicy &Policy,
3106
                              const NamedDecl *ND,
3107
2.70k
                              CodeCompletionBuilder &Result) {
3108
2.70k
  DeclarationName Name = ND->getDeclName();
3109
2.70k
  if (!Name)
3110
0
    return;
3111
2.70k
3112
2.70k
  switch (Name.getNameKind()) {
3113
2.70k
  case DeclarationName::CXXOperatorName: {
3114
274
    const char *OperatorName = nullptr;
3115
274
    switch (Name.getCXXOverloadedOperator()) {
3116
274
    case OO_None:
3117
0
    case OO_Conditional:
3118
0
    case NUM_OVERLOADED_OPERATORS:
3119
0
      OperatorName = "operator";
3120
0
      break;
3121
0
3122
0
#define OVERLOADED_OPERATOR(Name, Spelling, Token, Unary, Binary, MemberOnly)  \
3123
272
  case OO_##Name:                                                              \
3124
272
    OperatorName = "operator" Spelling;                                        \
3125
272
    break;
3126
0
#define OVERLOADED_OPERATOR_MULTI(Name, Spelling, Unary, Binary, MemberOnly)
3127
0
#include "clang/Basic/OperatorKinds.def"
3128
0
3129
0
    case OO_New:
3130
0
      OperatorName = "operator new";
3131
0
      break;
3132
0
    case OO_Delete:
3133
0
      OperatorName = "operator delete";
3134
0
      break;
3135
0
    case OO_Array_New:
3136
0
      OperatorName = "operator new[]";
3137
0
      break;
3138
0
    case OO_Array_Delete:
3139
0
      OperatorName = "operator delete[]";
3140
0
      break;
3141
1
    case OO_Call:
3142
1
      OperatorName = "operator()";
3143
1
      break;
3144
1
    case OO_Subscript:
3145
1
      OperatorName = "operator[]";
3146
1
      break;
3147
274
    }
3148
274
    Result.AddTypedTextChunk(OperatorName);
3149
274
    break;
3150
274
  }
3151
274
3152
2.13k
  case DeclarationName::Identifier:
3153
2.13k
  case DeclarationName::CXXConversionFunctionName:
3154
2.13k
  case DeclarationName::CXXDestructorName:
3155
2.13k
  case DeclarationName::CXXLiteralOperatorName:
3156
2.13k
    Result.AddTypedTextChunk(
3157
2.13k
        Result.getAllocator().CopyString(ND->getNameAsString()));
3158
2.13k
    break;
3159
2.13k
3160
2.13k
  case DeclarationName::CXXDeductionGuideName:
3161
0
  case DeclarationName::CXXUsingDirective:
3162
0
  case DeclarationName::ObjCZeroArgSelector:
3163
0
  case DeclarationName::ObjCOneArgSelector:
3164
0
  case DeclarationName::ObjCMultiArgSelector:
3165
0
    break;
3166
0
3167
305
  case DeclarationName::CXXConstructorName: {
3168
305
    CXXRecordDecl *Record = nullptr;
3169
305
    QualType Ty = Name.getCXXNameType();
3170
305
    if (const auto *RecordTy = Ty->getAs<RecordType>())
3171
279
      Record = cast<CXXRecordDecl>(RecordTy->getDecl());
3172
26
    else if (const auto *InjectedTy = Ty->getAs<InjectedClassNameType>())
3173
26
      Record = InjectedTy->getDecl();
3174
0
    else {
3175
0
      Result.AddTypedTextChunk(
3176
0
          Result.getAllocator().CopyString(ND->getNameAsString()));
3177
0
      break;
3178
0
    }
3179
305
3180
305
    Result.AddTypedTextChunk(
3181
305
        Result.getAllocator().CopyString(Record->getNameAsString()));
3182
305
    if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) {
3183
26
      Result.AddChunk(CodeCompletionString::CK_LeftAngle);
3184
26
      AddTemplateParameterChunks(Context, Policy, Template, Result);
3185
26
      Result.AddChunk(CodeCompletionString::CK_RightAngle);
3186
26
    }
3187
305
    break;
3188
305
  }
3189
2.70k
  }
3190
2.70k
}
3191
3192
CodeCompletionString *CodeCompletionResult::CreateCodeCompletionString(
3193
    Sema &S, const CodeCompletionContext &CCContext,
3194
    CodeCompletionAllocator &Allocator, CodeCompletionTUInfo &CCTUInfo,
3195
194k
    bool IncludeBriefComments) {
3196
194k
  return CreateCodeCompletionString(S.Context, S.PP, CCContext, Allocator,
3197
194k
                                    CCTUInfo, IncludeBriefComments);
3198
194k
}
3199
3200
CodeCompletionString *CodeCompletionResult::CreateCodeCompletionStringForMacro(
3201
    Preprocessor &PP, CodeCompletionAllocator &Allocator,
3202
124k
    CodeCompletionTUInfo &CCTUInfo) {
3203
124k
  assert(Kind == RK_Macro);
3204
124k
  CodeCompletionBuilder Result(Allocator, CCTUInfo, Priority, Availability);
3205
124k
  const MacroInfo *MI = PP.getMacroInfo(Macro);
3206
124k
  Result.AddTypedTextChunk(Result.getAllocator().CopyString(Macro->getName()));
3207
124k
3208
124k
  if (!MI || 
!MI->isFunctionLike()124k
)
3209
123k
    return Result.TakeString();
3210
180
3211
180
  // Format a function-like macro with placeholders for the arguments.
3212
180
  Result.AddChunk(CodeCompletionString::CK_LeftParen);
3213
180
  MacroInfo::param_iterator A = MI->param_begin(), AEnd = MI->param_end();
3214
180
3215
180
  // C99 variadic macros add __VA_ARGS__ at the end. Skip it.
3216
180
  if (MI->isC99Varargs()) {
3217
20
    --AEnd;
3218
20
3219
20
    if (A == AEnd) {
3220
8
      Result.AddPlaceholderChunk("...");
3221
8
    }
3222
20
  }
3223
180
3224
367
  for (MacroInfo::param_iterator A = MI->param_begin(); A != AEnd; 
++A187
) {
3225
211
    if (A != MI->param_begin())
3226
39
      Result.AddChunk(CodeCompletionString::CK_Comma);
3227
211
3228
211
    if (MI->isVariadic() && 
(A + 1) == AEnd48
) {
3229
24
      SmallString<32> Arg = (*A)->getName();
3230
24
      if (MI->isC99Varargs())
3231
12
        Arg += ", ...";
3232
12
      else
3233
12
        Arg += "...";
3234
24
      Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
3235
24
      break;
3236
24
    }
3237
187
3238
187
    // Non-variadic macros are simple.
3239
187
    Result.AddPlaceholderChunk(
3240
187
        Result.getAllocator().CopyString((*A)->getName()));
3241
187
  }
3242
180
  Result.AddChunk(CodeCompletionString::CK_RightParen);
3243
180
  return Result.TakeString();
3244
180
}
3245
3246
/// If possible, create a new code completion string for the given
3247
/// result.
3248
///
3249
/// \returns Either a new, heap-allocated code completion string describing
3250
/// how to use this result, or NULL to indicate that the string or name of the
3251
/// result is all that is needed.
3252
CodeCompletionString *CodeCompletionResult::CreateCodeCompletionString(
3253
    ASTContext &Ctx, Preprocessor &PP, const CodeCompletionContext &CCContext,
3254
    CodeCompletionAllocator &Allocator, CodeCompletionTUInfo &CCTUInfo,
3255
194k
    bool IncludeBriefComments) {
3256
194k
  if (Kind == RK_Macro)
3257
124k
    return CreateCodeCompletionStringForMacro(PP, Allocator, CCTUInfo);
3258
70.7k
3259
70.7k
  CodeCompletionBuilder Result(Allocator, CCTUInfo, Priority, Availability);
3260
70.7k
3261
70.7k
  PrintingPolicy Policy = getCompletionPrintingPolicy(Ctx, PP);
3262
70.7k
  if (Kind == RK_Pattern) {
3263
58.3k
    Pattern->Priority = Priority;
3264
58.3k
    Pattern->Availability = Availability;
3265
58.3k
3266
58.3k
    if (Declaration) {
3267
200
      Result.addParentContext(Declaration->getDeclContext());
3268
200
      Pattern->ParentName = Result.getParentName();
3269
200
      if (const RawComment *RC =
3270
4
              getPatternCompletionComment(Ctx, Declaration)) {
3271
4
        Result.addBriefComment(RC->getBriefText(Ctx));
3272
4
        Pattern->BriefComment = Result.getBriefComment();
3273
4
      }
3274
200
    }
3275
58.3k
3276
58.3k
    return Pattern;
3277
58.3k
  }
3278
12.3k
3279
12.3k
  if (Kind == RK_Keyword) {
3280
7.20k
    Result.AddTypedTextChunk(Keyword);
3281
7.20k
    return Result.TakeString();
3282
7.20k
  }
3283
5.17k
  assert(Kind == RK_Declaration && "Missed a result kind?");
3284
5.17k
  return createCodeCompletionStringForDecl(
3285
5.17k
      PP, Ctx, Result, IncludeBriefComments, CCContext, Policy);
3286
5.17k
}
3287
3288
static void printOverrideString(const CodeCompletionString &CCS,
3289
                                std::string &BeforeName,
3290
6
                                std::string &NameAndSignature) {
3291
6
  bool SeenTypedChunk = false;
3292
32
  for (auto &Chunk : CCS) {
3293
32
    if (Chunk.Kind == CodeCompletionString::CK_Optional) {
3294
2
      assert(SeenTypedChunk && "optional parameter before name");
3295
2
      // Note that we put all chunks inside into NameAndSignature.
3296
2
      printOverrideString(*Chunk.Optional, NameAndSignature, NameAndSignature);
3297
2
      continue;
3298
2
    }
3299
30
    SeenTypedChunk |= Chunk.Kind == CodeCompletionString::CK_TypedText;
3300
30
    if (SeenTypedChunk)
3301
22
      NameAndSignature += Chunk.Text;
3302
8
    else
3303
8
      BeforeName += Chunk.Text;
3304
30
  }
3305
6
}
3306
3307
CodeCompletionString *
3308
CodeCompletionResult::createCodeCompletionStringForOverride(
3309
    Preprocessor &PP, ASTContext &Ctx, CodeCompletionBuilder &Result,
3310
    bool IncludeBriefComments, const CodeCompletionContext &CCContext,
3311
4
    PrintingPolicy &Policy) {
3312
4
  auto *CCS = createCodeCompletionStringForDecl(PP, Ctx, Result,
3313
4
                                                /*IncludeBriefComments=*/false,
3314
4
                                                CCContext, Policy);
3315
4
  std::string BeforeName;
3316
4
  std::string NameAndSignature;
3317
4
  // For overrides all chunks go into the result, none are informative.
3318
4
  printOverrideString(*CCS, BeforeName, NameAndSignature);
3319
4
  NameAndSignature += " override";
3320
4
3321
4
  Result.AddTextChunk(Result.getAllocator().CopyString(BeforeName));
3322
4
  Result.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3323
4
  Result.AddTypedTextChunk(Result.getAllocator().CopyString(NameAndSignature));
3324
4
  return Result.TakeString();
3325
4
}
3326
3327
CodeCompletionString *CodeCompletionResult::createCodeCompletionStringForDecl(
3328
    Preprocessor &PP, ASTContext &Ctx, CodeCompletionBuilder &Result,
3329
    bool IncludeBriefComments, const CodeCompletionContext &CCContext,
3330
5.17k
    PrintingPolicy &Policy) {
3331
5.17k
  const NamedDecl *ND = Declaration;
3332
5.17k
  Result.addParentContext(ND->getDeclContext());
3333
5.17k
3334
5.17k
  if (IncludeBriefComments) {
3335
283
    // Add documentation comment, if it exists.
3336
283
    if (const RawComment *RC = getCompletionComment(Ctx, Declaration)) {
3337
114
      Result.addBriefComment(RC->getBriefText(Ctx));
3338
114
    }
3339
283
  }
3340
5.17k
3341
5.17k
  if (StartsNestedNameSpecifier) {
3342
173
    Result.AddTypedTextChunk(
3343
173
        Result.getAllocator().CopyString(ND->getNameAsString()));
3344
173
    Result.AddTextChunk("::");
3345
173
    return Result.TakeString();
3346
173
  }
3347
5.00k
3348
5.00k
  for (const auto *I : ND->specific_attrs<AnnotateAttr>())
3349
6
    Result.AddAnnotation(Result.getAllocator().CopyString(I->getAnnotation()));
3350
5.00k
3351
5.00k
  AddResultTypeChunk(Ctx, Policy, ND, CCContext.getBaseType(), Result);
3352
5.00k
3353
5.00k
  if (const auto *Function = dyn_cast<FunctionDecl>(ND)) {
3354
2.02k
    AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
3355
2.02k
                                   Ctx, Policy);
3356
2.02k
    AddTypedNameChunk(Ctx, Policy, ND, Result);
3357
2.02k
    Result.AddChunk(CodeCompletionString::CK_LeftParen);
3358
2.02k
    AddFunctionParameterChunks(PP, Policy, Function, Result);
3359
2.02k
    Result.AddChunk(CodeCompletionString::CK_RightParen);
3360
2.02k
    AddFunctionTypeQualsToCompletionString(Result, Function);
3361
2.02k
    return Result.TakeString();
3362
2.02k
  }
3363
2.97k
3364
2.97k
  if (const FunctionTemplateDecl *FunTmpl =
3365
643
          dyn_cast<FunctionTemplateDecl>(ND)) {
3366
643
    AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
3367
643
                                   Ctx, Policy);
3368
643
    FunctionDecl *Function = FunTmpl->getTemplatedDecl();
3369
643
    AddTypedNameChunk(Ctx, Policy, Function, Result);
3370
643
3371
643
    // Figure out which template parameters are deduced (or have default
3372
643
    // arguments).
3373
643
    llvm::SmallBitVector Deduced;
3374
643
    Sema::MarkDeducedTemplateParameters(Ctx, FunTmpl, Deduced);
3375
643
    unsigned LastDeducibleArgument;
3376
1.28k
    for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0;
3377
712
         
--LastDeducibleArgument640
) {
3378
712
      if (!Deduced[LastDeducibleArgument - 1]) {
3379
72
        // C++0x: Figure out if the template argument has a default. If so,
3380
72
        // the user doesn't need to type this argument.
3381
72
        // FIXME: We need to abstract template parameters better!
3382
72
        bool HasDefaultArg = false;
3383
72
        NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam(
3384
72
            LastDeducibleArgument - 1);
3385
72
        if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
3386
72
          HasDefaultArg = TTP->hasDefaultArgument();
3387
0
        else if (NonTypeTemplateParmDecl *NTTP =
3388
0
                     dyn_cast<NonTypeTemplateParmDecl>(Param))
3389
0
          HasDefaultArg = NTTP->hasDefaultArgument();
3390
0
        else {
3391
0
          assert(isa<TemplateTemplateParmDecl>(Param));
3392
0
          HasDefaultArg =
3393
0
              cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument();
3394
0
        }
3395
72
3396
72
        if (!HasDefaultArg)
3397
72
          break;
3398
72
      }
3399
712
    }
3400
643
3401
643
    if (LastDeducibleArgument) {
3402
72
      // Some of the function template arguments cannot be deduced from a
3403
72
      // function call, so we introduce an explicit template argument list
3404
72
      // containing all of the arguments up to the first deducible argument.
3405
72
      Result.AddChunk(CodeCompletionString::CK_LeftAngle);
3406
72
      AddTemplateParameterChunks(Ctx, Policy, FunTmpl, Result,
3407
72
                                 LastDeducibleArgument);
3408
72
      Result.AddChunk(CodeCompletionString::CK_RightAngle);
3409
72
    }
3410
643
3411
643
    // Add the function parameters
3412
643
    Result.AddChunk(CodeCompletionString::CK_LeftParen);
3413
643
    AddFunctionParameterChunks(PP, Policy, Function, Result);
3414
643
    Result.AddChunk(CodeCompletionString::CK_RightParen);
3415
643
    AddFunctionTypeQualsToCompletionString(Result, Function);
3416
643
    return Result.TakeString();
3417
643
  }
3418
2.33k
3419
2.33k
  if (const auto *Template = dyn_cast<TemplateDecl>(ND)) {
3420
136
    AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
3421
136
                                   Ctx, Policy);
3422
136
    Result.AddTypedTextChunk(
3423
136
        Result.getAllocator().CopyString(Template->getNameAsString()));
3424
136
    Result.AddChunk(CodeCompletionString::CK_LeftAngle);
3425
136
    AddTemplateParameterChunks(Ctx, Policy, Template, Result);
3426
136
    Result.AddChunk(CodeCompletionString::CK_RightAngle);
3427
136
    return Result.TakeString();
3428
136
  }
3429
2.19k
  if (const auto *Method = dyn_cast<ObjCMethodDecl>(ND)) {
3430
333
    Selector Sel = Method->getSelector();
3431
333
    if (Sel.isUnarySelector()) {
3432
157
      Result.AddTypedTextChunk(
3433
157
          Result.getAllocator().CopyString(Sel.getNameForSlot(0)));
3434
157
      return Result.TakeString();
3435
157
    }
3436
176
3437
176
    std::string SelName = Sel.getNameForSlot(0).str();
3438
176
    SelName += ':';
3439
176
    if (StartParameter == 0)
3440
139
      Result.AddTypedTextChunk(Result.getAllocator().CopyString(SelName));
3441
37
    else {
3442
37
      Result.AddInformativeChunk(Result.getAllocator().CopyString(SelName));
3443
37
3444
37
      // If there is only one parameter, and we're past it, add an empty
3445
37
      // typed-text chunk since there is nothing to type.
3446
37
      if (Method->param_size() == 1)
3447
1
        Result.AddTypedTextChunk("");
3448
37
    }
3449
176
    unsigned Idx = 0;
3450
176
    for (ObjCMethodDecl::param_const_iterator P = Method->param_begin(),
3451
176
                                              PEnd = Method->param_end();
3452
505
         P != PEnd; 
(void)++P, ++Idx329
) {
3453
329
      if (Idx > 0) {
3454
153
        std::string Keyword;
3455
153
        if (Idx > StartParameter)
3456
105
          Result.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3457
153
        if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(Idx))
3458
153
          Keyword += II->getName();
3459
153
        Keyword += ":";
3460
153
        if (Idx < StartParameter || 
AllParametersAreInformative140
)
3461
13
          Result.AddInformativeChunk(Result.getAllocator().CopyString(Keyword));
3462
140
        else
3463
140
          Result.AddTypedTextChunk(Result.getAllocator().CopyString(Keyword));
3464
153
      }
3465
329
3466
329
      // If we're before the starting parameter, skip the placeholder.
3467
329
      if (Idx < StartParameter)
3468
50
        continue;
3469
279
3470
279
      std::string Arg;
3471
279
      QualType ParamType = (*P)->getType();
3472
279
      Optional<ArrayRef<QualType>> ObjCSubsts;
3473
279
      if (!CCContext.getBaseType().isNull())
3474
221
        ObjCSubsts = CCContext.getBaseType()->getObjCSubstitutions(Method);
3475
279
3476
279
      if (ParamType->isBlockPointerType() && 
!DeclaringEntity16
)
3477
16
        Arg = FormatFunctionParameter(Policy, *P, true,
3478
16
                                      /*SuppressBlock=*/false, ObjCSubsts);
3479
263
      else {
3480
263
        if (ObjCSubsts)
3481
4
          ParamType = ParamType.substObjCTypeArgs(
3482
4
              Ctx, *ObjCSubsts, ObjCSubstitutionContext::Parameter);
3483
263
        Arg = "(" + formatObjCParamQualifiers((*P)->getObjCDeclQualifier(),
3484
263
                                              ParamType);
3485
263
        Arg += ParamType.getAsString(Policy) + ")";
3486
263
        if (IdentifierInfo *II = (*P)->getIdentifier())
3487
263
          if (DeclaringEntity || 
AllParametersAreInformative246
)
3488
24
            Arg += II->getName();
3489
263
      }
3490
279
3491
279
      if (Method->isVariadic() && 
(P + 1) == PEnd4
)
3492
4
        Arg += ", ...";
3493
279
3494
279
      if (DeclaringEntity)
3495
17
        Result.AddTextChunk(Result.getAllocator().CopyString(Arg));
3496
262
      else if (AllParametersAreInformative)
3497
7
        Result.AddInformativeChunk(Result.getAllocator().CopyString(Arg));
3498
255
      else
3499
255
        Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
3500
279
    }
3501
176
3502
176
    if (Method->isVariadic()) {
3503
4
      if (Method->param_size() == 0) {
3504
0
        if (DeclaringEntity)
3505
0
          Result.AddTextChunk(", ...");
3506
0
        else if (AllParametersAreInformative)
3507
0
          Result.AddInformativeChunk(", ...");
3508
0
        else
3509
0
          Result.AddPlaceholderChunk(", ...");
3510
0
      }
3511
4
3512
4
      MaybeAddSentinel(PP, Method, Result);
3513
4
    }
3514
176
3515
176
    return Result.TakeString();
3516
176
  }
3517
1.86k
3518
1.86k
  if (Qualifier)
3519
68
    AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
3520
68
                                   Ctx, Policy);
3521
1.86k
3522
1.86k
  Result.AddTypedTextChunk(
3523
1.86k
      Result.getAllocator().CopyString(ND->getNameAsString()));
3524
1.86k
  return Result.TakeString();
3525
1.86k
}
3526
3527
const RawComment *clang::getCompletionComment(const ASTContext &Ctx,
3528
283
                                              const NamedDecl *ND) {
3529
283
  if (!ND)
3530
0
    return nullptr;
3531
283
  if (auto *RC = Ctx.getRawCommentForAnyRedecl(ND))
3532
65
    return RC;
3533
218
3534
218
  // Try to find comment from a property for ObjC methods.
3535
218
  const auto *M = dyn_cast<ObjCMethodDecl>(ND);
3536
218
  if (!M)
3537
159
    return nullptr;
3538
59
  const ObjCPropertyDecl *PDecl = M->findPropertyDecl();
3539
59
  if (!PDecl)
3540
9
    return nullptr;
3541
50
3542
50
  return Ctx.getRawCommentForAnyRedecl(PDecl);
3543
50
}
3544
3545
const RawComment *clang::getPatternCompletionComment(const ASTContext &Ctx,
3546
200
                                                     const NamedDecl *ND) {
3547
200
  const auto *M = dyn_cast_or_null<ObjCMethodDecl>(ND);
3548
200
  if (!M || 
!M->isPropertyAccessor()111
)
3549
169
    return nullptr;
3550
31
3551
31
  // Provide code completion comment for self.GetterName where
3552
31
  // GetterName is the getter method for a property with name
3553
31
  // different from the property name (declared via a property
3554
31
  // getter attribute.
3555
31
  const ObjCPropertyDecl *PDecl = M->findPropertyDecl();
3556
31
  if (!PDecl)
3557
0
    return nullptr;
3558
31
  if (PDecl->getGetterName() == M->getSelector() &&
3559
31
      
PDecl->getIdentifier() != M->getIdentifier()18
) {
3560
18
    if (auto *RC = Ctx.getRawCommentForAnyRedecl(M))
3561
1
      return RC;
3562
17
    if (auto *RC = Ctx.getRawCommentForAnyRedecl(PDecl))
3563
3
      return RC;
3564
27
  }
3565
27
  return nullptr;
3566
27
}
3567
3568
const RawComment *clang::getParameterComment(
3569
    const ASTContext &Ctx,
3570
0
    const CodeCompleteConsumer::OverloadCandidate &Result, unsigned ArgIndex) {
3571
0
  auto FDecl = Result.getFunction();
3572
0
  if (!FDecl)
3573
0
    return nullptr;
3574
0
  if (ArgIndex < FDecl->getNumParams())
3575
0
    return Ctx.getRawCommentForAnyRedecl(FDecl->getParamDecl(ArgIndex));
3576
0
  return nullptr;
3577
0
}
3578
3579
/// Add function overload parameter chunks to the given code completion
3580
/// string.
3581
static void AddOverloadParameterChunks(ASTContext &Context,
3582
                                       const PrintingPolicy &Policy,
3583
                                       const FunctionDecl *Function,
3584
                                       const FunctionProtoType *Prototype,
3585
                                       CodeCompletionBuilder &Result,
3586
                                       unsigned CurrentArg, unsigned Start = 0,
3587
225
                                       bool InOptional = false) {
3588
225
  bool FirstParameter = true;
3589
225
  unsigned NumParams =
3590
225
      Function ? 
Function->getNumParams()220
:
Prototype->getNumParams()5
;
3591
225
3592
581
  for (unsigned P = Start; P != NumParams; 
++P356
) {
3593
369
    if (Function && 
Function->getParamDecl(P)->hasDefaultArg()363
&&
!InOptional26
) {
3594
13
      // When we see an optional default argument, put that argument and
3595
13
      // the remaining default arguments into a new, optional string.
3596
13
      CodeCompletionBuilder Opt(Result.getAllocator(),
3597
13
                                Result.getCodeCompletionTUInfo());
3598
13
      if (!FirstParameter)
3599
10
        Opt.AddChunk(CodeCompletionString::CK_Comma);
3600
13
      // Optional sections are nested.
3601
13
      AddOverloadParameterChunks(Context, Policy, Function, Prototype, Opt,
3602
13
                                 CurrentArg, P, /*InOptional=*/true);
3603
13
      Result.AddOptionalChunk(Opt.TakeString());
3604
13
      return;
3605
13
    }
3606
356
3607
356
    if (FirstParameter)
3608
207
      FirstParameter = false;
3609
149
    else
3610
149
      Result.AddChunk(CodeCompletionString::CK_Comma);
3611
356
3612
356
    InOptional = false;
3613
356
3614
356
    // Format the placeholder string.
3615
356
    std::string Placeholder;
3616
356
    if (Function) {
3617
350
      const ParmVarDecl *Param = Function->getParamDecl(P);
3618
350
      Placeholder = FormatFunctionParameter(Policy, Param);
3619
350
      if (Param->hasDefaultArg())
3620
13
        Placeholder += GetDefaultValueString(Param, Context.getSourceManager(),
3621
13
                                             Context.getLangOpts());
3622
350
    } else {
3623
6
      Placeholder = Prototype->getParamType(P).getAsString(Policy);
3624
6
    }
3625
356
3626
356
    if (P == CurrentArg)
3627
192
      Result.AddCurrentParameterChunk(
3628
192
          Result.getAllocator().CopyString(Placeholder));
3629
164
    else
3630
164
      Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Placeholder));
3631
356
  }
3632
225
3633
225
  
if (212
Prototype212
&&
Prototype->isVariadic()211
) {
3634
7
    CodeCompletionBuilder Opt(Result.getAllocator(),
3635
7
                              Result.getCodeCompletionTUInfo());
3636
7
    if (!FirstParameter)
3637
7
      Opt.AddChunk(CodeCompletionString::CK_Comma);
3638
7
3639
7
    if (CurrentArg < NumParams)
3640
2
      Opt.AddPlaceholderChunk("...");
3641
5
    else
3642
5
      Opt.AddCurrentParameterChunk("...");
3643
7
3644
7
    Result.AddOptionalChunk(Opt.TakeString());
3645
7
  }
3646
212
}
3647
3648
CodeCompletionString *
3649
CodeCompleteConsumer::OverloadCandidate::CreateSignatureString(
3650
    unsigned CurrentArg, Sema &S, CodeCompletionAllocator &Allocator,
3651
212
    CodeCompletionTUInfo &CCTUInfo, bool IncludeBriefComments) const {
3652
212
  PrintingPolicy Policy = getCompletionPrintingPolicy(S);
3653
212
3654
212
  // FIXME: Set priority, availability appropriately.
3655
212
  CodeCompletionBuilder Result(Allocator, CCTUInfo, 1,
3656
212
                               CXAvailability_Available);
3657
212
  FunctionDecl *FDecl = getFunction();
3658
212
  const FunctionProtoType *Proto =
3659
212
      dyn_cast<FunctionProtoType>(getFunctionType());
3660
212
  if (!FDecl && 
!Proto5
) {
3661
0
    // Function without a prototype. Just give the return type and a
3662
0
    // highlighted ellipsis.
3663
0
    const FunctionType *FT = getFunctionType();
3664
0
    Result.AddResultTypeChunk(Result.getAllocator().CopyString(
3665
0
        FT->getReturnType().getAsString(Policy)));
3666
0
    Result.AddChunk(CodeCompletionString::CK_LeftParen);
3667
0
    Result.AddChunk(CodeCompletionString::CK_CurrentParameter, "...");
3668
0
    Result.AddChunk(CodeCompletionString::CK_RightParen);
3669
0
    return Result.TakeString();
3670
0
  }
3671
212
3672
212
  if (FDecl) {
3673
207
    if (IncludeBriefComments) {
3674
0
      if (auto RC = getParameterComment(S.getASTContext(), *this, CurrentArg))
3675
0
        Result.addBriefComment(RC->getBriefText(S.getASTContext()));
3676
0
    }
3677
207
    AddResultTypeChunk(S.Context, Policy, FDecl, QualType(), Result);
3678
207
    Result.AddTextChunk(
3679
207
        Result.getAllocator().CopyString(FDecl->getNameAsString()));
3680
207
  } else {
3681
5
    Result.AddResultTypeChunk(Result.getAllocator().CopyString(
3682
5
        Proto->getReturnType().getAsString(Policy)));
3683
5
  }
3684
212
3685
212
  Result.AddChunk(CodeCompletionString::CK_LeftParen);
3686
212
  AddOverloadParameterChunks(S.getASTContext(), Policy, FDecl, Proto, Result,
3687
212
                             CurrentArg);
3688
212
  Result.AddChunk(CodeCompletionString::CK_RightParen);
3689
212
3690
212
  return Result.TakeString();
3691
212
}
3692
3693
unsigned clang::getMacroUsagePriority(StringRef MacroName,
3694
                                      const LangOptions &LangOpts,
3695
138k
                                      bool PreferredTypeIsPointer) {
3696
138k
  unsigned Priority = CCP_Macro;
3697
138k
3698
138k
  // Treat the "nil", "Nil" and "NULL" macros as null pointer constants.
3699
138k
  if (MacroName.equals("nil") || 
MacroName.equals("NULL")138k
||
3700
138k
      
MacroName.equals("Nil")138k
) {
3701
39
    Priority = CCP_Constant;
3702
39
    if (PreferredTypeIsPointer)
3703
7
      Priority = Priority / CCF_SimilarTypeMatch;
3704
39
  }
3705
138k
  // Treat "YES", "NO", "true", and "false" as constants.
3706
138k
  else if (MacroName.equals("YES") || 
MacroName.equals("NO")138k
||
3707
138k
           
MacroName.equals("true")138k
||
MacroName.equals("false")138k
)
3708
16
    Priority = CCP_Constant;
3709
138k
  // Treat "bool" as a type.
3710
138k
  else if (MacroName.equals("bool"))
3711
8
    Priority = CCP_Type + (LangOpts.ObjC ? CCD_bool_in_ObjC : 
00
);
3712
138k
3713
138k
  return Priority;
3714
138k
}
3715
3716
52.9k
CXCursorKind clang::getCursorKindForDecl(const Decl *D) {
3717
52.9k
  if (!D)
3718
0
    return CXCursor_UnexposedDecl;
3719
52.9k
3720
52.9k
  switch (D->getKind()) {
3721
52.9k
  case Decl::Enum:
3722
295
    return CXCursor_EnumDecl;
3723
52.9k
  case Decl::EnumConstant:
3724
648
    return CXCursor_EnumConstantDecl;
3725
52.9k
  case Decl::Field:
3726
1.36k
    return CXCursor_FieldDecl;
3727
52.9k
  case Decl::Function:
3728
8.16k
    return CXCursor_FunctionDecl;
3729
52.9k
  case Decl::ObjCCategory:
3730
158
    return CXCursor_ObjCCategoryDecl;
3731
52.9k
  case Decl::ObjCCategoryImpl:
3732
10
    return CXCursor_ObjCCategoryImplDecl;
3733
52.9k
  case Decl::ObjCImplementation:
3734
144
    return CXCursor_ObjCImplementationDecl;
3735
52.9k
3736
52.9k
  case Decl::ObjCInterface:
3737
1.36k
    return CXCursor_ObjCInterfaceDecl;
3738
52.9k
  case Decl::ObjCIvar:
3739
283
    return CXCursor_ObjCIvarDecl;
3740
52.9k
  case Decl::ObjCMethod:
3741
1.54k
    return cast<ObjCMethodDecl>(D)->isInstanceMethod()
3742
1.54k
               ? 
CXCursor_ObjCInstanceMethodDecl1.35k
3743
1.54k
               : 
CXCursor_ObjCClassMethodDecl189
;
3744
52.9k
  case Decl::CXXMethod:
3745
16.4k
    return CXCursor_CXXMethod;
3746
52.9k
  case Decl::CXXConstructor:
3747
1.31k
    return CXCursor_Constructor;
3748
52.9k
  case Decl::CXXDestructor:
3749
327
    return CXCursor_Destructor;
3750
52.9k
  case Decl::CXXConversion:
3751
9
    return CXCursor_ConversionFunction;
3752
52.9k
  case Decl::ObjCProperty:
3753
274
    return CXCursor_ObjCPropertyDecl;
3754
52.9k
  case Decl::ObjCProtocol:
3755
216
    return CXCursor_ObjCProtocolDecl;
3756
52.9k
  case Decl::ParmVar:
3757
3.13k
    return CXCursor_ParmDecl;
3758
52.9k
  case Decl::Typedef:
3759
7.11k
    return CXCursor_TypedefDecl;
3760
52.9k
  case Decl::TypeAlias:
3761
57
    return CXCursor_TypeAliasDecl;
3762
52.9k
  case Decl::TypeAliasTemplate:
3763
16
    return CXCursor_TypeAliasTemplateDecl;
3764
52.9k
  case Decl::Var:
3765
1.98k
    return CXCursor_VarDecl;
3766
52.9k
  case Decl::Namespace:
3767
568
    return CXCursor_Namespace;
3768
52.9k
  case Decl::NamespaceAlias:
3769
27
    return CXCursor_NamespaceAlias;
3770
52.9k
  case Decl::TemplateTypeParm:
3771
536
    return CXCursor_TemplateTypeParameter;
3772
52.9k
  case Decl::NonTypeTemplateParm:
3773
45
    return CXCursor_NonTypeTemplateParameter;
3774
52.9k
  case Decl::TemplateTemplateParm:
3775
26
    return CXCursor_TemplateTemplateParameter;
3776
52.9k
  case Decl::FunctionTemplate:
3777
1.42k
    return CXCursor_FunctionTemplate;
3778
52.9k
  case Decl::ClassTemplate:
3779
758
    return CXCursor_ClassTemplate;
3780
52.9k
  case Decl::AccessSpec:
3781
68
    return CXCursor_CXXAccessSpecifier;
3782
52.9k
  case Decl::ClassTemplatePartialSpecialization:
3783
22
    return CXCursor_ClassTemplatePartialSpecialization;
3784
52.9k
  case Decl::UsingDirective:
3785
7
    return CXCursor_UsingDirective;
3786
52.9k
  case Decl::StaticAssert:
3787
1
    return CXCursor_StaticAssert;
3788
52.9k
  case Decl::Friend:
3789
41
    return CXCursor_FriendDecl;
3790
52.9k
  case Decl::TranslationUnit:
3791
386
    return CXCursor_TranslationUnit;
3792
52.9k
3793
52.9k
  case Decl::Using:
3794
17
  case Decl::UnresolvedUsingValue:
3795
17
  case Decl::UnresolvedUsingTypename:
3796
17
    return CXCursor_UsingDeclaration;
3797
17
3798
47
  case Decl::ObjCPropertyImpl:
3799
47
    switch (cast<ObjCPropertyImplDecl>(D)->getPropertyImplementation()) {
3800
47
    case ObjCPropertyImplDecl::Dynamic:
3801
11
      return CXCursor_ObjCDynamicDecl;
3802
47
3803
47
    case ObjCPropertyImplDecl::Synthesize:
3804
36
      return CXCursor_ObjCSynthesizeDecl;
3805
0
    }
3806
0
    llvm_unreachable("Unexpected Kind!");
3807
0
3808
27
  case Decl::Import:
3809
27
    return CXCursor_ModuleImportDecl;
3810
0
3811
18
  case Decl::ObjCTypeParam:
3812
18
    return CXCursor_TemplateTypeParameter;
3813
0
3814
4.03k
  default:
3815
4.03k
    if (const auto *TD = dyn_cast<TagDecl>(D)) {
3816
3.82k
      switch (TD->getTagKind()) {
3817
3.82k
      case TTK_Interface: // fall through
3818
2.44k
      case TTK_Struct:
3819
2.44k
        return CXCursor_StructDecl;
3820
2.44k
      case TTK_Class:
3821
1.25k
        return CXCursor_ClassDecl;
3822
2.44k
      case TTK_Union:
3823
122
        return CXCursor_UnionDecl;
3824
2.44k
      case TTK_Enum:
3825
0
        return CXCursor_EnumDecl;
3826
207
      }
3827
207
    }
3828
207
  }
3829
207
3830
207
  return CXCursor_UnexposedDecl;
3831
207
}
3832
3833
static void AddMacroResults(Preprocessor &PP, ResultBuilder &Results,
3834
                            bool LoadExternal, bool IncludeUndefined,
3835
313
                            bool TargetTypeIsPointer = false) {
3836
313
  typedef CodeCompletionResult Result;
3837
313
3838
313
  Results.EnterNewScope();
3839
313
3840
313
  for (Preprocessor::macro_iterator M = PP.macro_begin(LoadExternal),
3841
313
                                    MEnd = PP.macro_end(LoadExternal);
3842
125k
       M != MEnd; 
++M124k
) {
3843
124k
    auto MD = PP.getMacroDefinition(M->first);
3844
124k
    if (IncludeUndefined || 
MD89.1k
) {
3845
124k
      MacroInfo *MI = MD.getMacroInfo();
3846
124k
      if (MI && 
MI->isUsedForHeaderGuard()124k
)
3847
28
        continue;
3848
124k
3849
124k
      Results.AddResult(
3850
124k
          Result(M->first, MI,
3851
124k
                 getMacroUsagePriority(M->first->getName(), PP.getLangOpts(),
3852
124k
                                       TargetTypeIsPointer)));
3853
124k
    }
3854
124k
  }
3855
313
3856
313
  Results.ExitScope();
3857
313
}
3858
3859
static void AddPrettyFunctionResults(const LangOptions &LangOpts,
3860
460
                                     ResultBuilder &Results) {
3861
460
  typedef CodeCompletionResult Result;
3862
460
3863
460
  Results.EnterNewScope();
3864
460
3865
460
  Results.AddResult(Result("__PRETTY_FUNCTION__", CCP_Constant));
3866
460
  Results.AddResult(Result("__FUNCTION__", CCP_Constant));
3867
460
  if (LangOpts.C99 || 
LangOpts.CPlusPlus11329
)
3868
452
    Results.AddResult(Result("__func__", CCP_Constant));
3869
460
  Results.ExitScope();
3870
460
}
3871
3872
static void HandleCodeCompleteResults(Sema *S,
3873
                                      CodeCompleteConsumer *CodeCompleter,
3874
                                      CodeCompletionContext Context,
3875
                                      CodeCompletionResult *Results,
3876
1.09k
                                      unsigned NumResults) {
3877
1.09k
  if (CodeCompleter)
3878
1.09k
    CodeCompleter->ProcessCodeCompleteResults(*S, Context, Results, NumResults);
3879
1.09k
}
3880
3881
static CodeCompletionContext
3882
185
mapCodeCompletionContext(Sema &S, Sema::ParserCompletionContext PCC) {
3883
185
  switch (PCC) {
3884
185
  case Sema::PCC_Namespace:
3885
51
    return CodeCompletionContext::CCC_TopLevel;
3886
185
3887
185
  case Sema::PCC_Class:
3888
9
    return CodeCompletionContext::CCC_ClassStructUnion;
3889
185
3890
185
  case Sema::PCC_ObjCInterface:
3891
1
    return CodeCompletionContext::CCC_ObjCInterface;
3892
185
3893
185
  case Sema::PCC_ObjCImplementation:
3894
1
    return CodeCompletionContext::CCC_ObjCImplementation;
3895
185
3896
185
  case Sema::PCC_ObjCInstanceVariableList:
3897
1
    return CodeCompletionContext::CCC_ObjCIvarList;
3898
185
3899
185
  case Sema::PCC_Template:
3900
0
  case Sema::PCC_MemberTemplate:
3901
0
    if (S.CurContext->isFileContext())
3902
0
      return CodeCompletionContext::CCC_TopLevel;
3903
0
    if (S.CurContext->isRecord())
3904
0
      return CodeCompletionContext::CCC_ClassStructUnion;
3905
0
    return CodeCompletionContext::CCC_Other;
3906
0
3907
3
  case Sema::PCC_RecoveryInFunction:
3908
3
    return CodeCompletionContext::CCC_Recovery;
3909
0
3910
6
  case Sema::PCC_ForInit:
3911
6
    if (S.getLangOpts().CPlusPlus || S.getLangOpts().C99 ||
3912
6
        
S.getLangOpts().ObjC0
)
3913
6
      return CodeCompletionContext::CCC_ParenthesizedExpression;
3914
0
    else
3915
0
      return CodeCompletionContext::CCC_Expression;
3916
0
3917
1
  case Sema::PCC_Expression:
3918
1
    return CodeCompletionContext::CCC_Expression;
3919
6
  case Sema::PCC_Condition:
3920
6
    return CodeCompletionContext(CodeCompletionContext::CCC_Expression,
3921
6
                                 S.getASTContext().BoolTy);
3922
0
3923
103
  case Sema::PCC_Statement:
3924
103
    return CodeCompletionContext::CCC_Statement;
3925
0
3926
2
  case Sema::PCC_Type:
3927
2
    return CodeCompletionContext::CCC_Type;
3928
0
3929
0
  case Sema::PCC_ParenthesizedExpression:
3930
0
    return CodeCompletionContext::CCC_ParenthesizedExpression;
3931
0
3932
1
  case Sema::PCC_LocalDeclarationSpecifiers:
3933
1
    return CodeCompletionContext::CCC_Type;
3934
0
  }
3935
0
3936
0
  llvm_unreachable("Invalid ParserCompletionContext!");
3937
0
}
3938
3939
/// If we're in a C++ virtual member function, add completion results
3940
/// that invoke the functions we override, since it's common to invoke the
3941
/// overridden function as well as adding new functionality.
3942
///
3943
/// \param S The semantic analysis object for which we are generating results.
3944
///
3945
/// \param InContext This context in which the nested-name-specifier preceding
3946
/// the code-completion point
3947
static void MaybeAddOverrideCalls(Sema &S, DeclContext *InContext,
3948
104
                                  ResultBuilder &Results) {
3949
104
  // Look through blocks.
3950
104
  DeclContext *CurContext = S.CurContext;
3951
104
  while (isa<BlockDecl>(CurContext))
3952
0
    CurContext = CurContext->getParent();
3953
104
3954
104
  CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(CurContext);
3955
104
  if (!Method || 
!Method->isVirtual()22
)
3956
101
    return;
3957
3
3958
3
  // We need to have names for all of the parameters, if we're going to
3959
3
  // generate a forwarding call.
3960
3
  for (auto P : Method->parameters())
3961
5
    if (!P->getDeclName())
3962
0
      return;
3963
3
3964
3
  PrintingPolicy Policy = getCompletionPrintingPolicy(S);
3965
3
  for (const CXXMethodDecl *Overridden : Method->overridden_methods()) {
3966
3
    CodeCompletionBuilder Builder(Results.getAllocator(),
3967
3
                                  Results.getCodeCompletionTUInfo());
3968
3
    if (Overridden->getCanonicalDecl() == Method->getCanonicalDecl())
3969
0
      continue;
3970
3
3971
3
    // If we need a nested-name-specifier, add one now.
3972
3
    if (!InContext) {
3973
2
      NestedNameSpecifier *NNS = getRequiredQualification(
3974
2
          S.Context, CurContext, Overridden->getDeclContext());
3975
2
      if (NNS) {
3976
2
        std::string Str;
3977
2
        llvm::raw_string_ostream OS(Str);
3978
2
        NNS->print(OS, Policy);
3979
2
        Builder.AddTextChunk(Results.getAllocator().CopyString(OS.str()));
3980
2
      }
3981
2
    } else 
if (1
!InContext->Equals(Overridden->getDeclContext())1
)
3982
0
      continue;
3983
3
3984
3
    Builder.AddTypedTextChunk(
3985
3
        Results.getAllocator().CopyString(Overridden->getNameAsString()));
3986
3
    Builder.AddChunk(CodeCompletionString::CK_LeftParen);
3987
3
    bool FirstParam = true;
3988
5
    for (auto P : Method->parameters()) {
3989
5
      if (FirstParam)
3990
3
        FirstParam = false;
3991
2
      else
3992
2
        Builder.AddChunk(CodeCompletionString::CK_Comma);
3993
5
3994
5
      Builder.AddPlaceholderChunk(
3995
5
          Results.getAllocator().CopyString(P->getIdentifier()->getName()));
3996
5
    }
3997
3
    Builder.AddChunk(CodeCompletionString::CK_RightParen);
3998
3
    Results.AddResult(CodeCompletionResult(
3999
3
        Builder.TakeString(), CCP_SuperCompletion, CXCursor_CXXMethod,
4000
3
        CXAvailability_Available, Overridden));
4001
3
    Results.Ignore(Overridden);
4002
3
  }
4003
3
}
4004
4005
void Sema::CodeCompleteModuleImport(SourceLocation ImportLoc,
4006
3
                                    ModuleIdPath Path) {
4007
3
  typedef CodeCompletionResult Result;
4008
3
  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4009
3
                        CodeCompleter->getCodeCompletionTUInfo(),
4010
3
                        CodeCompletionContext::CCC_Other);
4011
3
  Results.EnterNewScope();
4012
3
4013
3
  CodeCompletionAllocator &Allocator = Results.getAllocator();
4014
3
  CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
4015
3
  typedef CodeCompletionResult Result;
4016
3
  if (Path.empty()) {
4017
2
    // Enumerate all top-level modules.
4018
2
    SmallVector<Module *, 8> Modules;
4019
2
    PP.getHeaderSearchInfo().collectAllModules(Modules);
4020
336
    for (unsigned I = 0, N = Modules.size(); I != N; 
++I334
) {
4021
334
      Builder.AddTypedTextChunk(
4022
334
          Builder.getAllocator().CopyString(Modules[I]->Name));
4023
334
      Results.AddResult(Result(
4024
334
          Builder.TakeString(), CCP_Declaration, CXCursor_ModuleImportDecl,
4025
334
          Modules[I]->isAvailable() ? 
CXAvailability_Available332
4026
334
                                    : 
CXAvailability_NotAvailable2
));
4027
334
    }
4028
2
  } else 
if (1
getLangOpts().Modules1
) {
4029
1
    // Load the named module.
4030
1
    Module *Mod =
4031
1
        PP.getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
4032
1
                                        /*IsInclusionDirective=*/false);
4033
1
    // Enumerate submodules.
4034
1
    if (Mod) {
4035
1
      for (Module::submodule_iterator Sub = Mod->submodule_begin(),
4036
1
                                      SubEnd = Mod->submodule_end();
4037
2
           Sub != SubEnd; 
++Sub1
) {
4038
1
4039
1
        Builder.AddTypedTextChunk(
4040
1
            Builder.getAllocator().CopyString((*Sub)->Name));
4041
1
        Results.AddResult(Result(
4042
1
            Builder.TakeString(), CCP_Declaration, CXCursor_ModuleImportDecl,
4043
1
            (*Sub)->isAvailable() ? CXAvailability_Available
4044
1
                                  : 
CXAvailability_NotAvailable0
));
4045
1
      }
4046
1
    }
4047
1
  }
4048
3
  Results.ExitScope();
4049
3
  HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4050
3
                            Results.data(), Results.size());
4051
3
}
4052
4053
void Sema::CodeCompleteOrdinaryName(Scope *S,
4054
183
                                    ParserCompletionContext CompletionContext) {
4055
183
  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4056
183
                        CodeCompleter->getCodeCompletionTUInfo(),
4057
183
                        mapCodeCompletionContext(*this, CompletionContext));
4058
183
  Results.EnterNewScope();
4059
183
4060
183
  // Determine how to filter results, e.g., so that the names of
4061
183
  // values (functions, enumerators, function templates, etc.) are
4062
183
  // only allowed where we can have an expression.
4063
183
  switch (CompletionContext) {
4064
183
  case PCC_Namespace:
4065
66
  case PCC_Class:
4066
66
  case PCC_ObjCInterface:
4067
66
  case PCC_ObjCImplementation:
4068
66
  case PCC_ObjCInstanceVariableList:
4069
66
  case PCC_Template:
4070
66
  case PCC_MemberTemplate:
4071
66
  case PCC_Type:
4072
66
  case PCC_LocalDeclarationSpecifiers:
4073
66
    Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
4074
66
    break;
4075
66
4076
114
  case PCC_Statement:
4077
114
  case PCC_ParenthesizedExpression:
4078
114
  case PCC_Expression:
4079
114
  case PCC_ForInit:
4080
114
  case PCC_Condition:
4081
114
    if (WantTypesInContext(CompletionContext, getLangOpts()))
4082
113
      Results.setFilter(&ResultBuilder::IsOrdinaryName);
4083
1
    else
4084
1
      Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
4085
114
4086
114
    if (getLangOpts().CPlusPlus)
4087
61
      MaybeAddOverrideCalls(*this, /*InContext=*/nullptr, Results);
4088
114
    break;
4089
114
4090
114
  case PCC_RecoveryInFunction:
4091
3
    // Unfiltered
4092
3
    break;
4093
183
  }
4094
183
4095
183
  // If we are in a C++ non-static member function, check the qualifiers on
4096
183
  // the member function to filter/prioritize the results list.
4097
183
  auto ThisType = getCurrentThisType();
4098
183
  if (!ThisType.isNull())
4099
12
    Results.setObjectTypeQualifiers(ThisType->getPointeeType().getQualifiers(),
4100
12
                                    VK_LValue);
4101
183
4102
183
  CodeCompletionDeclConsumer Consumer(Results, CurContext);
4103
183
  LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4104
183
                     CodeCompleter->includeGlobals(),
4105
183
                     CodeCompleter->loadExternal());
4106
183
4107
183
  AddOrdinaryNameResults(CompletionContext, S, *this, Results);
4108
183
  Results.ExitScope();
4109
183
4110
183
  switch (CompletionContext) {
4111
183
  case PCC_ParenthesizedExpression:
4112
105
  case PCC_Expression:
4113
105
  case PCC_Statement:
4114
105
  case PCC_RecoveryInFunction:
4115
105
    if (S->getFnParent())
4116
105
      AddPrettyFunctionResults(getLangOpts(), Results);
4117
105
    break;
4118
105
4119
105
  case PCC_Namespace:
4120
78
  case PCC_Class:
4121
78
  case PCC_ObjCInterface:
4122
78
  case PCC_ObjCImplementation:
4123
78
  case PCC_ObjCInstanceVariableList:
4124
78
  case PCC_Template:
4125
78
  case PCC_MemberTemplate:
4126
78
  case PCC_ForInit:
4127
78
  case PCC_Condition:
4128
78
  case PCC_Type:
4129
78
  case PCC_LocalDeclarationSpecifiers:
4130
78
    break;
4131
183
  }
4132
183
4133
183
  if (CodeCompleter->includeMacros())
4134
62
    AddMacroResults(PP, Results, CodeCompleter->loadExternal(), false);
4135
183
4136
183
  HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4137
183
                            Results.data(), Results.size());
4138
183
}
4139
4140
static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
4141
                                       ParsedType Receiver,
4142
                                       ArrayRef<IdentifierInfo *> SelIdents,
4143
                                       bool AtArgumentExpression, bool IsSuper,
4144
                                       ResultBuilder &Results);
4145
4146
void Sema::CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
4147
                                bool AllowNonIdentifiers,
4148
35
                                bool AllowNestedNameSpecifiers) {
4149
35
  typedef CodeCompletionResult Result;
4150
35
  ResultBuilder Results(
4151
35
      *this, CodeCompleter->getAllocator(),
4152
35
      CodeCompleter->getCodeCompletionTUInfo(),
4153
35
      AllowNestedNameSpecifiers
4154
35
          // FIXME: Try to separate codepath leading here to deduce whether we
4155
35
          // need an existing symbol or a new one.
4156
35
          ? 
CodeCompletionContext::CCC_SymbolOrNewName17
4157
35
          : 
CodeCompletionContext::CCC_NewName18
);
4158
35
  Results.EnterNewScope();
4159
35
4160
35
  // Type qualifiers can come after names.
4161
35
  Results.AddResult(Result("const"));
4162
35
  Results.AddResult(Result("volatile"));
4163
35
  if (getLangOpts().C99)
4164
7
    Results.AddResult(Result("restrict"));
4165
35
4166
35
  if (getLangOpts().CPlusPlus) {
4167
28
    if (getLangOpts().CPlusPlus11 &&
4168
28
        (DS.getTypeSpecType() == DeclSpec::TST_class ||
4169
28
         
DS.getTypeSpecType() == DeclSpec::TST_struct26
))
4170
3
      Results.AddResult("final");
4171
28
4172
28
    if (AllowNonIdentifiers) {
4173
22
      Results.AddResult(Result("operator"));
4174
22
    }
4175
28
4176
28
    // Add nested-name-specifiers.
4177
28
    if (AllowNestedNameSpecifiers) {
4178
15
      Results.allowNestedNameSpecifiers();
4179
15
      Results.setFilter(&ResultBuilder::IsImpossibleToSatisfy);
4180
15
      CodeCompletionDeclConsumer Consumer(Results, CurContext);
4181
15
      LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer,
4182
15
                         CodeCompleter->includeGlobals(),
4183
15
                         CodeCompleter->loadExternal());
4184
15
      Results.setFilter(nullptr);
4185
15
    }
4186
28
  }
4187
35
  Results.ExitScope();
4188
35
4189
35
  // If we're in a context where we might have an expression (rather than a
4190
35
  // declaration), and what we've seen so far is an Objective-C type that could
4191
35
  // be a receiver of a class message, this may be a class message send with
4192
35
  // the initial opening bracket '[' missing. Add appropriate completions.
4193
35
  if (AllowNonIdentifiers && 
!AllowNestedNameSpecifiers28
&&
4194
35
      
DS.getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier11
&&
4195
35
      
DS.getTypeSpecType() == DeclSpec::TST_typename11
&&
4196
35
      
DS.getTypeSpecComplex() == DeclSpec::TSC_unspecified2
&&
4197
35
      
DS.getTypeSpecSign() == DeclSpec::TSS_unspecified2
&&
4198
35
      
!DS.isTypeAltiVecVector()2
&&
S2
&&
4199
35
      
(S->getFlags() & Scope::DeclScope) != 02
&&
4200
35
      (S->getFlags() & (Scope::ClassScope | Scope::TemplateParamScope |
4201
2
                        Scope::FunctionPrototypeScope | Scope::AtCatchScope)) ==
4202
2
          0) {
4203
2
    ParsedType T = DS.getRepAsType();
4204
2
    if (!T.get().isNull() && T.get()->isObjCObjectOrInterfaceType())
4205
2
      AddClassMessageCompletions(*this, S, T, None, false, false, Results);
4206
2
  }
4207
35
4208
35
  // Note that we intentionally suppress macro results here, since we do not
4209
35
  // encourage using macros to produce the names of entities.
4210
35
4211
35
  HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4212
35
                            Results.data(), Results.size());
4213
35
}
4214
4215
struct Sema::CodeCompleteExpressionData {
4216
  CodeCompleteExpressionData(QualType PreferredType = QualType(),
4217
                             bool IsParenthesized = false)
4218
      : PreferredType(PreferredType), IntegralConstantExpression(false),
4219
371
        ObjCCollection(false), IsParenthesized(IsParenthesized) {}
4220
4221
  QualType PreferredType;
4222
  bool IntegralConstantExpression;
4223
  bool ObjCCollection;
4224
  bool IsParenthesized;
4225
  SmallVector<Decl *, 4> IgnoreDecls;
4226
};
4227
4228
namespace {
4229
/// Information that allows to avoid completing redundant enumerators.
4230
struct CoveredEnumerators {
4231
  llvm::SmallPtrSet<EnumConstantDecl *, 8> Seen;
4232
  NestedNameSpecifier *SuggestedQualifier = nullptr;
4233
};
4234
} // namespace
4235
4236
static void AddEnumerators(ResultBuilder &Results, ASTContext &Context,
4237
                           EnumDecl *Enum, DeclContext *CurContext,
4238
23
                           const CoveredEnumerators &Enumerators) {
4239
23
  NestedNameSpecifier *Qualifier = Enumerators.SuggestedQualifier;
4240
23
  if (Context.getLangOpts().CPlusPlus && 
!Qualifier12
&&
Enumerators.Seen.empty()10
) {
4241
10
    // If there are no prior enumerators in C++, check whether we have to
4242
10
    // qualify the names of the enumerators that we suggest, because they
4243
10
    // may not be visible in this scope.
4244
10
    Qualifier = getRequiredQualification(Context, CurContext, Enum);
4245
10
  }
4246
23
4247
23
  Results.EnterNewScope();
4248
66
  for (auto *E : Enum->enumerators()) {
4249
66
    if (Enumerators.Seen.count(E))
4250
5
      continue;
4251
61
4252
61
    CodeCompletionResult R(E, CCP_EnumInCase, Qualifier);
4253
61
    Results.AddResult(R, CurContext, nullptr, false);
4254
61
  }
4255
23
  Results.ExitScope();
4256
23
}
4257
4258
/// Try to find a corresponding FunctionProtoType for function-like types (e.g.
4259
/// function pointers, std::function, etc).
4260
209
static const FunctionProtoType *TryDeconstructFunctionLike(QualType T) {
4261
209
  assert(!T.isNull());
4262
209
  // Try to extract first template argument from std::function<> and similar.
4263
209
  // Note we only handle the sugared types, they closely match what users wrote.
4264
209
  // We explicitly choose to not handle ClassTemplateSpecializationDecl.
4265
209
  if (auto *Specialization = T->getAs<TemplateSpecializationType>()) {
4266
10
    if (Specialization->getNumArgs() != 1)
4267
1
      return nullptr;
4268
9
    const TemplateArgument &Argument = Specialization->getArg(0);
4269
9
    if (Argument.getKind() != TemplateArgument::Type)
4270
0
      return nullptr;
4271
9
    return Argument.getAsType()->getAs<FunctionProtoType>();
4272
9
  }
4273
199
  // Handle other cases.
4274
199
  if (T->isPointerType())
4275
49
    T = T->getPointeeType();
4276
199
  return T->getAs<FunctionProtoType>();
4277
199
}
4278
4279
/// Adds a pattern completion for a lambda expression with the specified
4280
/// parameter types and placeholders for parameter names.
4281
static void AddLambdaCompletion(ResultBuilder &Results,
4282
                                llvm::ArrayRef<QualType> Parameters,
4283
9
                                const LangOptions &LangOpts) {
4284
9
  if (!Results.includeCodePatterns())
4285
1
    return;
4286
8
  CodeCompletionBuilder Completion(Results.getAllocator(),
4287
8
                                   Results.getCodeCompletionTUInfo());
4288
8
  // [](<parameters>) {}
4289
8
  Completion.AddChunk(CodeCompletionString::CK_LeftBracket);
4290
8
  Completion.AddPlaceholderChunk("=");
4291
8
  Completion.AddChunk(CodeCompletionString::CK_RightBracket);
4292
8
  if (!Parameters.empty()) {
4293
5
    Completion.AddChunk(CodeCompletionString::CK_LeftParen);
4294
5
    bool First = true;
4295
7
    for (auto Parameter : Parameters) {
4296
7
      if (!First)
4297
2
        Completion.AddChunk(CodeCompletionString::ChunkKind::CK_Comma);
4298
5
      else
4299
5
        First = false;
4300
7
4301
7
      constexpr llvm::StringLiteral NamePlaceholder = "!#!NAME_GOES_HERE!#!";
4302
7
      std::string Type = NamePlaceholder;
4303
7
      Parameter.getAsStringInternal(Type, PrintingPolicy(LangOpts));
4304
7
      llvm::StringRef Prefix, Suffix;
4305
7
      std::tie(Prefix, Suffix) = llvm::StringRef(Type).split(NamePlaceholder);
4306
7
      Prefix = Prefix.rtrim();
4307
7
      Suffix = Suffix.ltrim();
4308
7
4309
7
      Completion.AddTextChunk(Completion.getAllocator().CopyString(Prefix));
4310
7
      Completion.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4311
7
      Completion.AddPlaceholderChunk("parameter");
4312
7
      Completion.AddTextChunk(Completion.getAllocator().CopyString(Suffix));
4313
7
    };
4314
5
    Completion.AddChunk(CodeCompletionString::CK_RightParen);
4315
5
  }
4316
8
  Completion.AddChunk(clang::CodeCompletionString::CK_HorizontalSpace);
4317
8
  Completion.AddChunk(CodeCompletionString::CK_LeftBrace);
4318
8
  Completion.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4319
8
  Completion.AddPlaceholderChunk("body");
4320
8
  Completion.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4321
8
  Completion.AddChunk(CodeCompletionString::CK_RightBrace);
4322
8
4323
8
  Results.AddResult(Completion.TakeString());
4324
8
}
4325
4326
/// Perform code-completion in an expression context when we know what
4327
/// type we're looking for.
4328
void Sema::CodeCompleteExpression(Scope *S,
4329
371
                                  const CodeCompleteExpressionData &Data) {
4330
371
  ResultBuilder Results(
4331
371
      *this, CodeCompleter->getAllocator(),
4332
371
      CodeCompleter->getCodeCompletionTUInfo(),
4333
371
      CodeCompletionContext(
4334
371
          Data.IsParenthesized
4335
371
              ? 
CodeCompletionContext::CCC_ParenthesizedExpression30
4336
371
              : 
CodeCompletionContext::CCC_Expression341
,
4337
371
          Data.PreferredType));
4338
371
  auto PCC =
4339
371
      Data.IsParenthesized ? 
PCC_ParenthesizedExpression30
:
PCC_Expression341
;
4340
371
  if (Data.ObjCCollection)
4341
2
    Results.setFilter(&ResultBuilder::IsObjCCollection);
4342
369
  else if (Data.IntegralConstantExpression)
4343
1
    Results.setFilter(&ResultBuilder::IsIntegralConstantValue);
4344
368
  else if (WantTypesInContext(PCC, getLangOpts()))
4345
288
    Results.setFilter(&ResultBuilder::IsOrdinaryName);
4346
80
  else
4347
80
    Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
4348
371
4349
371
  if (!Data.PreferredType.isNull())
4350
271
    Results.setPreferredType(Data.PreferredType.getNonReferenceType());
4351
371
4352
371
  // Ignore any declarations that we were told that we don't care about.
4353
415
  for (unsigned I = 0, N = Data.IgnoreDecls.size(); I != N; 
++I44
)
4354
44
    Results.Ignore(Data.IgnoreDecls[I]);
4355
371
4356
371
  CodeCompletionDeclConsumer Consumer(Results, CurContext);
4357
371
  LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4358
371
                     CodeCompleter->includeGlobals(),
4359
371
                     CodeCompleter->loadExternal());
4360
371
4361
371
  Results.EnterNewScope();
4362
371
  AddOrdinaryNameResults(PCC, S, *this, Results);
4363
371
  Results.ExitScope();
4364
371
4365
371
  bool PreferredTypeIsPointer = false;
4366
371
  if (!Data.PreferredType.isNull()) {
4367
271
    PreferredTypeIsPointer = Data.PreferredType->isAnyPointerType() ||
4368
271
                             
Data.PreferredType->isMemberPointerType()215
||
4369
271
                             
Data.PreferredType->isBlockPointerType()215
;
4370
271
    if (Data.PreferredType->isEnumeralType()) {
4371
15
      EnumDecl *Enum = Data.PreferredType->castAs<EnumType>()->getDecl();
4372
15
      if (auto *Def = Enum->getDefinition())
4373
15
        Enum = Def;
4374
15
      // FIXME: collect covered enumerators in cases like:
4375
15
      //        if (x == my_enum::one) { ... } else if (x == ^) {}
4376
15
      AddEnumerators(Results, Context, Enum, CurContext, CoveredEnumerators());
4377
15
    }
4378
271
  }
4379
371
4380
371
  if (S->getFnParent() && 
!Data.ObjCCollection356
&&
4381
371
      
!Data.IntegralConstantExpression354
)
4382
353
    AddPrettyFunctionResults(getLangOpts(), Results);
4383
371
4384
371
  if (CodeCompleter->includeMacros())
4385
140
    AddMacroResults(PP, Results, CodeCompleter->loadExternal(), false,
4386
140
                    PreferredTypeIsPointer);
4387
371
4388
371
  // Complete a lambda expression when preferred type is a function.
4389
371
  if (!Data.PreferredType.isNull() && 
getLangOpts().CPlusPlus11271
) {
4390
209
    if (const FunctionProtoType *F =
4391
9
            TryDeconstructFunctionLike(Data.PreferredType))
4392
9
      AddLambdaCompletion(Results, F->getParamTypes(), getLangOpts());
4393
209
  }
4394
371
4395
371
  HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4396
371
                            Results.data(), Results.size());
4397
371
}
4398
4399
void Sema::CodeCompleteExpression(Scope *S, QualType PreferredType,
4400
326
                                  bool IsParenthesized) {
4401
326
  return CodeCompleteExpression(
4402
326
      S, CodeCompleteExpressionData(PreferredType, IsParenthesized));
4403
326
}
4404
4405
void Sema::CodeCompletePostfixExpression(Scope *S, ExprResult E,
4406
9
                                         QualType PreferredType) {
4407
9
  if (E.isInvalid())
4408
1
    CodeCompleteExpression(S, PreferredType);
4409
8
  else if (getLangOpts().ObjC)
4410
3
    CodeCompleteObjCInstanceMessage(S, E.get(), None, false);
4411
9
}
4412
4413
/// The set of properties that have already been added, referenced by
4414
/// property name.
4415
typedef llvm::SmallPtrSet<IdentifierInfo *, 16> AddedPropertiesSet;
4416
4417
/// Retrieve the container definition, if any?
4418
225
static ObjCContainerDecl *getContainerDef(ObjCContainerDecl *Container) {
4419
225
  if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
4420
150
    if (Interface->hasDefinition())
4421
150
      return Interface->getDefinition();
4422
0
4423
0
    return Interface;
4424
0
  }
4425
75
4426
75
  if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4427
24
    if (Protocol->hasDefinition())
4428
24
      return Protocol->getDefinition();
4429
0
4430
0
    return Protocol;
4431
0
  }
4432
51
  return Container;
4433
51
}
4434
4435
/// Adds a block invocation code completion result for the given block
4436
/// declaration \p BD.
4437
static void AddObjCBlockCall(ASTContext &Context, const PrintingPolicy &Policy,
4438
                             CodeCompletionBuilder &Builder,
4439
                             const NamedDecl *BD,
4440
                             const FunctionTypeLoc &BlockLoc,
4441
39
                             const FunctionProtoTypeLoc &BlockProtoLoc) {
4442
39
  Builder.AddResultTypeChunk(
4443
39
      GetCompletionTypeString(BlockLoc.getReturnLoc().getType(), Context,
4444
39
                              Policy, Builder.getAllocator()));
4445
39
4446
39
  AddTypedNameChunk(Context, Policy, BD, Builder);
4447
39
  Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4448
39
4449
39
  if (BlockProtoLoc && 
BlockProtoLoc.getTypePtr()->isVariadic()31
) {
4450
0
    Builder.AddPlaceholderChunk("...");
4451
39
  } else {
4452
79
    for (unsigned I = 0, N = BlockLoc.getNumParams(); I != N; 
++I40
) {
4453
40
      if (I)
4454
9
        Builder.AddChunk(CodeCompletionString::CK_Comma);
4455
40
4456
40
      // Format the placeholder string.
4457
40
      std::string PlaceholderStr =
4458
40
          FormatFunctionParameter(Policy, BlockLoc.getParam(I));
4459
40
4460
40
      if (I == N - 1 && 
BlockProtoLoc31
&&
4461
40
          
BlockProtoLoc.getTypePtr()->isVariadic()31
)
4462
0
        PlaceholderStr += ", ...";
4463
40
4464
40
      // Add the placeholder string.
4465
40
      Builder.AddPlaceholderChunk(
4466
40
          Builder.getAllocator().CopyString(PlaceholderStr));
4467
40
    }
4468
39
  }
4469
39
4470
39
  Builder.AddChunk(CodeCompletionString::CK_RightParen);
4471
39
}
4472
4473
static void
4474
AddObjCProperties(const CodeCompletionContext &CCContext,
4475
                  ObjCContainerDecl *Container, bool AllowCategories,
4476
                  bool AllowNullaryMethods, DeclContext *CurContext,
4477
                  AddedPropertiesSet &AddedProperties, ResultBuilder &Results,
4478
                  bool IsBaseExprStatement = false,
4479
65
                  bool IsClassProperty = false, bool InOriginalClass = true) {
4480
65
  typedef CodeCompletionResult Result;
4481
65
4482
65
  // Retrieve the definition.
4483
65
  Container = getContainerDef(Container);
4484
65
4485
65
  // Add properties in this container.
4486
132
  const auto AddProperty = [&](const ObjCPropertyDecl *P) {
4487
132
    if (!AddedProperties.insert(P->getIdentifier()).second)
4488
2
      return;
4489
130
4490
130
    // FIXME: Provide block invocation completion for non-statement
4491
130
    // expressions.
4492
130
    if (!P->getType().getTypePtr()->isBlockPointerType() ||
4493
130
        
!IsBaseExprStatement63
) {
4494
91
      Result R = Result(P, Results.getBasePriority(P), nullptr);
4495
91
      if (!InOriginalClass)
4496
40
        setInBaseClass(R);
4497
91
      Results.MaybeAddResult(R, CurContext);
4498
91
      return;
4499
91
    }
4500
39
4501
39
    // Block setter and invocation completion is provided only when we are able
4502
39
    // to find the FunctionProtoTypeLoc with parameter names for the block.
4503
39
    FunctionTypeLoc BlockLoc;
4504
39
    FunctionProtoTypeLoc BlockProtoLoc;
4505
39
    findTypeLocationForBlockDecl(P->getTypeSourceInfo(), BlockLoc,
4506
39
                                 BlockProtoLoc);
4507
39
    if (!BlockLoc) {
4508
0
      Result R = Result(P, Results.getBasePriority(P), nullptr);
4509
0
      if (!InOriginalClass)
4510
0
        setInBaseClass(R);
4511
0
      Results.MaybeAddResult(R, CurContext);
4512
0
      return;
4513
0
    }
4514
39
4515
39
    // The default completion result for block properties should be the block
4516
39
    // invocation completion when the base expression is a statement.
4517
39
    CodeCompletionBuilder Builder(Results.getAllocator(),
4518
39
                                  Results.getCodeCompletionTUInfo());
4519
39
    AddObjCBlockCall(Container->getASTContext(),
4520
39
                     getCompletionPrintingPolicy(Results.getSema()), Builder, P,
4521
39
                     BlockLoc, BlockProtoLoc);
4522
39
    Result R = Result(Builder.TakeString(), P, Results.getBasePriority(P));
4523
39
    if (!InOriginalClass)
4524
16
      setInBaseClass(R);
4525
39
    Results.MaybeAddResult(R, CurContext);
4526
39
4527
39
    // Provide additional block setter completion iff the base expression is a
4528
39
    // statement and the block property is mutable.
4529
39
    if (!P->isReadOnly()) {
4530
19
      CodeCompletionBuilder Builder(Results.getAllocator(),
4531
19
                                    Results.getCodeCompletionTUInfo());
4532
19
      AddResultTypeChunk(Container->getASTContext(),
4533
19
                         getCompletionPrintingPolicy(Results.getSema()), P,
4534
19
                         CCContext.getBaseType(), Builder);
4535
19
      Builder.AddTypedTextChunk(
4536
19
          Results.getAllocator().CopyString(P->getName()));
4537
19
      Builder.AddChunk(CodeCompletionString::CK_Equal);
4538
19
4539
19
      std::string PlaceholderStr = formatBlockPlaceholder(
4540
19
          getCompletionPrintingPolicy(Results.getSema()), P, BlockLoc,
4541
19
          BlockProtoLoc, /*SuppressBlockName=*/true);
4542
19
      // Add the placeholder string.
4543
19
      Builder.AddPlaceholderChunk(
4544
19
          Builder.getAllocator().CopyString(PlaceholderStr));
4545
19
4546
19
      // When completing blocks properties that return void the default
4547
19
      // property completion result should show up before the setter,
4548
19
      // otherwise the setter completion should show up before the default
4549
19
      // property completion, as we normally want to use the result of the
4550
19
      // call.
4551
19
      Result R =
4552
19
          Result(Builder.TakeString(), P,
4553
19
                 Results.getBasePriority(P) +
4554
19
                     (BlockLoc.getTypePtr()->getReturnType()->isVoidType()
4555
19
                          ? 
CCD_BlockPropertySetter12
4556
19
                          : 
-CCD_BlockPropertySetter7
));
4557
19
      if (!InOriginalClass)
4558
10
        setInBaseClass(R);
4559
19
      Results.MaybeAddResult(R, CurContext);
4560
19
    }
4561
39
  };
4562
65
4563
65
  if (IsClassProperty) {
4564
7
    for (const auto *P : Container->class_properties())
4565
8
      AddProperty(P);
4566
58
  } else {
4567
58
    for (const auto *P : Container->instance_properties())
4568
124
      AddProperty(P);
4569
58
  }
4570
65
4571
65
  // Add nullary methods or implicit class properties
4572
65
  if (AllowNullaryMethods) {
4573
57
    ASTContext &Context = Container->getASTContext();
4574
57
    PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema());
4575
57
    // Adds a method result
4576
128
    const auto AddMethod = [&](const ObjCMethodDecl *M) {
4577
128
      IdentifierInfo *Name = M->getSelector().getIdentifierInfoForSlot(0);
4578
128
      if (!Name)
4579
0
        return;
4580
128
      if (!AddedProperties.insert(Name).second)
4581
115
        return;
4582
13
      CodeCompletionBuilder Builder(Results.getAllocator(),
4583
13
                                    Results.getCodeCompletionTUInfo());
4584
13
      AddResultTypeChunk(Context, Policy, M, CCContext.getBaseType(), Builder);
4585
13
      Builder.AddTypedTextChunk(
4586
13
          Results.getAllocator().CopyString(Name->getName()));
4587
13
      Result R = Result(Builder.TakeString(), M,
4588
13
                        CCP_MemberDeclaration + CCD_MethodAsProperty);
4589
13
      if (!InOriginalClass)
4590
3
        setInBaseClass(R);
4591
13
      Results.MaybeAddResult(R, CurContext);
4592
13
    };
4593
57
4594
57
    if (IsClassProperty) {
4595
30
      for (const auto *M : Container->methods()) {
4596
30
        // Gather the class method that can be used as implicit property
4597
30
        // getters. Methods with arguments or methods that return void aren't
4598
30
        // added to the results as they can't be used as a getter.
4599
30
        if (!M->getSelector().isUnarySelector() ||
4600
30
            
M->getReturnType()->isVoidType()22
||
M->isInstanceMethod()20
)
4601
14
          continue;
4602
16
        AddMethod(M);
4603
16
      }
4604
50
    } else {
4605
191
      for (auto *M : Container->methods()) {
4606
191
        if (M->getSelector().isUnarySelector())
4607
112
          AddMethod(M);
4608
191
      }
4609
50
    }
4610
57
  }
4611
65
4612
65
  // Add properties in referenced protocols.
4613
65
  if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4614
7
    for (auto *P : Protocol->protocols())
4615
1
      AddObjCProperties(CCContext, P, AllowCategories, AllowNullaryMethods,
4616
1
                        CurContext, AddedProperties, Results,
4617
1
                        IsBaseExprStatement, IsClassProperty,
4618
1
                        /*InOriginalClass*/ false);
4619
58
  } else if (ObjCInterfaceDecl *IFace =
4620
54
                 dyn_cast<ObjCInterfaceDecl>(Container)) {
4621
54
    if (AllowCategories) {
4622
47
      // Look through categories.
4623
47
      for (auto *Cat : IFace->known_categories())
4624
4
        AddObjCProperties(CCContext, Cat, AllowCategories, AllowNullaryMethods,
4625
4
                          CurContext, AddedProperties, Results,
4626
4
                          IsBaseExprStatement, IsClassProperty,
4627
4
                          InOriginalClass);
4628
47
    }
4629
54
4630
54
    // Look through protocols.
4631
54
    for (auto *I : IFace->all_referenced_protocols())
4632
5
      AddObjCProperties(CCContext, I, AllowCategories, AllowNullaryMethods,
4633
5
                        CurContext, AddedProperties, Results,
4634
5
                        IsBaseExprStatement, IsClassProperty,
4635
5
                        /*InOriginalClass*/ false);
4636
54
4637
54
    // Look in the superclass.
4638
54
    if (IFace->getSuperClass())
4639
26
      AddObjCProperties(CCContext, IFace->getSuperClass(), AllowCategories,
4640
26
                        AllowNullaryMethods, CurContext, AddedProperties,
4641
26
                        Results, IsBaseExprStatement, IsClassProperty,
4642
26
                        /*InOriginalClass*/ false);
4643
54
  } else 
if (const auto *4
Category4
=
4644
4
                 dyn_cast<ObjCCategoryDecl>(Container)) {
4645
4
    // Look through protocols.
4646
4
    for (auto *P : Category->protocols())
4647
0
      AddObjCProperties(CCContext, P, AllowCategories, AllowNullaryMethods,
4648
0
                        CurContext, AddedProperties, Results,
4649
0
                        IsBaseExprStatement, IsClassProperty,
4650
0
                        /*InOriginalClass*/ false);
4651
4
  }
4652
65
}
4653
4654
static void AddRecordMembersCompletionResults(
4655
    Sema &SemaRef, ResultBuilder &Results, Scope *S, QualType BaseType,
4656
88
    ExprValueKind BaseKind, RecordDecl *RD, Optional<FixItHint> AccessOpFixIt) {
4657
88
  // Indicate that we are performing a member access, and the cv-qualifiers
4658
88
  // for the base object type.
4659
88
  Results.setObjectTypeQualifiers(BaseType.getQualifiers(), BaseKind);
4660
88
4661
88
  // Access to a C/C++ class, struct, or union.
4662
88
  Results.allowNestedNameSpecifiers();
4663
88
  std::vector<FixItHint> FixIts;
4664
88
  if (AccessOpFixIt)
4665
6
    FixIts.emplace_back(AccessOpFixIt.getValue());
4666
88
  CodeCompletionDeclConsumer Consumer(Results, RD, BaseType, std::move(FixIts));
4667
88
  SemaRef.LookupVisibleDecls(RD, Sema::LookupMemberName, Consumer,
4668
88
                             SemaRef.CodeCompleter->includeGlobals(),
4669
88
                             /*IncludeDependentBases=*/true,
4670
88
                             SemaRef.CodeCompleter->loadExternal());
4671
88
4672
88
  if (SemaRef.getLangOpts().CPlusPlus) {
4673
71
    if (!Results.empty()) {
4674
71
      // The "template" keyword can follow "->" or "." in the grammar.
4675
71
      // However, we only want to suggest the template keyword if something
4676
71
      // is dependent.
4677
71
      bool IsDependent = BaseType->isDependentType();
4678
71
      if (!IsDependent) {
4679
71
        for (Scope *DepScope = S; DepScope; 
DepScope = DepScope->getParent()4
)
4680
71
          if (DeclContext *Ctx = DepScope->getEntity()) {
4681
67
            IsDependent = Ctx->isDependentContext();
4682
67
            break;
4683
67
          }
4684
67
      }
4685
71
4686
71
      if (IsDependent)
4687
5
        Results.AddResult(CodeCompletionResult("template"));
4688
71
    }
4689
71
  }
4690
88
}
4691
4692
void Sema::CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base,
4693
                                           Expr *OtherOpBase,
4694
                                           SourceLocation OpLoc, bool IsArrow,
4695
                                           bool IsBaseExprStatement,
4696
118
                                           QualType PreferredType) {
4697
118
  if (!Base || 
!CodeCompleter117
)
4698
1
    return;
4699
117
4700
117
  ExprResult ConvertedBase = PerformMemberExprBaseConversion(Base, IsArrow);
4701
117
  if (ConvertedBase.isInvalid())
4702
0
    return;
4703
117
  QualType ConvertedBaseType = ConvertedBase.get()->getType();
4704
117
4705
117
  enum CodeCompletionContext::Kind contextKind;
4706
117
4707
117
  if (IsArrow) {
4708
35
    if (const auto *Ptr = ConvertedBaseType->getAs<PointerType>())
4709
25
      ConvertedBaseType = Ptr->getPointeeType();
4710
35
  }
4711
117
4712
117
  if (IsArrow) {
4713
35
    contextKind = CodeCompletionContext::CCC_ArrowMemberAccess;
4714
82
  } else {
4715
82
    if (ConvertedBaseType->isObjCObjectPointerType() ||
4716
82
        
ConvertedBaseType->isObjCObjectOrInterfaceType()60
) {
4717
22
      contextKind = CodeCompletionContext::CCC_ObjCPropertyAccess;
4718
60
    } else {
4719
60
      contextKind = CodeCompletionContext::CCC_DotMemberAccess;
4720
60
    }
4721
82
  }
4722
117
4723
117
  CodeCompletionContext CCContext(contextKind, ConvertedBaseType);
4724
117
  CCContext.setPreferredType(PreferredType);
4725
117
  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4726
117
                        CodeCompleter->getCodeCompletionTUInfo(), CCContext,
4727
117
                        &ResultBuilder::IsMember);
4728
117
4729
117
  auto DoCompletion = [&](Expr *Base, bool IsArrow,
4730
123
                          Optional<FixItHint> AccessOpFixIt) -> bool {
4731
123
    if (!Base)
4732
0
      return false;
4733
123
4734
123
    ExprResult ConvertedBase = PerformMemberExprBaseConversion(Base, IsArrow);
4735
123
    if (ConvertedBase.isInvalid())
4736
0
      return false;
4737
123
    Base = ConvertedBase.get();
4738
123
4739
123
    QualType BaseType = Base->getType();
4740
123
    ExprValueKind BaseKind = Base->getValueKind();
4741
123
4742
123
    if (IsArrow) {
4743
38
      if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
4744
28
        BaseType = Ptr->getPointeeType();
4745
28
        BaseKind = VK_LValue;
4746
28
      } else 
if (10
BaseType->isObjCObjectPointerType()10
)
4747
7
        /*Do nothing*/;
4748
3
      else
4749
3
        return false;
4750
120
    }
4751
120
4752
120
    if (const RecordType *Record = BaseType->getAs<RecordType>()) {
4753
84
      AddRecordMembersCompletionResults(*this, Results, S, BaseType, BaseKind,
4754
84
                                        Record->getDecl(),
4755
84
                                        std::move(AccessOpFixIt));
4756
84
    } else 
if (const auto *36
TST36
=
4757
3
                   BaseType->getAs<TemplateSpecializationType>()) {
4758
3
      TemplateName TN = TST->getTemplateName();
4759
3
      if (const auto *TD =
4760
3
              dyn_cast_or_null<ClassTemplateDecl>(TN.getAsTemplateDecl())) {
4761
3
        CXXRecordDecl *RD = TD->getTemplatedDecl();
4762
3
        AddRecordMembersCompletionResults(*this, Results, S, BaseType, BaseKind,
4763
3
                                          RD, std::move(AccessOpFixIt));
4764
3
      }
4765
33
    } else if (const auto *ICNT = BaseType->getAs<InjectedClassNameType>()) {
4766
1
      if (auto *RD = ICNT->getDecl())
4767
1
        AddRecordMembersCompletionResults(*this, Results, S, BaseType, BaseKind,
4768
1
                                          RD, std::move(AccessOpFixIt));
4769
32
    } else if (!IsArrow && 
BaseType->isObjCObjectPointerType()25
) {
4770
22
      // Objective-C property reference.
4771
22
      AddedPropertiesSet AddedProperties;
4772
22
4773
22
      if (const ObjCObjectPointerType *ObjCPtr =
4774
21
              BaseType->getAsObjCInterfacePointerType()) {
4775
21
        // Add property results based on our interface.
4776
21
        assert(ObjCPtr && "Non-NULL pointer guaranteed above!");
4777
21
        AddObjCProperties(CCContext, ObjCPtr->getInterfaceDecl(), true,
4778
21
                          /*AllowNullaryMethods=*/true, CurContext,
4779
21
                          AddedProperties, Results, IsBaseExprStatement);
4780
21
      }
4781
22
4782
22
      // Add properties from the protocols in a qualified interface.
4783
22
      for (auto *I : BaseType->getAs<ObjCObjectPointerType>()->quals())
4784
1
        AddObjCProperties(CCContext, I, true, /*AllowNullaryMethods=*/true,
4785
1
                          CurContext, AddedProperties, Results,
4786
1
                          IsBaseExprStatement, /*IsClassProperty*/ false,
4787
1
                          /*InOriginalClass*/ false);
4788
22
    } else 
if (10
(10
IsArrow10
&&
BaseType->isObjCObjectPointerType()7
) ||
4789
10
               
(3
!IsArrow3
&&
BaseType->isObjCObjectType()3
)) {
4790
7
      // Objective-C instance variable access.
4791
7
      ObjCInterfaceDecl *Class = nullptr;
4792
7
      if (const ObjCObjectPointerType *ObjCPtr =
4793
7
              BaseType->getAs<ObjCObjectPointerType>())
4794
7
        Class = ObjCPtr->getInterfaceDecl();
4795
0
      else
4796
0
        Class = BaseType->getAs<ObjCObjectType>()->getInterface();
4797
7
4798
7
      // Add all ivars from this class and its superclasses.
4799
7
      if (Class) {
4800
7
        CodeCompletionDeclConsumer Consumer(Results, Class, BaseType);
4801
7
        Results.setFilter(&ResultBuilder::IsObjCIvar);
4802
7
        LookupVisibleDecls(
4803
7
            Class, LookupMemberName, Consumer, CodeCompleter->includeGlobals(),
4804
7
            /*IncludeDependentBases=*/false, CodeCompleter->loadExternal());
4805
7
      }
4806
7
    }
4807
120
4808
120
    // FIXME: How do we cope with isa?
4809
120
    return true;
4810
120
  };
4811
117
4812
117
  Results.EnterNewScope();
4813
117
4814
117
  bool CompletionSucceded = DoCompletion(Base, IsArrow, None);
4815
117
  if (CodeCompleter->includeFixIts()) {
4816
6
    const CharSourceRange OpRange =
4817
6
        CharSourceRange::getTokenRange(OpLoc, OpLoc);
4818
6
    CompletionSucceded |= DoCompletion(
4819
6
        OtherOpBase, !IsArrow,
4820
6
        FixItHint::CreateReplacement(OpRange, IsArrow ? 
"."3
:
"->"3
));
4821
6
  }
4822
117
4823
117
  Results.ExitScope();
4824
117
4825
117
  if (!CompletionSucceded)
4826
1
    return;
4827
116
4828
116
  // Hand off the results found for code completion.
4829
116
  HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4830
116
                            Results.data(), Results.size());
4831
116
}
4832
4833
void Sema::CodeCompleteObjCClassPropertyRefExpr(Scope *S,
4834
                                                IdentifierInfo &ClassName,
4835
                                                SourceLocation ClassNameLoc,
4836
3
                                                bool IsBaseExprStatement) {
4837
3
  IdentifierInfo *ClassNamePtr = &ClassName;
4838
3
  ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(ClassNamePtr, ClassNameLoc);
4839
3
  if (!IFace)
4840
0
    return;
4841
3
  CodeCompletionContext CCContext(
4842
3
      CodeCompletionContext::CCC_ObjCPropertyAccess);
4843
3
  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4844
3
                        CodeCompleter->getCodeCompletionTUInfo(), CCContext,
4845
3
                        &ResultBuilder::IsMember);
4846
3
  Results.EnterNewScope();
4847
3
  AddedPropertiesSet AddedProperties;
4848
3
  AddObjCProperties(CCContext, IFace, true,
4849
3
                    /*AllowNullaryMethods=*/true, CurContext, AddedProperties,
4850
3
                    Results, IsBaseExprStatement,
4851
3
                    /*IsClassProperty=*/true);
4852
3
  Results.ExitScope();
4853
3
  HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4854
3
                            Results.data(), Results.size());
4855
3
}
4856
4857
13
void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) {
4858
13
  if (!CodeCompleter)
4859
0
    return;
4860
13
4861
13
  ResultBuilder::LookupFilter Filter = nullptr;
4862
13
  enum CodeCompletionContext::Kind ContextKind =
4863
13
      CodeCompletionContext::CCC_Other;
4864
13
  switch ((DeclSpec::TST)TagSpec) {
4865
13
  case DeclSpec::TST_enum:
4866
2
    Filter = &ResultBuilder::IsEnum;
4867
2
    ContextKind = CodeCompletionContext::CCC_EnumTag;
4868
2
    break;
4869
13
4870
13
  case DeclSpec::TST_union:
4871
0
    Filter = &ResultBuilder::IsUnion;
4872
0
    ContextKind = CodeCompletionContext::CCC_UnionTag;
4873
0
    break;
4874
13
4875
13
  case DeclSpec::TST_struct:
4876
11
  case DeclSpec::TST_class:
4877
11
  case DeclSpec::TST_interface:
4878
11
    Filter = &ResultBuilder::IsClassOrStruct;
4879
11
    ContextKind = CodeCompletionContext::CCC_ClassOrStructTag;
4880
11
    break;
4881
11
4882
11
  default:
4883
0
    llvm_unreachable("Unknown type specifier kind in CodeCompleteTag");
4884
13
  }
4885
13
4886
13
  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4887
13
                        CodeCompleter->getCodeCompletionTUInfo(), ContextKind);
4888
13
  CodeCompletionDeclConsumer Consumer(Results, CurContext);
4889
13
4890
13
  // First pass: look for tags.
4891
13
  Results.setFilter(Filter);
4892
13
  LookupVisibleDecls(S, LookupTagName, Consumer,
4893
13
                     CodeCompleter->includeGlobals(),
4894
13
                     CodeCompleter->loadExternal());
4895
13
4896
13
  if (CodeCompleter->includeGlobals()) {
4897
8
    // Second pass: look for nested name specifiers.
4898
8
    Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
4899
8
    LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer,
4900
8
                       CodeCompleter->includeGlobals(),
4901
8
                       CodeCompleter->loadExternal());
4902
8
  }
4903
13
4904
13
  HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4905
13
                            Results.data(), Results.size());
4906
13
}
4907
4908
static void AddTypeQualifierResults(DeclSpec &DS, ResultBuilder &Results,
4909
10
                                    const LangOptions &LangOpts) {
4910
10
  if (!(DS.getTypeQualifiers() & DeclSpec::TQ_const))
4911
9
    Results.AddResult("const");
4912
10
  if (!(DS.getTypeQualifiers() & DeclSpec::TQ_volatile))
4913
10
    Results.AddResult("volatile");
4914
10
  if (LangOpts.C99 && 
!(DS.getTypeQualifiers() & DeclSpec::TQ_restrict)0
)
4915
0
    Results.AddResult("restrict");
4916
10
  if (LangOpts.C11 && 
!(DS.getTypeQualifiers() & DeclSpec::TQ_atomic)0
)
4917
0
    Results.AddResult("_Atomic");
4918
10
  if (LangOpts.MSVCCompat && 
!(DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)0
)
4919
0
    Results.AddResult("__unaligned");
4920
10
}
4921
4922
0
void Sema::CodeCompleteTypeQualifiers(DeclSpec &DS) {
4923
0
  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4924
0
                        CodeCompleter->getCodeCompletionTUInfo(),
4925
0
                        CodeCompletionContext::CCC_TypeQualifiers);
4926
0
  Results.EnterNewScope();
4927
0
  AddTypeQualifierResults(DS, Results, LangOpts);
4928
0
  Results.ExitScope();
4929
0
  HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4930
0
                            Results.data(), Results.size());
4931
0
}
4932
4933
void Sema::CodeCompleteFunctionQualifiers(DeclSpec &DS, Declarator &D,
4934
10
                                          const VirtSpecifiers *VS) {
4935
10
  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4936
10
                        CodeCompleter->getCodeCompletionTUInfo(),
4937
10
                        CodeCompletionContext::CCC_TypeQualifiers);
4938
10
  Results.EnterNewScope();
4939
10
  AddTypeQualifierResults(DS, Results, LangOpts);
4940
10
  if (LangOpts.CPlusPlus11) {
4941
10
    Results.AddResult("noexcept");
4942
10
    if (D.getContext() == DeclaratorContext::MemberContext &&
4943
10
        
!D.isCtorOrDtor()9
&&
!D.isStaticMember()8
) {
4944
7
      if (!VS || 
!VS->isFinalSpecified()2
)
4945
6
        Results.AddResult("final");
4946
7
      if (!VS || 
!VS->isOverrideSpecified()2
)
4947
5
        Results.AddResult("override");
4948
7
    }
4949
10
  }
4950
10
  Results.ExitScope();
4951
10
  HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4952
10
                            Results.data(), Results.size());
4953
10
}
4954
4955
1
void Sema::CodeCompleteBracketDeclarator(Scope *S) {
4956
1
  CodeCompleteExpression(S, QualType(getASTContext().getSizeType()));
4957
1
}
4958
4959
10
void Sema::CodeCompleteCase(Scope *S) {
4960
10
  if (getCurFunction()->SwitchStack.empty() || !CodeCompleter)
4961
0
    return;
4962
10
4963
10
  SwitchStmt *Switch = getCurFunction()->SwitchStack.back().getPointer();
4964
10
  // Condition expression might be invalid, do not continue in this case.
4965
10
  if (!Switch->getCond())
4966
1
    return;
4967
9
  QualType type = Switch->getCond()->IgnoreImplicit()->getType();
4968
9
  if (!type->isEnumeralType()) {
4969
1
    CodeCompleteExpressionData Data(type);
4970
1
    Data.IntegralConstantExpression = true;
4971
1
    CodeCompleteExpression(S, Data);
4972
1
    return;
4973
1
  }
4974
8
4975
8
  // Code-complete the cases of a switch statement over an enumeration type
4976
8
  // by providing the list of
4977
8
  EnumDecl *Enum = type->castAs<EnumType>()->getDecl();
4978
8
  if (EnumDecl *Def = Enum->getDefinition())
4979
8
    Enum = Def;
4980
8
4981
8
  // Determine which enumerators we have already seen in the switch statement.
4982
8
  // FIXME: Ideally, we would also be able to look *past* the code-completion
4983
8
  // token, in case we are code-completing in the middle of the switch and not
4984
8
  // at the end. However, we aren't able to do so at the moment.
4985
8
  CoveredEnumerators Enumerators;
4986
13
  for (SwitchCase *SC = Switch->getSwitchCaseList(); SC;
4987
8
       
SC = SC->getNextSwitchCase()5
) {
4988
5
    CaseStmt *Case = dyn_cast<CaseStmt>(SC);
4989
5
    if (!Case)
4990
0
      continue;
4991
5
4992
5
    Expr *CaseVal = Case->getLHS()->IgnoreParenCasts();
4993
5
    if (auto *DRE = dyn_cast<DeclRefExpr>(CaseVal))
4994
5
      if (auto *Enumerator =
4995
5
              dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
4996
5
        // We look into the AST of the case statement to determine which
4997
5
        // enumerator was named. Alternatively, we could compute the value of
4998
5
        // the integral constant expression, then compare it against the
4999
5
        // values of each enumerator. However, value-based approach would not
5000
5
        // work as well with C++ templates where enumerators declared within a
5001
5
        // template are type- and value-dependent.
5002
5
        Enumerators.Seen.insert(Enumerator);
5003
5
5004
5
        // If this is a qualified-id, keep track of the nested-name-specifier
5005
5
        // so that we can reproduce it as part of code completion, e.g.,
5006
5
        //
5007
5
        //   switch (TagD.getKind()) {
5008
5
        //     case TagDecl::TK_enum:
5009
5
        //       break;
5010
5
        //     case XXX
5011
5
        //
5012
5
        // At the XXX, our completions are TagDecl::TK_union,
5013
5
        // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
5014
5
        // TK_struct, and TK_class.
5015
5
        Enumerators.SuggestedQualifier = DRE->getQualifier();
5016
5
      }
5017
5
  }
5018
8
5019
8
  // Add any enumerators that have not yet been mentioned.
5020
8
  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5021
8
                        CodeCompleter->getCodeCompletionTUInfo(),
5022
8
                        CodeCompletionContext::CCC_Expression);
5023
8
  AddEnumerators(Results, Context, Enum, CurContext, Enumerators);
5024
8
5025
8
  if (CodeCompleter->includeMacros()) {
5026
5
    AddMacroResults(PP, Results, CodeCompleter->loadExternal(), false);
5027
5
  }
5028
8
  HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
5029
8
                            Results.data(), Results.size());
5030
8
}
5031
5032
160
static bool anyNullArguments(ArrayRef<Expr *> Args) {
5033
160
  if (Args.size() && 
!Args.data()76
)
5034
0
    return true;
5035
160
5036
252
  
for (unsigned I = 0; 160
I != Args.size();
++I92
)
5037
92
    if (!Args[I])
5038
0
      return true;
5039
160
5040
160
  return false;
5041
160
}
5042
5043
typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate;
5044
5045
static void mergeCandidatesWithResults(
5046
    Sema &SemaRef, SmallVectorImpl<ResultCandidate> &Results,
5047
183
    OverloadCandidateSet &CandidateSet, SourceLocation Loc) {
5048
183
  // Sort the overload candidate set by placing the best overloads first.
5049
183
  llvm::stable_sort(CandidateSet, [&](const OverloadCandidate &X,
5050
214
                                      const OverloadCandidate &Y) {
5051
214
    return isBetterOverloadCandidate(SemaRef, X, Y, Loc,
5052
214
                                     CandidateSet.getKind());
5053
214
  });
5054
183
5055
183
  // Add the remaining viable overload candidates as code-completion results.
5056
340
  for (OverloadCandidate &Candidate : CandidateSet) {
5057
340
    if (Candidate.Function && Candidate.Function->isDeleted())
5058
1
      continue;
5059
339
    if (Candidate.Viable)
5060
260
      Results.push_back(ResultCandidate(Candidate.Function));
5061
339
  }
5062
183
}
5063
5064
/// Get the type of the Nth parameter from a given set of overload
5065
/// candidates.
5066
static QualType getParamType(Sema &SemaRef,
5067
169
                             ArrayRef<ResultCandidate> Candidates, unsigned N) {
5068
169
5069
169
  // Given the overloads 'Candidates' for a function call matching all arguments
5070
169
  // up to N, return the type of the Nth parameter if it is the same for all
5071
169
  // overload candidates.
5072
169
  QualType ParamType;
5073
252
  for (auto &Candidate : Candidates) {
5074
252
    if (const auto *FType = Candidate.getFunctionType())
5075
252
      if (const auto *Proto = dyn_cast<FunctionProtoType>(FType))
5076
251
        if (N < Proto->getNumParams()) {
5077
232
          if (ParamType.isNull())
5078
158
            ParamType = Proto->getParamType(N);
5079
74
          else if (!SemaRef.Context.hasSameUnqualifiedType(
5080
74
                       ParamType.getNonReferenceType(),
5081
74
                       Proto->getParamType(N).getNonReferenceType()))
5082
36
            // Otherwise return a default-constructed QualType.
5083
36
            return QualType();
5084
232
        }
5085
252
  }
5086
169
5087
169
  
return ParamType133
;
5088
169
}
5089
5090
static QualType
5091
ProduceSignatureHelp(Sema &SemaRef, Scope *S,
5092
                     MutableArrayRef<ResultCandidate> Candidates,
5093
183
                     unsigned CurrentArg, SourceLocation OpenParLoc) {
5094
183
  if (Candidates.empty())
5095
14
    return QualType();
5096
169
  SemaRef.CodeCompleter->ProcessOverloadCandidates(
5097
169
      SemaRef, CurrentArg, Candidates.data(), Candidates.size(), OpenPar