Coverage Report

Created: 2022-05-21 09:15

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