Coverage Report

Created: 2021-08-24 07:12

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