Coverage Report

Created: 2020-07-11 14:00

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