Coverage Report

Created: 2022-07-16 07:03

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