Coverage Report

Created: 2020-02-25 14:32

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