Coverage Report

Created: 2024-01-17 10:31

/src/llvm-project/clang/lib/Sema/SemaCodeComplete.cpp
Line
Count
Source (jump to first uncovered line)
1
//===---------------- SemaCodeComplete.cpp - Code Completion ----*- C++ -*-===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
//
9
//  This file defines the code-completion semantic actions.
10
//
11
//===----------------------------------------------------------------------===//
12
#include "clang/AST/ASTConcept.h"
13
#include "clang/AST/Decl.h"
14
#include "clang/AST/DeclBase.h"
15
#include "clang/AST/DeclCXX.h"
16
#include "clang/AST/DeclObjC.h"
17
#include "clang/AST/DeclTemplate.h"
18
#include "clang/AST/Expr.h"
19
#include "clang/AST/ExprCXX.h"
20
#include "clang/AST/ExprConcepts.h"
21
#include "clang/AST/ExprObjC.h"
22
#include "clang/AST/NestedNameSpecifier.h"
23
#include "clang/AST/QualTypeNames.h"
24
#include "clang/AST/RecursiveASTVisitor.h"
25
#include "clang/AST/Type.h"
26
#include "clang/Basic/AttributeCommonInfo.h"
27
#include "clang/Basic/CharInfo.h"
28
#include "clang/Basic/OperatorKinds.h"
29
#include "clang/Basic/Specifiers.h"
30
#include "clang/Lex/HeaderSearch.h"
31
#include "clang/Lex/MacroInfo.h"
32
#include "clang/Lex/Preprocessor.h"
33
#include "clang/Sema/CodeCompleteConsumer.h"
34
#include "clang/Sema/DeclSpec.h"
35
#include "clang/Sema/Designator.h"
36
#include "clang/Sema/Lookup.h"
37
#include "clang/Sema/Overload.h"
38
#include "clang/Sema/ParsedAttr.h"
39
#include "clang/Sema/ParsedTemplate.h"
40
#include "clang/Sema/Scope.h"
41
#include "clang/Sema/ScopeInfo.h"
42
#include "clang/Sema/Sema.h"
43
#include "clang/Sema/SemaInternal.h"
44
#include "llvm/ADT/ArrayRef.h"
45
#include "llvm/ADT/DenseSet.h"
46
#include "llvm/ADT/SmallBitVector.h"
47
#include "llvm/ADT/SmallPtrSet.h"
48
#include "llvm/ADT/SmallString.h"
49
#include "llvm/ADT/StringExtras.h"
50
#include "llvm/ADT/StringSwitch.h"
51
#include "llvm/ADT/Twine.h"
52
#include "llvm/ADT/iterator_range.h"
53
#include "llvm/Support/Casting.h"
54
#include "llvm/Support/Path.h"
55
#include "llvm/Support/raw_ostream.h"
56
57
#include <list>
58
#include <map>
59
#include <optional>
60
#include <string>
61
#include <vector>
62
63
using namespace clang;
64
using namespace sema;
65
66
namespace {
67
/// A container of code-completion results.
68
class ResultBuilder {
69
public:
70
  /// The type of a name-lookup filter, which can be provided to the
71
  /// name-lookup routines to specify which declarations should be included in
72
  /// the result set (when it returns true) and which declarations should be
73
  /// filtered out (returns false).
74
  typedef bool (ResultBuilder::*LookupFilter)(const NamedDecl *) const;
75
76
  typedef CodeCompletionResult Result;
77
78
private:
79
  /// The actual results we have found.
80
  std::vector<Result> Results;
81
82
  /// A record of all of the declarations we have found and placed
83
  /// into the result set, used to ensure that no declaration ever gets into
84
  /// the result set twice.
85
  llvm::SmallPtrSet<const Decl *, 16> AllDeclsFound;
86
87
  typedef std::pair<const NamedDecl *, unsigned> DeclIndexPair;
88
89
  /// An entry in the shadow map, which is optimized to store
90
  /// a single (declaration, index) mapping (the common case) but
91
  /// can also store a list of (declaration, index) mappings.
92
  class ShadowMapEntry {
93
    typedef SmallVector<DeclIndexPair, 4> DeclIndexPairVector;
94
95
    /// Contains either the solitary NamedDecl * or a vector
96
    /// of (declaration, index) pairs.
97
    llvm::PointerUnion<const NamedDecl *, DeclIndexPairVector *> DeclOrVector;
98
99
    /// When the entry contains a single declaration, this is
100
    /// the index associated with that entry.
101
    unsigned SingleDeclIndex = 0;
102
103
  public:
104
0
    ShadowMapEntry() = default;
105
    ShadowMapEntry(const ShadowMapEntry &) = delete;
106
0
    ShadowMapEntry(ShadowMapEntry &&Move) { *this = std::move(Move); }
107
    ShadowMapEntry &operator=(const ShadowMapEntry &) = delete;
108
0
    ShadowMapEntry &operator=(ShadowMapEntry &&Move) {
109
0
      SingleDeclIndex = Move.SingleDeclIndex;
110
0
      DeclOrVector = Move.DeclOrVector;
111
0
      Move.DeclOrVector = nullptr;
112
0
      return *this;
113
0
    }
114
115
0
    void Add(const NamedDecl *ND, unsigned Index) {
116
0
      if (DeclOrVector.isNull()) {
117
        // 0 - > 1 elements: just set the single element information.
118
0
        DeclOrVector = ND;
119
0
        SingleDeclIndex = Index;
120
0
        return;
121
0
      }
122
123
0
      if (const NamedDecl *PrevND =
124
0
              DeclOrVector.dyn_cast<const NamedDecl *>()) {
125
        // 1 -> 2 elements: create the vector of results and push in the
126
        // existing declaration.
127
0
        DeclIndexPairVector *Vec = new DeclIndexPairVector;
128
0
        Vec->push_back(DeclIndexPair(PrevND, SingleDeclIndex));
129
0
        DeclOrVector = Vec;
130
0
      }
131
132
      // Add the new element to the end of the vector.
133
0
      DeclOrVector.get<DeclIndexPairVector *>()->push_back(
134
0
          DeclIndexPair(ND, Index));
135
0
    }
136
137
0
    ~ShadowMapEntry() {
138
0
      if (DeclIndexPairVector *Vec =
139
0
              DeclOrVector.dyn_cast<DeclIndexPairVector *>()) {
140
0
        delete Vec;
141
0
        DeclOrVector = ((NamedDecl *)nullptr);
142
0
      }
143
0
    }
144
145
    // Iteration.
146
    class iterator;
147
    iterator begin() const;
148
    iterator end() const;
149
  };
150
151
  /// A mapping from declaration names to the declarations that have
152
  /// this name within a particular scope and their index within the list of
153
  /// results.
154
  typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
155
156
  /// The semantic analysis object for which results are being
157
  /// produced.
158
  Sema &SemaRef;
159
160
  /// The allocator used to allocate new code-completion strings.
161
  CodeCompletionAllocator &Allocator;
162
163
  CodeCompletionTUInfo &CCTUInfo;
164
165
  /// If non-NULL, a filter function used to remove any code-completion
166
  /// results that are not desirable.
167
  LookupFilter Filter;
168
169
  /// Whether we should allow declarations as
170
  /// nested-name-specifiers that would otherwise be filtered out.
171
  bool AllowNestedNameSpecifiers;
172
173
  /// If set, the type that we would prefer our resulting value
174
  /// declarations to have.
175
  ///
176
  /// Closely matching the preferred type gives a boost to a result's
177
  /// priority.
178
  CanQualType PreferredType;
179
180
  /// A list of shadow maps, which is used to model name hiding at
181
  /// different levels of, e.g., the inheritance hierarchy.
182
  std::list<ShadowMap> ShadowMaps;
183
184
  /// Overloaded C++ member functions found by SemaLookup.
185
  /// Used to determine when one overload is dominated by another.
186
  llvm::DenseMap<std::pair<DeclContext *, /*Name*/uintptr_t>, ShadowMapEntry>
187
      OverloadMap;
188
189
  /// If we're potentially referring to a C++ member function, the set
190
  /// of qualifiers applied to the object type.
191
  Qualifiers ObjectTypeQualifiers;
192
  /// The kind of the object expression, for rvalue/lvalue overloads.
193
  ExprValueKind ObjectKind;
194
195
  /// Whether the \p ObjectTypeQualifiers field is active.
196
  bool HasObjectTypeQualifiers;
197
198
  /// The selector that we prefer.
199
  Selector PreferredSelector;
200
201
  /// The completion context in which we are gathering results.
202
  CodeCompletionContext CompletionContext;
203
204
  /// If we are in an instance method definition, the \@implementation
205
  /// object.
206
  ObjCImplementationDecl *ObjCImplementation;
207
208
  void AdjustResultPriorityForDecl(Result &R);
209
210
  void MaybeAddConstructorResults(Result R);
211
212
public:
213
  explicit ResultBuilder(Sema &SemaRef, CodeCompletionAllocator &Allocator,
214
                         CodeCompletionTUInfo &CCTUInfo,
215
                         const CodeCompletionContext &CompletionContext,
216
                         LookupFilter Filter = nullptr)
217
      : SemaRef(SemaRef), Allocator(Allocator), CCTUInfo(CCTUInfo),
218
        Filter(Filter), AllowNestedNameSpecifiers(false),
219
        HasObjectTypeQualifiers(false), CompletionContext(CompletionContext),
220
0
        ObjCImplementation(nullptr) {
221
    // If this is an Objective-C instance method definition, dig out the
222
    // corresponding implementation.
223
0
    switch (CompletionContext.getKind()) {
224
0
    case CodeCompletionContext::CCC_Expression:
225
0
    case CodeCompletionContext::CCC_ObjCMessageReceiver:
226
0
    case CodeCompletionContext::CCC_ParenthesizedExpression:
227
0
    case CodeCompletionContext::CCC_Statement:
228
0
    case CodeCompletionContext::CCC_TopLevelOrExpression:
229
0
    case CodeCompletionContext::CCC_Recovery:
230
0
      if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl())
231
0
        if (Method->isInstanceMethod())
232
0
          if (ObjCInterfaceDecl *Interface = Method->getClassInterface())
233
0
            ObjCImplementation = Interface->getImplementation();
234
0
      break;
235
236
0
    default:
237
0
      break;
238
0
    }
239
0
  }
240
241
  /// Determine the priority for a reference to the given declaration.
242
  unsigned getBasePriority(const NamedDecl *D);
243
244
  /// Whether we should include code patterns in the completion
245
  /// results.
246
0
  bool includeCodePatterns() const {
247
0
    return SemaRef.CodeCompleter &&
248
0
           SemaRef.CodeCompleter->includeCodePatterns();
249
0
  }
250
251
  /// Set the filter used for code-completion results.
252
0
  void setFilter(LookupFilter Filter) { this->Filter = Filter; }
253
254
0
  Result *data() { return Results.empty() ? nullptr : &Results.front(); }
255
0
  unsigned size() const { return Results.size(); }
256
0
  bool empty() const { return Results.empty(); }
257
258
  /// Specify the preferred type.
259
0
  void setPreferredType(QualType T) {
260
0
    PreferredType = SemaRef.Context.getCanonicalType(T);
261
0
  }
262
263
  /// Set the cv-qualifiers on the object type, for us in filtering
264
  /// calls to member functions.
265
  ///
266
  /// When there are qualifiers in this set, they will be used to filter
267
  /// out member functions that aren't available (because there will be a
268
  /// cv-qualifier mismatch) or prefer functions with an exact qualifier
269
  /// match.
270
0
  void setObjectTypeQualifiers(Qualifiers Quals, ExprValueKind Kind) {
271
0
    ObjectTypeQualifiers = Quals;
272
0
    ObjectKind = Kind;
273
0
    HasObjectTypeQualifiers = true;
274
0
  }
275
276
  /// Set the preferred selector.
277
  ///
278
  /// When an Objective-C method declaration result is added, and that
279
  /// method's selector matches this preferred selector, we give that method
280
  /// a slight priority boost.
281
0
  void setPreferredSelector(Selector Sel) { PreferredSelector = Sel; }
282
283
  /// Retrieve the code-completion context for which results are
284
  /// being collected.
285
0
  const CodeCompletionContext &getCompletionContext() const {
286
0
    return CompletionContext;
287
0
  }
288
289
  /// Specify whether nested-name-specifiers are allowed.
290
0
  void allowNestedNameSpecifiers(bool Allow = true) {
291
0
    AllowNestedNameSpecifiers = Allow;
292
0
  }
293
294
  /// Return the semantic analysis object for which we are collecting
295
  /// code completion results.
296
0
  Sema &getSema() const { return SemaRef; }
297
298
  /// Retrieve the allocator used to allocate code completion strings.
299
0
  CodeCompletionAllocator &getAllocator() const { return Allocator; }
300
301
0
  CodeCompletionTUInfo &getCodeCompletionTUInfo() const { return CCTUInfo; }
302
303
  /// Determine whether the given declaration is at all interesting
304
  /// as a code-completion result.
305
  ///
306
  /// \param ND the declaration that we are inspecting.
307
  ///
308
  /// \param AsNestedNameSpecifier will be set true if this declaration is
309
  /// only interesting when it is a nested-name-specifier.
310
  bool isInterestingDecl(const NamedDecl *ND,
311
                         bool &AsNestedNameSpecifier) const;
312
313
  /// Decide whether or not a use of function Decl can be a call.
314
  ///
315
  /// \param ND the function declaration.
316
  ///
317
  /// \param BaseExprType the object type in a member access expression,
318
  /// if any.
319
  bool canFunctionBeCalled(const NamedDecl *ND, QualType BaseExprType) const;
320
321
  /// Decide whether or not a use of member function Decl can be a call.
322
  ///
323
  /// \param Method the function declaration.
324
  ///
325
  /// \param BaseExprType the object type in a member access expression,
326
  /// if any.
327
  bool canCxxMethodBeCalled(const CXXMethodDecl *Method,
328
                            QualType BaseExprType) const;
329
330
  /// Check whether the result is hidden by the Hiding declaration.
331
  ///
332
  /// \returns true if the result is hidden and cannot be found, false if
333
  /// the hidden result could still be found. When false, \p R may be
334
  /// modified to describe how the result can be found (e.g., via extra
335
  /// qualification).
336
  bool CheckHiddenResult(Result &R, DeclContext *CurContext,
337
                         const NamedDecl *Hiding);
338
339
  /// Add a new result to this result set (if it isn't already in one
340
  /// of the shadow maps), or replace an existing result (for, e.g., a
341
  /// redeclaration).
342
  ///
343
  /// \param R the result to add (if it is unique).
344
  ///
345
  /// \param CurContext the context in which this result will be named.
346
  void MaybeAddResult(Result R, DeclContext *CurContext = nullptr);
347
348
  /// Add a new result to this result set, where we already know
349
  /// the hiding declaration (if any).
350
  ///
351
  /// \param R the result to add (if it is unique).
352
  ///
353
  /// \param CurContext the context in which this result will be named.
354
  ///
355
  /// \param Hiding the declaration that hides the result.
356
  ///
357
  /// \param InBaseClass whether the result was found in a base
358
  /// class of the searched context.
359
  ///
360
  /// \param BaseExprType the type of expression that precedes the "." or "->"
361
  /// in a member access expression.
362
  void AddResult(Result R, DeclContext *CurContext, NamedDecl *Hiding,
363
                 bool InBaseClass, QualType BaseExprType);
364
365
  /// Add a new non-declaration result to this result set.
366
  void AddResult(Result R);
367
368
  /// Enter into a new scope.
369
  void EnterNewScope();
370
371
  /// Exit from the current scope.
372
  void ExitScope();
373
374
  /// Ignore this declaration, if it is seen again.
375
0
  void Ignore(const Decl *D) { AllDeclsFound.insert(D->getCanonicalDecl()); }
376
377
  /// Add a visited context.
378
0
  void addVisitedContext(DeclContext *Ctx) {
379
0
    CompletionContext.addVisitedContext(Ctx);
380
0
  }
381
382
  /// \name Name lookup predicates
383
  ///
384
  /// These predicates can be passed to the name lookup functions to filter the
385
  /// results of name lookup. All of the predicates have the same type, so that
386
  ///
387
  //@{
388
  bool IsOrdinaryName(const NamedDecl *ND) const;
389
  bool IsOrdinaryNonTypeName(const NamedDecl *ND) const;
390
  bool IsIntegralConstantValue(const NamedDecl *ND) const;
391
  bool IsOrdinaryNonValueName(const NamedDecl *ND) const;
392
  bool IsNestedNameSpecifier(const NamedDecl *ND) const;
393
  bool IsEnum(const NamedDecl *ND) const;
394
  bool IsClassOrStruct(const NamedDecl *ND) const;
395
  bool IsUnion(const NamedDecl *ND) const;
396
  bool IsNamespace(const NamedDecl *ND) const;
397
  bool IsNamespaceOrAlias(const NamedDecl *ND) const;
398
  bool IsType(const NamedDecl *ND) const;
399
  bool IsMember(const NamedDecl *ND) const;
400
  bool IsObjCIvar(const NamedDecl *ND) const;
401
  bool IsObjCMessageReceiver(const NamedDecl *ND) const;
402
  bool IsObjCMessageReceiverOrLambdaCapture(const NamedDecl *ND) const;
403
  bool IsObjCCollection(const NamedDecl *ND) const;
404
  bool IsImpossibleToSatisfy(const NamedDecl *ND) const;
405
  //@}
406
};
407
} // namespace
408
409
0
void PreferredTypeBuilder::enterReturn(Sema &S, SourceLocation Tok) {
410
0
  if (!Enabled)
411
0
    return;
412
0
  if (isa<BlockDecl>(S.CurContext)) {
413
0
    if (sema::BlockScopeInfo *BSI = S.getCurBlock()) {
414
0
      ComputeType = nullptr;
415
0
      Type = BSI->ReturnType;
416
0
      ExpectedLoc = Tok;
417
0
    }
418
0
  } else if (const auto *Function = dyn_cast<FunctionDecl>(S.CurContext)) {
419
0
    ComputeType = nullptr;
420
0
    Type = Function->getReturnType();
421
0
    ExpectedLoc = Tok;
422
0
  } else if (const auto *Method = dyn_cast<ObjCMethodDecl>(S.CurContext)) {
423
0
    ComputeType = nullptr;
424
0
    Type = Method->getReturnType();
425
0
    ExpectedLoc = Tok;
426
0
  }
427
0
}
428
429
327
void PreferredTypeBuilder::enterVariableInit(SourceLocation Tok, Decl *D) {
430
327
  if (!Enabled)
431
327
    return;
432
0
  auto *VD = llvm::dyn_cast_or_null<ValueDecl>(D);
433
0
  ComputeType = nullptr;
434
0
  Type = VD ? VD->getType() : QualType();
435
0
  ExpectedLoc = Tok;
436
0
}
437
438
static QualType getDesignatedType(QualType BaseType, const Designation &Desig);
439
440
void PreferredTypeBuilder::enterDesignatedInitializer(SourceLocation Tok,
441
                                                      QualType BaseType,
442
1
                                                      const Designation &D) {
443
1
  if (!Enabled)
444
1
    return;
445
0
  ComputeType = nullptr;
446
0
  Type = getDesignatedType(BaseType, D);
447
0
  ExpectedLoc = Tok;
448
0
}
449
450
void PreferredTypeBuilder::enterFunctionArgument(
451
313
    SourceLocation Tok, llvm::function_ref<QualType()> ComputeType) {
452
313
  if (!Enabled)
453
313
    return;
454
0
  this->ComputeType = ComputeType;
455
0
  Type = QualType();
456
0
  ExpectedLoc = Tok;
457
0
}
458
459
void PreferredTypeBuilder::enterParenExpr(SourceLocation Tok,
460
9
                                          SourceLocation LParLoc) {
461
9
  if (!Enabled)
462
9
    return;
463
  // expected type for parenthesized expression does not change.
464
0
  if (ExpectedLoc == LParLoc)
465
0
    ExpectedLoc = Tok;
466
0
}
467
468
static QualType getPreferredTypeOfBinaryRHS(Sema &S, Expr *LHS,
469
0
                                            tok::TokenKind Op) {
470
0
  if (!LHS)
471
0
    return QualType();
472
473
0
  QualType LHSType = LHS->getType();
474
0
  if (LHSType->isPointerType()) {
475
0
    if (Op == tok::plus || Op == tok::plusequal || Op == tok::minusequal)
476
0
      return S.getASTContext().getPointerDiffType();
477
    // Pointer difference is more common than subtracting an int from a pointer.
478
0
    if (Op == tok::minus)
479
0
      return LHSType;
480
0
  }
481
482
0
  switch (Op) {
483
  // No way to infer the type of RHS from LHS.
484
0
  case tok::comma:
485
0
    return QualType();
486
  // Prefer the type of the left operand for all of these.
487
  // Arithmetic operations.
488
0
  case tok::plus:
489
0
  case tok::plusequal:
490
0
  case tok::minus:
491
0
  case tok::minusequal:
492
0
  case tok::percent:
493
0
  case tok::percentequal:
494
0
  case tok::slash:
495
0
  case tok::slashequal:
496
0
  case tok::star:
497
0
  case tok::starequal:
498
  // Assignment.
499
0
  case tok::equal:
500
  // Comparison operators.
501
0
  case tok::equalequal:
502
0
  case tok::exclaimequal:
503
0
  case tok::less:
504
0
  case tok::lessequal:
505
0
  case tok::greater:
506
0
  case tok::greaterequal:
507
0
  case tok::spaceship:
508
0
    return LHS->getType();
509
  // Binary shifts are often overloaded, so don't try to guess those.
510
0
  case tok::greatergreater:
511
0
  case tok::greatergreaterequal:
512
0
  case tok::lessless:
513
0
  case tok::lesslessequal:
514
0
    if (LHSType->isIntegralOrEnumerationType())
515
0
      return S.getASTContext().IntTy;
516
0
    return QualType();
517
  // Logical operators, assume we want bool.
518
0
  case tok::ampamp:
519
0
  case tok::pipepipe:
520
0
  case tok::caretcaret:
521
0
    return S.getASTContext().BoolTy;
522
  // Operators often used for bit manipulation are typically used with the type
523
  // of the left argument.
524
0
  case tok::pipe:
525
0
  case tok::pipeequal:
526
0
  case tok::caret:
527
0
  case tok::caretequal:
528
0
  case tok::amp:
529
0
  case tok::ampequal:
530
0
    if (LHSType->isIntegralOrEnumerationType())
531
0
      return LHSType;
532
0
    return QualType();
533
  // RHS should be a pointer to a member of the 'LHS' type, but we can't give
534
  // any particular type here.
535
0
  case tok::periodstar:
536
0
  case tok::arrowstar:
537
0
    return QualType();
538
0
  default:
539
    // FIXME(ibiryukov): handle the missing op, re-add the assertion.
540
    // assert(false && "unhandled binary op");
541
0
    return QualType();
542
0
  }
543
0
}
544
545
/// Get preferred type for an argument of an unary expression. \p ContextType is
546
/// preferred type of the whole unary expression.
547
static QualType getPreferredTypeOfUnaryArg(Sema &S, QualType ContextType,
548
0
                                           tok::TokenKind Op) {
549
0
  switch (Op) {
550
0
  case tok::exclaim:
551
0
    return S.getASTContext().BoolTy;
552
0
  case tok::amp:
553
0
    if (!ContextType.isNull() && ContextType->isPointerType())
554
0
      return ContextType->getPointeeType();
555
0
    return QualType();
556
0
  case tok::star:
557
0
    if (ContextType.isNull())
558
0
      return QualType();
559
0
    return S.getASTContext().getPointerType(ContextType.getNonReferenceType());
560
0
  case tok::plus:
561
0
  case tok::minus:
562
0
  case tok::tilde:
563
0
  case tok::minusminus:
564
0
  case tok::plusplus:
565
0
    if (ContextType.isNull())
566
0
      return S.getASTContext().IntTy;
567
    // leave as is, these operators typically return the same type.
568
0
    return ContextType;
569
0
  case tok::kw___real:
570
0
  case tok::kw___imag:
571
0
    return QualType();
572
0
  default:
573
0
    assert(false && "unhandled unary op");
574
0
    return QualType();
575
0
  }
576
0
}
577
578
void PreferredTypeBuilder::enterBinary(Sema &S, SourceLocation Tok, Expr *LHS,
579
194
                                       tok::TokenKind Op) {
580
194
  if (!Enabled)
581
194
    return;
582
0
  ComputeType = nullptr;
583
0
  Type = getPreferredTypeOfBinaryRHS(S, LHS, Op);
584
0
  ExpectedLoc = Tok;
585
0
}
586
587
void PreferredTypeBuilder::enterMemAccess(Sema &S, SourceLocation Tok,
588
8
                                          Expr *Base) {
589
8
  if (!Enabled || !Base)
590
8
    return;
591
  // Do we have expected type for Base?
592
0
  if (ExpectedLoc != Base->getBeginLoc())
593
0
    return;
594
  // Keep the expected type, only update the location.
595
0
  ExpectedLoc = Tok;
596
0
}
597
598
void PreferredTypeBuilder::enterUnary(Sema &S, SourceLocation Tok,
599
                                      tok::TokenKind OpKind,
600
38
                                      SourceLocation OpLoc) {
601
38
  if (!Enabled)
602
38
    return;
603
0
  ComputeType = nullptr;
604
0
  Type = getPreferredTypeOfUnaryArg(S, this->get(OpLoc), OpKind);
605
0
  ExpectedLoc = Tok;
606
0
}
607
608
void PreferredTypeBuilder::enterSubscript(Sema &S, SourceLocation Tok,
609
6
                                          Expr *LHS) {
610
6
  if (!Enabled)
611
6
    return;
612
0
  ComputeType = nullptr;
613
0
  Type = S.getASTContext().IntTy;
614
0
  ExpectedLoc = Tok;
615
0
}
616
617
void PreferredTypeBuilder::enterTypeCast(SourceLocation Tok,
618
0
                                         QualType CastType) {
619
0
  if (!Enabled)
620
0
    return;
621
0
  ComputeType = nullptr;
622
0
  Type = !CastType.isNull() ? CastType.getCanonicalType() : QualType();
623
0
  ExpectedLoc = Tok;
624
0
}
625
626
0
void PreferredTypeBuilder::enterCondition(Sema &S, SourceLocation Tok) {
627
0
  if (!Enabled)
628
0
    return;
629
0
  ComputeType = nullptr;
630
0
  Type = S.getASTContext().BoolTy;
631
0
  ExpectedLoc = Tok;
632
0
}
633
634
class ResultBuilder::ShadowMapEntry::iterator {
635
  llvm::PointerUnion<const NamedDecl *, const DeclIndexPair *> DeclOrIterator;
636
  unsigned SingleDeclIndex;
637
638
public:
639
  typedef DeclIndexPair value_type;
640
  typedef value_type reference;
641
  typedef std::ptrdiff_t difference_type;
642
  typedef std::input_iterator_tag iterator_category;
643
644
  class pointer {
645
    DeclIndexPair Value;
646
647
  public:
648
0
    pointer(const DeclIndexPair &Value) : Value(Value) {}
649
650
0
    const DeclIndexPair *operator->() const { return &Value; }
651
  };
652
653
0
  iterator() : DeclOrIterator((NamedDecl *)nullptr), SingleDeclIndex(0) {}
654
655
  iterator(const NamedDecl *SingleDecl, unsigned Index)
656
0
      : DeclOrIterator(SingleDecl), SingleDeclIndex(Index) {}
657
658
  iterator(const DeclIndexPair *Iterator)
659
0
      : DeclOrIterator(Iterator), SingleDeclIndex(0) {}
660
661
0
  iterator &operator++() {
662
0
    if (DeclOrIterator.is<const NamedDecl *>()) {
663
0
      DeclOrIterator = (NamedDecl *)nullptr;
664
0
      SingleDeclIndex = 0;
665
0
      return *this;
666
0
    }
667
668
0
    const DeclIndexPair *I = DeclOrIterator.get<const DeclIndexPair *>();
669
0
    ++I;
670
0
    DeclOrIterator = I;
671
0
    return *this;
672
0
  }
673
674
  /*iterator operator++(int) {
675
    iterator tmp(*this);
676
    ++(*this);
677
    return tmp;
678
  }*/
679
680
0
  reference operator*() const {
681
0
    if (const NamedDecl *ND = DeclOrIterator.dyn_cast<const NamedDecl *>())
682
0
      return reference(ND, SingleDeclIndex);
683
684
0
    return *DeclOrIterator.get<const DeclIndexPair *>();
685
0
  }
686
687
0
  pointer operator->() const { return pointer(**this); }
688
689
0
  friend bool operator==(const iterator &X, const iterator &Y) {
690
0
    return X.DeclOrIterator.getOpaqueValue() ==
691
0
               Y.DeclOrIterator.getOpaqueValue() &&
692
0
           X.SingleDeclIndex == Y.SingleDeclIndex;
693
0
  }
694
695
0
  friend bool operator!=(const iterator &X, const iterator &Y) {
696
0
    return !(X == Y);
697
0
  }
698
};
699
700
ResultBuilder::ShadowMapEntry::iterator
701
0
ResultBuilder::ShadowMapEntry::begin() const {
702
0
  if (DeclOrVector.isNull())
703
0
    return iterator();
704
705
0
  if (const NamedDecl *ND = DeclOrVector.dyn_cast<const NamedDecl *>())
706
0
    return iterator(ND, SingleDeclIndex);
707
708
0
  return iterator(DeclOrVector.get<DeclIndexPairVector *>()->begin());
709
0
}
710
711
ResultBuilder::ShadowMapEntry::iterator
712
0
ResultBuilder::ShadowMapEntry::end() const {
713
0
  if (DeclOrVector.is<const NamedDecl *>() || DeclOrVector.isNull())
714
0
    return iterator();
715
716
0
  return iterator(DeclOrVector.get<DeclIndexPairVector *>()->end());
717
0
}
718
719
/// Compute the qualification required to get from the current context
720
/// (\p CurContext) to the target context (\p TargetContext).
721
///
722
/// \param Context the AST context in which the qualification will be used.
723
///
724
/// \param CurContext the context where an entity is being named, which is
725
/// typically based on the current scope.
726
///
727
/// \param TargetContext the context in which the named entity actually
728
/// resides.
729
///
730
/// \returns a nested name specifier that refers into the target context, or
731
/// NULL if no qualification is needed.
732
static NestedNameSpecifier *
733
getRequiredQualification(ASTContext &Context, const DeclContext *CurContext,
734
0
                         const DeclContext *TargetContext) {
735
0
  SmallVector<const DeclContext *, 4> TargetParents;
736
737
0
  for (const DeclContext *CommonAncestor = TargetContext;
738
0
       CommonAncestor && !CommonAncestor->Encloses(CurContext);
739
0
       CommonAncestor = CommonAncestor->getLookupParent()) {
740
0
    if (CommonAncestor->isTransparentContext() ||
741
0
        CommonAncestor->isFunctionOrMethod())
742
0
      continue;
743
744
0
    TargetParents.push_back(CommonAncestor);
745
0
  }
746
747
0
  NestedNameSpecifier *Result = nullptr;
748
0
  while (!TargetParents.empty()) {
749
0
    const DeclContext *Parent = TargetParents.pop_back_val();
750
751
0
    if (const auto *Namespace = dyn_cast<NamespaceDecl>(Parent)) {
752
0
      if (!Namespace->getIdentifier())
753
0
        continue;
754
755
0
      Result = NestedNameSpecifier::Create(Context, Result, Namespace);
756
0
    } else if (const auto *TD = dyn_cast<TagDecl>(Parent))
757
0
      Result = NestedNameSpecifier::Create(
758
0
          Context, Result, false, Context.getTypeDeclType(TD).getTypePtr());
759
0
  }
760
0
  return Result;
761
0
}
762
763
// Some declarations have reserved names that we don't want to ever show.
764
// Filter out names reserved for the implementation if they come from a
765
// system header.
766
0
static bool shouldIgnoreDueToReservedName(const NamedDecl *ND, Sema &SemaRef) {
767
0
  ReservedIdentifierStatus Status = ND->isReserved(SemaRef.getLangOpts());
768
  // Ignore reserved names for compiler provided decls.
769
0
  if (isReservedInAllContexts(Status) && ND->getLocation().isInvalid())
770
0
    return true;
771
772
  // For system headers ignore only double-underscore names.
773
  // This allows for system headers providing private symbols with a single
774
  // underscore.
775
0
  if (Status == ReservedIdentifierStatus::StartsWithDoubleUnderscore &&
776
0
      SemaRef.SourceMgr.isInSystemHeader(
777
0
          SemaRef.SourceMgr.getSpellingLoc(ND->getLocation())))
778
0
    return true;
779
780
0
  return false;
781
0
}
782
783
bool ResultBuilder::isInterestingDecl(const NamedDecl *ND,
784
0
                                      bool &AsNestedNameSpecifier) const {
785
0
  AsNestedNameSpecifier = false;
786
787
0
  auto *Named = ND;
788
0
  ND = ND->getUnderlyingDecl();
789
790
  // Skip unnamed entities.
791
0
  if (!ND->getDeclName())
792
0
    return false;
793
794
  // Friend declarations and declarations introduced due to friends are never
795
  // added as results.
796
0
  if (ND->getFriendObjectKind() == Decl::FOK_Undeclared)
797
0
    return false;
798
799
  // Class template (partial) specializations are never added as results.
800
0
  if (isa<ClassTemplateSpecializationDecl>(ND) ||
801
0
      isa<ClassTemplatePartialSpecializationDecl>(ND))
802
0
    return false;
803
804
  // Using declarations themselves are never added as results.
805
0
  if (isa<UsingDecl>(ND))
806
0
    return false;
807
808
0
  if (shouldIgnoreDueToReservedName(ND, SemaRef))
809
0
    return false;
810
811
0
  if (Filter == &ResultBuilder::IsNestedNameSpecifier ||
812
0
      (isa<NamespaceDecl>(ND) && Filter != &ResultBuilder::IsNamespace &&
813
0
       Filter != &ResultBuilder::IsNamespaceOrAlias && Filter != nullptr))
814
0
    AsNestedNameSpecifier = true;
815
816
  // Filter out any unwanted results.
817
0
  if (Filter && !(this->*Filter)(Named)) {
818
    // Check whether it is interesting as a nested-name-specifier.
819
0
    if (AllowNestedNameSpecifiers && SemaRef.getLangOpts().CPlusPlus &&
820
0
        IsNestedNameSpecifier(ND) &&
821
0
        (Filter != &ResultBuilder::IsMember ||
822
0
         (isa<CXXRecordDecl>(ND) &&
823
0
          cast<CXXRecordDecl>(ND)->isInjectedClassName()))) {
824
0
      AsNestedNameSpecifier = true;
825
0
      return true;
826
0
    }
827
828
0
    return false;
829
0
  }
830
  // ... then it must be interesting!
831
0
  return true;
832
0
}
833
834
bool ResultBuilder::CheckHiddenResult(Result &R, DeclContext *CurContext,
835
0
                                      const NamedDecl *Hiding) {
836
  // In C, there is no way to refer to a hidden name.
837
  // FIXME: This isn't true; we can find a tag name hidden by an ordinary
838
  // name if we introduce the tag type.
839
0
  if (!SemaRef.getLangOpts().CPlusPlus)
840
0
    return true;
841
842
0
  const DeclContext *HiddenCtx =
843
0
      R.Declaration->getDeclContext()->getRedeclContext();
844
845
  // There is no way to qualify a name declared in a function or method.
846
0
  if (HiddenCtx->isFunctionOrMethod())
847
0
    return true;
848
849
0
  if (HiddenCtx == Hiding->getDeclContext()->getRedeclContext())
850
0
    return true;
851
852
  // We can refer to the result with the appropriate qualification. Do it.
853
0
  R.Hidden = true;
854
0
  R.QualifierIsInformative = false;
855
856
0
  if (!R.Qualifier)
857
0
    R.Qualifier = getRequiredQualification(SemaRef.Context, CurContext,
858
0
                                           R.Declaration->getDeclContext());
859
0
  return false;
860
0
}
861
862
/// A simplified classification of types used to determine whether two
863
/// types are "similar enough" when adjusting priorities.
864
0
SimplifiedTypeClass clang::getSimplifiedTypeClass(CanQualType T) {
865
0
  switch (T->getTypeClass()) {
866
0
  case Type::Builtin:
867
0
    switch (cast<BuiltinType>(T)->getKind()) {
868
0
    case BuiltinType::Void:
869
0
      return STC_Void;
870
871
0
    case BuiltinType::NullPtr:
872
0
      return STC_Pointer;
873
874
0
    case BuiltinType::Overload:
875
0
    case BuiltinType::Dependent:
876
0
      return STC_Other;
877
878
0
    case BuiltinType::ObjCId:
879
0
    case BuiltinType::ObjCClass:
880
0
    case BuiltinType::ObjCSel:
881
0
      return STC_ObjectiveC;
882
883
0
    default:
884
0
      return STC_Arithmetic;
885
0
    }
886
887
0
  case Type::Complex:
888
0
    return STC_Arithmetic;
889
890
0
  case Type::Pointer:
891
0
    return STC_Pointer;
892
893
0
  case Type::BlockPointer:
894
0
    return STC_Block;
895
896
0
  case Type::LValueReference:
897
0
  case Type::RValueReference:
898
0
    return getSimplifiedTypeClass(T->getAs<ReferenceType>()->getPointeeType());
899
900
0
  case Type::ConstantArray:
901
0
  case Type::IncompleteArray:
902
0
  case Type::VariableArray:
903
0
  case Type::DependentSizedArray:
904
0
    return STC_Array;
905
906
0
  case Type::DependentSizedExtVector:
907
0
  case Type::Vector:
908
0
  case Type::ExtVector:
909
0
    return STC_Arithmetic;
910
911
0
  case Type::FunctionProto:
912
0
  case Type::FunctionNoProto:
913
0
    return STC_Function;
914
915
0
  case Type::Record:
916
0
    return STC_Record;
917
918
0
  case Type::Enum:
919
0
    return STC_Arithmetic;
920
921
0
  case Type::ObjCObject:
922
0
  case Type::ObjCInterface:
923
0
  case Type::ObjCObjectPointer:
924
0
    return STC_ObjectiveC;
925
926
0
  default:
927
0
    return STC_Other;
928
0
  }
929
0
}
930
931
/// Get the type that a given expression will have if this declaration
932
/// is used as an expression in its "typical" code-completion form.
933
0
QualType clang::getDeclUsageType(ASTContext &C, const NamedDecl *ND) {
934
0
  ND = ND->getUnderlyingDecl();
935
936
0
  if (const auto *Type = dyn_cast<TypeDecl>(ND))
937
0
    return C.getTypeDeclType(Type);
938
0
  if (const auto *Iface = dyn_cast<ObjCInterfaceDecl>(ND))
939
0
    return C.getObjCInterfaceType(Iface);
940
941
0
  QualType T;
942
0
  if (const FunctionDecl *Function = ND->getAsFunction())
943
0
    T = Function->getCallResultType();
944
0
  else if (const auto *Method = dyn_cast<ObjCMethodDecl>(ND))
945
0
    T = Method->getSendResultType();
946
0
  else if (const auto *Enumerator = dyn_cast<EnumConstantDecl>(ND))
947
0
    T = C.getTypeDeclType(cast<EnumDecl>(Enumerator->getDeclContext()));
948
0
  else if (const auto *Property = dyn_cast<ObjCPropertyDecl>(ND))
949
0
    T = Property->getType();
950
0
  else if (const auto *Value = dyn_cast<ValueDecl>(ND))
951
0
    T = Value->getType();
952
953
0
  if (T.isNull())
954
0
    return QualType();
955
956
  // Dig through references, function pointers, and block pointers to
957
  // get down to the likely type of an expression when the entity is
958
  // used.
959
0
  do {
960
0
    if (const auto *Ref = T->getAs<ReferenceType>()) {
961
0
      T = Ref->getPointeeType();
962
0
      continue;
963
0
    }
964
965
0
    if (const auto *Pointer = T->getAs<PointerType>()) {
966
0
      if (Pointer->getPointeeType()->isFunctionType()) {
967
0
        T = Pointer->getPointeeType();
968
0
        continue;
969
0
      }
970
971
0
      break;
972
0
    }
973
974
0
    if (const auto *Block = T->getAs<BlockPointerType>()) {
975
0
      T = Block->getPointeeType();
976
0
      continue;
977
0
    }
978
979
0
    if (const auto *Function = T->getAs<FunctionType>()) {
980
0
      T = Function->getReturnType();
981
0
      continue;
982
0
    }
983
984
0
    break;
985
0
  } while (true);
986
987
0
  return T;
988
0
}
989
990
0
unsigned ResultBuilder::getBasePriority(const NamedDecl *ND) {
991
0
  if (!ND)
992
0
    return CCP_Unlikely;
993
994
  // Context-based decisions.
995
0
  const DeclContext *LexicalDC = ND->getLexicalDeclContext();
996
0
  if (LexicalDC->isFunctionOrMethod()) {
997
    // _cmd is relatively rare
998
0
    if (const auto *ImplicitParam = dyn_cast<ImplicitParamDecl>(ND))
999
0
      if (ImplicitParam->getIdentifier() &&
1000
0
          ImplicitParam->getIdentifier()->isStr("_cmd"))
1001
0
        return CCP_ObjC_cmd;
1002
1003
0
    return CCP_LocalDeclaration;
1004
0
  }
1005
1006
0
  const DeclContext *DC = ND->getDeclContext()->getRedeclContext();
1007
0
  if (DC->isRecord() || isa<ObjCContainerDecl>(DC)) {
1008
    // Explicit destructor calls are very rare.
1009
0
    if (isa<CXXDestructorDecl>(ND))
1010
0
      return CCP_Unlikely;
1011
    // Explicit operator and conversion function calls are also very rare.
1012
0
    auto DeclNameKind = ND->getDeclName().getNameKind();
1013
0
    if (DeclNameKind == DeclarationName::CXXOperatorName ||
1014
0
        DeclNameKind == DeclarationName::CXXLiteralOperatorName ||
1015
0
        DeclNameKind == DeclarationName::CXXConversionFunctionName)
1016
0
      return CCP_Unlikely;
1017
0
    return CCP_MemberDeclaration;
1018
0
  }
1019
1020
  // Content-based decisions.
1021
0
  if (isa<EnumConstantDecl>(ND))
1022
0
    return CCP_Constant;
1023
1024
  // Use CCP_Type for type declarations unless we're in a statement, Objective-C
1025
  // message receiver, or parenthesized expression context. There, it's as
1026
  // likely that the user will want to write a type as other declarations.
1027
0
  if ((isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) &&
1028
0
      !(CompletionContext.getKind() == CodeCompletionContext::CCC_Statement ||
1029
0
        CompletionContext.getKind() ==
1030
0
            CodeCompletionContext::CCC_ObjCMessageReceiver ||
1031
0
        CompletionContext.getKind() ==
1032
0
            CodeCompletionContext::CCC_ParenthesizedExpression))
1033
0
    return CCP_Type;
1034
1035
0
  return CCP_Declaration;
1036
0
}
1037
1038
0
void ResultBuilder::AdjustResultPriorityForDecl(Result &R) {
1039
  // If this is an Objective-C method declaration whose selector matches our
1040
  // preferred selector, give it a priority boost.
1041
0
  if (!PreferredSelector.isNull())
1042
0
    if (const auto *Method = dyn_cast<ObjCMethodDecl>(R.Declaration))
1043
0
      if (PreferredSelector == Method->getSelector())
1044
0
        R.Priority += CCD_SelectorMatch;
1045
1046
  // If we have a preferred type, adjust the priority for results with exactly-
1047
  // matching or nearly-matching types.
1048
0
  if (!PreferredType.isNull()) {
1049
0
    QualType T = getDeclUsageType(SemaRef.Context, R.Declaration);
1050
0
    if (!T.isNull()) {
1051
0
      CanQualType TC = SemaRef.Context.getCanonicalType(T);
1052
      // Check for exactly-matching types (modulo qualifiers).
1053
0
      if (SemaRef.Context.hasSameUnqualifiedType(PreferredType, TC))
1054
0
        R.Priority /= CCF_ExactTypeMatch;
1055
      // Check for nearly-matching types, based on classification of each.
1056
0
      else if ((getSimplifiedTypeClass(PreferredType) ==
1057
0
                getSimplifiedTypeClass(TC)) &&
1058
0
               !(PreferredType->isEnumeralType() && TC->isEnumeralType()))
1059
0
        R.Priority /= CCF_SimilarTypeMatch;
1060
0
    }
1061
0
  }
1062
0
}
1063
1064
static DeclContext::lookup_result getConstructors(ASTContext &Context,
1065
0
                                                  const CXXRecordDecl *Record) {
1066
0
  QualType RecordTy = Context.getTypeDeclType(Record);
1067
0
  DeclarationName ConstructorName =
1068
0
      Context.DeclarationNames.getCXXConstructorName(
1069
0
          Context.getCanonicalType(RecordTy));
1070
0
  return Record->lookup(ConstructorName);
1071
0
}
1072
1073
0
void ResultBuilder::MaybeAddConstructorResults(Result R) {
1074
0
  if (!SemaRef.getLangOpts().CPlusPlus || !R.Declaration ||
1075
0
      !CompletionContext.wantConstructorResults())
1076
0
    return;
1077
1078
0
  const NamedDecl *D = R.Declaration;
1079
0
  const CXXRecordDecl *Record = nullptr;
1080
0
  if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D))
1081
0
    Record = ClassTemplate->getTemplatedDecl();
1082
0
  else if ((Record = dyn_cast<CXXRecordDecl>(D))) {
1083
    // Skip specializations and partial specializations.
1084
0
    if (isa<ClassTemplateSpecializationDecl>(Record))
1085
0
      return;
1086
0
  } else {
1087
    // There are no constructors here.
1088
0
    return;
1089
0
  }
1090
1091
0
  Record = Record->getDefinition();
1092
0
  if (!Record)
1093
0
    return;
1094
1095
0
  for (NamedDecl *Ctor : getConstructors(SemaRef.Context, Record)) {
1096
0
    R.Declaration = Ctor;
1097
0
    R.CursorKind = getCursorKindForDecl(R.Declaration);
1098
0
    Results.push_back(R);
1099
0
  }
1100
0
}
1101
1102
0
static bool isConstructor(const Decl *ND) {
1103
0
  if (const auto *Tmpl = dyn_cast<FunctionTemplateDecl>(ND))
1104
0
    ND = Tmpl->getTemplatedDecl();
1105
0
  return isa<CXXConstructorDecl>(ND);
1106
0
}
1107
1108
0
void ResultBuilder::MaybeAddResult(Result R, DeclContext *CurContext) {
1109
0
  assert(!ShadowMaps.empty() && "Must enter into a results scope");
1110
1111
0
  if (R.Kind != Result::RK_Declaration) {
1112
    // For non-declaration results, just add the result.
1113
0
    Results.push_back(R);
1114
0
    return;
1115
0
  }
1116
1117
  // Look through using declarations.
1118
0
  if (const UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
1119
0
    CodeCompletionResult Result(Using->getTargetDecl(),
1120
0
                                getBasePriority(Using->getTargetDecl()),
1121
0
                                R.Qualifier, false,
1122
0
                                (R.Availability == CXAvailability_Available ||
1123
0
                                 R.Availability == CXAvailability_Deprecated),
1124
0
                                std::move(R.FixIts));
1125
0
    Result.ShadowDecl = Using;
1126
0
    MaybeAddResult(Result, CurContext);
1127
0
    return;
1128
0
  }
1129
1130
0
  const Decl *CanonDecl = R.Declaration->getCanonicalDecl();
1131
0
  unsigned IDNS = CanonDecl->getIdentifierNamespace();
1132
1133
0
  bool AsNestedNameSpecifier = false;
1134
0
  if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
1135
0
    return;
1136
1137
  // C++ constructors are never found by name lookup.
1138
0
  if (isConstructor(R.Declaration))
1139
0
    return;
1140
1141
0
  ShadowMap &SMap = ShadowMaps.back();
1142
0
  ShadowMapEntry::iterator I, IEnd;
1143
0
  ShadowMap::iterator NamePos = SMap.find(R.Declaration->getDeclName());
1144
0
  if (NamePos != SMap.end()) {
1145
0
    I = NamePos->second.begin();
1146
0
    IEnd = NamePos->second.end();
1147
0
  }
1148
1149
0
  for (; I != IEnd; ++I) {
1150
0
    const NamedDecl *ND = I->first;
1151
0
    unsigned Index = I->second;
1152
0
    if (ND->getCanonicalDecl() == CanonDecl) {
1153
      // This is a redeclaration. Always pick the newer declaration.
1154
0
      Results[Index].Declaration = R.Declaration;
1155
1156
      // We're done.
1157
0
      return;
1158
0
    }
1159
0
  }
1160
1161
  // This is a new declaration in this scope. However, check whether this
1162
  // declaration name is hidden by a similarly-named declaration in an outer
1163
  // scope.
1164
0
  std::list<ShadowMap>::iterator SM, SMEnd = ShadowMaps.end();
1165
0
  --SMEnd;
1166
0
  for (SM = ShadowMaps.begin(); SM != SMEnd; ++SM) {
1167
0
    ShadowMapEntry::iterator I, IEnd;
1168
0
    ShadowMap::iterator NamePos = SM->find(R.Declaration->getDeclName());
1169
0
    if (NamePos != SM->end()) {
1170
0
      I = NamePos->second.begin();
1171
0
      IEnd = NamePos->second.end();
1172
0
    }
1173
0
    for (; I != IEnd; ++I) {
1174
      // A tag declaration does not hide a non-tag declaration.
1175
0
      if (I->first->hasTagIdentifierNamespace() &&
1176
0
          (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
1177
0
                   Decl::IDNS_LocalExtern | Decl::IDNS_ObjCProtocol)))
1178
0
        continue;
1179
1180
      // Protocols are in distinct namespaces from everything else.
1181
0
      if (((I->first->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol) ||
1182
0
           (IDNS & Decl::IDNS_ObjCProtocol)) &&
1183
0
          I->first->getIdentifierNamespace() != IDNS)
1184
0
        continue;
1185
1186
      // The newly-added result is hidden by an entry in the shadow map.
1187
0
      if (CheckHiddenResult(R, CurContext, I->first))
1188
0
        return;
1189
1190
0
      break;
1191
0
    }
1192
0
  }
1193
1194
  // Make sure that any given declaration only shows up in the result set once.
1195
0
  if (!AllDeclsFound.insert(CanonDecl).second)
1196
0
    return;
1197
1198
  // If the filter is for nested-name-specifiers, then this result starts a
1199
  // nested-name-specifier.
1200
0
  if (AsNestedNameSpecifier) {
1201
0
    R.StartsNestedNameSpecifier = true;
1202
0
    R.Priority = CCP_NestedNameSpecifier;
1203
0
  } else
1204
0
    AdjustResultPriorityForDecl(R);
1205
1206
  // If this result is supposed to have an informative qualifier, add one.
1207
0
  if (R.QualifierIsInformative && !R.Qualifier &&
1208
0
      !R.StartsNestedNameSpecifier) {
1209
0
    const DeclContext *Ctx = R.Declaration->getDeclContext();
1210
0
    if (const NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
1211
0
      R.Qualifier =
1212
0
          NestedNameSpecifier::Create(SemaRef.Context, nullptr, Namespace);
1213
0
    else if (const TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
1214
0
      R.Qualifier = NestedNameSpecifier::Create(
1215
0
          SemaRef.Context, nullptr, false,
1216
0
          SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
1217
0
    else
1218
0
      R.QualifierIsInformative = false;
1219
0
  }
1220
1221
  // Insert this result into the set of results and into the current shadow
1222
  // map.
1223
0
  SMap[R.Declaration->getDeclName()].Add(R.Declaration, Results.size());
1224
0
  Results.push_back(R);
1225
1226
0
  if (!AsNestedNameSpecifier)
1227
0
    MaybeAddConstructorResults(R);
1228
0
}
1229
1230
0
static void setInBaseClass(ResultBuilder::Result &R) {
1231
0
  R.Priority += CCD_InBaseClass;
1232
0
  R.InBaseClass = true;
1233
0
}
1234
1235
enum class OverloadCompare { BothViable, Dominates, Dominated };
1236
// Will Candidate ever be called on the object, when overloaded with Incumbent?
1237
// Returns Dominates if Candidate is always called, Dominated if Incumbent is
1238
// always called, BothViable if either may be called depending on arguments.
1239
// Precondition: must actually be overloads!
1240
static OverloadCompare compareOverloads(const CXXMethodDecl &Candidate,
1241
                                        const CXXMethodDecl &Incumbent,
1242
                                        const Qualifiers &ObjectQuals,
1243
0
                                        ExprValueKind ObjectKind) {
1244
  // Base/derived shadowing is handled elsewhere.
1245
0
  if (Candidate.getDeclContext() != Incumbent.getDeclContext())
1246
0
    return OverloadCompare::BothViable;
1247
0
  if (Candidate.isVariadic() != Incumbent.isVariadic() ||
1248
0
      Candidate.getNumParams() != Incumbent.getNumParams() ||
1249
0
      Candidate.getMinRequiredArguments() !=
1250
0
          Incumbent.getMinRequiredArguments())
1251
0
    return OverloadCompare::BothViable;
1252
0
  for (unsigned I = 0, E = Candidate.getNumParams(); I != E; ++I)
1253
0
    if (Candidate.parameters()[I]->getType().getCanonicalType() !=
1254
0
        Incumbent.parameters()[I]->getType().getCanonicalType())
1255
0
      return OverloadCompare::BothViable;
1256
0
  if (!Candidate.specific_attrs<EnableIfAttr>().empty() ||
1257
0
      !Incumbent.specific_attrs<EnableIfAttr>().empty())
1258
0
    return OverloadCompare::BothViable;
1259
  // At this point, we know calls can't pick one or the other based on
1260
  // arguments, so one of the two must win. (Or both fail, handled elsewhere).
1261
0
  RefQualifierKind CandidateRef = Candidate.getRefQualifier();
1262
0
  RefQualifierKind IncumbentRef = Incumbent.getRefQualifier();
1263
0
  if (CandidateRef != IncumbentRef) {
1264
    // If the object kind is LValue/RValue, there's one acceptable ref-qualifier
1265
    // and it can't be mixed with ref-unqualified overloads (in valid code).
1266
1267
    // For xvalue objects, we prefer the rvalue overload even if we have to
1268
    // add qualifiers (which is rare, because const&& is rare).
1269
0
    if (ObjectKind == clang::VK_XValue)
1270
0
      return CandidateRef == RQ_RValue ? OverloadCompare::Dominates
1271
0
                                       : OverloadCompare::Dominated;
1272
0
  }
1273
  // Now the ref qualifiers are the same (or we're in some invalid state).
1274
  // So make some decision based on the qualifiers.
1275
0
  Qualifiers CandidateQual = Candidate.getMethodQualifiers();
1276
0
  Qualifiers IncumbentQual = Incumbent.getMethodQualifiers();
1277
0
  bool CandidateSuperset = CandidateQual.compatiblyIncludes(IncumbentQual);
1278
0
  bool IncumbentSuperset = IncumbentQual.compatiblyIncludes(CandidateQual);
1279
0
  if (CandidateSuperset == IncumbentSuperset)
1280
0
    return OverloadCompare::BothViable;
1281
0
  return IncumbentSuperset ? OverloadCompare::Dominates
1282
0
                           : OverloadCompare::Dominated;
1283
0
}
1284
1285
bool ResultBuilder::canCxxMethodBeCalled(const CXXMethodDecl *Method,
1286
0
                                         QualType BaseExprType) const {
1287
  // Find the class scope that we're currently in.
1288
  // We could e.g. be inside a lambda, so walk up the DeclContext until we
1289
  // find a CXXMethodDecl.
1290
0
  DeclContext *CurContext = SemaRef.CurContext;
1291
0
  const auto *CurrentClassScope = [&]() -> const CXXRecordDecl * {
1292
0
    for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getParent()) {
1293
0
      const auto *CtxMethod = llvm::dyn_cast<CXXMethodDecl>(Ctx);
1294
0
      if (CtxMethod && !CtxMethod->getParent()->isLambda()) {
1295
0
        return CtxMethod->getParent();
1296
0
      }
1297
0
    }
1298
0
    return nullptr;
1299
0
  }();
1300
1301
  // If we're not inside the scope of the method's class, it can't be a call.
1302
0
  bool FunctionCanBeCall =
1303
0
      CurrentClassScope &&
1304
0
      (CurrentClassScope == Method->getParent() ||
1305
0
       CurrentClassScope->isDerivedFrom(Method->getParent()));
1306
1307
  // We skip the following calculation for exceptions if it's already true.
1308
0
  if (FunctionCanBeCall)
1309
0
    return true;
1310
1311
  // Exception: foo->FooBase::bar() or foo->Foo::bar() *is* a call.
1312
0
  if (const CXXRecordDecl *MaybeDerived =
1313
0
          BaseExprType.isNull() ? nullptr
1314
0
                                : BaseExprType->getAsCXXRecordDecl()) {
1315
0
    auto *MaybeBase = Method->getParent();
1316
0
    FunctionCanBeCall =
1317
0
        MaybeDerived == MaybeBase || MaybeDerived->isDerivedFrom(MaybeBase);
1318
0
  }
1319
1320
0
  return FunctionCanBeCall;
1321
0
}
1322
1323
bool ResultBuilder::canFunctionBeCalled(const NamedDecl *ND,
1324
0
                                        QualType BaseExprType) const {
1325
  // We apply heuristics only to CCC_Symbol:
1326
  // * CCC_{Arrow,Dot}MemberAccess reflect member access expressions:
1327
  //   f.method() and f->method(). These are always calls.
1328
  // * A qualified name to a member function may *not* be a call. We have to
1329
  //   subdivide the cases: For example, f.Base::method(), which is regarded as
1330
  //   CCC_Symbol, should be a call.
1331
  // * Non-member functions and static member functions are always considered
1332
  //   calls.
1333
0
  if (CompletionContext.getKind() == clang::CodeCompletionContext::CCC_Symbol) {
1334
0
    if (const auto *FuncTmpl = dyn_cast<FunctionTemplateDecl>(ND)) {
1335
0
      ND = FuncTmpl->getTemplatedDecl();
1336
0
    }
1337
0
    const auto *Method = dyn_cast<CXXMethodDecl>(ND);
1338
0
    if (Method && !Method->isStatic()) {
1339
0
      return canCxxMethodBeCalled(Method, BaseExprType);
1340
0
    }
1341
0
  }
1342
0
  return true;
1343
0
}
1344
1345
void ResultBuilder::AddResult(Result R, DeclContext *CurContext,
1346
                              NamedDecl *Hiding, bool InBaseClass = false,
1347
0
                              QualType BaseExprType = QualType()) {
1348
0
  if (R.Kind != Result::RK_Declaration) {
1349
    // For non-declaration results, just add the result.
1350
0
    Results.push_back(R);
1351
0
    return;
1352
0
  }
1353
1354
  // Look through using declarations.
1355
0
  if (const auto *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
1356
0
    CodeCompletionResult Result(Using->getTargetDecl(),
1357
0
                                getBasePriority(Using->getTargetDecl()),
1358
0
                                R.Qualifier, false,
1359
0
                                (R.Availability == CXAvailability_Available ||
1360
0
                                 R.Availability == CXAvailability_Deprecated),
1361
0
                                std::move(R.FixIts));
1362
0
    Result.ShadowDecl = Using;
1363
0
    AddResult(Result, CurContext, Hiding, /*InBaseClass=*/false,
1364
0
              /*BaseExprType=*/BaseExprType);
1365
0
    return;
1366
0
  }
1367
1368
0
  bool AsNestedNameSpecifier = false;
1369
0
  if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
1370
0
    return;
1371
1372
  // C++ constructors are never found by name lookup.
1373
0
  if (isConstructor(R.Declaration))
1374
0
    return;
1375
1376
0
  if (Hiding && CheckHiddenResult(R, CurContext, Hiding))
1377
0
    return;
1378
1379
  // Make sure that any given declaration only shows up in the result set once.
1380
0
  if (!AllDeclsFound.insert(R.Declaration->getCanonicalDecl()).second)
1381
0
    return;
1382
1383
  // If the filter is for nested-name-specifiers, then this result starts a
1384
  // nested-name-specifier.
1385
0
  if (AsNestedNameSpecifier) {
1386
0
    R.StartsNestedNameSpecifier = true;
1387
0
    R.Priority = CCP_NestedNameSpecifier;
1388
0
  } else if (Filter == &ResultBuilder::IsMember && !R.Qualifier &&
1389
0
             InBaseClass &&
1390
0
             isa<CXXRecordDecl>(
1391
0
                 R.Declaration->getDeclContext()->getRedeclContext()))
1392
0
    R.QualifierIsInformative = true;
1393
1394
  // If this result is supposed to have an informative qualifier, add one.
1395
0
  if (R.QualifierIsInformative && !R.Qualifier &&
1396
0
      !R.StartsNestedNameSpecifier) {
1397
0
    const DeclContext *Ctx = R.Declaration->getDeclContext();
1398
0
    if (const auto *Namespace = dyn_cast<NamespaceDecl>(Ctx))
1399
0
      R.Qualifier =
1400
0
          NestedNameSpecifier::Create(SemaRef.Context, nullptr, Namespace);
1401
0
    else if (const auto *Tag = dyn_cast<TagDecl>(Ctx))
1402
0
      R.Qualifier = NestedNameSpecifier::Create(
1403
0
          SemaRef.Context, nullptr, false,
1404
0
          SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
1405
0
    else
1406
0
      R.QualifierIsInformative = false;
1407
0
  }
1408
1409
  // Adjust the priority if this result comes from a base class.
1410
0
  if (InBaseClass)
1411
0
    setInBaseClass(R);
1412
1413
0
  AdjustResultPriorityForDecl(R);
1414
1415
0
  if (HasObjectTypeQualifiers)
1416
0
    if (const auto *Method = dyn_cast<CXXMethodDecl>(R.Declaration))
1417
0
      if (Method->isInstance()) {
1418
0
        Qualifiers MethodQuals = Method->getMethodQualifiers();
1419
0
        if (ObjectTypeQualifiers == MethodQuals)
1420
0
          R.Priority += CCD_ObjectQualifierMatch;
1421
0
        else if (ObjectTypeQualifiers - MethodQuals) {
1422
          // The method cannot be invoked, because doing so would drop
1423
          // qualifiers.
1424
0
          return;
1425
0
        }
1426
        // Detect cases where a ref-qualified method cannot be invoked.
1427
0
        switch (Method->getRefQualifier()) {
1428
0
          case RQ_LValue:
1429
0
            if (ObjectKind != VK_LValue && !MethodQuals.hasConst())
1430
0
              return;
1431
0
            break;
1432
0
          case RQ_RValue:
1433
0
            if (ObjectKind == VK_LValue)
1434
0
              return;
1435
0
            break;
1436
0
          case RQ_None:
1437
0
            break;
1438
0
        }
1439
1440
        /// Check whether this dominates another overloaded method, which should
1441
        /// be suppressed (or vice versa).
1442
        /// Motivating case is const_iterator begin() const vs iterator begin().
1443
0
        auto &OverloadSet = OverloadMap[std::make_pair(
1444
0
            CurContext, Method->getDeclName().getAsOpaqueInteger())];
1445
0
        for (const DeclIndexPair Entry : OverloadSet) {
1446
0
          Result &Incumbent = Results[Entry.second];
1447
0
          switch (compareOverloads(*Method,
1448
0
                                   *cast<CXXMethodDecl>(Incumbent.Declaration),
1449
0
                                   ObjectTypeQualifiers, ObjectKind)) {
1450
0
          case OverloadCompare::Dominates:
1451
            // Replace the dominated overload with this one.
1452
            // FIXME: if the overload dominates multiple incumbents then we
1453
            // should remove all. But two overloads is by far the common case.
1454
0
            Incumbent = std::move(R);
1455
0
            return;
1456
0
          case OverloadCompare::Dominated:
1457
            // This overload can't be called, drop it.
1458
0
            return;
1459
0
          case OverloadCompare::BothViable:
1460
0
            break;
1461
0
          }
1462
0
        }
1463
0
        OverloadSet.Add(Method, Results.size());
1464
0
      }
1465
1466
0
  R.FunctionCanBeCall = canFunctionBeCalled(R.getDeclaration(), BaseExprType);
1467
1468
  // Insert this result into the set of results.
1469
0
  Results.push_back(R);
1470
1471
0
  if (!AsNestedNameSpecifier)
1472
0
    MaybeAddConstructorResults(R);
1473
0
}
1474
1475
0
void ResultBuilder::AddResult(Result R) {
1476
0
  assert(R.Kind != Result::RK_Declaration &&
1477
0
         "Declaration results need more context");
1478
0
  Results.push_back(R);
1479
0
}
1480
1481
/// Enter into a new scope.
1482
0
void ResultBuilder::EnterNewScope() { ShadowMaps.emplace_back(); }
1483
1484
/// Exit from the current scope.
1485
0
void ResultBuilder::ExitScope() {
1486
0
  ShadowMaps.pop_back();
1487
0
}
1488
1489
/// Determines whether this given declaration will be found by
1490
/// ordinary name lookup.
1491
0
bool ResultBuilder::IsOrdinaryName(const NamedDecl *ND) const {
1492
0
  ND = ND->getUnderlyingDecl();
1493
1494
  // If name lookup finds a local extern declaration, then we are in a
1495
  // context where it behaves like an ordinary name.
1496
0
  unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_LocalExtern;
1497
0
  if (SemaRef.getLangOpts().CPlusPlus)
1498
0
    IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
1499
0
  else if (SemaRef.getLangOpts().ObjC) {
1500
0
    if (isa<ObjCIvarDecl>(ND))
1501
0
      return true;
1502
0
  }
1503
1504
0
  return ND->getIdentifierNamespace() & IDNS;
1505
0
}
1506
1507
/// Determines whether this given declaration will be found by
1508
/// ordinary name lookup but is not a type name.
1509
0
bool ResultBuilder::IsOrdinaryNonTypeName(const NamedDecl *ND) const {
1510
0
  ND = ND->getUnderlyingDecl();
1511
0
  if (isa<TypeDecl>(ND))
1512
0
    return false;
1513
  // Objective-C interfaces names are not filtered by this method because they
1514
  // can be used in a class property expression. We can still filter out
1515
  // @class declarations though.
1516
0
  if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND)) {
1517
0
    if (!ID->getDefinition())
1518
0
      return false;
1519
0
  }
1520
1521
0
  unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_LocalExtern;
1522
0
  if (SemaRef.getLangOpts().CPlusPlus)
1523
0
    IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
1524
0
  else if (SemaRef.getLangOpts().ObjC) {
1525
0
    if (isa<ObjCIvarDecl>(ND))
1526
0
      return true;
1527
0
  }
1528
1529
0
  return ND->getIdentifierNamespace() & IDNS;
1530
0
}
1531
1532
0
bool ResultBuilder::IsIntegralConstantValue(const NamedDecl *ND) const {
1533
0
  if (!IsOrdinaryNonTypeName(ND))
1534
0
    return false;
1535
1536
0
  if (const auto *VD = dyn_cast<ValueDecl>(ND->getUnderlyingDecl()))
1537
0
    if (VD->getType()->isIntegralOrEnumerationType())
1538
0
      return true;
1539
1540
0
  return false;
1541
0
}
1542
1543
/// Determines whether this given declaration will be found by
1544
/// ordinary name lookup.
1545
0
bool ResultBuilder::IsOrdinaryNonValueName(const NamedDecl *ND) const {
1546
0
  ND = ND->getUnderlyingDecl();
1547
1548
0
  unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_LocalExtern;
1549
0
  if (SemaRef.getLangOpts().CPlusPlus)
1550
0
    IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace;
1551
1552
0
  return (ND->getIdentifierNamespace() & IDNS) && !isa<ValueDecl>(ND) &&
1553
0
         !isa<FunctionTemplateDecl>(ND) && !isa<ObjCPropertyDecl>(ND);
1554
0
}
1555
1556
/// Determines whether the given declaration is suitable as the
1557
/// start of a C++ nested-name-specifier, e.g., a class or namespace.
1558
0
bool ResultBuilder::IsNestedNameSpecifier(const NamedDecl *ND) const {
1559
  // Allow us to find class templates, too.
1560
0
  if (const auto *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
1561
0
    ND = ClassTemplate->getTemplatedDecl();
1562
1563
0
  return SemaRef.isAcceptableNestedNameSpecifier(ND);
1564
0
}
1565
1566
/// Determines whether the given declaration is an enumeration.
1567
0
bool ResultBuilder::IsEnum(const NamedDecl *ND) const {
1568
0
  return isa<EnumDecl>(ND);
1569
0
}
1570
1571
/// Determines whether the given declaration is a class or struct.
1572
0
bool ResultBuilder::IsClassOrStruct(const NamedDecl *ND) const {
1573
  // Allow us to find class templates, too.
1574
0
  if (const auto *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
1575
0
    ND = ClassTemplate->getTemplatedDecl();
1576
1577
  // For purposes of this check, interfaces match too.
1578
0
  if (const auto *RD = dyn_cast<RecordDecl>(ND))
1579
0
    return RD->getTagKind() == TagTypeKind::Class ||
1580
0
           RD->getTagKind() == TagTypeKind::Struct ||
1581
0
           RD->getTagKind() == TagTypeKind::Interface;
1582
1583
0
  return false;
1584
0
}
1585
1586
/// Determines whether the given declaration is a union.
1587
0
bool ResultBuilder::IsUnion(const NamedDecl *ND) const {
1588
  // Allow us to find class templates, too.
1589
0
  if (const auto *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
1590
0
    ND = ClassTemplate->getTemplatedDecl();
1591
1592
0
  if (const auto *RD = dyn_cast<RecordDecl>(ND))
1593
0
    return RD->getTagKind() == TagTypeKind::Union;
1594
1595
0
  return false;
1596
0
}
1597
1598
/// Determines whether the given declaration is a namespace.
1599
0
bool ResultBuilder::IsNamespace(const NamedDecl *ND) const {
1600
0
  return isa<NamespaceDecl>(ND);
1601
0
}
1602
1603
/// Determines whether the given declaration is a namespace or
1604
/// namespace alias.
1605
0
bool ResultBuilder::IsNamespaceOrAlias(const NamedDecl *ND) const {
1606
0
  return isa<NamespaceDecl>(ND->getUnderlyingDecl());
1607
0
}
1608
1609
/// Determines whether the given declaration is a type.
1610
0
bool ResultBuilder::IsType(const NamedDecl *ND) const {
1611
0
  ND = ND->getUnderlyingDecl();
1612
0
  return isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
1613
0
}
1614
1615
/// Determines which members of a class should be visible via
1616
/// "." or "->".  Only value declarations, nested name specifiers, and
1617
/// using declarations thereof should show up.
1618
0
bool ResultBuilder::IsMember(const NamedDecl *ND) const {
1619
0
  ND = ND->getUnderlyingDecl();
1620
0
  return isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND) ||
1621
0
         isa<ObjCPropertyDecl>(ND);
1622
0
}
1623
1624
0
static bool isObjCReceiverType(ASTContext &C, QualType T) {
1625
0
  T = C.getCanonicalType(T);
1626
0
  switch (T->getTypeClass()) {
1627
0
  case Type::ObjCObject:
1628
0
  case Type::ObjCInterface:
1629
0
  case Type::ObjCObjectPointer:
1630
0
    return true;
1631
1632
0
  case Type::Builtin:
1633
0
    switch (cast<BuiltinType>(T)->getKind()) {
1634
0
    case BuiltinType::ObjCId:
1635
0
    case BuiltinType::ObjCClass:
1636
0
    case BuiltinType::ObjCSel:
1637
0
      return true;
1638
1639
0
    default:
1640
0
      break;
1641
0
    }
1642
0
    return false;
1643
1644
0
  default:
1645
0
    break;
1646
0
  }
1647
1648
0
  if (!C.getLangOpts().CPlusPlus)
1649
0
    return false;
1650
1651
  // FIXME: We could perform more analysis here to determine whether a
1652
  // particular class type has any conversions to Objective-C types. For now,
1653
  // just accept all class types.
1654
0
  return T->isDependentType() || T->isRecordType();
1655
0
}
1656
1657
0
bool ResultBuilder::IsObjCMessageReceiver(const NamedDecl *ND) const {
1658
0
  QualType T = getDeclUsageType(SemaRef.Context, ND);
1659
0
  if (T.isNull())
1660
0
    return false;
1661
1662
0
  T = SemaRef.Context.getBaseElementType(T);
1663
0
  return isObjCReceiverType(SemaRef.Context, T);
1664
0
}
1665
1666
bool ResultBuilder::IsObjCMessageReceiverOrLambdaCapture(
1667
0
    const NamedDecl *ND) const {
1668
0
  if (IsObjCMessageReceiver(ND))
1669
0
    return true;
1670
1671
0
  const auto *Var = dyn_cast<VarDecl>(ND);
1672
0
  if (!Var)
1673
0
    return false;
1674
1675
0
  return Var->hasLocalStorage() && !Var->hasAttr<BlocksAttr>();
1676
0
}
1677
1678
0
bool ResultBuilder::IsObjCCollection(const NamedDecl *ND) const {
1679
0
  if ((SemaRef.getLangOpts().CPlusPlus && !IsOrdinaryName(ND)) ||
1680
0
      (!SemaRef.getLangOpts().CPlusPlus && !IsOrdinaryNonTypeName(ND)))
1681
0
    return false;
1682
1683
0
  QualType T = getDeclUsageType(SemaRef.Context, ND);
1684
0
  if (T.isNull())
1685
0
    return false;
1686
1687
0
  T = SemaRef.Context.getBaseElementType(T);
1688
0
  return T->isObjCObjectType() || T->isObjCObjectPointerType() ||
1689
0
         T->isObjCIdType() ||
1690
0
         (SemaRef.getLangOpts().CPlusPlus && T->isRecordType());
1691
0
}
1692
1693
0
bool ResultBuilder::IsImpossibleToSatisfy(const NamedDecl *ND) const {
1694
0
  return false;
1695
0
}
1696
1697
/// Determines whether the given declaration is an Objective-C
1698
/// instance variable.
1699
0
bool ResultBuilder::IsObjCIvar(const NamedDecl *ND) const {
1700
0
  return isa<ObjCIvarDecl>(ND);
1701
0
}
1702
1703
namespace {
1704
1705
/// Visible declaration consumer that adds a code-completion result
1706
/// for each visible declaration.
1707
class CodeCompletionDeclConsumer : public VisibleDeclConsumer {
1708
  ResultBuilder &Results;
1709
  DeclContext *InitialLookupCtx;
1710
  // NamingClass and BaseType are used for access-checking. See
1711
  // Sema::IsSimplyAccessible for details.
1712
  CXXRecordDecl *NamingClass;
1713
  QualType BaseType;
1714
  std::vector<FixItHint> FixIts;
1715
1716
public:
1717
  CodeCompletionDeclConsumer(
1718
      ResultBuilder &Results, DeclContext *InitialLookupCtx,
1719
      QualType BaseType = QualType(),
1720
      std::vector<FixItHint> FixIts = std::vector<FixItHint>())
1721
      : Results(Results), InitialLookupCtx(InitialLookupCtx),
1722
0
        FixIts(std::move(FixIts)) {
1723
0
    NamingClass = llvm::dyn_cast<CXXRecordDecl>(InitialLookupCtx);
1724
    // If BaseType was not provided explicitly, emulate implicit 'this->'.
1725
0
    if (BaseType.isNull()) {
1726
0
      auto ThisType = Results.getSema().getCurrentThisType();
1727
0
      if (!ThisType.isNull()) {
1728
0
        assert(ThisType->isPointerType());
1729
0
        BaseType = ThisType->getPointeeType();
1730
0
        if (!NamingClass)
1731
0
          NamingClass = BaseType->getAsCXXRecordDecl();
1732
0
      }
1733
0
    }
1734
0
    this->BaseType = BaseType;
1735
0
  }
1736
1737
  void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
1738
0
                 bool InBaseClass) override {
1739
0
    ResultBuilder::Result Result(ND, Results.getBasePriority(ND), nullptr,
1740
0
                                 false, IsAccessible(ND, Ctx), FixIts);
1741
0
    Results.AddResult(Result, InitialLookupCtx, Hiding, InBaseClass, BaseType);
1742
0
  }
1743
1744
0
  void EnteredContext(DeclContext *Ctx) override {
1745
0
    Results.addVisitedContext(Ctx);
1746
0
  }
1747
1748
private:
1749
0
  bool IsAccessible(NamedDecl *ND, DeclContext *Ctx) {
1750
    // Naming class to use for access check. In most cases it was provided
1751
    // explicitly (e.g. member access (lhs.foo) or qualified lookup (X::)),
1752
    // for unqualified lookup we fallback to the \p Ctx in which we found the
1753
    // member.
1754
0
    auto *NamingClass = this->NamingClass;
1755
0
    QualType BaseType = this->BaseType;
1756
0
    if (auto *Cls = llvm::dyn_cast_or_null<CXXRecordDecl>(Ctx)) {
1757
0
      if (!NamingClass)
1758
0
        NamingClass = Cls;
1759
      // When we emulate implicit 'this->' in an unqualified lookup, we might
1760
      // end up with an invalid naming class. In that case, we avoid emulating
1761
      // 'this->' qualifier to satisfy preconditions of the access checking.
1762
0
      if (NamingClass->getCanonicalDecl() != Cls->getCanonicalDecl() &&
1763
0
          !NamingClass->isDerivedFrom(Cls)) {
1764
0
        NamingClass = Cls;
1765
0
        BaseType = QualType();
1766
0
      }
1767
0
    } else {
1768
      // The decl was found outside the C++ class, so only ObjC access checks
1769
      // apply. Those do not rely on NamingClass and BaseType, so we clear them
1770
      // out.
1771
0
      NamingClass = nullptr;
1772
0
      BaseType = QualType();
1773
0
    }
1774
0
    return Results.getSema().IsSimplyAccessible(ND, NamingClass, BaseType);
1775
0
  }
1776
};
1777
} // namespace
1778
1779
/// Add type specifiers for the current language as keyword results.
1780
static void AddTypeSpecifierResults(const LangOptions &LangOpts,
1781
0
                                    ResultBuilder &Results) {
1782
0
  typedef CodeCompletionResult Result;
1783
0
  Results.AddResult(Result("short", CCP_Type));
1784
0
  Results.AddResult(Result("long", CCP_Type));
1785
0
  Results.AddResult(Result("signed", CCP_Type));
1786
0
  Results.AddResult(Result("unsigned", CCP_Type));
1787
0
  Results.AddResult(Result("void", CCP_Type));
1788
0
  Results.AddResult(Result("char", CCP_Type));
1789
0
  Results.AddResult(Result("int", CCP_Type));
1790
0
  Results.AddResult(Result("float", CCP_Type));
1791
0
  Results.AddResult(Result("double", CCP_Type));
1792
0
  Results.AddResult(Result("enum", CCP_Type));
1793
0
  Results.AddResult(Result("struct", CCP_Type));
1794
0
  Results.AddResult(Result("union", CCP_Type));
1795
0
  Results.AddResult(Result("const", CCP_Type));
1796
0
  Results.AddResult(Result("volatile", CCP_Type));
1797
1798
0
  if (LangOpts.C99) {
1799
    // C99-specific
1800
0
    Results.AddResult(Result("_Complex", CCP_Type));
1801
0
    Results.AddResult(Result("_Imaginary", CCP_Type));
1802
0
    Results.AddResult(Result("_Bool", CCP_Type));
1803
0
    Results.AddResult(Result("restrict", CCP_Type));
1804
0
  }
1805
1806
0
  CodeCompletionBuilder Builder(Results.getAllocator(),
1807
0
                                Results.getCodeCompletionTUInfo());
1808
0
  if (LangOpts.CPlusPlus) {
1809
    // C++-specific
1810
0
    Results.AddResult(
1811
0
        Result("bool", CCP_Type + (LangOpts.ObjC ? CCD_bool_in_ObjC : 0)));
1812
0
    Results.AddResult(Result("class", CCP_Type));
1813
0
    Results.AddResult(Result("wchar_t", CCP_Type));
1814
1815
    // typename name
1816
0
    Builder.AddTypedTextChunk("typename");
1817
0
    Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1818
0
    Builder.AddPlaceholderChunk("name");
1819
0
    Results.AddResult(Result(Builder.TakeString()));
1820
1821
0
    if (LangOpts.CPlusPlus11) {
1822
0
      Results.AddResult(Result("auto", CCP_Type));
1823
0
      Results.AddResult(Result("char16_t", CCP_Type));
1824
0
      Results.AddResult(Result("char32_t", CCP_Type));
1825
1826
0
      Builder.AddTypedTextChunk("decltype");
1827
0
      Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1828
0
      Builder.AddPlaceholderChunk("expression");
1829
0
      Builder.AddChunk(CodeCompletionString::CK_RightParen);
1830
0
      Results.AddResult(Result(Builder.TakeString()));
1831
0
    }
1832
0
  } else
1833
0
    Results.AddResult(Result("__auto_type", CCP_Type));
1834
1835
  // GNU keywords
1836
0
  if (LangOpts.GNUKeywords) {
1837
    // FIXME: Enable when we actually support decimal floating point.
1838
    //    Results.AddResult(Result("_Decimal32"));
1839
    //    Results.AddResult(Result("_Decimal64"));
1840
    //    Results.AddResult(Result("_Decimal128"));
1841
1842
0
    Builder.AddTypedTextChunk("typeof");
1843
0
    Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1844
0
    Builder.AddPlaceholderChunk("expression");
1845
0
    Results.AddResult(Result(Builder.TakeString()));
1846
1847
0
    Builder.AddTypedTextChunk("typeof");
1848
0
    Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1849
0
    Builder.AddPlaceholderChunk("type");
1850
0
    Builder.AddChunk(CodeCompletionString::CK_RightParen);
1851
0
    Results.AddResult(Result(Builder.TakeString()));
1852
0
  }
1853
1854
  // Nullability
1855
0
  Results.AddResult(Result("_Nonnull", CCP_Type));
1856
0
  Results.AddResult(Result("_Null_unspecified", CCP_Type));
1857
0
  Results.AddResult(Result("_Nullable", CCP_Type));
1858
0
}
1859
1860
static void AddStorageSpecifiers(Sema::ParserCompletionContext CCC,
1861
                                 const LangOptions &LangOpts,
1862
0
                                 ResultBuilder &Results) {
1863
0
  typedef CodeCompletionResult Result;
1864
  // Note: we don't suggest either "auto" or "register", because both
1865
  // are pointless as storage specifiers. Elsewhere, we suggest "auto"
1866
  // in C++0x as a type specifier.
1867
0
  Results.AddResult(Result("extern"));
1868
0
  Results.AddResult(Result("static"));
1869
1870
0
  if (LangOpts.CPlusPlus11) {
1871
0
    CodeCompletionAllocator &Allocator = Results.getAllocator();
1872
0
    CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
1873
1874
    // alignas
1875
0
    Builder.AddTypedTextChunk("alignas");
1876
0
    Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1877
0
    Builder.AddPlaceholderChunk("expression");
1878
0
    Builder.AddChunk(CodeCompletionString::CK_RightParen);
1879
0
    Results.AddResult(Result(Builder.TakeString()));
1880
1881
0
    Results.AddResult(Result("constexpr"));
1882
0
    Results.AddResult(Result("thread_local"));
1883
0
  }
1884
0
}
1885
1886
static void AddFunctionSpecifiers(Sema::ParserCompletionContext CCC,
1887
                                  const LangOptions &LangOpts,
1888
0
                                  ResultBuilder &Results) {
1889
0
  typedef CodeCompletionResult Result;
1890
0
  switch (CCC) {
1891
0
  case Sema::PCC_Class:
1892
0
  case Sema::PCC_MemberTemplate:
1893
0
    if (LangOpts.CPlusPlus) {
1894
0
      Results.AddResult(Result("explicit"));
1895
0
      Results.AddResult(Result("friend"));
1896
0
      Results.AddResult(Result("mutable"));
1897
0
      Results.AddResult(Result("virtual"));
1898
0
    }
1899
0
    [[fallthrough]];
1900
1901
0
  case Sema::PCC_ObjCInterface:
1902
0
  case Sema::PCC_ObjCImplementation:
1903
0
  case Sema::PCC_Namespace:
1904
0
  case Sema::PCC_Template:
1905
0
    if (LangOpts.CPlusPlus || LangOpts.C99)
1906
0
      Results.AddResult(Result("inline"));
1907
0
    break;
1908
1909
0
  case Sema::PCC_ObjCInstanceVariableList:
1910
0
  case Sema::PCC_Expression:
1911
0
  case Sema::PCC_Statement:
1912
0
  case Sema::PCC_TopLevelOrExpression:
1913
0
  case Sema::PCC_ForInit:
1914
0
  case Sema::PCC_Condition:
1915
0
  case Sema::PCC_RecoveryInFunction:
1916
0
  case Sema::PCC_Type:
1917
0
  case Sema::PCC_ParenthesizedExpression:
1918
0
  case Sema::PCC_LocalDeclarationSpecifiers:
1919
0
    break;
1920
0
  }
1921
0
}
1922
1923
static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt);
1924
static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt);
1925
static void AddObjCVisibilityResults(const LangOptions &LangOpts,
1926
                                     ResultBuilder &Results, bool NeedAt);
1927
static void AddObjCImplementationResults(const LangOptions &LangOpts,
1928
                                         ResultBuilder &Results, bool NeedAt);
1929
static void AddObjCInterfaceResults(const LangOptions &LangOpts,
1930
                                    ResultBuilder &Results, bool NeedAt);
1931
static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt);
1932
1933
0
static void AddTypedefResult(ResultBuilder &Results) {
1934
0
  CodeCompletionBuilder Builder(Results.getAllocator(),
1935
0
                                Results.getCodeCompletionTUInfo());
1936
0
  Builder.AddTypedTextChunk("typedef");
1937
0
  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1938
0
  Builder.AddPlaceholderChunk("type");
1939
0
  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1940
0
  Builder.AddPlaceholderChunk("name");
1941
0
  Builder.AddChunk(CodeCompletionString::CK_SemiColon);
1942
0
  Results.AddResult(CodeCompletionResult(Builder.TakeString()));
1943
0
}
1944
1945
// using name = type
1946
static void AddUsingAliasResult(CodeCompletionBuilder &Builder,
1947
0
                                ResultBuilder &Results) {
1948
0
  Builder.AddTypedTextChunk("using");
1949
0
  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1950
0
  Builder.AddPlaceholderChunk("name");
1951
0
  Builder.AddChunk(CodeCompletionString::CK_Equal);
1952
0
  Builder.AddPlaceholderChunk("type");
1953
0
  Builder.AddChunk(CodeCompletionString::CK_SemiColon);
1954
0
  Results.AddResult(CodeCompletionResult(Builder.TakeString()));
1955
0
}
1956
1957
static bool WantTypesInContext(Sema::ParserCompletionContext CCC,
1958
0
                               const LangOptions &LangOpts) {
1959
0
  switch (CCC) {
1960
0
  case Sema::PCC_Namespace:
1961
0
  case Sema::PCC_Class:
1962
0
  case Sema::PCC_ObjCInstanceVariableList:
1963
0
  case Sema::PCC_Template:
1964
0
  case Sema::PCC_MemberTemplate:
1965
0
  case Sema::PCC_Statement:
1966
0
  case Sema::PCC_RecoveryInFunction:
1967
0
  case Sema::PCC_Type:
1968
0
  case Sema::PCC_ParenthesizedExpression:
1969
0
  case Sema::PCC_LocalDeclarationSpecifiers:
1970
0
  case Sema::PCC_TopLevelOrExpression:
1971
0
    return true;
1972
1973
0
  case Sema::PCC_Expression:
1974
0
  case Sema::PCC_Condition:
1975
0
    return LangOpts.CPlusPlus;
1976
1977
0
  case Sema::PCC_ObjCInterface:
1978
0
  case Sema::PCC_ObjCImplementation:
1979
0
    return false;
1980
1981
0
  case Sema::PCC_ForInit:
1982
0
    return LangOpts.CPlusPlus || LangOpts.ObjC || LangOpts.C99;
1983
0
  }
1984
1985
0
  llvm_unreachable("Invalid ParserCompletionContext!");
1986
0
}
1987
1988
static PrintingPolicy getCompletionPrintingPolicy(const ASTContext &Context,
1989
0
                                                  const Preprocessor &PP) {
1990
0
  PrintingPolicy Policy = Sema::getPrintingPolicy(Context, PP);
1991
0
  Policy.AnonymousTagLocations = false;
1992
0
  Policy.SuppressStrongLifetime = true;
1993
0
  Policy.SuppressUnwrittenScope = true;
1994
0
  Policy.SuppressScope = true;
1995
0
  Policy.CleanUglifiedParameters = true;
1996
0
  return Policy;
1997
0
}
1998
1999
/// Retrieve a printing policy suitable for code completion.
2000
0
static PrintingPolicy getCompletionPrintingPolicy(Sema &S) {
2001
0
  return getCompletionPrintingPolicy(S.Context, S.PP);
2002
0
}
2003
2004
/// Retrieve the string representation of the given type as a string
2005
/// that has the appropriate lifetime for code completion.
2006
///
2007
/// This routine provides a fast path where we provide constant strings for
2008
/// common type names.
2009
static const char *GetCompletionTypeString(QualType T, ASTContext &Context,
2010
                                           const PrintingPolicy &Policy,
2011
0
                                           CodeCompletionAllocator &Allocator) {
2012
0
  if (!T.getLocalQualifiers()) {
2013
    // Built-in type names are constant strings.
2014
0
    if (const BuiltinType *BT = dyn_cast<BuiltinType>(T))
2015
0
      return BT->getNameAsCString(Policy);
2016
2017
    // Anonymous tag types are constant strings.
2018
0
    if (const TagType *TagT = dyn_cast<TagType>(T))
2019
0
      if (TagDecl *Tag = TagT->getDecl())
2020
0
        if (!Tag->hasNameForLinkage()) {
2021
0
          switch (Tag->getTagKind()) {
2022
0
          case TagTypeKind::Struct:
2023
0
            return "struct <anonymous>";
2024
0
          case TagTypeKind::Interface:
2025
0
            return "__interface <anonymous>";
2026
0
          case TagTypeKind::Class:
2027
0
            return "class <anonymous>";
2028
0
          case TagTypeKind::Union:
2029
0
            return "union <anonymous>";
2030
0
          case TagTypeKind::Enum:
2031
0
            return "enum <anonymous>";
2032
0
          }
2033
0
        }
2034
0
  }
2035
2036
  // Slow path: format the type as a string.
2037
0
  std::string Result;
2038
0
  T.getAsStringInternal(Result, Policy);
2039
0
  return Allocator.CopyString(Result);
2040
0
}
2041
2042
/// Add a completion for "this", if we're in a member function.
2043
0
static void addThisCompletion(Sema &S, ResultBuilder &Results) {
2044
0
  QualType ThisTy = S.getCurrentThisType();
2045
0
  if (ThisTy.isNull())
2046
0
    return;
2047
2048
0
  CodeCompletionAllocator &Allocator = Results.getAllocator();
2049
0
  CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
2050
0
  PrintingPolicy Policy = getCompletionPrintingPolicy(S);
2051
0
  Builder.AddResultTypeChunk(
2052
0
      GetCompletionTypeString(ThisTy, S.Context, Policy, Allocator));
2053
0
  Builder.AddTypedTextChunk("this");
2054
0
  Results.AddResult(CodeCompletionResult(Builder.TakeString()));
2055
0
}
2056
2057
static void AddStaticAssertResult(CodeCompletionBuilder &Builder,
2058
                                  ResultBuilder &Results,
2059
0
                                  const LangOptions &LangOpts) {
2060
0
  if (!LangOpts.CPlusPlus11)
2061
0
    return;
2062
2063
0
  Builder.AddTypedTextChunk("static_assert");
2064
0
  Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2065
0
  Builder.AddPlaceholderChunk("expression");
2066
0
  Builder.AddChunk(CodeCompletionString::CK_Comma);
2067
0
  Builder.AddPlaceholderChunk("message");
2068
0
  Builder.AddChunk(CodeCompletionString::CK_RightParen);
2069
0
  Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2070
0
  Results.AddResult(CodeCompletionResult(Builder.TakeString()));
2071
0
}
2072
2073
static void AddOverrideResults(ResultBuilder &Results,
2074
                               const CodeCompletionContext &CCContext,
2075
0
                               CodeCompletionBuilder &Builder) {
2076
0
  Sema &S = Results.getSema();
2077
0
  const auto *CR = llvm::dyn_cast<CXXRecordDecl>(S.CurContext);
2078
  // If not inside a class/struct/union return empty.
2079
0
  if (!CR)
2080
0
    return;
2081
  // First store overrides within current class.
2082
  // These are stored by name to make querying fast in the later step.
2083
0
  llvm::StringMap<std::vector<FunctionDecl *>> Overrides;
2084
0
  for (auto *Method : CR->methods()) {
2085
0
    if (!Method->isVirtual() || !Method->getIdentifier())
2086
0
      continue;
2087
0
    Overrides[Method->getName()].push_back(Method);
2088
0
  }
2089
2090
0
  for (const auto &Base : CR->bases()) {
2091
0
    const auto *BR = Base.getType().getTypePtr()->getAsCXXRecordDecl();
2092
0
    if (!BR)
2093
0
      continue;
2094
0
    for (auto *Method : BR->methods()) {
2095
0
      if (!Method->isVirtual() || !Method->getIdentifier())
2096
0
        continue;
2097
0
      const auto it = Overrides.find(Method->getName());
2098
0
      bool IsOverriden = false;
2099
0
      if (it != Overrides.end()) {
2100
0
        for (auto *MD : it->second) {
2101
          // If the method in current body is not an overload of this virtual
2102
          // function, then it overrides this one.
2103
0
          if (!S.IsOverload(MD, Method, false)) {
2104
0
            IsOverriden = true;
2105
0
            break;
2106
0
          }
2107
0
        }
2108
0
      }
2109
0
      if (!IsOverriden) {
2110
        // Generates a new CodeCompletionResult by taking this function and
2111
        // converting it into an override declaration with only one chunk in the
2112
        // final CodeCompletionString as a TypedTextChunk.
2113
0
        std::string OverrideSignature;
2114
0
        llvm::raw_string_ostream OS(OverrideSignature);
2115
0
        CodeCompletionResult CCR(Method, 0);
2116
0
        PrintingPolicy Policy =
2117
0
            getCompletionPrintingPolicy(S.getASTContext(), S.getPreprocessor());
2118
0
        auto *CCS = CCR.createCodeCompletionStringForOverride(
2119
0
            S.getPreprocessor(), S.getASTContext(), Builder,
2120
0
            /*IncludeBriefComments=*/false, CCContext, Policy);
2121
0
        Results.AddResult(CodeCompletionResult(CCS, Method, CCP_CodePattern));
2122
0
      }
2123
0
    }
2124
0
  }
2125
0
}
2126
2127
/// Add language constructs that show up for "ordinary" names.
2128
static void AddOrdinaryNameResults(Sema::ParserCompletionContext CCC, Scope *S,
2129
0
                                   Sema &SemaRef, ResultBuilder &Results) {
2130
0
  CodeCompletionAllocator &Allocator = Results.getAllocator();
2131
0
  CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
2132
2133
0
  typedef CodeCompletionResult Result;
2134
0
  switch (CCC) {
2135
0
  case Sema::PCC_Namespace:
2136
0
    if (SemaRef.getLangOpts().CPlusPlus) {
2137
0
      if (Results.includeCodePatterns()) {
2138
        // namespace <identifier> { declarations }
2139
0
        Builder.AddTypedTextChunk("namespace");
2140
0
        Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2141
0
        Builder.AddPlaceholderChunk("identifier");
2142
0
        Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2143
0
        Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
2144
0
        Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2145
0
        Builder.AddPlaceholderChunk("declarations");
2146
0
        Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2147
0
        Builder.AddChunk(CodeCompletionString::CK_RightBrace);
2148
0
        Results.AddResult(Result(Builder.TakeString()));
2149
0
      }
2150
2151
      // namespace identifier = identifier ;
2152
0
      Builder.AddTypedTextChunk("namespace");
2153
0
      Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2154
0
      Builder.AddPlaceholderChunk("name");
2155
0
      Builder.AddChunk(CodeCompletionString::CK_Equal);
2156
0
      Builder.AddPlaceholderChunk("namespace");
2157
0
      Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2158
0
      Results.AddResult(Result(Builder.TakeString()));
2159
2160
      // Using directives
2161
0
      Builder.AddTypedTextChunk("using namespace");
2162
0
      Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2163
0
      Builder.AddPlaceholderChunk("identifier");
2164
0
      Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2165
0
      Results.AddResult(Result(Builder.TakeString()));
2166
2167
      // asm(string-literal)
2168
0
      Builder.AddTypedTextChunk("asm");
2169
0
      Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2170
0
      Builder.AddPlaceholderChunk("string-literal");
2171
0
      Builder.AddChunk(CodeCompletionString::CK_RightParen);
2172
0
      Results.AddResult(Result(Builder.TakeString()));
2173
2174
0
      if (Results.includeCodePatterns()) {
2175
        // Explicit template instantiation
2176
0
        Builder.AddTypedTextChunk("template");
2177
0
        Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2178
0
        Builder.AddPlaceholderChunk("declaration");
2179
0
        Results.AddResult(Result(Builder.TakeString()));
2180
0
      } else {
2181
0
        Results.AddResult(Result("template", CodeCompletionResult::RK_Keyword));
2182
0
      }
2183
0
    }
2184
2185
0
    if (SemaRef.getLangOpts().ObjC)
2186
0
      AddObjCTopLevelResults(Results, true);
2187
2188
0
    AddTypedefResult(Results);
2189
0
    [[fallthrough]];
2190
2191
0
  case Sema::PCC_Class:
2192
0
    if (SemaRef.getLangOpts().CPlusPlus) {
2193
      // Using declaration
2194
0
      Builder.AddTypedTextChunk("using");
2195
0
      Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2196
0
      Builder.AddPlaceholderChunk("qualifier");
2197
0
      Builder.AddTextChunk("::");
2198
0
      Builder.AddPlaceholderChunk("name");
2199
0
      Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2200
0
      Results.AddResult(Result(Builder.TakeString()));
2201
2202
0
      if (SemaRef.getLangOpts().CPlusPlus11)
2203
0
        AddUsingAliasResult(Builder, Results);
2204
2205
      // using typename qualifier::name (only in a dependent context)
2206
0
      if (SemaRef.CurContext->isDependentContext()) {
2207
0
        Builder.AddTypedTextChunk("using typename");
2208
0
        Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2209
0
        Builder.AddPlaceholderChunk("qualifier");
2210
0
        Builder.AddTextChunk("::");
2211
0
        Builder.AddPlaceholderChunk("name");
2212
0
        Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2213
0
        Results.AddResult(Result(Builder.TakeString()));
2214
0
      }
2215
2216
0
      AddStaticAssertResult(Builder, Results, SemaRef.getLangOpts());
2217
2218
0
      if (CCC == Sema::PCC_Class) {
2219
0
        AddTypedefResult(Results);
2220
2221
0
        bool IsNotInheritanceScope = !S->isClassInheritanceScope();
2222
        // public:
2223
0
        Builder.AddTypedTextChunk("public");
2224
0
        if (IsNotInheritanceScope && Results.includeCodePatterns())
2225
0
          Builder.AddChunk(CodeCompletionString::CK_Colon);
2226
0
        Results.AddResult(Result(Builder.TakeString()));
2227
2228
        // protected:
2229
0
        Builder.AddTypedTextChunk("protected");
2230
0
        if (IsNotInheritanceScope && Results.includeCodePatterns())
2231
0
          Builder.AddChunk(CodeCompletionString::CK_Colon);
2232
0
        Results.AddResult(Result(Builder.TakeString()));
2233
2234
        // private:
2235
0
        Builder.AddTypedTextChunk("private");
2236
0
        if (IsNotInheritanceScope && Results.includeCodePatterns())
2237
0
          Builder.AddChunk(CodeCompletionString::CK_Colon);
2238
0
        Results.AddResult(Result(Builder.TakeString()));
2239
2240
        // FIXME: This adds override results only if we are at the first word of
2241
        // the declaration/definition. Also call this from other sides to have
2242
        // more use-cases.
2243
0
        AddOverrideResults(Results, CodeCompletionContext::CCC_ClassStructUnion,
2244
0
                           Builder);
2245
0
      }
2246
0
    }
2247
0
    [[fallthrough]];
2248
2249
0
  case Sema::PCC_Template:
2250
0
  case Sema::PCC_MemberTemplate:
2251
0
    if (SemaRef.getLangOpts().CPlusPlus && Results.includeCodePatterns()) {
2252
      // template < parameters >
2253
0
      Builder.AddTypedTextChunk("template");
2254
0
      Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
2255
0
      Builder.AddPlaceholderChunk("parameters");
2256
0
      Builder.AddChunk(CodeCompletionString::CK_RightAngle);
2257
0
      Results.AddResult(Result(Builder.TakeString()));
2258
0
    } else {
2259
0
      Results.AddResult(Result("template", CodeCompletionResult::RK_Keyword));
2260
0
    }
2261
2262
0
    AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
2263
0
    AddFunctionSpecifiers(CCC, SemaRef.getLangOpts(), Results);
2264
0
    break;
2265
2266
0
  case Sema::PCC_ObjCInterface:
2267
0
    AddObjCInterfaceResults(SemaRef.getLangOpts(), Results, true);
2268
0
    AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
2269
0
    AddFunctionSpecifiers(CCC, SemaRef.getLangOpts(), Results);
2270
0
    break;
2271
2272
0
  case Sema::PCC_ObjCImplementation:
2273
0
    AddObjCImplementationResults(SemaRef.getLangOpts(), Results, true);
2274
0
    AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
2275
0
    AddFunctionSpecifiers(CCC, SemaRef.getLangOpts(), Results);
2276
0
    break;
2277
2278
0
  case Sema::PCC_ObjCInstanceVariableList:
2279
0
    AddObjCVisibilityResults(SemaRef.getLangOpts(), Results, true);
2280
0
    break;
2281
2282
0
  case Sema::PCC_RecoveryInFunction:
2283
0
  case Sema::PCC_TopLevelOrExpression:
2284
0
  case Sema::PCC_Statement: {
2285
0
    if (SemaRef.getLangOpts().CPlusPlus11)
2286
0
      AddUsingAliasResult(Builder, Results);
2287
2288
0
    AddTypedefResult(Results);
2289
2290
0
    if (SemaRef.getLangOpts().CPlusPlus && Results.includeCodePatterns() &&
2291
0
        SemaRef.getLangOpts().CXXExceptions) {
2292
0
      Builder.AddTypedTextChunk("try");
2293
0
      Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2294
0
      Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
2295
0
      Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2296
0
      Builder.AddPlaceholderChunk("statements");
2297
0
      Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2298
0
      Builder.AddChunk(CodeCompletionString::CK_RightBrace);
2299
0
      Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2300
0
      Builder.AddTextChunk("catch");
2301
0
      Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2302
0
      Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2303
0
      Builder.AddPlaceholderChunk("declaration");
2304
0
      Builder.AddChunk(CodeCompletionString::CK_RightParen);
2305
0
      Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2306
0
      Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
2307
0
      Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2308
0
      Builder.AddPlaceholderChunk("statements");
2309
0
      Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2310
0
      Builder.AddChunk(CodeCompletionString::CK_RightBrace);
2311
0
      Results.AddResult(Result(Builder.TakeString()));
2312
0
    }
2313
0
    if (SemaRef.getLangOpts().ObjC)
2314
0
      AddObjCStatementResults(Results, true);
2315
2316
0
    if (Results.includeCodePatterns()) {
2317
      // if (condition) { statements }
2318
0
      Builder.AddTypedTextChunk("if");
2319
0
      Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2320
0
      Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2321
0
      if (SemaRef.getLangOpts().CPlusPlus)
2322
0
        Builder.AddPlaceholderChunk("condition");
2323
0
      else
2324
0
        Builder.AddPlaceholderChunk("expression");
2325
0
      Builder.AddChunk(CodeCompletionString::CK_RightParen);
2326
0
      Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2327
0
      Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
2328
0
      Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2329
0
      Builder.AddPlaceholderChunk("statements");
2330
0
      Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2331
0
      Builder.AddChunk(CodeCompletionString::CK_RightBrace);
2332
0
      Results.AddResult(Result(Builder.TakeString()));
2333
2334
      // switch (condition) { }
2335
0
      Builder.AddTypedTextChunk("switch");
2336
0
      Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2337
0
      Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2338
0
      if (SemaRef.getLangOpts().CPlusPlus)
2339
0
        Builder.AddPlaceholderChunk("condition");
2340
0
      else
2341
0
        Builder.AddPlaceholderChunk("expression");
2342
0
      Builder.AddChunk(CodeCompletionString::CK_RightParen);
2343
0
      Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2344
0
      Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
2345
0
      Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2346
0
      Builder.AddPlaceholderChunk("cases");
2347
0
      Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2348
0
      Builder.AddChunk(CodeCompletionString::CK_RightBrace);
2349
0
      Results.AddResult(Result(Builder.TakeString()));
2350
0
    }
2351
2352
    // Switch-specific statements.
2353
0
    if (SemaRef.getCurFunction() &&
2354
0
        !SemaRef.getCurFunction()->SwitchStack.empty()) {
2355
      // case expression:
2356
0
      Builder.AddTypedTextChunk("case");
2357
0
      Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2358
0
      Builder.AddPlaceholderChunk("expression");
2359
0
      Builder.AddChunk(CodeCompletionString::CK_Colon);
2360
0
      Results.AddResult(Result(Builder.TakeString()));
2361
2362
      // default:
2363
0
      Builder.AddTypedTextChunk("default");
2364
0
      Builder.AddChunk(CodeCompletionString::CK_Colon);
2365
0
      Results.AddResult(Result(Builder.TakeString()));
2366
0
    }
2367
2368
0
    if (Results.includeCodePatterns()) {
2369
      /// while (condition) { statements }
2370
0
      Builder.AddTypedTextChunk("while");
2371
0
      Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2372
0
      Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2373
0
      if (SemaRef.getLangOpts().CPlusPlus)
2374
0
        Builder.AddPlaceholderChunk("condition");
2375
0
      else
2376
0
        Builder.AddPlaceholderChunk("expression");
2377
0
      Builder.AddChunk(CodeCompletionString::CK_RightParen);
2378
0
      Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2379
0
      Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
2380
0
      Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2381
0
      Builder.AddPlaceholderChunk("statements");
2382
0
      Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2383
0
      Builder.AddChunk(CodeCompletionString::CK_RightBrace);
2384
0
      Results.AddResult(Result(Builder.TakeString()));
2385
2386
      // do { statements } while ( expression );
2387
0
      Builder.AddTypedTextChunk("do");
2388
0
      Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2389
0
      Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
2390
0
      Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2391
0
      Builder.AddPlaceholderChunk("statements");
2392
0
      Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2393
0
      Builder.AddChunk(CodeCompletionString::CK_RightBrace);
2394
0
      Builder.AddTextChunk("while");
2395
0
      Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2396
0
      Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2397
0
      Builder.AddPlaceholderChunk("expression");
2398
0
      Builder.AddChunk(CodeCompletionString::CK_RightParen);
2399
0
      Results.AddResult(Result(Builder.TakeString()));
2400
2401
      // for ( for-init-statement ; condition ; expression ) { statements }
2402
0
      Builder.AddTypedTextChunk("for");
2403
0
      Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2404
0
      Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2405
0
      if (SemaRef.getLangOpts().CPlusPlus || SemaRef.getLangOpts().C99)
2406
0
        Builder.AddPlaceholderChunk("init-statement");
2407
0
      else
2408
0
        Builder.AddPlaceholderChunk("init-expression");
2409
0
      Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2410
0
      Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2411
0
      Builder.AddPlaceholderChunk("condition");
2412
0
      Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2413
0
      Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2414
0
      Builder.AddPlaceholderChunk("inc-expression");
2415
0
      Builder.AddChunk(CodeCompletionString::CK_RightParen);
2416
0
      Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2417
0
      Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
2418
0
      Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2419
0
      Builder.AddPlaceholderChunk("statements");
2420
0
      Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2421
0
      Builder.AddChunk(CodeCompletionString::CK_RightBrace);
2422
0
      Results.AddResult(Result(Builder.TakeString()));
2423
2424
0
      if (SemaRef.getLangOpts().CPlusPlus11 || SemaRef.getLangOpts().ObjC) {
2425
        // for ( range_declaration (:|in) range_expression ) { statements }
2426
0
        Builder.AddTypedTextChunk("for");
2427
0
        Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2428
0
        Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2429
0
        Builder.AddPlaceholderChunk("range-declaration");
2430
0
        Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2431
0
        if (SemaRef.getLangOpts().ObjC)
2432
0
          Builder.AddTextChunk("in");
2433
0
        else
2434
0
          Builder.AddChunk(CodeCompletionString::CK_Colon);
2435
0
        Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2436
0
        Builder.AddPlaceholderChunk("range-expression");
2437
0
        Builder.AddChunk(CodeCompletionString::CK_RightParen);
2438
0
        Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2439
0
        Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
2440
0
        Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2441
0
        Builder.AddPlaceholderChunk("statements");
2442
0
        Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2443
0
        Builder.AddChunk(CodeCompletionString::CK_RightBrace);
2444
0
        Results.AddResult(Result(Builder.TakeString()));
2445
0
      }
2446
0
    }
2447
2448
0
    if (S->getContinueParent()) {
2449
      // continue ;
2450
0
      Builder.AddTypedTextChunk("continue");
2451
0
      Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2452
0
      Results.AddResult(Result(Builder.TakeString()));
2453
0
    }
2454
2455
0
    if (S->getBreakParent()) {
2456
      // break ;
2457
0
      Builder.AddTypedTextChunk("break");
2458
0
      Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2459
0
      Results.AddResult(Result(Builder.TakeString()));
2460
0
    }
2461
2462
    // "return expression ;" or "return ;", depending on the return type.
2463
0
    QualType ReturnType;
2464
0
    if (const auto *Function = dyn_cast<FunctionDecl>(SemaRef.CurContext))
2465
0
      ReturnType = Function->getReturnType();
2466
0
    else if (const auto *Method = dyn_cast<ObjCMethodDecl>(SemaRef.CurContext))
2467
0
      ReturnType = Method->getReturnType();
2468
0
    else if (SemaRef.getCurBlock() &&
2469
0
             !SemaRef.getCurBlock()->ReturnType.isNull())
2470
0
      ReturnType = SemaRef.getCurBlock()->ReturnType;;
2471
0
    if (ReturnType.isNull() || ReturnType->isVoidType()) {
2472
0
      Builder.AddTypedTextChunk("return");
2473
0
      Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2474
0
      Results.AddResult(Result(Builder.TakeString()));
2475
0
    } else {
2476
0
      assert(!ReturnType.isNull());
2477
      // "return expression ;"
2478
0
      Builder.AddTypedTextChunk("return");
2479
0
      Builder.AddChunk(clang::CodeCompletionString::CK_HorizontalSpace);
2480
0
      Builder.AddPlaceholderChunk("expression");
2481
0
      Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2482
0
      Results.AddResult(Result(Builder.TakeString()));
2483
      // When boolean, also add 'return true;' and 'return false;'.
2484
0
      if (ReturnType->isBooleanType()) {
2485
0
        Builder.AddTypedTextChunk("return true");
2486
0
        Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2487
0
        Results.AddResult(Result(Builder.TakeString()));
2488
2489
0
        Builder.AddTypedTextChunk("return false");
2490
0
        Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2491
0
        Results.AddResult(Result(Builder.TakeString()));
2492
0
      }
2493
      // For pointers, suggest 'return nullptr' in C++.
2494
0
      if (SemaRef.getLangOpts().CPlusPlus11 &&
2495
0
          (ReturnType->isPointerType() || ReturnType->isMemberPointerType())) {
2496
0
        Builder.AddTypedTextChunk("return nullptr");
2497
0
        Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2498
0
        Results.AddResult(Result(Builder.TakeString()));
2499
0
      }
2500
0
    }
2501
2502
    // goto identifier ;
2503
0
    Builder.AddTypedTextChunk("goto");
2504
0
    Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2505
0
    Builder.AddPlaceholderChunk("label");
2506
0
    Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2507
0
    Results.AddResult(Result(Builder.TakeString()));
2508
2509
    // Using directives
2510
0
    Builder.AddTypedTextChunk("using namespace");
2511
0
    Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2512
0
    Builder.AddPlaceholderChunk("identifier");
2513
0
    Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2514
0
    Results.AddResult(Result(Builder.TakeString()));
2515
2516
0
    AddStaticAssertResult(Builder, Results, SemaRef.getLangOpts());
2517
0
  }
2518
0
    [[fallthrough]];
2519
2520
  // Fall through (for statement expressions).
2521
0
  case Sema::PCC_ForInit:
2522
0
  case Sema::PCC_Condition:
2523
0
    AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
2524
    // Fall through: conditions and statements can have expressions.
2525
0
    [[fallthrough]];
2526
2527
0
  case Sema::PCC_ParenthesizedExpression:
2528
0
    if (SemaRef.getLangOpts().ObjCAutoRefCount &&
2529
0
        CCC == Sema::PCC_ParenthesizedExpression) {
2530
      // (__bridge <type>)<expression>
2531
0
      Builder.AddTypedTextChunk("__bridge");
2532
0
      Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2533
0
      Builder.AddPlaceholderChunk("type");
2534
0
      Builder.AddChunk(CodeCompletionString::CK_RightParen);
2535
0
      Builder.AddPlaceholderChunk("expression");
2536
0
      Results.AddResult(Result(Builder.TakeString()));
2537
2538
      // (__bridge_transfer <Objective-C type>)<expression>
2539
0
      Builder.AddTypedTextChunk("__bridge_transfer");
2540
0
      Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2541
0
      Builder.AddPlaceholderChunk("Objective-C type");
2542
0
      Builder.AddChunk(CodeCompletionString::CK_RightParen);
2543
0
      Builder.AddPlaceholderChunk("expression");
2544
0
      Results.AddResult(Result(Builder.TakeString()));
2545
2546
      // (__bridge_retained <CF type>)<expression>
2547
0
      Builder.AddTypedTextChunk("__bridge_retained");
2548
0
      Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2549
0
      Builder.AddPlaceholderChunk("CF type");
2550
0
      Builder.AddChunk(CodeCompletionString::CK_RightParen);
2551
0
      Builder.AddPlaceholderChunk("expression");
2552
0
      Results.AddResult(Result(Builder.TakeString()));
2553
0
    }
2554
    // Fall through
2555
0
    [[fallthrough]];
2556
2557
0
  case Sema::PCC_Expression: {
2558
0
    if (SemaRef.getLangOpts().CPlusPlus) {
2559
      // 'this', if we're in a non-static member function.
2560
0
      addThisCompletion(SemaRef, Results);
2561
2562
      // true
2563
0
      Builder.AddResultTypeChunk("bool");
2564
0
      Builder.AddTypedTextChunk("true");
2565
0
      Results.AddResult(Result(Builder.TakeString()));
2566
2567
      // false
2568
0
      Builder.AddResultTypeChunk("bool");
2569
0
      Builder.AddTypedTextChunk("false");
2570
0
      Results.AddResult(Result(Builder.TakeString()));
2571
2572
0
      if (SemaRef.getLangOpts().RTTI) {
2573
        // dynamic_cast < type-id > ( expression )
2574
0
        Builder.AddTypedTextChunk("dynamic_cast");
2575
0
        Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
2576
0
        Builder.AddPlaceholderChunk("type");
2577
0
        Builder.AddChunk(CodeCompletionString::CK_RightAngle);
2578
0
        Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2579
0
        Builder.AddPlaceholderChunk("expression");
2580
0
        Builder.AddChunk(CodeCompletionString::CK_RightParen);
2581
0
        Results.AddResult(Result(Builder.TakeString()));
2582
0
      }
2583
2584
      // static_cast < type-id > ( expression )
2585
0
      Builder.AddTypedTextChunk("static_cast");
2586
0
      Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
2587
0
      Builder.AddPlaceholderChunk("type");
2588
0
      Builder.AddChunk(CodeCompletionString::CK_RightAngle);
2589
0
      Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2590
0
      Builder.AddPlaceholderChunk("expression");
2591
0
      Builder.AddChunk(CodeCompletionString::CK_RightParen);
2592
0
      Results.AddResult(Result(Builder.TakeString()));
2593
2594
      // reinterpret_cast < type-id > ( expression )
2595
0
      Builder.AddTypedTextChunk("reinterpret_cast");
2596
0
      Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
2597
0
      Builder.AddPlaceholderChunk("type");
2598
0
      Builder.AddChunk(CodeCompletionString::CK_RightAngle);
2599
0
      Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2600
0
      Builder.AddPlaceholderChunk("expression");
2601
0
      Builder.AddChunk(CodeCompletionString::CK_RightParen);
2602
0
      Results.AddResult(Result(Builder.TakeString()));
2603
2604
      // const_cast < type-id > ( expression )
2605
0
      Builder.AddTypedTextChunk("const_cast");
2606
0
      Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
2607
0
      Builder.AddPlaceholderChunk("type");
2608
0
      Builder.AddChunk(CodeCompletionString::CK_RightAngle);
2609
0
      Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2610
0
      Builder.AddPlaceholderChunk("expression");
2611
0
      Builder.AddChunk(CodeCompletionString::CK_RightParen);
2612
0
      Results.AddResult(Result(Builder.TakeString()));
2613
2614
0
      if (SemaRef.getLangOpts().RTTI) {
2615
        // typeid ( expression-or-type )
2616
0
        Builder.AddResultTypeChunk("std::type_info");
2617
0
        Builder.AddTypedTextChunk("typeid");
2618
0
        Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2619
0
        Builder.AddPlaceholderChunk("expression-or-type");
2620
0
        Builder.AddChunk(CodeCompletionString::CK_RightParen);
2621
0
        Results.AddResult(Result(Builder.TakeString()));
2622
0
      }
2623
2624
      // new T ( ... )
2625
0
      Builder.AddTypedTextChunk("new");
2626
0
      Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2627
0
      Builder.AddPlaceholderChunk("type");
2628
0
      Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2629
0
      Builder.AddPlaceholderChunk("expressions");
2630
0
      Builder.AddChunk(CodeCompletionString::CK_RightParen);
2631
0
      Results.AddResult(Result(Builder.TakeString()));
2632
2633
      // new T [ ] ( ... )
2634
0
      Builder.AddTypedTextChunk("new");
2635
0
      Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2636
0
      Builder.AddPlaceholderChunk("type");
2637
0
      Builder.AddChunk(CodeCompletionString::CK_LeftBracket);
2638
0
      Builder.AddPlaceholderChunk("size");
2639
0
      Builder.AddChunk(CodeCompletionString::CK_RightBracket);
2640
0
      Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2641
0
      Builder.AddPlaceholderChunk("expressions");
2642
0
      Builder.AddChunk(CodeCompletionString::CK_RightParen);
2643
0
      Results.AddResult(Result(Builder.TakeString()));
2644
2645
      // delete expression
2646
0
      Builder.AddResultTypeChunk("void");
2647
0
      Builder.AddTypedTextChunk("delete");
2648
0
      Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2649
0
      Builder.AddPlaceholderChunk("expression");
2650
0
      Results.AddResult(Result(Builder.TakeString()));
2651
2652
      // delete [] expression
2653
0
      Builder.AddResultTypeChunk("void");
2654
0
      Builder.AddTypedTextChunk("delete");
2655
0
      Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2656
0
      Builder.AddChunk(CodeCompletionString::CK_LeftBracket);
2657
0
      Builder.AddChunk(CodeCompletionString::CK_RightBracket);
2658
0
      Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2659
0
      Builder.AddPlaceholderChunk("expression");
2660
0
      Results.AddResult(Result(Builder.TakeString()));
2661
2662
0
      if (SemaRef.getLangOpts().CXXExceptions) {
2663
        // throw expression
2664
0
        Builder.AddResultTypeChunk("void");
2665
0
        Builder.AddTypedTextChunk("throw");
2666
0
        Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2667
0
        Builder.AddPlaceholderChunk("expression");
2668
0
        Results.AddResult(Result(Builder.TakeString()));
2669
0
      }
2670
2671
      // FIXME: Rethrow?
2672
2673
0
      if (SemaRef.getLangOpts().CPlusPlus11) {
2674
        // nullptr
2675
0
        Builder.AddResultTypeChunk("std::nullptr_t");
2676
0
        Builder.AddTypedTextChunk("nullptr");
2677
0
        Results.AddResult(Result(Builder.TakeString()));
2678
2679
        // alignof
2680
0
        Builder.AddResultTypeChunk("size_t");
2681
0
        Builder.AddTypedTextChunk("alignof");
2682
0
        Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2683
0
        Builder.AddPlaceholderChunk("type");
2684
0
        Builder.AddChunk(CodeCompletionString::CK_RightParen);
2685
0
        Results.AddResult(Result(Builder.TakeString()));
2686
2687
        // noexcept
2688
0
        Builder.AddResultTypeChunk("bool");
2689
0
        Builder.AddTypedTextChunk("noexcept");
2690
0
        Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2691
0
        Builder.AddPlaceholderChunk("expression");
2692
0
        Builder.AddChunk(CodeCompletionString::CK_RightParen);
2693
0
        Results.AddResult(Result(Builder.TakeString()));
2694
2695
        // sizeof... expression
2696
0
        Builder.AddResultTypeChunk("size_t");
2697
0
        Builder.AddTypedTextChunk("sizeof...");
2698
0
        Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2699
0
        Builder.AddPlaceholderChunk("parameter-pack");
2700
0
        Builder.AddChunk(CodeCompletionString::CK_RightParen);
2701
0
        Results.AddResult(Result(Builder.TakeString()));
2702
0
      }
2703
0
    }
2704
2705
0
    if (SemaRef.getLangOpts().ObjC) {
2706
      // Add "super", if we're in an Objective-C class with a superclass.
2707
0
      if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
2708
        // The interface can be NULL.
2709
0
        if (ObjCInterfaceDecl *ID = Method->getClassInterface())
2710
0
          if (ID->getSuperClass()) {
2711
0
            std::string SuperType;
2712
0
            SuperType = ID->getSuperClass()->getNameAsString();
2713
0
            if (Method->isInstanceMethod())
2714
0
              SuperType += " *";
2715
2716
0
            Builder.AddResultTypeChunk(Allocator.CopyString(SuperType));
2717
0
            Builder.AddTypedTextChunk("super");
2718
0
            Results.AddResult(Result(Builder.TakeString()));
2719
0
          }
2720
0
      }
2721
2722
0
      AddObjCExpressionResults(Results, true);
2723
0
    }
2724
2725
0
    if (SemaRef.getLangOpts().C11) {
2726
      // _Alignof
2727
0
      Builder.AddResultTypeChunk("size_t");
2728
0
      if (SemaRef.PP.isMacroDefined("alignof"))
2729
0
        Builder.AddTypedTextChunk("alignof");
2730
0
      else
2731
0
        Builder.AddTypedTextChunk("_Alignof");
2732
0
      Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2733
0
      Builder.AddPlaceholderChunk("type");
2734
0
      Builder.AddChunk(CodeCompletionString::CK_RightParen);
2735
0
      Results.AddResult(Result(Builder.TakeString()));
2736
0
    }
2737
2738
0
    if (SemaRef.getLangOpts().C23) {
2739
      // nullptr
2740
0
      Builder.AddResultTypeChunk("nullptr_t");
2741
0
      Builder.AddTypedTextChunk("nullptr");
2742
0
      Results.AddResult(Result(Builder.TakeString()));
2743
0
    }
2744
2745
    // sizeof expression
2746
0
    Builder.AddResultTypeChunk("size_t");
2747
0
    Builder.AddTypedTextChunk("sizeof");
2748
0
    Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2749
0
    Builder.AddPlaceholderChunk("expression-or-type");
2750
0
    Builder.AddChunk(CodeCompletionString::CK_RightParen);
2751
0
    Results.AddResult(Result(Builder.TakeString()));
2752
0
    break;
2753
0
  }
2754
2755
0
  case Sema::PCC_Type:
2756
0
  case Sema::PCC_LocalDeclarationSpecifiers:
2757
0
    break;
2758
0
  }
2759
2760
0
  if (WantTypesInContext(CCC, SemaRef.getLangOpts()))
2761
0
    AddTypeSpecifierResults(SemaRef.getLangOpts(), Results);
2762
2763
0
  if (SemaRef.getLangOpts().CPlusPlus && CCC != Sema::PCC_Type)
2764
0
    Results.AddResult(Result("operator"));
2765
0
}
2766
2767
/// If the given declaration has an associated type, add it as a result
2768
/// type chunk.
2769
static void AddResultTypeChunk(ASTContext &Context,
2770
                               const PrintingPolicy &Policy,
2771
                               const NamedDecl *ND, QualType BaseType,
2772
0
                               CodeCompletionBuilder &Result) {
2773
0
  if (!ND)
2774
0
    return;
2775
2776
  // Skip constructors and conversion functions, which have their return types
2777
  // built into their names.
2778
0
  if (isConstructor(ND) || isa<CXXConversionDecl>(ND))
2779
0
    return;
2780
2781
  // Determine the type of the declaration (if it has a type).
2782
0
  QualType T;
2783
0
  if (const FunctionDecl *Function = ND->getAsFunction())
2784
0
    T = Function->getReturnType();
2785
0
  else if (const auto *Method = dyn_cast<ObjCMethodDecl>(ND)) {
2786
0
    if (!BaseType.isNull())
2787
0
      T = Method->getSendResultType(BaseType);
2788
0
    else
2789
0
      T = Method->getReturnType();
2790
0
  } else if (const auto *Enumerator = dyn_cast<EnumConstantDecl>(ND)) {
2791
0
    T = Context.getTypeDeclType(cast<TypeDecl>(Enumerator->getDeclContext()));
2792
0
    T = clang::TypeName::getFullyQualifiedType(T, Context);
2793
0
  } else if (isa<UnresolvedUsingValueDecl>(ND)) {
2794
    /* Do nothing: ignore unresolved using declarations*/
2795
0
  } else if (const auto *Ivar = dyn_cast<ObjCIvarDecl>(ND)) {
2796
0
    if (!BaseType.isNull())
2797
0
      T = Ivar->getUsageType(BaseType);
2798
0
    else
2799
0
      T = Ivar->getType();
2800
0
  } else if (const auto *Value = dyn_cast<ValueDecl>(ND)) {
2801
0
    T = Value->getType();
2802
0
  } else if (const auto *Property = dyn_cast<ObjCPropertyDecl>(ND)) {
2803
0
    if (!BaseType.isNull())
2804
0
      T = Property->getUsageType(BaseType);
2805
0
    else
2806
0
      T = Property->getType();
2807
0
  }
2808
2809
0
  if (T.isNull() || Context.hasSameType(T, Context.DependentTy))
2810
0
    return;
2811
2812
0
  Result.AddResultTypeChunk(
2813
0
      GetCompletionTypeString(T, Context, Policy, Result.getAllocator()));
2814
0
}
2815
2816
static void MaybeAddSentinel(Preprocessor &PP,
2817
                             const NamedDecl *FunctionOrMethod,
2818
0
                             CodeCompletionBuilder &Result) {
2819
0
  if (SentinelAttr *Sentinel = FunctionOrMethod->getAttr<SentinelAttr>())
2820
0
    if (Sentinel->getSentinel() == 0) {
2821
0
      if (PP.getLangOpts().ObjC && PP.isMacroDefined("nil"))
2822
0
        Result.AddTextChunk(", nil");
2823
0
      else if (PP.isMacroDefined("NULL"))
2824
0
        Result.AddTextChunk(", NULL");
2825
0
      else
2826
0
        Result.AddTextChunk(", (void*)0");
2827
0
    }
2828
0
}
2829
2830
static std::string formatObjCParamQualifiers(unsigned ObjCQuals,
2831
0
                                             QualType &Type) {
2832
0
  std::string Result;
2833
0
  if (ObjCQuals & Decl::OBJC_TQ_In)
2834
0
    Result += "in ";
2835
0
  else if (ObjCQuals & Decl::OBJC_TQ_Inout)
2836
0
    Result += "inout ";
2837
0
  else if (ObjCQuals & Decl::OBJC_TQ_Out)
2838
0
    Result += "out ";
2839
0
  if (ObjCQuals & Decl::OBJC_TQ_Bycopy)
2840
0
    Result += "bycopy ";
2841
0
  else if (ObjCQuals & Decl::OBJC_TQ_Byref)
2842
0
    Result += "byref ";
2843
0
  if (ObjCQuals & Decl::OBJC_TQ_Oneway)
2844
0
    Result += "oneway ";
2845
0
  if (ObjCQuals & Decl::OBJC_TQ_CSNullability) {
2846
0
    if (auto nullability = AttributedType::stripOuterNullability(Type)) {
2847
0
      switch (*nullability) {
2848
0
      case NullabilityKind::NonNull:
2849
0
        Result += "nonnull ";
2850
0
        break;
2851
2852
0
      case NullabilityKind::Nullable:
2853
0
        Result += "nullable ";
2854
0
        break;
2855
2856
0
      case NullabilityKind::Unspecified:
2857
0
        Result += "null_unspecified ";
2858
0
        break;
2859
2860
0
      case NullabilityKind::NullableResult:
2861
0
        llvm_unreachable("Not supported as a context-sensitive keyword!");
2862
0
        break;
2863
0
      }
2864
0
    }
2865
0
  }
2866
0
  return Result;
2867
0
}
2868
2869
/// Tries to find the most appropriate type location for an Objective-C
2870
/// block placeholder.
2871
///
2872
/// This function ignores things like typedefs and qualifiers in order to
2873
/// present the most relevant and accurate block placeholders in code completion
2874
/// results.
2875
static void findTypeLocationForBlockDecl(const TypeSourceInfo *TSInfo,
2876
                                         FunctionTypeLoc &Block,
2877
                                         FunctionProtoTypeLoc &BlockProto,
2878
0
                                         bool SuppressBlock = false) {
2879
0
  if (!TSInfo)
2880
0
    return;
2881
0
  TypeLoc TL = TSInfo->getTypeLoc().getUnqualifiedLoc();
2882
0
  while (true) {
2883
    // Look through typedefs.
2884
0
    if (!SuppressBlock) {
2885
0
      if (TypedefTypeLoc TypedefTL = TL.getAsAdjusted<TypedefTypeLoc>()) {
2886
0
        if (TypeSourceInfo *InnerTSInfo =
2887
0
                TypedefTL.getTypedefNameDecl()->getTypeSourceInfo()) {
2888
0
          TL = InnerTSInfo->getTypeLoc().getUnqualifiedLoc();
2889
0
          continue;
2890
0
        }
2891
0
      }
2892
2893
      // Look through qualified types
2894
0
      if (QualifiedTypeLoc QualifiedTL = TL.getAs<QualifiedTypeLoc>()) {
2895
0
        TL = QualifiedTL.getUnqualifiedLoc();
2896
0
        continue;
2897
0
      }
2898
2899
0
      if (AttributedTypeLoc AttrTL = TL.getAs<AttributedTypeLoc>()) {
2900
0
        TL = AttrTL.getModifiedLoc();
2901
0
        continue;
2902
0
      }
2903
0
    }
2904
2905
    // Try to get the function prototype behind the block pointer type,
2906
    // then we're done.
2907
0
    if (BlockPointerTypeLoc BlockPtr = TL.getAs<BlockPointerTypeLoc>()) {
2908
0
      TL = BlockPtr.getPointeeLoc().IgnoreParens();
2909
0
      Block = TL.getAs<FunctionTypeLoc>();
2910
0
      BlockProto = TL.getAs<FunctionProtoTypeLoc>();
2911
0
    }
2912
0
    break;
2913
0
  }
2914
0
}
2915
2916
static std::string formatBlockPlaceholder(
2917
    const PrintingPolicy &Policy, const NamedDecl *BlockDecl,
2918
    FunctionTypeLoc &Block, FunctionProtoTypeLoc &BlockProto,
2919
    bool SuppressBlockName = false, bool SuppressBlock = false,
2920
    std::optional<ArrayRef<QualType>> ObjCSubsts = std::nullopt);
2921
2922
static std::string FormatFunctionParameter(
2923
    const PrintingPolicy &Policy, const DeclaratorDecl *Param,
2924
    bool SuppressName = false, bool SuppressBlock = false,
2925
0
    std::optional<ArrayRef<QualType>> ObjCSubsts = std::nullopt) {
2926
  // Params are unavailable in FunctionTypeLoc if the FunctionType is invalid.
2927
  // It would be better to pass in the param Type, which is usually available.
2928
  // But this case is rare, so just pretend we fell back to int as elsewhere.
2929
0
  if (!Param)
2930
0
    return "int";
2931
0
  Decl::ObjCDeclQualifier ObjCQual = Decl::OBJC_TQ_None;
2932
0
  if (const auto *PVD = dyn_cast<ParmVarDecl>(Param))
2933
0
    ObjCQual = PVD->getObjCDeclQualifier();
2934
0
  bool ObjCMethodParam = isa<ObjCMethodDecl>(Param->getDeclContext());
2935
0
  if (Param->getType()->isDependentType() ||
2936
0
      !Param->getType()->isBlockPointerType()) {
2937
    // The argument for a dependent or non-block parameter is a placeholder
2938
    // containing that parameter's type.
2939
0
    std::string Result;
2940
2941
0
    if (Param->getIdentifier() && !ObjCMethodParam && !SuppressName)
2942
0
      Result = std::string(Param->getIdentifier()->deuglifiedName());
2943
2944
0
    QualType Type = Param->getType();
2945
0
    if (ObjCSubsts)
2946
0
      Type = Type.substObjCTypeArgs(Param->getASTContext(), *ObjCSubsts,
2947
0
                                    ObjCSubstitutionContext::Parameter);
2948
0
    if (ObjCMethodParam) {
2949
0
      Result = "(" + formatObjCParamQualifiers(ObjCQual, Type);
2950
0
      Result += Type.getAsString(Policy) + ")";
2951
0
      if (Param->getIdentifier() && !SuppressName)
2952
0
        Result += Param->getIdentifier()->deuglifiedName();
2953
0
    } else {
2954
0
      Type.getAsStringInternal(Result, Policy);
2955
0
    }
2956
0
    return Result;
2957
0
  }
2958
2959
  // The argument for a block pointer parameter is a block literal with
2960
  // the appropriate type.
2961
0
  FunctionTypeLoc Block;
2962
0
  FunctionProtoTypeLoc BlockProto;
2963
0
  findTypeLocationForBlockDecl(Param->getTypeSourceInfo(), Block, BlockProto,
2964
0
                               SuppressBlock);
2965
  // Try to retrieve the block type information from the property if this is a
2966
  // parameter in a setter.
2967
0
  if (!Block && ObjCMethodParam &&
2968
0
      cast<ObjCMethodDecl>(Param->getDeclContext())->isPropertyAccessor()) {
2969
0
    if (const auto *PD = cast<ObjCMethodDecl>(Param->getDeclContext())
2970
0
                             ->findPropertyDecl(/*CheckOverrides=*/false))
2971
0
      findTypeLocationForBlockDecl(PD->getTypeSourceInfo(), Block, BlockProto,
2972
0
                                   SuppressBlock);
2973
0
  }
2974
2975
0
  if (!Block) {
2976
    // We were unable to find a FunctionProtoTypeLoc with parameter names
2977
    // for the block; just use the parameter type as a placeholder.
2978
0
    std::string Result;
2979
0
    if (!ObjCMethodParam && Param->getIdentifier())
2980
0
      Result = std::string(Param->getIdentifier()->deuglifiedName());
2981
2982
0
    QualType Type = Param->getType().getUnqualifiedType();
2983
2984
0
    if (ObjCMethodParam) {
2985
0
      Result = Type.getAsString(Policy);
2986
0
      std::string Quals = formatObjCParamQualifiers(ObjCQual, Type);
2987
0
      if (!Quals.empty())
2988
0
        Result = "(" + Quals + " " + Result + ")";
2989
0
      if (Result.back() != ')')
2990
0
        Result += " ";
2991
0
      if (Param->getIdentifier())
2992
0
        Result += Param->getIdentifier()->deuglifiedName();
2993
0
    } else {
2994
0
      Type.getAsStringInternal(Result, Policy);
2995
0
    }
2996
2997
0
    return Result;
2998
0
  }
2999
3000
  // We have the function prototype behind the block pointer type, as it was
3001
  // written in the source.
3002
0
  return formatBlockPlaceholder(Policy, Param, Block, BlockProto,
3003
0
                                /*SuppressBlockName=*/false, SuppressBlock,
3004
0
                                ObjCSubsts);
3005
0
}
3006
3007
/// Returns a placeholder string that corresponds to an Objective-C block
3008
/// declaration.
3009
///
3010
/// \param BlockDecl A declaration with an Objective-C block type.
3011
///
3012
/// \param Block The most relevant type location for that block type.
3013
///
3014
/// \param SuppressBlockName Determines whether or not the name of the block
3015
/// declaration is included in the resulting string.
3016
static std::string
3017
formatBlockPlaceholder(const PrintingPolicy &Policy, const NamedDecl *BlockDecl,
3018
                       FunctionTypeLoc &Block, FunctionProtoTypeLoc &BlockProto,
3019
                       bool SuppressBlockName, bool SuppressBlock,
3020
0
                       std::optional<ArrayRef<QualType>> ObjCSubsts) {
3021
0
  std::string Result;
3022
0
  QualType ResultType = Block.getTypePtr()->getReturnType();
3023
0
  if (ObjCSubsts)
3024
0
    ResultType =
3025
0
        ResultType.substObjCTypeArgs(BlockDecl->getASTContext(), *ObjCSubsts,
3026
0
                                     ObjCSubstitutionContext::Result);
3027
0
  if (!ResultType->isVoidType() || SuppressBlock)
3028
0
    ResultType.getAsStringInternal(Result, Policy);
3029
3030
  // Format the parameter list.
3031
0
  std::string Params;
3032
0
  if (!BlockProto || Block.getNumParams() == 0) {
3033
0
    if (BlockProto && BlockProto.getTypePtr()->isVariadic())
3034
0
      Params = "(...)";
3035
0
    else
3036
0
      Params = "(void)";
3037
0
  } else {
3038
0
    Params += "(";
3039
0
    for (unsigned I = 0, N = Block.getNumParams(); I != N; ++I) {
3040
0
      if (I)
3041
0
        Params += ", ";
3042
0
      Params += FormatFunctionParameter(Policy, Block.getParam(I),
3043
0
                                        /*SuppressName=*/false,
3044
0
                                        /*SuppressBlock=*/true, ObjCSubsts);
3045
3046
0
      if (I == N - 1 && BlockProto.getTypePtr()->isVariadic())
3047
0
        Params += ", ...";
3048
0
    }
3049
0
    Params += ")";
3050
0
  }
3051
3052
0
  if (SuppressBlock) {
3053
    // Format as a parameter.
3054
0
    Result = Result + " (^";
3055
0
    if (!SuppressBlockName && BlockDecl->getIdentifier())
3056
0
      Result += BlockDecl->getIdentifier()->getName();
3057
0
    Result += ")";
3058
0
    Result += Params;
3059
0
  } else {
3060
    // Format as a block literal argument.
3061
0
    Result = '^' + Result;
3062
0
    Result += Params;
3063
3064
0
    if (!SuppressBlockName && BlockDecl->getIdentifier())
3065
0
      Result += BlockDecl->getIdentifier()->getName();
3066
0
  }
3067
3068
0
  return Result;
3069
0
}
3070
3071
static std::string GetDefaultValueString(const ParmVarDecl *Param,
3072
                                         const SourceManager &SM,
3073
0
                                         const LangOptions &LangOpts) {
3074
0
  const SourceRange SrcRange = Param->getDefaultArgRange();
3075
0
  CharSourceRange CharSrcRange = CharSourceRange::getTokenRange(SrcRange);
3076
0
  bool Invalid = CharSrcRange.isInvalid();
3077
0
  if (Invalid)
3078
0
    return "";
3079
0
  StringRef srcText =
3080
0
      Lexer::getSourceText(CharSrcRange, SM, LangOpts, &Invalid);
3081
0
  if (Invalid)
3082
0
    return "";
3083
3084
0
  if (srcText.empty() || srcText == "=") {
3085
    // Lexer can't determine the value.
3086
    // This happens if the code is incorrect (for example class is forward
3087
    // declared).
3088
0
    return "";
3089
0
  }
3090
0
  std::string DefValue(srcText.str());
3091
  // FIXME: remove this check if the Lexer::getSourceText value is fixed and
3092
  // this value always has (or always does not have) '=' in front of it
3093
0
  if (DefValue.at(0) != '=') {
3094
    // If we don't have '=' in front of value.
3095
    // Lexer returns built-in types values without '=' and user-defined types
3096
    // values with it.
3097
0
    return " = " + DefValue;
3098
0
  }
3099
0
  return " " + DefValue;
3100
0
}
3101
3102
/// Add function parameter chunks to the given code completion string.
3103
static void AddFunctionParameterChunks(Preprocessor &PP,
3104
                                       const PrintingPolicy &Policy,
3105
                                       const FunctionDecl *Function,
3106
                                       CodeCompletionBuilder &Result,
3107
                                       unsigned Start = 0,
3108
0
                                       bool InOptional = false) {
3109
0
  bool FirstParameter = true;
3110
3111
0
  for (unsigned P = Start, N = Function->getNumParams(); P != N; ++P) {
3112
0
    const ParmVarDecl *Param = Function->getParamDecl(P);
3113
3114
0
    if (Param->hasDefaultArg() && !InOptional) {
3115
      // When we see an optional default argument, put that argument and
3116
      // the remaining default arguments into a new, optional string.
3117
0
      CodeCompletionBuilder Opt(Result.getAllocator(),
3118
0
                                Result.getCodeCompletionTUInfo());
3119
0
      if (!FirstParameter)
3120
0
        Opt.AddChunk(CodeCompletionString::CK_Comma);
3121
0
      AddFunctionParameterChunks(PP, Policy, Function, Opt, P, true);
3122
0
      Result.AddOptionalChunk(Opt.TakeString());
3123
0
      break;
3124
0
    }
3125
3126
0
    if (FirstParameter)
3127
0
      FirstParameter = false;
3128
0
    else
3129
0
      Result.AddChunk(CodeCompletionString::CK_Comma);
3130
3131
0
    InOptional = false;
3132
3133
    // Format the placeholder string.
3134
0
    std::string PlaceholderStr = FormatFunctionParameter(Policy, Param);
3135
0
    if (Param->hasDefaultArg())
3136
0
      PlaceholderStr +=
3137
0
          GetDefaultValueString(Param, PP.getSourceManager(), PP.getLangOpts());
3138
3139
0
    if (Function->isVariadic() && P == N - 1)
3140
0
      PlaceholderStr += ", ...";
3141
3142
    // Add the placeholder string.
3143
0
    Result.AddPlaceholderChunk(
3144
0
        Result.getAllocator().CopyString(PlaceholderStr));
3145
0
  }
3146
3147
0
  if (const auto *Proto = Function->getType()->getAs<FunctionProtoType>())
3148
0
    if (Proto->isVariadic()) {
3149
0
      if (Proto->getNumParams() == 0)
3150
0
        Result.AddPlaceholderChunk("...");
3151
3152
0
      MaybeAddSentinel(PP, Function, Result);
3153
0
    }
3154
0
}
3155
3156
/// Add template parameter chunks to the given code completion string.
3157
static void AddTemplateParameterChunks(
3158
    ASTContext &Context, const PrintingPolicy &Policy,
3159
    const TemplateDecl *Template, CodeCompletionBuilder &Result,
3160
0
    unsigned MaxParameters = 0, unsigned Start = 0, bool InDefaultArg = false) {
3161
0
  bool FirstParameter = true;
3162
3163
  // Prefer to take the template parameter names from the first declaration of
3164
  // the template.
3165
0
  Template = cast<TemplateDecl>(Template->getCanonicalDecl());
3166
3167
0
  TemplateParameterList *Params = Template->getTemplateParameters();
3168
0
  TemplateParameterList::iterator PEnd = Params->end();
3169
0
  if (MaxParameters)
3170
0
    PEnd = Params->begin() + MaxParameters;
3171
0
  for (TemplateParameterList::iterator P = Params->begin() + Start; P != PEnd;
3172
0
       ++P) {
3173
0
    bool HasDefaultArg = false;
3174
0
    std::string PlaceholderStr;
3175
0
    if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
3176
0
      if (TTP->wasDeclaredWithTypename())
3177
0
        PlaceholderStr = "typename";
3178
0
      else if (const auto *TC = TTP->getTypeConstraint()) {
3179
0
        llvm::raw_string_ostream OS(PlaceholderStr);
3180
0
        TC->print(OS, Policy);
3181
0
        OS.flush();
3182
0
      } else
3183
0
        PlaceholderStr = "class";
3184
3185
0
      if (TTP->getIdentifier()) {
3186
0
        PlaceholderStr += ' ';
3187
0
        PlaceholderStr += TTP->getIdentifier()->deuglifiedName();
3188
0
      }
3189
3190
0
      HasDefaultArg = TTP->hasDefaultArgument();
3191
0
    } else if (NonTypeTemplateParmDecl *NTTP =
3192
0
                   dyn_cast<NonTypeTemplateParmDecl>(*P)) {
3193
0
      if (NTTP->getIdentifier())
3194
0
        PlaceholderStr = std::string(NTTP->getIdentifier()->deuglifiedName());
3195
0
      NTTP->getType().getAsStringInternal(PlaceholderStr, Policy);
3196
0
      HasDefaultArg = NTTP->hasDefaultArgument();
3197
0
    } else {
3198
0
      assert(isa<TemplateTemplateParmDecl>(*P));
3199
0
      TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
3200
3201
      // Since putting the template argument list into the placeholder would
3202
      // be very, very long, we just use an abbreviation.
3203
0
      PlaceholderStr = "template<...> class";
3204
0
      if (TTP->getIdentifier()) {
3205
0
        PlaceholderStr += ' ';
3206
0
        PlaceholderStr += TTP->getIdentifier()->deuglifiedName();
3207
0
      }
3208
3209
0
      HasDefaultArg = TTP->hasDefaultArgument();
3210
0
    }
3211
3212
0
    if (HasDefaultArg && !InDefaultArg) {
3213
      // When we see an optional default argument, put that argument and
3214
      // the remaining default arguments into a new, optional string.
3215
0
      CodeCompletionBuilder Opt(Result.getAllocator(),
3216
0
                                Result.getCodeCompletionTUInfo());
3217
0
      if (!FirstParameter)
3218
0
        Opt.AddChunk(CodeCompletionString::CK_Comma);
3219
0
      AddTemplateParameterChunks(Context, Policy, Template, Opt, MaxParameters,
3220
0
                                 P - Params->begin(), true);
3221
0
      Result.AddOptionalChunk(Opt.TakeString());
3222
0
      break;
3223
0
    }
3224
3225
0
    InDefaultArg = false;
3226
3227
0
    if (FirstParameter)
3228
0
      FirstParameter = false;
3229
0
    else
3230
0
      Result.AddChunk(CodeCompletionString::CK_Comma);
3231
3232
    // Add the placeholder string.
3233
0
    Result.AddPlaceholderChunk(
3234
0
        Result.getAllocator().CopyString(PlaceholderStr));
3235
0
  }
3236
0
}
3237
3238
/// Add a qualifier to the given code-completion string, if the
3239
/// provided nested-name-specifier is non-NULL.
3240
static void AddQualifierToCompletionString(CodeCompletionBuilder &Result,
3241
                                           NestedNameSpecifier *Qualifier,
3242
                                           bool QualifierIsInformative,
3243
                                           ASTContext &Context,
3244
0
                                           const PrintingPolicy &Policy) {
3245
0
  if (!Qualifier)
3246
0
    return;
3247
3248
0
  std::string PrintedNNS;
3249
0
  {
3250
0
    llvm::raw_string_ostream OS(PrintedNNS);
3251
0
    Qualifier->print(OS, Policy);
3252
0
  }
3253
0
  if (QualifierIsInformative)
3254
0
    Result.AddInformativeChunk(Result.getAllocator().CopyString(PrintedNNS));
3255
0
  else
3256
0
    Result.AddTextChunk(Result.getAllocator().CopyString(PrintedNNS));
3257
0
}
3258
3259
static void
3260
AddFunctionTypeQualsToCompletionString(CodeCompletionBuilder &Result,
3261
0
                                       const FunctionDecl *Function) {
3262
0
  const auto *Proto = Function->getType()->getAs<FunctionProtoType>();
3263
0
  if (!Proto || !Proto->getMethodQuals())
3264
0
    return;
3265
3266
  // FIXME: Add ref-qualifier!
3267
3268
  // Handle single qualifiers without copying
3269
0
  if (Proto->getMethodQuals().hasOnlyConst()) {
3270
0
    Result.AddInformativeChunk(" const");
3271
0
    return;
3272
0
  }
3273
3274
0
  if (Proto->getMethodQuals().hasOnlyVolatile()) {
3275
0
    Result.AddInformativeChunk(" volatile");
3276
0
    return;
3277
0
  }
3278
3279
0
  if (Proto->getMethodQuals().hasOnlyRestrict()) {
3280
0
    Result.AddInformativeChunk(" restrict");
3281
0
    return;
3282
0
  }
3283
3284
  // Handle multiple qualifiers.
3285
0
  std::string QualsStr;
3286
0
  if (Proto->isConst())
3287
0
    QualsStr += " const";
3288
0
  if (Proto->isVolatile())
3289
0
    QualsStr += " volatile";
3290
0
  if (Proto->isRestrict())
3291
0
    QualsStr += " restrict";
3292
0
  Result.AddInformativeChunk(Result.getAllocator().CopyString(QualsStr));
3293
0
}
3294
3295
/// Add the name of the given declaration
3296
static void AddTypedNameChunk(ASTContext &Context, const PrintingPolicy &Policy,
3297
                              const NamedDecl *ND,
3298
0
                              CodeCompletionBuilder &Result) {
3299
0
  DeclarationName Name = ND->getDeclName();
3300
0
  if (!Name)
3301
0
    return;
3302
3303
0
  switch (Name.getNameKind()) {
3304
0
  case DeclarationName::CXXOperatorName: {
3305
0
    const char *OperatorName = nullptr;
3306
0
    switch (Name.getCXXOverloadedOperator()) {
3307
0
    case OO_None:
3308
0
    case OO_Conditional:
3309
0
    case NUM_OVERLOADED_OPERATORS:
3310
0
      OperatorName = "operator";
3311
0
      break;
3312
3313
0
#define OVERLOADED_OPERATOR(Name, Spelling, Token, Unary, Binary, MemberOnly)  \
3314
0
  case OO_##Name:                                                              \
3315
0
    OperatorName = "operator" Spelling;                                        \
3316
0
    break;
3317
0
#define OVERLOADED_OPERATOR_MULTI(Name, Spelling, Unary, Binary, MemberOnly)
3318
0
#include "clang/Basic/OperatorKinds.def"
3319
3320
0
    case OO_New:
3321
0
      OperatorName = "operator new";
3322
0
      break;
3323
0
    case OO_Delete:
3324
0
      OperatorName = "operator delete";
3325
0
      break;
3326
0
    case OO_Array_New:
3327
0
      OperatorName = "operator new[]";
3328
0
      break;
3329
0
    case OO_Array_Delete:
3330
0
      OperatorName = "operator delete[]";
3331
0
      break;
3332
0
    case OO_Call:
3333
0
      OperatorName = "operator()";
3334
0
      break;
3335
0
    case OO_Subscript:
3336
0
      OperatorName = "operator[]";
3337
0
      break;
3338
0
    }
3339
0
    Result.AddTypedTextChunk(OperatorName);
3340
0
    break;
3341
0
  }
3342
3343
0
  case DeclarationName::Identifier:
3344
0
  case DeclarationName::CXXConversionFunctionName:
3345
0
  case DeclarationName::CXXDestructorName:
3346
0
  case DeclarationName::CXXLiteralOperatorName:
3347
0
    Result.AddTypedTextChunk(
3348
0
        Result.getAllocator().CopyString(ND->getNameAsString()));
3349
0
    break;
3350
3351
0
  case DeclarationName::CXXDeductionGuideName:
3352
0
  case DeclarationName::CXXUsingDirective:
3353
0
  case DeclarationName::ObjCZeroArgSelector:
3354
0
  case DeclarationName::ObjCOneArgSelector:
3355
0
  case DeclarationName::ObjCMultiArgSelector:
3356
0
    break;
3357
3358
0
  case DeclarationName::CXXConstructorName: {
3359
0
    CXXRecordDecl *Record = nullptr;
3360
0
    QualType Ty = Name.getCXXNameType();
3361
0
    if (const auto *RecordTy = Ty->getAs<RecordType>())
3362
0
      Record = cast<CXXRecordDecl>(RecordTy->getDecl());
3363
0
    else if (const auto *InjectedTy = Ty->getAs<InjectedClassNameType>())
3364
0
      Record = InjectedTy->getDecl();
3365
0
    else {
3366
0
      Result.AddTypedTextChunk(
3367
0
          Result.getAllocator().CopyString(ND->getNameAsString()));
3368
0
      break;
3369
0
    }
3370
3371
0
    Result.AddTypedTextChunk(
3372
0
        Result.getAllocator().CopyString(Record->getNameAsString()));
3373
0
    if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) {
3374
0
      Result.AddChunk(CodeCompletionString::CK_LeftAngle);
3375
0
      AddTemplateParameterChunks(Context, Policy, Template, Result);
3376
0
      Result.AddChunk(CodeCompletionString::CK_RightAngle);
3377
0
    }
3378
0
    break;
3379
0
  }
3380
0
  }
3381
0
}
3382
3383
CodeCompletionString *CodeCompletionResult::CreateCodeCompletionString(
3384
    Sema &S, const CodeCompletionContext &CCContext,
3385
    CodeCompletionAllocator &Allocator, CodeCompletionTUInfo &CCTUInfo,
3386
0
    bool IncludeBriefComments) {
3387
0
  return CreateCodeCompletionString(S.Context, S.PP, CCContext, Allocator,
3388
0
                                    CCTUInfo, IncludeBriefComments);
3389
0
}
3390
3391
CodeCompletionString *CodeCompletionResult::CreateCodeCompletionStringForMacro(
3392
    Preprocessor &PP, CodeCompletionAllocator &Allocator,
3393
0
    CodeCompletionTUInfo &CCTUInfo) {
3394
0
  assert(Kind == RK_Macro);
3395
0
  CodeCompletionBuilder Result(Allocator, CCTUInfo, Priority, Availability);
3396
0
  const MacroInfo *MI = PP.getMacroInfo(Macro);
3397
0
  Result.AddTypedTextChunk(Result.getAllocator().CopyString(Macro->getName()));
3398
3399
0
  if (!MI || !MI->isFunctionLike())
3400
0
    return Result.TakeString();
3401
3402
  // Format a function-like macro with placeholders for the arguments.
3403
0
  Result.AddChunk(CodeCompletionString::CK_LeftParen);
3404
0
  MacroInfo::param_iterator A = MI->param_begin(), AEnd = MI->param_end();
3405
3406
  // C99 variadic macros add __VA_ARGS__ at the end. Skip it.
3407
0
  if (MI->isC99Varargs()) {
3408
0
    --AEnd;
3409
3410
0
    if (A == AEnd) {
3411
0
      Result.AddPlaceholderChunk("...");
3412
0
    }
3413
0
  }
3414
3415
0
  for (MacroInfo::param_iterator A = MI->param_begin(); A != AEnd; ++A) {
3416
0
    if (A != MI->param_begin())
3417
0
      Result.AddChunk(CodeCompletionString::CK_Comma);
3418
3419
0
    if (MI->isVariadic() && (A + 1) == AEnd) {
3420
0
      SmallString<32> Arg = (*A)->getName();
3421
0
      if (MI->isC99Varargs())
3422
0
        Arg += ", ...";
3423
0
      else
3424
0
        Arg += "...";
3425
0
      Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
3426
0
      break;
3427
0
    }
3428
3429
    // Non-variadic macros are simple.
3430
0
    Result.AddPlaceholderChunk(
3431
0
        Result.getAllocator().CopyString((*A)->getName()));
3432
0
  }
3433
0
  Result.AddChunk(CodeCompletionString::CK_RightParen);
3434
0
  return Result.TakeString();
3435
0
}
3436
3437
/// If possible, create a new code completion string for the given
3438
/// result.
3439
///
3440
/// \returns Either a new, heap-allocated code completion string describing
3441
/// how to use this result, or NULL to indicate that the string or name of the
3442
/// result is all that is needed.
3443
CodeCompletionString *CodeCompletionResult::CreateCodeCompletionString(
3444
    ASTContext &Ctx, Preprocessor &PP, const CodeCompletionContext &CCContext,
3445
    CodeCompletionAllocator &Allocator, CodeCompletionTUInfo &CCTUInfo,
3446
0
    bool IncludeBriefComments) {
3447
0
  if (Kind == RK_Macro)
3448
0
    return CreateCodeCompletionStringForMacro(PP, Allocator, CCTUInfo);
3449
3450
0
  CodeCompletionBuilder Result(Allocator, CCTUInfo, Priority, Availability);
3451
3452
0
  PrintingPolicy Policy = getCompletionPrintingPolicy(Ctx, PP);
3453
0
  if (Kind == RK_Pattern) {
3454
0
    Pattern->Priority = Priority;
3455
0
    Pattern->Availability = Availability;
3456
3457
0
    if (Declaration) {
3458
0
      Result.addParentContext(Declaration->getDeclContext());
3459
0
      Pattern->ParentName = Result.getParentName();
3460
0
      if (const RawComment *RC =
3461
0
              getPatternCompletionComment(Ctx, Declaration)) {
3462
0
        Result.addBriefComment(RC->getBriefText(Ctx));
3463
0
        Pattern->BriefComment = Result.getBriefComment();
3464
0
      }
3465
0
    }
3466
3467
0
    return Pattern;
3468
0
  }
3469
3470
0
  if (Kind == RK_Keyword) {
3471
0
    Result.AddTypedTextChunk(Keyword);
3472
0
    return Result.TakeString();
3473
0
  }
3474
0
  assert(Kind == RK_Declaration && "Missed a result kind?");
3475
0
  return createCodeCompletionStringForDecl(
3476
0
      PP, Ctx, Result, IncludeBriefComments, CCContext, Policy);
3477
0
}
3478
3479
static void printOverrideString(const CodeCompletionString &CCS,
3480
                                std::string &BeforeName,
3481
0
                                std::string &NameAndSignature) {
3482
0
  bool SeenTypedChunk = false;
3483
0
  for (auto &Chunk : CCS) {
3484
0
    if (Chunk.Kind == CodeCompletionString::CK_Optional) {
3485
0
      assert(SeenTypedChunk && "optional parameter before name");
3486
      // Note that we put all chunks inside into NameAndSignature.
3487
0
      printOverrideString(*Chunk.Optional, NameAndSignature, NameAndSignature);
3488
0
      continue;
3489
0
    }
3490
0
    SeenTypedChunk |= Chunk.Kind == CodeCompletionString::CK_TypedText;
3491
0
    if (SeenTypedChunk)
3492
0
      NameAndSignature += Chunk.Text;
3493
0
    else
3494
0
      BeforeName += Chunk.Text;
3495
0
  }
3496
0
}
3497
3498
CodeCompletionString *
3499
CodeCompletionResult::createCodeCompletionStringForOverride(
3500
    Preprocessor &PP, ASTContext &Ctx, CodeCompletionBuilder &Result,
3501
    bool IncludeBriefComments, const CodeCompletionContext &CCContext,
3502
0
    PrintingPolicy &Policy) {
3503
0
  auto *CCS = createCodeCompletionStringForDecl(PP, Ctx, Result,
3504
0
                                                /*IncludeBriefComments=*/false,
3505
0
                                                CCContext, Policy);
3506
0
  std::string BeforeName;
3507
0
  std::string NameAndSignature;
3508
  // For overrides all chunks go into the result, none are informative.
3509
0
  printOverrideString(*CCS, BeforeName, NameAndSignature);
3510
0
  NameAndSignature += " override";
3511
3512
0
  Result.AddTextChunk(Result.getAllocator().CopyString(BeforeName));
3513
0
  Result.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3514
0
  Result.AddTypedTextChunk(Result.getAllocator().CopyString(NameAndSignature));
3515
0
  return Result.TakeString();
3516
0
}
3517
3518
// FIXME: Right now this works well with lambdas. Add support for other functor
3519
// types like std::function.
3520
0
static const NamedDecl *extractFunctorCallOperator(const NamedDecl *ND) {
3521
0
  const auto *VD = dyn_cast<VarDecl>(ND);
3522
0
  if (!VD)
3523
0
    return nullptr;
3524
0
  const auto *RecordDecl = VD->getType()->getAsCXXRecordDecl();
3525
0
  if (!RecordDecl || !RecordDecl->isLambda())
3526
0
    return nullptr;
3527
0
  return RecordDecl->getLambdaCallOperator();
3528
0
}
3529
3530
CodeCompletionString *CodeCompletionResult::createCodeCompletionStringForDecl(
3531
    Preprocessor &PP, ASTContext &Ctx, CodeCompletionBuilder &Result,
3532
    bool IncludeBriefComments, const CodeCompletionContext &CCContext,
3533
0
    PrintingPolicy &Policy) {
3534
0
  const NamedDecl *ND = Declaration;
3535
0
  Result.addParentContext(ND->getDeclContext());
3536
3537
0
  if (IncludeBriefComments) {
3538
    // Add documentation comment, if it exists.
3539
0
    if (const RawComment *RC = getCompletionComment(Ctx, Declaration)) {
3540
0
      Result.addBriefComment(RC->getBriefText(Ctx));
3541
0
    }
3542
0
  }
3543
3544
0
  if (StartsNestedNameSpecifier) {
3545
0
    Result.AddTypedTextChunk(
3546
0
        Result.getAllocator().CopyString(ND->getNameAsString()));
3547
0
    Result.AddTextChunk("::");
3548
0
    return Result.TakeString();
3549
0
  }
3550
3551
0
  for (const auto *I : ND->specific_attrs<AnnotateAttr>())
3552
0
    Result.AddAnnotation(Result.getAllocator().CopyString(I->getAnnotation()));
3553
3554
0
  auto AddFunctionTypeAndResult = [&](const FunctionDecl *Function) {
3555
0
    AddResultTypeChunk(Ctx, Policy, Function, CCContext.getBaseType(), Result);
3556
0
    AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
3557
0
                                   Ctx, Policy);
3558
0
    AddTypedNameChunk(Ctx, Policy, ND, Result);
3559
0
    Result.AddChunk(CodeCompletionString::CK_LeftParen);
3560
0
    AddFunctionParameterChunks(PP, Policy, Function, Result);
3561
0
    Result.AddChunk(CodeCompletionString::CK_RightParen);
3562
0
    AddFunctionTypeQualsToCompletionString(Result, Function);
3563
0
  };
3564
3565
0
  if (const auto *Function = dyn_cast<FunctionDecl>(ND)) {
3566
0
    AddFunctionTypeAndResult(Function);
3567
0
    return Result.TakeString();
3568
0
  }
3569
3570
0
  if (const auto *CallOperator =
3571
0
          dyn_cast_or_null<FunctionDecl>(extractFunctorCallOperator(ND))) {
3572
0
    AddFunctionTypeAndResult(CallOperator);
3573
0
    return Result.TakeString();
3574
0
  }
3575
3576
0
  AddResultTypeChunk(Ctx, Policy, ND, CCContext.getBaseType(), Result);
3577
3578
0
  if (const FunctionTemplateDecl *FunTmpl =
3579
0
          dyn_cast<FunctionTemplateDecl>(ND)) {
3580
0
    AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
3581
0
                                   Ctx, Policy);
3582
0
    FunctionDecl *Function = FunTmpl->getTemplatedDecl();
3583
0
    AddTypedNameChunk(Ctx, Policy, Function, Result);
3584
3585
    // Figure out which template parameters are deduced (or have default
3586
    // arguments).
3587
    // Note that we're creating a non-empty bit vector so that we can go
3588
    // through the loop below to omit default template parameters for non-call
3589
    // cases.
3590
0
    llvm::SmallBitVector Deduced(FunTmpl->getTemplateParameters()->size());
3591
    // Avoid running it if this is not a call: We should emit *all* template
3592
    // parameters.
3593
0
    if (FunctionCanBeCall)
3594
0
      Sema::MarkDeducedTemplateParameters(Ctx, FunTmpl, Deduced);
3595
0
    unsigned LastDeducibleArgument;
3596
0
    for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0;
3597
0
         --LastDeducibleArgument) {
3598
0
      if (!Deduced[LastDeducibleArgument - 1]) {
3599
        // C++0x: Figure out if the template argument has a default. If so,
3600
        // the user doesn't need to type this argument.
3601
        // FIXME: We need to abstract template parameters better!
3602
0
        bool HasDefaultArg = false;
3603
0
        NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam(
3604
0
            LastDeducibleArgument - 1);
3605
0
        if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
3606
0
          HasDefaultArg = TTP->hasDefaultArgument();
3607
0
        else if (NonTypeTemplateParmDecl *NTTP =
3608
0
                     dyn_cast<NonTypeTemplateParmDecl>(Param))
3609
0
          HasDefaultArg = NTTP->hasDefaultArgument();
3610
0
        else {
3611
0
          assert(isa<TemplateTemplateParmDecl>(Param));
3612
0
          HasDefaultArg =
3613
0
              cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument();
3614
0
        }
3615
3616
0
        if (!HasDefaultArg)
3617
0
          break;
3618
0
      }
3619
0
    }
3620
3621
0
    if (LastDeducibleArgument || !FunctionCanBeCall) {
3622
      // Some of the function template arguments cannot be deduced from a
3623
      // function call, so we introduce an explicit template argument list
3624
      // containing all of the arguments up to the first deducible argument.
3625
      //
3626
      // Or, if this isn't a call, emit all the template arguments
3627
      // to disambiguate the (potential) overloads.
3628
      //
3629
      // FIXME: Detect cases where the function parameters can be deduced from
3630
      // the surrounding context, as per [temp.deduct.funcaddr].
3631
      // e.g.,
3632
      // template <class T> void foo(T);
3633
      // void (*f)(int) = foo;
3634
0
      Result.AddChunk(CodeCompletionString::CK_LeftAngle);
3635
0
      AddTemplateParameterChunks(Ctx, Policy, FunTmpl, Result,
3636
0
                                 LastDeducibleArgument);
3637
0
      Result.AddChunk(CodeCompletionString::CK_RightAngle);
3638
0
    }
3639
3640
    // Add the function parameters
3641
0
    Result.AddChunk(CodeCompletionString::CK_LeftParen);
3642
0
    AddFunctionParameterChunks(PP, Policy, Function, Result);
3643
0
    Result.AddChunk(CodeCompletionString::CK_RightParen);
3644
0
    AddFunctionTypeQualsToCompletionString(Result, Function);
3645
0
    return Result.TakeString();
3646
0
  }
3647
3648
0
  if (const auto *Template = dyn_cast<TemplateDecl>(ND)) {
3649
0
    AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
3650
0
                                   Ctx, Policy);
3651
0
    Result.AddTypedTextChunk(
3652
0
        Result.getAllocator().CopyString(Template->getNameAsString()));
3653
0
    Result.AddChunk(CodeCompletionString::CK_LeftAngle);
3654
0
    AddTemplateParameterChunks(Ctx, Policy, Template, Result);
3655
0
    Result.AddChunk(CodeCompletionString::CK_RightAngle);
3656
0
    return Result.TakeString();
3657
0
  }
3658
3659
0
  if (const auto *Method = dyn_cast<ObjCMethodDecl>(ND)) {
3660
0
    Selector Sel = Method->getSelector();
3661
0
    if (Sel.isUnarySelector()) {
3662
0
      Result.AddTypedTextChunk(
3663
0
          Result.getAllocator().CopyString(Sel.getNameForSlot(0)));
3664
0
      return Result.TakeString();
3665
0
    }
3666
3667
0
    std::string SelName = Sel.getNameForSlot(0).str();
3668
0
    SelName += ':';
3669
0
    if (StartParameter == 0)
3670
0
      Result.AddTypedTextChunk(Result.getAllocator().CopyString(SelName));
3671
0
    else {
3672
0
      Result.AddInformativeChunk(Result.getAllocator().CopyString(SelName));
3673
3674
      // If there is only one parameter, and we're past it, add an empty
3675
      // typed-text chunk since there is nothing to type.
3676
0
      if (Method->param_size() == 1)
3677
0
        Result.AddTypedTextChunk("");
3678
0
    }
3679
0
    unsigned Idx = 0;
3680
    // The extra Idx < Sel.getNumArgs() check is needed due to legacy C-style
3681
    // method parameters.
3682
0
    for (ObjCMethodDecl::param_const_iterator P = Method->param_begin(),
3683
0
                                              PEnd = Method->param_end();
3684
0
         P != PEnd && Idx < Sel.getNumArgs(); (void)++P, ++Idx) {
3685
0
      if (Idx > 0) {
3686
0
        std::string Keyword;
3687
0
        if (Idx > StartParameter)
3688
0
          Result.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3689
0
        if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(Idx))
3690
0
          Keyword += II->getName();
3691
0
        Keyword += ":";
3692
0
        if (Idx < StartParameter || AllParametersAreInformative)
3693
0
          Result.AddInformativeChunk(Result.getAllocator().CopyString(Keyword));
3694
0
        else
3695
0
          Result.AddTypedTextChunk(Result.getAllocator().CopyString(Keyword));
3696
0
      }
3697
3698
      // If we're before the starting parameter, skip the placeholder.
3699
0
      if (Idx < StartParameter)
3700
0
        continue;
3701
3702
0
      std::string Arg;
3703
0
      QualType ParamType = (*P)->getType();
3704
0
      std::optional<ArrayRef<QualType>> ObjCSubsts;
3705
0
      if (!CCContext.getBaseType().isNull())
3706
0
        ObjCSubsts = CCContext.getBaseType()->getObjCSubstitutions(Method);
3707
3708
0
      if (ParamType->isBlockPointerType() && !DeclaringEntity)
3709
0
        Arg = FormatFunctionParameter(Policy, *P, true,
3710
0
                                      /*SuppressBlock=*/false, ObjCSubsts);
3711
0
      else {
3712
0
        if (ObjCSubsts)
3713
0
          ParamType = ParamType.substObjCTypeArgs(
3714
0
              Ctx, *ObjCSubsts, ObjCSubstitutionContext::Parameter);
3715
0
        Arg = "(" + formatObjCParamQualifiers((*P)->getObjCDeclQualifier(),
3716
0
                                              ParamType);
3717
0
        Arg += ParamType.getAsString(Policy) + ")";
3718
0
        if (IdentifierInfo *II = (*P)->getIdentifier())
3719
0
          if (DeclaringEntity || AllParametersAreInformative)
3720
0
            Arg += II->getName();
3721
0
      }
3722
3723
0
      if (Method->isVariadic() && (P + 1) == PEnd)
3724
0
        Arg += ", ...";
3725
3726
0
      if (DeclaringEntity)
3727
0
        Result.AddTextChunk(Result.getAllocator().CopyString(Arg));
3728
0
      else if (AllParametersAreInformative)
3729
0
        Result.AddInformativeChunk(Result.getAllocator().CopyString(Arg));
3730
0
      else
3731
0
        Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
3732
0
    }
3733
3734
0
    if (Method->isVariadic()) {
3735
0
      if (Method->param_size() == 0) {
3736
0
        if (DeclaringEntity)
3737
0
          Result.AddTextChunk(", ...");
3738
0
        else if (AllParametersAreInformative)
3739
0
          Result.AddInformativeChunk(", ...");
3740
0
        else
3741
0
          Result.AddPlaceholderChunk(", ...");
3742
0
      }
3743
3744
0
      MaybeAddSentinel(PP, Method, Result);
3745
0
    }
3746
3747
0
    return Result.TakeString();
3748
0
  }
3749
3750
0
  if (Qualifier)
3751
0
    AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
3752
0
                                   Ctx, Policy);
3753
3754
0
  Result.AddTypedTextChunk(
3755
0
      Result.getAllocator().CopyString(ND->getNameAsString()));
3756
0
  return Result.TakeString();
3757
0
}
3758
3759
const RawComment *clang::getCompletionComment(const ASTContext &Ctx,
3760
0
                                              const NamedDecl *ND) {
3761
0
  if (!ND)
3762
0
    return nullptr;
3763
0
  if (auto *RC = Ctx.getRawCommentForAnyRedecl(ND))
3764
0
    return RC;
3765
3766
  // Try to find comment from a property for ObjC methods.
3767
0
  const auto *M = dyn_cast<ObjCMethodDecl>(ND);
3768
0
  if (!M)
3769
0
    return nullptr;
3770
0
  const ObjCPropertyDecl *PDecl = M->findPropertyDecl();
3771
0
  if (!PDecl)
3772
0
    return nullptr;
3773
3774
0
  return Ctx.getRawCommentForAnyRedecl(PDecl);
3775
0
}
3776
3777
const RawComment *clang::getPatternCompletionComment(const ASTContext &Ctx,
3778
0
                                                     const NamedDecl *ND) {
3779
0
  const auto *M = dyn_cast_or_null<ObjCMethodDecl>(ND);
3780
0
  if (!M || !M->isPropertyAccessor())
3781
0
    return nullptr;
3782
3783
  // Provide code completion comment for self.GetterName where
3784
  // GetterName is the getter method for a property with name
3785
  // different from the property name (declared via a property
3786
  // getter attribute.
3787
0
  const ObjCPropertyDecl *PDecl = M->findPropertyDecl();
3788
0
  if (!PDecl)
3789
0
    return nullptr;
3790
0
  if (PDecl->getGetterName() == M->getSelector() &&
3791
0
      PDecl->getIdentifier() != M->getIdentifier()) {
3792
0
    if (auto *RC = Ctx.getRawCommentForAnyRedecl(M))
3793
0
      return RC;
3794
0
    if (auto *RC = Ctx.getRawCommentForAnyRedecl(PDecl))
3795
0
      return RC;
3796
0
  }
3797
0
  return nullptr;
3798
0
}
3799
3800
const RawComment *clang::getParameterComment(
3801
    const ASTContext &Ctx,
3802
0
    const CodeCompleteConsumer::OverloadCandidate &Result, unsigned ArgIndex) {
3803
0
  auto FDecl = Result.getFunction();
3804
0
  if (!FDecl)
3805
0
    return nullptr;
3806
0
  if (ArgIndex < FDecl->getNumParams())
3807
0
    return Ctx.getRawCommentForAnyRedecl(FDecl->getParamDecl(ArgIndex));
3808
0
  return nullptr;
3809
0
}
3810
3811
static void AddOverloadAggregateChunks(const RecordDecl *RD,
3812
                                       const PrintingPolicy &Policy,
3813
                                       CodeCompletionBuilder &Result,
3814
0
                                       unsigned CurrentArg) {
3815
0
  unsigned ChunkIndex = 0;
3816
0
  auto AddChunk = [&](llvm::StringRef Placeholder) {
3817
0
    if (ChunkIndex > 0)
3818
0
      Result.AddChunk(CodeCompletionString::CK_Comma);
3819
0
    const char *Copy = Result.getAllocator().CopyString(Placeholder);
3820
0
    if (ChunkIndex == CurrentArg)
3821
0
      Result.AddCurrentParameterChunk(Copy);
3822
0
    else
3823
0
      Result.AddPlaceholderChunk(Copy);
3824
0
    ++ChunkIndex;
3825
0
  };
3826
  // Aggregate initialization has all bases followed by all fields.
3827
  // (Bases are not legal in C++11 but in that case we never get here).
3828
0
  if (auto *CRD = llvm::dyn_cast<CXXRecordDecl>(RD)) {
3829
0
    for (const auto &Base : CRD->bases())
3830
0
      AddChunk(Base.getType().getAsString(Policy));
3831
0
  }
3832
0
  for (const auto &Field : RD->fields())
3833
0
    AddChunk(FormatFunctionParameter(Policy, Field));
3834
0
}
3835
3836
/// Add function overload parameter chunks to the given code completion
3837
/// string.
3838
static void AddOverloadParameterChunks(
3839
    ASTContext &Context, const PrintingPolicy &Policy,
3840
    const FunctionDecl *Function, const FunctionProtoType *Prototype,
3841
    FunctionProtoTypeLoc PrototypeLoc, CodeCompletionBuilder &Result,
3842
0
    unsigned CurrentArg, unsigned Start = 0, bool InOptional = false) {
3843
0
  if (!Function && !Prototype) {
3844
0
    Result.AddChunk(CodeCompletionString::CK_CurrentParameter, "...");
3845
0
    return;
3846
0
  }
3847
3848
0
  bool FirstParameter = true;
3849
0
  unsigned NumParams =
3850
0
      Function ? Function->getNumParams() : Prototype->getNumParams();
3851
3852
0
  for (unsigned P = Start; P != NumParams; ++P) {
3853
0
    if (Function && Function->getParamDecl(P)->hasDefaultArg() && !InOptional) {
3854
      // When we see an optional default argument, put that argument and
3855
      // the remaining default arguments into a new, optional string.
3856
0
      CodeCompletionBuilder Opt(Result.getAllocator(),
3857
0
                                Result.getCodeCompletionTUInfo());
3858
0
      if (!FirstParameter)
3859
0
        Opt.AddChunk(CodeCompletionString::CK_Comma);
3860
      // Optional sections are nested.
3861
0
      AddOverloadParameterChunks(Context, Policy, Function, Prototype,
3862
0
                                 PrototypeLoc, Opt, CurrentArg, P,
3863
0
                                 /*InOptional=*/true);
3864
0
      Result.AddOptionalChunk(Opt.TakeString());
3865
0
      return;
3866
0
    }
3867
3868
0
    if (FirstParameter)
3869
0
      FirstParameter = false;
3870
0
    else
3871
0
      Result.AddChunk(CodeCompletionString::CK_Comma);
3872
3873
0
    InOptional = false;
3874
3875
    // Format the placeholder string.
3876
0
    std::string Placeholder;
3877
0
    assert(P < Prototype->getNumParams());
3878
0
    if (Function || PrototypeLoc) {
3879
0
      const ParmVarDecl *Param =
3880
0
          Function ? Function->getParamDecl(P) : PrototypeLoc.getParam(P);
3881
0
      Placeholder = FormatFunctionParameter(Policy, Param);
3882
0
      if (Param->hasDefaultArg())
3883
0
        Placeholder += GetDefaultValueString(Param, Context.getSourceManager(),
3884
0
                                             Context.getLangOpts());
3885
0
    } else {
3886
0
      Placeholder = Prototype->getParamType(P).getAsString(Policy);
3887
0
    }
3888
3889
0
    if (P == CurrentArg)
3890
0
      Result.AddCurrentParameterChunk(
3891
0
          Result.getAllocator().CopyString(Placeholder));
3892
0
    else
3893
0
      Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Placeholder));
3894
0
  }
3895
3896
0
  if (Prototype && Prototype->isVariadic()) {
3897
0
    CodeCompletionBuilder Opt(Result.getAllocator(),
3898
0
                              Result.getCodeCompletionTUInfo());
3899
0
    if (!FirstParameter)
3900
0
      Opt.AddChunk(CodeCompletionString::CK_Comma);
3901
3902
0
    if (CurrentArg < NumParams)
3903
0
      Opt.AddPlaceholderChunk("...");
3904
0
    else
3905
0
      Opt.AddCurrentParameterChunk("...");
3906
3907
0
    Result.AddOptionalChunk(Opt.TakeString());
3908
0
  }
3909
0
}
3910
3911
static std::string
3912
formatTemplateParameterPlaceholder(const NamedDecl *Param, bool &Optional,
3913
0
                                   const PrintingPolicy &Policy) {
3914
0
  if (const auto *Type = dyn_cast<TemplateTypeParmDecl>(Param)) {
3915
0
    Optional = Type->hasDefaultArgument();
3916
0
  } else if (const auto *NonType = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3917
0
    Optional = NonType->hasDefaultArgument();
3918
0
  } else if (const auto *Template = dyn_cast<TemplateTemplateParmDecl>(Param)) {
3919
0
    Optional = Template->hasDefaultArgument();
3920
0
  }
3921
0
  std::string Result;
3922
0
  llvm::raw_string_ostream OS(Result);
3923
0
  Param->print(OS, Policy);
3924
0
  return Result;
3925
0
}
3926
3927
static std::string templateResultType(const TemplateDecl *TD,
3928
0
                                      const PrintingPolicy &Policy) {
3929
0
  if (const auto *CTD = dyn_cast<ClassTemplateDecl>(TD))
3930
0
    return CTD->getTemplatedDecl()->getKindName().str();
3931
0
  if (const auto *VTD = dyn_cast<VarTemplateDecl>(TD))
3932
0
    return VTD->getTemplatedDecl()->getType().getAsString(Policy);
3933
0
  if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(TD))
3934
0
    return FTD->getTemplatedDecl()->getReturnType().getAsString(Policy);
3935
0
  if (isa<TypeAliasTemplateDecl>(TD))
3936
0
    return "type";
3937
0
  if (isa<TemplateTemplateParmDecl>(TD))
3938
0
    return "class";
3939
0
  if (isa<ConceptDecl>(TD))
3940
0
    return "concept";
3941
0
  return "";
3942
0
}
3943
3944
static CodeCompletionString *createTemplateSignatureString(
3945
    const TemplateDecl *TD, CodeCompletionBuilder &Builder, unsigned CurrentArg,
3946
0
    const PrintingPolicy &Policy) {
3947
0
  llvm::ArrayRef<NamedDecl *> Params = TD->getTemplateParameters()->asArray();
3948
0
  CodeCompletionBuilder OptionalBuilder(Builder.getAllocator(),
3949
0
                                        Builder.getCodeCompletionTUInfo());
3950
0
  std::string ResultType = templateResultType(TD, Policy);
3951
0
  if (!ResultType.empty())
3952
0
    Builder.AddResultTypeChunk(Builder.getAllocator().CopyString(ResultType));
3953
0
  Builder.AddTextChunk(
3954
0
      Builder.getAllocator().CopyString(TD->getNameAsString()));
3955
0
  Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
3956
  // Initially we're writing into the main string. Once we see an optional arg
3957
  // (with default), we're writing into the nested optional chunk.
3958
0
  CodeCompletionBuilder *Current = &Builder;
3959
0
  for (unsigned I = 0; I < Params.size(); ++I) {
3960
0
    bool Optional = false;
3961
0
    std::string Placeholder =
3962
0
        formatTemplateParameterPlaceholder(Params[I], Optional, Policy);
3963
0
    if (Optional)
3964
0
      Current = &OptionalBuilder;
3965
0
    if (I > 0)
3966
0
      Current->AddChunk(CodeCompletionString::CK_Comma);
3967
0
    Current->AddChunk(I == CurrentArg
3968
0
                          ? CodeCompletionString::CK_CurrentParameter
3969
0
                          : CodeCompletionString::CK_Placeholder,
3970
0
                      Current->getAllocator().CopyString(Placeholder));
3971
0
  }
3972
  // Add the optional chunk to the main string if we ever used it.
3973
0
  if (Current == &OptionalBuilder)
3974
0
    Builder.AddOptionalChunk(OptionalBuilder.TakeString());
3975
0
  Builder.AddChunk(CodeCompletionString::CK_RightAngle);
3976
  // For function templates, ResultType was the function's return type.
3977
  // Give some clue this is a function. (Don't show the possibly-bulky params).
3978
0
  if (isa<FunctionTemplateDecl>(TD))
3979
0
    Builder.AddInformativeChunk("()");
3980
0
  return Builder.TakeString();
3981
0
}
3982
3983
CodeCompletionString *
3984
CodeCompleteConsumer::OverloadCandidate::CreateSignatureString(
3985
    unsigned CurrentArg, Sema &S, CodeCompletionAllocator &Allocator,
3986
    CodeCompletionTUInfo &CCTUInfo, bool IncludeBriefComments,
3987
0
    bool Braced) const {
3988
0
  PrintingPolicy Policy = getCompletionPrintingPolicy(S);
3989
  // Show signatures of constructors as they are declared:
3990
  //   vector(int n) rather than vector<string>(int n)
3991
  // This is less noisy without being less clear, and avoids tricky cases.
3992
0
  Policy.SuppressTemplateArgsInCXXConstructors = true;
3993
3994
  // FIXME: Set priority, availability appropriately.
3995
0
  CodeCompletionBuilder Result(Allocator, CCTUInfo, 1,
3996
0
                               CXAvailability_Available);
3997
3998
0
  if (getKind() == CK_Template)
3999
0
    return createTemplateSignatureString(getTemplate(), Result, CurrentArg,
4000
0
                                         Policy);
4001
4002
0
  FunctionDecl *FDecl = getFunction();
4003
0
  const FunctionProtoType *Proto =
4004
0
      dyn_cast_or_null<FunctionProtoType>(getFunctionType());
4005
4006
  // First, the name/type of the callee.
4007
0
  if (getKind() == CK_Aggregate) {
4008
0
    Result.AddTextChunk(
4009
0
        Result.getAllocator().CopyString(getAggregate()->getName()));
4010
0
  } else if (FDecl) {
4011
0
    if (IncludeBriefComments) {
4012
0
      if (auto RC = getParameterComment(S.getASTContext(), *this, CurrentArg))
4013
0
        Result.addBriefComment(RC->getBriefText(S.getASTContext()));
4014
0
    }
4015
0
    AddResultTypeChunk(S.Context, Policy, FDecl, QualType(), Result);
4016
4017
0
    std::string Name;
4018
0
    llvm::raw_string_ostream OS(Name);
4019
0
    FDecl->getDeclName().print(OS, Policy);
4020
0
    Result.AddTextChunk(Result.getAllocator().CopyString(OS.str()));
4021
0
  } else {
4022
    // Function without a declaration. Just give the return type.
4023
0
    Result.AddResultTypeChunk(Result.getAllocator().CopyString(
4024
0
        getFunctionType()->getReturnType().getAsString(Policy)));
4025
0
  }
4026
4027
  // Next, the brackets and parameters.
4028
0
  Result.AddChunk(Braced ? CodeCompletionString::CK_LeftBrace
4029
0
                         : CodeCompletionString::CK_LeftParen);
4030
0
  if (getKind() == CK_Aggregate)
4031
0
    AddOverloadAggregateChunks(getAggregate(), Policy, Result, CurrentArg);
4032
0
  else
4033
0
    AddOverloadParameterChunks(S.getASTContext(), Policy, FDecl, Proto,
4034
0
                               getFunctionProtoTypeLoc(), Result, CurrentArg);
4035
0
  Result.AddChunk(Braced ? CodeCompletionString::CK_RightBrace
4036
0
                         : CodeCompletionString::CK_RightParen);
4037
4038
0
  return Result.TakeString();
4039
0
}
4040
4041
unsigned clang::getMacroUsagePriority(StringRef MacroName,
4042
                                      const LangOptions &LangOpts,
4043
0
                                      bool PreferredTypeIsPointer) {
4044
0
  unsigned Priority = CCP_Macro;
4045
4046
  // Treat the "nil", "Nil" and "NULL" macros as null pointer constants.
4047
0
  if (MacroName.equals("nil") || MacroName.equals("NULL") ||
4048
0
      MacroName.equals("Nil")) {
4049
0
    Priority = CCP_Constant;
4050
0
    if (PreferredTypeIsPointer)
4051
0
      Priority = Priority / CCF_SimilarTypeMatch;
4052
0
  }
4053
  // Treat "YES", "NO", "true", and "false" as constants.
4054
0
  else if (MacroName.equals("YES") || MacroName.equals("NO") ||
4055
0
           MacroName.equals("true") || MacroName.equals("false"))
4056
0
    Priority = CCP_Constant;
4057
  // Treat "bool" as a type.
4058
0
  else if (MacroName.equals("bool"))
4059
0
    Priority = CCP_Type + (LangOpts.ObjC ? CCD_bool_in_ObjC : 0);
4060
4061
0
  return Priority;
4062
0
}
4063
4064
0
CXCursorKind clang::getCursorKindForDecl(const Decl *D) {
4065
0
  if (!D)
4066
0
    return CXCursor_UnexposedDecl;
4067
4068
0
  switch (D->getKind()) {
4069
0
  case Decl::Enum:
4070
0
    return CXCursor_EnumDecl;
4071
0
  case Decl::EnumConstant:
4072
0
    return CXCursor_EnumConstantDecl;
4073
0
  case Decl::Field:
4074
0
    return CXCursor_FieldDecl;
4075
0
  case Decl::Function:
4076
0
    return CXCursor_FunctionDecl;
4077
0
  case Decl::ObjCCategory:
4078
0
    return CXCursor_ObjCCategoryDecl;
4079
0
  case Decl::ObjCCategoryImpl:
4080
0
    return CXCursor_ObjCCategoryImplDecl;
4081
0
  case Decl::ObjCImplementation:
4082
0
    return CXCursor_ObjCImplementationDecl;
4083
4084
0
  case Decl::ObjCInterface:
4085
0
    return CXCursor_ObjCInterfaceDecl;
4086
0
  case Decl::ObjCIvar:
4087
0
    return CXCursor_ObjCIvarDecl;
4088
0
  case Decl::ObjCMethod:
4089
0
    return cast<ObjCMethodDecl>(D)->isInstanceMethod()
4090
0
               ? CXCursor_ObjCInstanceMethodDecl
4091
0
               : CXCursor_ObjCClassMethodDecl;
4092
0
  case Decl::CXXMethod:
4093
0
    return CXCursor_CXXMethod;
4094
0
  case Decl::CXXConstructor:
4095
0
    return CXCursor_Constructor;
4096
0
  case Decl::CXXDestructor:
4097
0
    return CXCursor_Destructor;
4098
0
  case Decl::CXXConversion:
4099
0
    return CXCursor_ConversionFunction;
4100
0
  case Decl::ObjCProperty:
4101
0
    return CXCursor_ObjCPropertyDecl;
4102
0
  case Decl::ObjCProtocol:
4103
0
    return CXCursor_ObjCProtocolDecl;
4104
0
  case Decl::ParmVar:
4105
0
    return CXCursor_ParmDecl;
4106
0
  case Decl::Typedef:
4107
0
    return CXCursor_TypedefDecl;
4108
0
  case Decl::TypeAlias:
4109
0
    return CXCursor_TypeAliasDecl;
4110
0
  case Decl::TypeAliasTemplate:
4111
0
    return CXCursor_TypeAliasTemplateDecl;
4112
0
  case Decl::Var:
4113
0
    return CXCursor_VarDecl;
4114
0
  case Decl::Namespace:
4115
0
    return CXCursor_Namespace;
4116
0
  case Decl::NamespaceAlias:
4117
0
    return CXCursor_NamespaceAlias;
4118
0
  case Decl::TemplateTypeParm:
4119
0
    return CXCursor_TemplateTypeParameter;
4120
0
  case Decl::NonTypeTemplateParm:
4121
0
    return CXCursor_NonTypeTemplateParameter;
4122
0
  case Decl::TemplateTemplateParm:
4123
0
    return CXCursor_TemplateTemplateParameter;
4124
0
  case Decl::FunctionTemplate:
4125
0
    return CXCursor_FunctionTemplate;
4126
0
  case Decl::ClassTemplate:
4127
0
    return CXCursor_ClassTemplate;
4128
0
  case Decl::AccessSpec:
4129
0
    return CXCursor_CXXAccessSpecifier;
4130
0
  case Decl::ClassTemplatePartialSpecialization:
4131
0
    return CXCursor_ClassTemplatePartialSpecialization;
4132
0
  case Decl::UsingDirective:
4133
0
    return CXCursor_UsingDirective;
4134
0
  case Decl::StaticAssert:
4135
0
    return CXCursor_StaticAssert;
4136
0
  case Decl::Friend:
4137
0
    return CXCursor_FriendDecl;
4138
0
  case Decl::TranslationUnit:
4139
0
    return CXCursor_TranslationUnit;
4140
4141
0
  case Decl::Using:
4142
0
  case Decl::UnresolvedUsingValue:
4143
0
  case Decl::UnresolvedUsingTypename:
4144
0
    return CXCursor_UsingDeclaration;
4145
4146
0
  case Decl::UsingEnum:
4147
0
    return CXCursor_EnumDecl;
4148
4149
0
  case Decl::ObjCPropertyImpl:
4150
0
    switch (cast<ObjCPropertyImplDecl>(D)->getPropertyImplementation()) {
4151
0
    case ObjCPropertyImplDecl::Dynamic:
4152
0
      return CXCursor_ObjCDynamicDecl;
4153
4154
0
    case ObjCPropertyImplDecl::Synthesize:
4155
0
      return CXCursor_ObjCSynthesizeDecl;
4156
0
    }
4157
0
    llvm_unreachable("Unexpected Kind!");
4158
4159
0
  case Decl::Import:
4160
0
    return CXCursor_ModuleImportDecl;
4161
4162
0
  case Decl::ObjCTypeParam:
4163
0
    return CXCursor_TemplateTypeParameter;
4164
4165
0
  case Decl::Concept:
4166
0
    return CXCursor_ConceptDecl;
4167
4168
0
  case Decl::LinkageSpec:
4169
0
    return CXCursor_LinkageSpec;
4170
4171
0
  default:
4172
0
    if (const auto *TD = dyn_cast<TagDecl>(D)) {
4173
0
      switch (TD->getTagKind()) {
4174
0
      case TagTypeKind::Interface: // fall through
4175
0
      case TagTypeKind::Struct:
4176
0
        return CXCursor_StructDecl;
4177
0
      case TagTypeKind::Class:
4178
0
        return CXCursor_ClassDecl;
4179
0
      case TagTypeKind::Union:
4180
0
        return CXCursor_UnionDecl;
4181
0
      case TagTypeKind::Enum:
4182
0
        return CXCursor_EnumDecl;
4183
0
      }
4184
0
    }
4185
0
  }
4186
4187
0
  return CXCursor_UnexposedDecl;
4188
0
}
4189
4190
static void AddMacroResults(Preprocessor &PP, ResultBuilder &Results,
4191
                            bool LoadExternal, bool IncludeUndefined,
4192
0
                            bool TargetTypeIsPointer = false) {
4193
0
  typedef CodeCompletionResult Result;
4194
4195
0
  Results.EnterNewScope();
4196
4197
0
  for (Preprocessor::macro_iterator M = PP.macro_begin(LoadExternal),
4198
0
                                    MEnd = PP.macro_end(LoadExternal);
4199
0
       M != MEnd; ++M) {
4200
0
    auto MD = PP.getMacroDefinition(M->first);
4201
0
    if (IncludeUndefined || MD) {
4202
0
      MacroInfo *MI = MD.getMacroInfo();
4203
0
      if (MI && MI->isUsedForHeaderGuard())
4204
0
        continue;
4205
4206
0
      Results.AddResult(
4207
0
          Result(M->first, MI,
4208
0
                 getMacroUsagePriority(M->first->getName(), PP.getLangOpts(),
4209
0
                                       TargetTypeIsPointer)));
4210
0
    }
4211
0
  }
4212
4213
0
  Results.ExitScope();
4214
0
}
4215
4216
static void AddPrettyFunctionResults(const LangOptions &LangOpts,
4217
0
                                     ResultBuilder &Results) {
4218
0
  typedef CodeCompletionResult Result;
4219
4220
0
  Results.EnterNewScope();
4221
4222
0
  Results.AddResult(Result("__PRETTY_FUNCTION__", CCP_Constant));
4223
0
  Results.AddResult(Result("__FUNCTION__", CCP_Constant));
4224
0
  if (LangOpts.C99 || LangOpts.CPlusPlus11)
4225
0
    Results.AddResult(Result("__func__", CCP_Constant));
4226
0
  Results.ExitScope();
4227
0
}
4228
4229
static void HandleCodeCompleteResults(Sema *S,
4230
                                      CodeCompleteConsumer *CodeCompleter,
4231
                                      const CodeCompletionContext &Context,
4232
                                      CodeCompletionResult *Results,
4233
0
                                      unsigned NumResults) {
4234
0
  if (CodeCompleter)
4235
0
    CodeCompleter->ProcessCodeCompleteResults(*S, Context, Results, NumResults);
4236
0
}
4237
4238
static CodeCompletionContext
4239
0
mapCodeCompletionContext(Sema &S, Sema::ParserCompletionContext PCC) {
4240
0
  switch (PCC) {
4241
0
  case Sema::PCC_Namespace:
4242
0
    return CodeCompletionContext::CCC_TopLevel;
4243
4244
0
  case Sema::PCC_Class:
4245
0
    return CodeCompletionContext::CCC_ClassStructUnion;
4246
4247
0
  case Sema::PCC_ObjCInterface:
4248
0
    return CodeCompletionContext::CCC_ObjCInterface;
4249
4250
0
  case Sema::PCC_ObjCImplementation:
4251
0
    return CodeCompletionContext::CCC_ObjCImplementation;
4252
4253
0
  case Sema::PCC_ObjCInstanceVariableList:
4254
0
    return CodeCompletionContext::CCC_ObjCIvarList;
4255
4256
0
  case Sema::PCC_Template:
4257
0
  case Sema::PCC_MemberTemplate:
4258
0
    if (S.CurContext->isFileContext())
4259
0
      return CodeCompletionContext::CCC_TopLevel;
4260
0
    if (S.CurContext->isRecord())
4261
0
      return CodeCompletionContext::CCC_ClassStructUnion;
4262
0
    return CodeCompletionContext::CCC_Other;
4263
4264
0
  case Sema::PCC_RecoveryInFunction:
4265
0
    return CodeCompletionContext::CCC_Recovery;
4266
4267
0
  case Sema::PCC_ForInit:
4268
0
    if (S.getLangOpts().CPlusPlus || S.getLangOpts().C99 ||
4269
0
        S.getLangOpts().ObjC)
4270
0
      return CodeCompletionContext::CCC_ParenthesizedExpression;
4271
0
    else
4272
0
      return CodeCompletionContext::CCC_Expression;
4273
4274
0
  case Sema::PCC_Expression:
4275
0
    return CodeCompletionContext::CCC_Expression;
4276
0
  case Sema::PCC_Condition:
4277
0
    return CodeCompletionContext(CodeCompletionContext::CCC_Expression,
4278
0
                                 S.getASTContext().BoolTy);
4279
4280
0
  case Sema::PCC_Statement:
4281
0
    return CodeCompletionContext::CCC_Statement;
4282
4283
0
  case Sema::PCC_Type:
4284
0
    return CodeCompletionContext::CCC_Type;
4285
4286
0
  case Sema::PCC_ParenthesizedExpression:
4287
0
    return CodeCompletionContext::CCC_ParenthesizedExpression;
4288
4289
0
  case Sema::PCC_LocalDeclarationSpecifiers:
4290
0
    return CodeCompletionContext::CCC_Type;
4291
0
  case Sema::PCC_TopLevelOrExpression:
4292
0
    return CodeCompletionContext::CCC_TopLevelOrExpression;
4293
0
  }
4294
4295
0
  llvm_unreachable("Invalid ParserCompletionContext!");
4296
0
}
4297
4298
/// If we're in a C++ virtual member function, add completion results
4299
/// that invoke the functions we override, since it's common to invoke the
4300
/// overridden function as well as adding new functionality.
4301
///
4302
/// \param S The semantic analysis object for which we are generating results.
4303
///
4304
/// \param InContext This context in which the nested-name-specifier preceding
4305
/// the code-completion point
4306
static void MaybeAddOverrideCalls(Sema &S, DeclContext *InContext,
4307
0
                                  ResultBuilder &Results) {
4308
  // Look through blocks.
4309
0
  DeclContext *CurContext = S.CurContext;
4310
0
  while (isa<BlockDecl>(CurContext))
4311
0
    CurContext = CurContext->getParent();
4312
4313
0
  CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(CurContext);
4314
0
  if (!Method || !Method->isVirtual())
4315
0
    return;
4316
4317
  // We need to have names for all of the parameters, if we're going to
4318
  // generate a forwarding call.
4319
0
  for (auto *P : Method->parameters())
4320
0
    if (!P->getDeclName())
4321
0
      return;
4322
4323
0
  PrintingPolicy Policy = getCompletionPrintingPolicy(S);
4324
0
  for (const CXXMethodDecl *Overridden : Method->overridden_methods()) {
4325
0
    CodeCompletionBuilder Builder(Results.getAllocator(),
4326
0
                                  Results.getCodeCompletionTUInfo());
4327
0
    if (Overridden->getCanonicalDecl() == Method->getCanonicalDecl())
4328
0
      continue;
4329
4330
    // If we need a nested-name-specifier, add one now.
4331
0
    if (!InContext) {
4332
0
      NestedNameSpecifier *NNS = getRequiredQualification(
4333
0
          S.Context, CurContext, Overridden->getDeclContext());
4334
0
      if (NNS) {
4335
0
        std::string Str;
4336
0
        llvm::raw_string_ostream OS(Str);
4337
0
        NNS->print(OS, Policy);
4338
0
        Builder.AddTextChunk(Results.getAllocator().CopyString(OS.str()));
4339
0
      }
4340
0
    } else if (!InContext->Equals(Overridden->getDeclContext()))
4341
0
      continue;
4342
4343
0
    Builder.AddTypedTextChunk(
4344
0
        Results.getAllocator().CopyString(Overridden->getNameAsString()));
4345
0
    Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4346
0
    bool FirstParam = true;
4347
0
    for (auto *P : Method->parameters()) {
4348
0
      if (FirstParam)
4349
0
        FirstParam = false;
4350
0
      else
4351
0
        Builder.AddChunk(CodeCompletionString::CK_Comma);
4352
4353
0
      Builder.AddPlaceholderChunk(
4354
0
          Results.getAllocator().CopyString(P->getIdentifier()->getName()));
4355
0
    }
4356
0
    Builder.AddChunk(CodeCompletionString::CK_RightParen);
4357
0
    Results.AddResult(CodeCompletionResult(
4358
0
        Builder.TakeString(), CCP_SuperCompletion, CXCursor_CXXMethod,
4359
0
        CXAvailability_Available, Overridden));
4360
0
    Results.Ignore(Overridden);
4361
0
  }
4362
0
}
4363
4364
void Sema::CodeCompleteModuleImport(SourceLocation ImportLoc,
4365
0
                                    ModuleIdPath Path) {
4366
0
  typedef CodeCompletionResult Result;
4367
0
  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4368
0
                        CodeCompleter->getCodeCompletionTUInfo(),
4369
0
                        CodeCompletionContext::CCC_Other);
4370
0
  Results.EnterNewScope();
4371
4372
0
  CodeCompletionAllocator &Allocator = Results.getAllocator();
4373
0
  CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
4374
0
  typedef CodeCompletionResult Result;
4375
0
  if (Path.empty()) {
4376
    // Enumerate all top-level modules.
4377
0
    SmallVector<Module *, 8> Modules;
4378
0
    PP.getHeaderSearchInfo().collectAllModules(Modules);
4379
0
    for (unsigned I = 0, N = Modules.size(); I != N; ++I) {
4380
0
      Builder.AddTypedTextChunk(
4381
0
          Builder.getAllocator().CopyString(Modules[I]->Name));
4382
0
      Results.AddResult(Result(
4383
0
          Builder.TakeString(), CCP_Declaration, CXCursor_ModuleImportDecl,
4384
0
          Modules[I]->isAvailable() ? CXAvailability_Available
4385
0
                                    : CXAvailability_NotAvailable));
4386
0
    }
4387
0
  } else if (getLangOpts().Modules) {
4388
    // Load the named module.
4389
0
    Module *Mod =
4390
0
        PP.getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
4391
0
                                        /*IsInclusionDirective=*/false);
4392
    // Enumerate submodules.
4393
0
    if (Mod) {
4394
0
      for (auto *Submodule : Mod->submodules()) {
4395
0
        Builder.AddTypedTextChunk(
4396
0
            Builder.getAllocator().CopyString(Submodule->Name));
4397
0
        Results.AddResult(Result(
4398
0
            Builder.TakeString(), CCP_Declaration, CXCursor_ModuleImportDecl,
4399
0
            Submodule->isAvailable() ? CXAvailability_Available
4400
0
                                     : CXAvailability_NotAvailable));
4401
0
      }
4402
0
    }
4403
0
  }
4404
0
  Results.ExitScope();
4405
0
  HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4406
0
                            Results.data(), Results.size());
4407
0
}
4408
4409
void Sema::CodeCompleteOrdinaryName(Scope *S,
4410
0
                                    ParserCompletionContext CompletionContext) {
4411
0
  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4412
0
                        CodeCompleter->getCodeCompletionTUInfo(),
4413
0
                        mapCodeCompletionContext(*this, CompletionContext));
4414
0
  Results.EnterNewScope();
4415
4416
  // Determine how to filter results, e.g., so that the names of
4417
  // values (functions, enumerators, function templates, etc.) are
4418
  // only allowed where we can have an expression.
4419
0
  switch (CompletionContext) {
4420
0
  case PCC_Namespace:
4421
0
  case PCC_Class:
4422
0
  case PCC_ObjCInterface:
4423
0
  case PCC_ObjCImplementation:
4424
0
  case PCC_ObjCInstanceVariableList:
4425
0
  case PCC_Template:
4426
0
  case PCC_MemberTemplate:
4427
0
  case PCC_Type:
4428
0
  case PCC_LocalDeclarationSpecifiers:
4429
0
    Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
4430
0
    break;
4431
4432
0
  case PCC_Statement:
4433
0
  case PCC_TopLevelOrExpression:
4434
0
  case PCC_ParenthesizedExpression:
4435
0
  case PCC_Expression:
4436
0
  case PCC_ForInit:
4437
0
  case PCC_Condition:
4438
0
    if (WantTypesInContext(CompletionContext, getLangOpts()))
4439
0
      Results.setFilter(&ResultBuilder::IsOrdinaryName);
4440
0
    else
4441
0
      Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
4442
4443
0
    if (getLangOpts().CPlusPlus)
4444
0
      MaybeAddOverrideCalls(*this, /*InContext=*/nullptr, Results);
4445
0
    break;
4446
4447
0
  case PCC_RecoveryInFunction:
4448
    // Unfiltered
4449
0
    break;
4450
0
  }
4451
4452
  // If we are in a C++ non-static member function, check the qualifiers on
4453
  // the member function to filter/prioritize the results list.
4454
0
  auto ThisType = getCurrentThisType();
4455
0
  if (!ThisType.isNull())
4456
0
    Results.setObjectTypeQualifiers(ThisType->getPointeeType().getQualifiers(),
4457
0
                                    VK_LValue);
4458
4459
0
  CodeCompletionDeclConsumer Consumer(Results, CurContext);
4460
0
  LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4461
0
                     CodeCompleter->includeGlobals(),
4462
0
                     CodeCompleter->loadExternal());
4463
4464
0
  AddOrdinaryNameResults(CompletionContext, S, *this, Results);
4465
0
  Results.ExitScope();
4466
4467
0
  switch (CompletionContext) {
4468
0
  case PCC_ParenthesizedExpression:
4469
0
  case PCC_Expression:
4470
0
  case PCC_Statement:
4471
0
  case PCC_TopLevelOrExpression:
4472
0
  case PCC_RecoveryInFunction:
4473
0
    if (S->getFnParent())
4474
0
      AddPrettyFunctionResults(getLangOpts(), Results);
4475
0
    break;
4476
4477
0
  case PCC_Namespace:
4478
0
  case PCC_Class:
4479
0
  case PCC_ObjCInterface:
4480
0
  case PCC_ObjCImplementation:
4481
0
  case PCC_ObjCInstanceVariableList:
4482
0
  case PCC_Template:
4483
0
  case PCC_MemberTemplate:
4484
0
  case PCC_ForInit:
4485
0
  case PCC_Condition:
4486
0
  case PCC_Type:
4487
0
  case PCC_LocalDeclarationSpecifiers:
4488
0
    break;
4489
0
  }
4490
4491
0
  if (CodeCompleter->includeMacros())
4492
0
    AddMacroResults(PP, Results, CodeCompleter->loadExternal(), false);
4493
4494
0
  HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4495
0
                            Results.data(), Results.size());
4496
0
}
4497
4498
static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
4499
                                       ParsedType Receiver,
4500
                                       ArrayRef<IdentifierInfo *> SelIdents,
4501
                                       bool AtArgumentExpression, bool IsSuper,
4502
                                       ResultBuilder &Results);
4503
4504
void Sema::CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
4505
                                bool AllowNonIdentifiers,
4506
0
                                bool AllowNestedNameSpecifiers) {
4507
0
  typedef CodeCompletionResult Result;
4508
0
  ResultBuilder Results(
4509
0
      *this, CodeCompleter->getAllocator(),
4510
0
      CodeCompleter->getCodeCompletionTUInfo(),
4511
0
      AllowNestedNameSpecifiers
4512
          // FIXME: Try to separate codepath leading here to deduce whether we
4513
          // need an existing symbol or a new one.
4514
0
          ? CodeCompletionContext::CCC_SymbolOrNewName
4515
0
          : CodeCompletionContext::CCC_NewName);
4516
0
  Results.EnterNewScope();
4517
4518
  // Type qualifiers can come after names.
4519
0
  Results.AddResult(Result("const"));
4520
0
  Results.AddResult(Result("volatile"));
4521
0
  if (getLangOpts().C99)
4522
0
    Results.AddResult(Result("restrict"));
4523
4524
0
  if (getLangOpts().CPlusPlus) {
4525
0
    if (getLangOpts().CPlusPlus11 &&
4526
0
        (DS.getTypeSpecType() == DeclSpec::TST_class ||
4527
0
         DS.getTypeSpecType() == DeclSpec::TST_struct))
4528
0
      Results.AddResult("final");
4529
4530
0
    if (AllowNonIdentifiers) {
4531
0
      Results.AddResult(Result("operator"));
4532
0
    }
4533
4534
    // Add nested-name-specifiers.
4535
0
    if (AllowNestedNameSpecifiers) {
4536
0
      Results.allowNestedNameSpecifiers();
4537
0
      Results.setFilter(&ResultBuilder::IsImpossibleToSatisfy);
4538
0
      CodeCompletionDeclConsumer Consumer(Results, CurContext);
4539
0
      LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer,
4540
0
                         CodeCompleter->includeGlobals(),
4541
0
                         CodeCompleter->loadExternal());
4542
0
      Results.setFilter(nullptr);
4543
0
    }
4544
0
  }
4545
0
  Results.ExitScope();
4546
4547
  // If we're in a context where we might have an expression (rather than a
4548
  // declaration), and what we've seen so far is an Objective-C type that could
4549
  // be a receiver of a class message, this may be a class message send with
4550
  // the initial opening bracket '[' missing. Add appropriate completions.
4551
0
  if (AllowNonIdentifiers && !AllowNestedNameSpecifiers &&
4552
0
      DS.getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier &&
4553
0
      DS.getTypeSpecType() == DeclSpec::TST_typename &&
4554
0
      DS.getTypeSpecComplex() == DeclSpec::TSC_unspecified &&
4555
0
      DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&
4556
0
      !DS.isTypeAltiVecVector() && S &&
4557
0
      (S->getFlags() & Scope::DeclScope) != 0 &&
4558
0
      (S->getFlags() & (Scope::ClassScope | Scope::TemplateParamScope |
4559
0
                        Scope::FunctionPrototypeScope | Scope::AtCatchScope)) ==
4560
0
          0) {
4561
0
    ParsedType T = DS.getRepAsType();
4562
0
    if (!T.get().isNull() && T.get()->isObjCObjectOrInterfaceType())
4563
0
      AddClassMessageCompletions(*this, S, T, std::nullopt, false, false,
4564
0
                                 Results);
4565
0
  }
4566
4567
  // Note that we intentionally suppress macro results here, since we do not
4568
  // encourage using macros to produce the names of entities.
4569
4570
0
  HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4571
0
                            Results.data(), Results.size());
4572
0
}
4573
4574
0
static const char *underscoreAttrScope(llvm::StringRef Scope) {
4575
0
  if (Scope == "clang")
4576
0
    return "_Clang";
4577
0
  if (Scope == "gnu")
4578
0
    return "__gnu__";
4579
0
  return nullptr;
4580
0
}
4581
4582
0
static const char *noUnderscoreAttrScope(llvm::StringRef Scope) {
4583
0
  if (Scope == "_Clang")
4584
0
    return "clang";
4585
0
  if (Scope == "__gnu__")
4586
0
    return "gnu";
4587
0
  return nullptr;
4588
0
}
4589
4590
void Sema::CodeCompleteAttribute(AttributeCommonInfo::Syntax Syntax,
4591
                                 AttributeCompletion Completion,
4592
0
                                 const IdentifierInfo *InScope) {
4593
0
  if (Completion == AttributeCompletion::None)
4594
0
    return;
4595
0
  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4596
0
                        CodeCompleter->getCodeCompletionTUInfo(),
4597
0
                        CodeCompletionContext::CCC_Attribute);
4598
4599
  // We're going to iterate over the normalized spellings of the attribute.
4600
  // These don't include "underscore guarding": the normalized spelling is
4601
  // clang::foo but you can also write _Clang::__foo__.
4602
  //
4603
  // (Clang supports a mix like clang::__foo__ but we won't suggest it: either
4604
  // you care about clashing with macros or you don't).
4605
  //
4606
  // So if we're already in a scope, we determine its canonical spellings
4607
  // (for comparison with normalized attr spelling) and remember whether it was
4608
  // underscore-guarded (so we know how to spell contained attributes).
4609
0
  llvm::StringRef InScopeName;
4610
0
  bool InScopeUnderscore = false;
4611
0
  if (InScope) {
4612
0
    InScopeName = InScope->getName();
4613
0
    if (const char *NoUnderscore = noUnderscoreAttrScope(InScopeName)) {
4614
0
      InScopeName = NoUnderscore;
4615
0
      InScopeUnderscore = true;
4616
0
    }
4617
0
  }
4618
0
  bool SyntaxSupportsGuards = Syntax == AttributeCommonInfo::AS_GNU ||
4619
0
                              Syntax == AttributeCommonInfo::AS_CXX11 ||
4620
0
                              Syntax == AttributeCommonInfo::AS_C23;
4621
4622
0
  llvm::DenseSet<llvm::StringRef> FoundScopes;
4623
0
  auto AddCompletions = [&](const ParsedAttrInfo &A) {
4624
0
    if (A.IsTargetSpecific && !A.existsInTarget(Context.getTargetInfo()))
4625
0
      return;
4626
0
    if (!A.acceptsLangOpts(getLangOpts()))
4627
0
      return;
4628
0
    for (const auto &S : A.Spellings) {
4629
0
      if (S.Syntax != Syntax)
4630
0
        continue;
4631
0
      llvm::StringRef Name = S.NormalizedFullName;
4632
0
      llvm::StringRef Scope;
4633
0
      if ((Syntax == AttributeCommonInfo::AS_CXX11 ||
4634
0
           Syntax == AttributeCommonInfo::AS_C23)) {
4635
0
        std::tie(Scope, Name) = Name.split("::");
4636
0
        if (Name.empty()) // oops, unscoped
4637
0
          std::swap(Name, Scope);
4638
0
      }
4639
4640
      // Do we just want a list of scopes rather than attributes?
4641
0
      if (Completion == AttributeCompletion::Scope) {
4642
        // Make sure to emit each scope only once.
4643
0
        if (!Scope.empty() && FoundScopes.insert(Scope).second) {
4644
0
          Results.AddResult(
4645
0
              CodeCompletionResult(Results.getAllocator().CopyString(Scope)));
4646
          // Include alternate form (__gnu__ instead of gnu).
4647
0
          if (const char *Scope2 = underscoreAttrScope(Scope))
4648
0
            Results.AddResult(CodeCompletionResult(Scope2));
4649
0
        }
4650
0
        continue;
4651
0
      }
4652
4653
      // If a scope was specified, it must match but we don't need to print it.
4654
0
      if (!InScopeName.empty()) {
4655
0
        if (Scope != InScopeName)
4656
0
          continue;
4657
0
        Scope = "";
4658
0
      }
4659
4660
0
      auto Add = [&](llvm::StringRef Scope, llvm::StringRef Name,
4661
0
                     bool Underscores) {
4662
0
        CodeCompletionBuilder Builder(Results.getAllocator(),
4663
0
                                      Results.getCodeCompletionTUInfo());
4664
0
        llvm::SmallString<32> Text;
4665
0
        if (!Scope.empty()) {
4666
0
          Text.append(Scope);
4667
0
          Text.append("::");
4668
0
        }
4669
0
        if (Underscores)
4670
0
          Text.append("__");
4671
0
        Text.append(Name);
4672
0
        if (Underscores)
4673
0
          Text.append("__");
4674
0
        Builder.AddTypedTextChunk(Results.getAllocator().CopyString(Text));
4675
4676
0
        if (!A.ArgNames.empty()) {
4677
0
          Builder.AddChunk(CodeCompletionString::CK_LeftParen, "(");
4678
0
          bool First = true;
4679
0
          for (const char *Arg : A.ArgNames) {
4680
0
            if (!First)
4681
0
              Builder.AddChunk(CodeCompletionString::CK_Comma, ", ");
4682
0
            First = false;
4683
0
            Builder.AddPlaceholderChunk(Arg);
4684
0
          }
4685
0
          Builder.AddChunk(CodeCompletionString::CK_RightParen, ")");
4686
0
        }
4687
4688
0
        Results.AddResult(Builder.TakeString());
4689
0
      };
4690
4691
      // Generate the non-underscore-guarded result.
4692
      // Note this is (a suffix of) the NormalizedFullName, no need to copy.
4693
      // If an underscore-guarded scope was specified, only the
4694
      // underscore-guarded attribute name is relevant.
4695
0
      if (!InScopeUnderscore)
4696
0
        Add(Scope, Name, /*Underscores=*/false);
4697
4698
      // Generate the underscore-guarded version, for syntaxes that support it.
4699
      // We skip this if the scope was already spelled and not guarded, or
4700
      // we must spell it and can't guard it.
4701
0
      if (!(InScope && !InScopeUnderscore) && SyntaxSupportsGuards) {
4702
0
        llvm::SmallString<32> Guarded;
4703
0
        if (Scope.empty()) {
4704
0
          Add(Scope, Name, /*Underscores=*/true);
4705
0
        } else {
4706
0
          const char *GuardedScope = underscoreAttrScope(Scope);
4707
0
          if (!GuardedScope)
4708
0
            continue;
4709
0
          Add(GuardedScope, Name, /*Underscores=*/true);
4710
0
        }
4711
0
      }
4712
4713
      // It may be nice to include the Kind so we can look up the docs later.
4714
0
    }
4715
0
  };
4716
4717
0
  for (const auto *A : ParsedAttrInfo::getAllBuiltin())
4718
0
    AddCompletions(*A);
4719
0
  for (const auto &Entry : ParsedAttrInfoRegistry::entries())
4720
0
    AddCompletions(*Entry.instantiate());
4721
4722
0
  HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4723
0
                            Results.data(), Results.size());
4724
0
}
4725
4726
struct Sema::CodeCompleteExpressionData {
4727
  CodeCompleteExpressionData(QualType PreferredType = QualType(),
4728
                             bool IsParenthesized = false)
4729
      : PreferredType(PreferredType), IntegralConstantExpression(false),
4730
0
        ObjCCollection(false), IsParenthesized(IsParenthesized) {}
4731
4732
  QualType PreferredType;
4733
  bool IntegralConstantExpression;
4734
  bool ObjCCollection;
4735
  bool IsParenthesized;
4736
  SmallVector<Decl *, 4> IgnoreDecls;
4737
};
4738
4739
namespace {
4740
/// Information that allows to avoid completing redundant enumerators.
4741
struct CoveredEnumerators {
4742
  llvm::SmallPtrSet<EnumConstantDecl *, 8> Seen;
4743
  NestedNameSpecifier *SuggestedQualifier = nullptr;
4744
};
4745
} // namespace
4746
4747
static void AddEnumerators(ResultBuilder &Results, ASTContext &Context,
4748
                           EnumDecl *Enum, DeclContext *CurContext,
4749
0
                           const CoveredEnumerators &Enumerators) {
4750
0
  NestedNameSpecifier *Qualifier = Enumerators.SuggestedQualifier;
4751
0
  if (Context.getLangOpts().CPlusPlus && !Qualifier && Enumerators.Seen.empty()) {
4752
    // If there are no prior enumerators in C++, check whether we have to
4753
    // qualify the names of the enumerators that we suggest, because they
4754
    // may not be visible in this scope.
4755
0
    Qualifier = getRequiredQualification(Context, CurContext, Enum);
4756
0
  }
4757
4758
0
  Results.EnterNewScope();
4759
0
  for (auto *E : Enum->enumerators()) {
4760
0
    if (Enumerators.Seen.count(E))
4761
0
      continue;
4762
4763
0
    CodeCompletionResult R(E, CCP_EnumInCase, Qualifier);
4764
0
    Results.AddResult(R, CurContext, nullptr, false);
4765
0
  }
4766
0
  Results.ExitScope();
4767
0
}
4768
4769
/// Try to find a corresponding FunctionProtoType for function-like types (e.g.
4770
/// function pointers, std::function, etc).
4771
0
static const FunctionProtoType *TryDeconstructFunctionLike(QualType T) {
4772
0
  assert(!T.isNull());
4773
  // Try to extract first template argument from std::function<> and similar.
4774
  // Note we only handle the sugared types, they closely match what users wrote.
4775
  // We explicitly choose to not handle ClassTemplateSpecializationDecl.
4776
0
  if (auto *Specialization = T->getAs<TemplateSpecializationType>()) {
4777
0
    if (Specialization->template_arguments().size() != 1)
4778
0
      return nullptr;
4779
0
    const TemplateArgument &Argument = Specialization->template_arguments()[0];
4780
0
    if (Argument.getKind() != TemplateArgument::Type)
4781
0
      return nullptr;
4782
0
    return Argument.getAsType()->getAs<FunctionProtoType>();
4783
0
  }
4784
  // Handle other cases.
4785
0
  if (T->isPointerType())
4786
0
    T = T->getPointeeType();
4787
0
  return T->getAs<FunctionProtoType>();
4788
0
}
4789
4790
/// Adds a pattern completion for a lambda expression with the specified
4791
/// parameter types and placeholders for parameter names.
4792
static void AddLambdaCompletion(ResultBuilder &Results,
4793
                                llvm::ArrayRef<QualType> Parameters,
4794
0
                                const LangOptions &LangOpts) {
4795
0
  if (!Results.includeCodePatterns())
4796
0
    return;
4797
0
  CodeCompletionBuilder Completion(Results.getAllocator(),
4798
0
                                   Results.getCodeCompletionTUInfo());
4799
  // [](<parameters>) {}
4800
0
  Completion.AddChunk(CodeCompletionString::CK_LeftBracket);
4801
0
  Completion.AddPlaceholderChunk("=");
4802
0
  Completion.AddChunk(CodeCompletionString::CK_RightBracket);
4803
0
  if (!Parameters.empty()) {
4804
0
    Completion.AddChunk(CodeCompletionString::CK_LeftParen);
4805
0
    bool First = true;
4806
0
    for (auto Parameter : Parameters) {
4807
0
      if (!First)
4808
0
        Completion.AddChunk(CodeCompletionString::ChunkKind::CK_Comma);
4809
0
      else
4810
0
        First = false;
4811
4812
0
      constexpr llvm::StringLiteral NamePlaceholder = "!#!NAME_GOES_HERE!#!";
4813
0
      std::string Type = std::string(NamePlaceholder);
4814
0
      Parameter.getAsStringInternal(Type, PrintingPolicy(LangOpts));
4815
0
      llvm::StringRef Prefix, Suffix;
4816
0
      std::tie(Prefix, Suffix) = llvm::StringRef(Type).split(NamePlaceholder);
4817
0
      Prefix = Prefix.rtrim();
4818
0
      Suffix = Suffix.ltrim();
4819
4820
0
      Completion.AddTextChunk(Completion.getAllocator().CopyString(Prefix));
4821
0
      Completion.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4822
0
      Completion.AddPlaceholderChunk("parameter");
4823
0
      Completion.AddTextChunk(Completion.getAllocator().CopyString(Suffix));
4824
0
    };
4825
0
    Completion.AddChunk(CodeCompletionString::CK_RightParen);
4826
0
  }
4827
0
  Completion.AddChunk(clang::CodeCompletionString::CK_HorizontalSpace);
4828
0
  Completion.AddChunk(CodeCompletionString::CK_LeftBrace);
4829
0
  Completion.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4830
0
  Completion.AddPlaceholderChunk("body");
4831
0
  Completion.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4832
0
  Completion.AddChunk(CodeCompletionString::CK_RightBrace);
4833
4834
0
  Results.AddResult(Completion.TakeString());
4835
0
}
4836
4837
/// Perform code-completion in an expression context when we know what
4838
/// type we're looking for.
4839
void Sema::CodeCompleteExpression(Scope *S,
4840
0
                                  const CodeCompleteExpressionData &Data) {
4841
0
  ResultBuilder Results(
4842
0
      *this, CodeCompleter->getAllocator(),
4843
0
      CodeCompleter->getCodeCompletionTUInfo(),
4844
0
      CodeCompletionContext(
4845
0
          Data.IsParenthesized
4846
0
              ? CodeCompletionContext::CCC_ParenthesizedExpression
4847
0
              : CodeCompletionContext::CCC_Expression,
4848
0
          Data.PreferredType));
4849
0
  auto PCC =
4850
0
      Data.IsParenthesized ? PCC_ParenthesizedExpression : PCC_Expression;
4851
0
  if (Data.ObjCCollection)
4852
0
    Results.setFilter(&ResultBuilder::IsObjCCollection);
4853
0
  else if (Data.IntegralConstantExpression)
4854
0
    Results.setFilter(&ResultBuilder::IsIntegralConstantValue);
4855
0
  else if (WantTypesInContext(PCC, getLangOpts()))
4856
0
    Results.setFilter(&ResultBuilder::IsOrdinaryName);
4857
0
  else
4858
0
    Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
4859
4860
0
  if (!Data.PreferredType.isNull())
4861
0
    Results.setPreferredType(Data.PreferredType.getNonReferenceType());
4862
4863
  // Ignore any declarations that we were told that we don't care about.
4864
0
  for (unsigned I = 0, N = Data.IgnoreDecls.size(); I != N; ++I)
4865
0
    Results.Ignore(Data.IgnoreDecls[I]);
4866
4867
0
  CodeCompletionDeclConsumer Consumer(Results, CurContext);
4868
0
  LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4869
0
                     CodeCompleter->includeGlobals(),
4870
0
                     CodeCompleter->loadExternal());
4871
4872
0
  Results.EnterNewScope();
4873
0
  AddOrdinaryNameResults(PCC, S, *this, Results);
4874
0
  Results.ExitScope();
4875
4876
0
  bool PreferredTypeIsPointer = false;
4877
0
  if (!Data.PreferredType.isNull()) {
4878
0
    PreferredTypeIsPointer = Data.PreferredType->isAnyPointerType() ||
4879
0
                             Data.PreferredType->isMemberPointerType() ||
4880
0
                             Data.PreferredType->isBlockPointerType();
4881
0
    if (Data.PreferredType->isEnumeralType()) {
4882
0
      EnumDecl *Enum = Data.PreferredType->castAs<EnumType>()->getDecl();
4883
0
      if (auto *Def = Enum->getDefinition())
4884
0
        Enum = Def;
4885
      // FIXME: collect covered enumerators in cases like:
4886
      //        if (x == my_enum::one) { ... } else if (x == ^) {}
4887
0
      AddEnumerators(Results, Context, Enum, CurContext, CoveredEnumerators());
4888
0
    }
4889
0
  }
4890
4891
0
  if (S->getFnParent() && !Data.ObjCCollection &&
4892
0
      !Data.IntegralConstantExpression)
4893
0
    AddPrettyFunctionResults(getLangOpts(), Results);
4894
4895
0
  if (CodeCompleter->includeMacros())
4896
0
    AddMacroResults(PP, Results, CodeCompleter->loadExternal(), false,
4897
0
                    PreferredTypeIsPointer);
4898
4899
  // Complete a lambda expression when preferred type is a function.
4900
0
  if (!Data.PreferredType.isNull() && getLangOpts().CPlusPlus11) {
4901
0
    if (const FunctionProtoType *F =
4902
0
            TryDeconstructFunctionLike(Data.PreferredType))
4903
0
      AddLambdaCompletion(Results, F->getParamTypes(), getLangOpts());
4904
0
  }
4905
4906
0
  HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4907
0
                            Results.data(), Results.size());
4908
0
}
4909
4910
void Sema::CodeCompleteExpression(Scope *S, QualType PreferredType,
4911
0
                                  bool IsParenthesized) {
4912
0
  return CodeCompleteExpression(
4913
0
      S, CodeCompleteExpressionData(PreferredType, IsParenthesized));
4914
0
}
4915
4916
void Sema::CodeCompletePostfixExpression(Scope *S, ExprResult E,
4917
0
                                         QualType PreferredType) {
4918
0
  if (E.isInvalid())
4919
0
    CodeCompleteExpression(S, PreferredType);
4920
0
  else if (getLangOpts().ObjC)
4921
0
    CodeCompleteObjCInstanceMessage(S, E.get(), std::nullopt, false);
4922
0
}
4923
4924
/// The set of properties that have already been added, referenced by
4925
/// property name.
4926
typedef llvm::SmallPtrSet<IdentifierInfo *, 16> AddedPropertiesSet;
4927
4928
/// Retrieve the container definition, if any?
4929
0
static ObjCContainerDecl *getContainerDef(ObjCContainerDecl *Container) {
4930
0
  if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
4931
0
    if (Interface->hasDefinition())
4932
0
      return Interface->getDefinition();
4933
4934
0
    return Interface;
4935
0
  }
4936
4937
0
  if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4938
0
    if (Protocol->hasDefinition())
4939
0
      return Protocol->getDefinition();
4940
4941
0
    return Protocol;
4942
0
  }
4943
0
  return Container;
4944
0
}
4945
4946
/// Adds a block invocation code completion result for the given block
4947
/// declaration \p BD.
4948
static void AddObjCBlockCall(ASTContext &Context, const PrintingPolicy &Policy,
4949
                             CodeCompletionBuilder &Builder,
4950
                             const NamedDecl *BD,
4951
                             const FunctionTypeLoc &BlockLoc,
4952
0
                             const FunctionProtoTypeLoc &BlockProtoLoc) {
4953
0
  Builder.AddResultTypeChunk(
4954
0
      GetCompletionTypeString(BlockLoc.getReturnLoc().getType(), Context,
4955
0
                              Policy, Builder.getAllocator()));
4956
4957
0
  AddTypedNameChunk(Context, Policy, BD, Builder);
4958
0
  Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4959
4960
0
  if (BlockProtoLoc && BlockProtoLoc.getTypePtr()->isVariadic()) {
4961
0
    Builder.AddPlaceholderChunk("...");
4962
0
  } else {
4963
0
    for (unsigned I = 0, N = BlockLoc.getNumParams(); I != N; ++I) {
4964
0
      if (I)
4965
0
        Builder.AddChunk(CodeCompletionString::CK_Comma);
4966
4967
      // Format the placeholder string.
4968
0
      std::string PlaceholderStr =
4969
0
          FormatFunctionParameter(Policy, BlockLoc.getParam(I));
4970
4971
0
      if (I == N - 1 && BlockProtoLoc &&
4972
0
          BlockProtoLoc.getTypePtr()->isVariadic())
4973
0
        PlaceholderStr += ", ...";
4974
4975
      // Add the placeholder string.
4976
0
      Builder.AddPlaceholderChunk(
4977
0
          Builder.getAllocator().CopyString(PlaceholderStr));
4978
0
    }
4979
0
  }
4980
4981
0
  Builder.AddChunk(CodeCompletionString::CK_RightParen);
4982
0
}
4983
4984
static void
4985
AddObjCProperties(const CodeCompletionContext &CCContext,
4986
                  ObjCContainerDecl *Container, bool AllowCategories,
4987
                  bool AllowNullaryMethods, DeclContext *CurContext,
4988
                  AddedPropertiesSet &AddedProperties, ResultBuilder &Results,
4989
                  bool IsBaseExprStatement = false,
4990
0
                  bool IsClassProperty = false, bool InOriginalClass = true) {
4991
0
  typedef CodeCompletionResult Result;
4992
4993
  // Retrieve the definition.
4994
0
  Container = getContainerDef(Container);
4995
4996
  // Add properties in this container.
4997
0
  const auto AddProperty = [&](const ObjCPropertyDecl *P) {
4998
0
    if (!AddedProperties.insert(P->getIdentifier()).second)
4999
0
      return;
5000
5001
    // FIXME: Provide block invocation completion for non-statement
5002
    // expressions.
5003
0
    if (!P->getType().getTypePtr()->isBlockPointerType() ||
5004
0
        !IsBaseExprStatement) {
5005
0
      Result R = Result(P, Results.getBasePriority(P), nullptr);
5006
0
      if (!InOriginalClass)
5007
0
        setInBaseClass(R);
5008
0
      Results.MaybeAddResult(R, CurContext);
5009
0
      return;
5010
0
    }
5011
5012
    // Block setter and invocation completion is provided only when we are able
5013
    // to find the FunctionProtoTypeLoc with parameter names for the block.
5014
0
    FunctionTypeLoc BlockLoc;
5015
0
    FunctionProtoTypeLoc BlockProtoLoc;
5016
0
    findTypeLocationForBlockDecl(P->getTypeSourceInfo(), BlockLoc,
5017
0
                                 BlockProtoLoc);
5018
0
    if (!BlockLoc) {
5019
0
      Result R = Result(P, Results.getBasePriority(P), nullptr);
5020
0
      if (!InOriginalClass)
5021
0
        setInBaseClass(R);
5022
0
      Results.MaybeAddResult(R, CurContext);
5023
0
      return;
5024
0
    }
5025
5026
    // The default completion result for block properties should be the block
5027
    // invocation completion when the base expression is a statement.
5028
0
    CodeCompletionBuilder Builder(Results.getAllocator(),
5029
0
                                  Results.getCodeCompletionTUInfo());
5030
0
    AddObjCBlockCall(Container->getASTContext(),
5031
0
                     getCompletionPrintingPolicy(Results.getSema()), Builder, P,
5032
0
                     BlockLoc, BlockProtoLoc);
5033
0
    Result R = Result(Builder.TakeString(), P, Results.getBasePriority(P));
5034
0
    if (!InOriginalClass)
5035
0
      setInBaseClass(R);
5036
0
    Results.MaybeAddResult(R, CurContext);
5037
5038
    // Provide additional block setter completion iff the base expression is a
5039
    // statement and the block property is mutable.
5040
0
    if (!P->isReadOnly()) {
5041
0
      CodeCompletionBuilder Builder(Results.getAllocator(),
5042
0
                                    Results.getCodeCompletionTUInfo());
5043
0
      AddResultTypeChunk(Container->getASTContext(),
5044
0
                         getCompletionPrintingPolicy(Results.getSema()), P,
5045
0
                         CCContext.getBaseType(), Builder);
5046
0
      Builder.AddTypedTextChunk(
5047
0
          Results.getAllocator().CopyString(P->getName()));
5048
0
      Builder.AddChunk(CodeCompletionString::CK_Equal);
5049
5050
0
      std::string PlaceholderStr = formatBlockPlaceholder(
5051
0
          getCompletionPrintingPolicy(Results.getSema()), P, BlockLoc,
5052
0
          BlockProtoLoc, /*SuppressBlockName=*/true);
5053
      // Add the placeholder string.
5054
0
      Builder.AddPlaceholderChunk(
5055
0
          Builder.getAllocator().CopyString(PlaceholderStr));
5056
5057
      // When completing blocks properties that return void the default
5058
      // property completion result should show up before the setter,
5059
      // otherwise the setter completion should show up before the default
5060
      // property completion, as we normally want to use the result of the
5061
      // call.
5062
0
      Result R =
5063
0
          Result(Builder.TakeString(), P,
5064
0
                 Results.getBasePriority(P) +
5065
0
                     (BlockLoc.getTypePtr()->getReturnType()->isVoidType()
5066
0
                          ? CCD_BlockPropertySetter
5067
0
                          : -CCD_BlockPropertySetter));
5068
0
      if (!InOriginalClass)
5069
0
        setInBaseClass(R);
5070
0
      Results.MaybeAddResult(R, CurContext);
5071
0
    }
5072
0
  };
5073
5074
0
  if (IsClassProperty) {
5075
0
    for (const auto *P : Container->class_properties())
5076
0
      AddProperty(P);
5077
0
  } else {
5078
0
    for (const auto *P : Container->instance_properties())
5079
0
      AddProperty(P);
5080
0
  }
5081
5082
  // Add nullary methods or implicit class properties
5083
0
  if (AllowNullaryMethods) {
5084
0
    ASTContext &Context = Container->getASTContext();
5085
0
    PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema());
5086
    // Adds a method result
5087
0
    const auto AddMethod = [&](const ObjCMethodDecl *M) {
5088
0
      IdentifierInfo *Name = M->getSelector().getIdentifierInfoForSlot(0);
5089
0
      if (!Name)
5090
0
        return;
5091
0
      if (!AddedProperties.insert(Name).second)
5092
0
        return;
5093
0
      CodeCompletionBuilder Builder(Results.getAllocator(),
5094
0
                                    Results.getCodeCompletionTUInfo());
5095
0
      AddResultTypeChunk(Context, Policy, M, CCContext.getBaseType(), Builder);
5096
0
      Builder.AddTypedTextChunk(
5097
0
          Results.getAllocator().CopyString(Name->getName()));
5098
0
      Result R = Result(Builder.TakeString(), M,
5099
0
                        CCP_MemberDeclaration + CCD_MethodAsProperty);
5100
0
      if (!InOriginalClass)
5101
0
        setInBaseClass(R);
5102
0
      Results.MaybeAddResult(R, CurContext);
5103
0
    };
5104
5105
0
    if (IsClassProperty) {
5106
0
      for (const auto *M : Container->methods()) {
5107
        // Gather the class method that can be used as implicit property
5108
        // getters. Methods with arguments or methods that return void aren't
5109
        // added to the results as they can't be used as a getter.
5110
0
        if (!M->getSelector().isUnarySelector() ||
5111
0
            M->getReturnType()->isVoidType() || M->isInstanceMethod())
5112
0
          continue;
5113
0
        AddMethod(M);
5114
0
      }
5115
0
    } else {
5116
0
      for (auto *M : Container->methods()) {
5117
0
        if (M->getSelector().isUnarySelector())
5118
0
          AddMethod(M);
5119
0
      }
5120
0
    }
5121
0
  }
5122
5123
  // Add properties in referenced protocols.
5124
0
  if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
5125
0
    for (auto *P : Protocol->protocols())
5126
0
      AddObjCProperties(CCContext, P, AllowCategories, AllowNullaryMethods,
5127
0
                        CurContext, AddedProperties, Results,
5128
0
                        IsBaseExprStatement, IsClassProperty,
5129
0
                        /*InOriginalClass*/ false);
5130
0
  } else if (ObjCInterfaceDecl *IFace =
5131
0
                 dyn_cast<ObjCInterfaceDecl>(Container)) {
5132
0
    if (AllowCategories) {
5133
      // Look through categories.
5134
0
      for (auto *Cat : IFace->known_categories())
5135
0
        AddObjCProperties(CCContext, Cat, AllowCategories, AllowNullaryMethods,
5136
0
                          CurContext, AddedProperties, Results,
5137
0
                          IsBaseExprStatement, IsClassProperty,
5138
0
                          InOriginalClass);
5139
0
    }
5140
5141
    // Look through protocols.
5142
0
    for (auto *I : IFace->all_referenced_protocols())
5143
0
      AddObjCProperties(CCContext, I, AllowCategories, AllowNullaryMethods,
5144
0
                        CurContext, AddedProperties, Results,
5145
0
                        IsBaseExprStatement, IsClassProperty,
5146
0
                        /*InOriginalClass*/ false);
5147
5148
    // Look in the superclass.
5149
0
    if (IFace->getSuperClass())
5150
0
      AddObjCProperties(CCContext, IFace->getSuperClass(), AllowCategories,
5151
0
                        AllowNullaryMethods, CurContext, AddedProperties,
5152
0
                        Results, IsBaseExprStatement, IsClassProperty,
5153
0
                        /*InOriginalClass*/ false);
5154
0
  } else if (const auto *Category =
5155
0
                 dyn_cast<ObjCCategoryDecl>(Container)) {
5156
    // Look through protocols.
5157
0
    for (auto *P : Category->protocols())
5158
0
      AddObjCProperties(CCContext, P, AllowCategories, AllowNullaryMethods,
5159
0
                        CurContext, AddedProperties, Results,
5160
0
                        IsBaseExprStatement, IsClassProperty,
5161
0
                        /*InOriginalClass*/ false);
5162
0
  }
5163
0
}
5164
5165
static void
5166
AddRecordMembersCompletionResults(Sema &SemaRef, ResultBuilder &Results,
5167
                                  Scope *S, QualType BaseType,
5168
                                  ExprValueKind BaseKind, RecordDecl *RD,
5169
0
                                  std::optional<FixItHint> AccessOpFixIt) {
5170
  // Indicate that we are performing a member access, and the cv-qualifiers
5171
  // for the base object type.
5172
0
  Results.setObjectTypeQualifiers(BaseType.getQualifiers(), BaseKind);
5173
5174
  // Access to a C/C++ class, struct, or union.
5175
0
  Results.allowNestedNameSpecifiers();
5176
0
  std::vector<FixItHint> FixIts;
5177
0
  if (AccessOpFixIt)
5178
0
    FixIts.emplace_back(*AccessOpFixIt);
5179
0
  CodeCompletionDeclConsumer Consumer(Results, RD, BaseType, std::move(FixIts));
5180
0
  SemaRef.LookupVisibleDecls(RD, Sema::LookupMemberName, Consumer,
5181
0
                             SemaRef.CodeCompleter->includeGlobals(),
5182
0
                             /*IncludeDependentBases=*/true,
5183
0
                             SemaRef.CodeCompleter->loadExternal());
5184
5185
0
  if (SemaRef.getLangOpts().CPlusPlus) {
5186
0
    if (!Results.empty()) {
5187
      // The "template" keyword can follow "->" or "." in the grammar.
5188
      // However, we only want to suggest the template keyword if something
5189
      // is dependent.
5190
0
      bool IsDependent = BaseType->isDependentType();
5191
0
      if (!IsDependent) {
5192
0
        for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent())
5193
0
          if (DeclContext *Ctx = DepScope->getEntity()) {
5194
0
            IsDependent = Ctx->isDependentContext();
5195
0
            break;
5196
0
          }
5197
0
      }
5198
5199
0
      if (IsDependent)
5200
0
        Results.AddResult(CodeCompletionResult("template"));
5201
0
    }
5202
0
  }
5203
0
}
5204
5205
// Returns the RecordDecl inside the BaseType, falling back to primary template
5206
// in case of specializations. Since we might not have a decl for the
5207
// instantiation/specialization yet, e.g. dependent code.
5208
0
static RecordDecl *getAsRecordDecl(QualType BaseType) {
5209
0
  BaseType = BaseType.getNonReferenceType();
5210
0
  if (auto *RD = BaseType->getAsRecordDecl()) {
5211
0
    if (const auto *CTSD =
5212
0
            llvm::dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
5213
      // Template might not be instantiated yet, fall back to primary template
5214
      // in such cases.
5215
0
      if (CTSD->getTemplateSpecializationKind() == TSK_Undeclared)
5216
0
        RD = CTSD->getSpecializedTemplate()->getTemplatedDecl();
5217
0
    }
5218
0
    return RD;
5219
0
  }
5220
5221
0
  if (const auto *TST = BaseType->getAs<TemplateSpecializationType>()) {
5222
0
    if (const auto *TD = dyn_cast_or_null<ClassTemplateDecl>(
5223
0
            TST->getTemplateName().getAsTemplateDecl())) {
5224
0
      return TD->getTemplatedDecl();
5225
0
    }
5226
0
  }
5227
5228
0
  return nullptr;
5229
0
}
5230
5231
namespace {
5232
// Collects completion-relevant information about a concept-constrainted type T.
5233
// In particular, examines the constraint expressions to find members of T.
5234
//
5235
// The design is very simple: we walk down each constraint looking for
5236
// expressions of the form T.foo().
5237
// If we're extra lucky, the return type is specified.
5238
// We don't do any clever handling of && or || in constraint expressions, we
5239
// take members from both branches.
5240
//
5241
// For example, given:
5242
//   template <class T> concept X = requires (T t, string& s) { t.print(s); };
5243
//   template <X U> void foo(U u) { u.^ }
5244
// We want to suggest the inferred member function 'print(string)'.
5245
// We see that u has type U, so X<U> holds.
5246
// X<U> requires t.print(s) to be valid, where t has type U (substituted for T).
5247
// By looking at the CallExpr we find the signature of print().
5248
//
5249
// While we tend to know in advance which kind of members (access via . -> ::)
5250
// we want, it's simpler just to gather them all and post-filter.
5251
//
5252
// FIXME: some of this machinery could be used for non-concept type-parms too,
5253
// enabling completion for type parameters based on other uses of that param.
5254
//
5255
// FIXME: there are other cases where a type can be constrained by a concept,
5256
// e.g. inside `if constexpr(ConceptSpecializationExpr) { ... }`
5257
class ConceptInfo {
5258
public:
5259
  // Describes a likely member of a type, inferred by concept constraints.
5260
  // Offered as a code completion for T. T-> and T:: contexts.
5261
  struct Member {
5262
    // Always non-null: we only handle members with ordinary identifier names.
5263
    const IdentifierInfo *Name = nullptr;
5264
    // Set for functions we've seen called.
5265
    // We don't have the declared parameter types, only the actual types of
5266
    // arguments we've seen. These are still valuable, as it's hard to render
5267
    // a useful function completion with neither parameter types nor names!
5268
    std::optional<SmallVector<QualType, 1>> ArgTypes;
5269
    // Whether this is accessed as T.member, T->member, or T::member.
5270
    enum AccessOperator {
5271
      Colons,
5272
      Arrow,
5273
      Dot,
5274
    } Operator = Dot;
5275
    // What's known about the type of a variable or return type of a function.
5276
    const TypeConstraint *ResultType = nullptr;
5277
    // FIXME: also track:
5278
    //   - kind of entity (function/variable/type), to expose structured results
5279
    //   - template args kinds/types, as a proxy for template params
5280
5281
    // For now we simply return these results as "pattern" strings.
5282
    CodeCompletionString *render(Sema &S, CodeCompletionAllocator &Alloc,
5283
0
                                 CodeCompletionTUInfo &Info) const {
5284
0
      CodeCompletionBuilder B(Alloc, Info);
5285
      // Result type
5286
0
      if (ResultType) {
5287
0
        std::string AsString;
5288
0
        {
5289
0
          llvm::raw_string_ostream OS(AsString);
5290
0
          QualType ExactType = deduceType(*ResultType);
5291
0
          if (!ExactType.isNull())
5292
0
            ExactType.print(OS, getCompletionPrintingPolicy(S));
5293
0
          else
5294
0
            ResultType->print(OS, getCompletionPrintingPolicy(S));
5295
0
        }
5296
0
        B.AddResultTypeChunk(Alloc.CopyString(AsString));
5297
0
      }
5298
      // Member name
5299
0
      B.AddTypedTextChunk(Alloc.CopyString(Name->getName()));
5300
      // Function argument list
5301
0
      if (ArgTypes) {
5302
0
        B.AddChunk(clang::CodeCompletionString::CK_LeftParen);
5303
0
        bool First = true;
5304
0
        for (QualType Arg : *ArgTypes) {
5305
0
          if (First)
5306
0
            First = false;
5307
0
          else {
5308
0
            B.AddChunk(clang::CodeCompletionString::CK_Comma);
5309
0
            B.AddChunk(clang::CodeCompletionString::CK_HorizontalSpace);
5310
0
          }
5311
0
          B.AddPlaceholderChunk(Alloc.CopyString(
5312
0
              Arg.getAsString(getCompletionPrintingPolicy(S))));
5313
0
        }
5314
0
        B.AddChunk(clang::CodeCompletionString::CK_RightParen);
5315
0
      }
5316
0
      return B.TakeString();
5317
0
    }
5318
  };
5319
5320
  // BaseType is the type parameter T to infer members from.
5321
  // T must be accessible within S, as we use it to find the template entity
5322
  // that T is attached to in order to gather the relevant constraints.
5323
0
  ConceptInfo(const TemplateTypeParmType &BaseType, Scope *S) {
5324
0
    auto *TemplatedEntity = getTemplatedEntity(BaseType.getDecl(), S);
5325
0
    for (const Expr *E : constraintsForTemplatedEntity(TemplatedEntity))
5326
0
      believe(E, &BaseType);
5327
0
  }
5328
5329
0
  std::vector<Member> members() {
5330
0
    std::vector<Member> Results;
5331
0
    for (const auto &E : this->Results)
5332
0
      Results.push_back(E.second);
5333
0
    llvm::sort(Results, [](const Member &L, const Member &R) {
5334
0
      return L.Name->getName() < R.Name->getName();
5335
0
    });
5336
0
    return Results;
5337
0
  }
5338
5339
private:
5340
  // Infer members of T, given that the expression E (dependent on T) is true.
5341
0
  void believe(const Expr *E, const TemplateTypeParmType *T) {
5342
0
    if (!E || !T)
5343
0
      return;
5344
0
    if (auto *CSE = dyn_cast<ConceptSpecializationExpr>(E)) {
5345
      // If the concept is
5346
      //   template <class A, class B> concept CD = f<A, B>();
5347
      // And the concept specialization is
5348
      //   CD<int, T>
5349
      // Then we're substituting T for B, so we want to make f<A, B>() true
5350
      // by adding members to B - i.e. believe(f<A, B>(), B);
5351
      //
5352
      // For simplicity:
5353
      // - we don't attempt to substitute int for A
5354
      // - when T is used in other ways (like CD<T*>) we ignore it
5355
0
      ConceptDecl *CD = CSE->getNamedConcept();
5356
0
      TemplateParameterList *Params = CD->getTemplateParameters();
5357
0
      unsigned Index = 0;
5358
0
      for (const auto &Arg : CSE->getTemplateArguments()) {
5359
0
        if (Index >= Params->size())
5360
0
          break; // Won't happen in valid code.
5361
0
        if (isApprox(Arg, T)) {
5362
0
          auto *TTPD = dyn_cast<TemplateTypeParmDecl>(Params->getParam(Index));
5363
0
          if (!TTPD)
5364
0
            continue;
5365
          // T was used as an argument, and bound to the parameter TT.
5366
0
          auto *TT = cast<TemplateTypeParmType>(TTPD->getTypeForDecl());
5367
          // So now we know the constraint as a function of TT is true.
5368
0
          believe(CD->getConstraintExpr(), TT);
5369
          // (concepts themselves have no associated constraints to require)
5370
0
        }
5371
5372
0
        ++Index;
5373
0
      }
5374
0
    } else if (auto *BO = dyn_cast<BinaryOperator>(E)) {
5375
      // For A && B, we can infer members from both branches.
5376
      // For A || B, the union is still more useful than the intersection.
5377
0
      if (BO->getOpcode() == BO_LAnd || BO->getOpcode() == BO_LOr) {
5378
0
        believe(BO->getLHS(), T);
5379
0
        believe(BO->getRHS(), T);
5380
0
      }
5381
0
    } else if (auto *RE = dyn_cast<RequiresExpr>(E)) {
5382
      // A requires(){...} lets us infer members from each requirement.
5383
0
      for (const concepts::Requirement *Req : RE->getRequirements()) {
5384
0
        if (!Req->isDependent())
5385
0
          continue; // Can't tell us anything about T.
5386
        // Now Req cannot a substitution-error: those aren't dependent.
5387
5388
0
        if (auto *TR = dyn_cast<concepts::TypeRequirement>(Req)) {
5389
          // Do a full traversal so we get `foo` from `typename T::foo::bar`.
5390
0
          QualType AssertedType = TR->getType()->getType();
5391
0
          ValidVisitor(this, T).TraverseType(AssertedType);
5392
0
        } else if (auto *ER = dyn_cast<concepts::ExprRequirement>(Req)) {
5393
0
          ValidVisitor Visitor(this, T);
5394
          // If we have a type constraint on the value of the expression,
5395
          // AND the whole outer expression describes a member, then we'll
5396
          // be able to use the constraint to provide the return type.
5397
0
          if (ER->getReturnTypeRequirement().isTypeConstraint()) {
5398
0
            Visitor.OuterType =
5399
0
                ER->getReturnTypeRequirement().getTypeConstraint();
5400
0
            Visitor.OuterExpr = ER->getExpr();
5401
0
          }
5402
0
          Visitor.TraverseStmt(ER->getExpr());
5403
0
        } else if (auto *NR = dyn_cast<concepts::NestedRequirement>(Req)) {
5404
0
          believe(NR->getConstraintExpr(), T);
5405
0
        }
5406
0
      }
5407
0
    }
5408
0
  }
5409
5410
  // This visitor infers members of T based on traversing expressions/types
5411
  // that involve T. It is invoked with code known to be valid for T.
5412
  class ValidVisitor : public RecursiveASTVisitor<ValidVisitor> {
5413
    ConceptInfo *Outer;
5414
    const TemplateTypeParmType *T;
5415
5416
    CallExpr *Caller = nullptr;
5417
    Expr *Callee = nullptr;
5418
5419
  public:
5420
    // If set, OuterExpr is constrained by OuterType.
5421
    Expr *OuterExpr = nullptr;
5422
    const TypeConstraint *OuterType = nullptr;
5423
5424
    ValidVisitor(ConceptInfo *Outer, const TemplateTypeParmType *T)
5425
0
        : Outer(Outer), T(T) {
5426
0
      assert(T);
5427
0
    }
5428
5429
    // In T.foo or T->foo, `foo` is a member function/variable.
5430
0
    bool VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E) {
5431
0
      const Type *Base = E->getBaseType().getTypePtr();
5432
0
      bool IsArrow = E->isArrow();
5433
0
      if (Base->isPointerType() && IsArrow) {
5434
0
        IsArrow = false;
5435
0
        Base = Base->getPointeeType().getTypePtr();
5436
0
      }
5437
0
      if (isApprox(Base, T))
5438
0
        addValue(E, E->getMember(), IsArrow ? Member::Arrow : Member::Dot);
5439
0
      return true;
5440
0
    }
5441
5442
    // In T::foo, `foo` is a static member function/variable.
5443
0
    bool VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) {
5444
0
      if (E->getQualifier() && isApprox(E->getQualifier()->getAsType(), T))
5445
0
        addValue(E, E->getDeclName(), Member::Colons);
5446
0
      return true;
5447
0
    }
5448
5449
    // In T::typename foo, `foo` is a type.
5450
0
    bool VisitDependentNameType(DependentNameType *DNT) {
5451
0
      const auto *Q = DNT->getQualifier();
5452
0
      if (Q && isApprox(Q->getAsType(), T))
5453
0
        addType(DNT->getIdentifier());
5454
0
      return true;
5455
0
    }
5456
5457
    // In T::foo::bar, `foo` must be a type.
5458
    // VisitNNS() doesn't exist, and TraverseNNS isn't always called :-(
5459
0
    bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNSL) {
5460
0
      if (NNSL) {
5461
0
        NestedNameSpecifier *NNS = NNSL.getNestedNameSpecifier();
5462
0
        const auto *Q = NNS->getPrefix();
5463
0
        if (Q && isApprox(Q->getAsType(), T))
5464
0
          addType(NNS->getAsIdentifier());
5465
0
      }
5466
      // FIXME: also handle T::foo<X>::bar
5467
0
      return RecursiveASTVisitor::TraverseNestedNameSpecifierLoc(NNSL);
5468
0
    }
5469
5470
    // FIXME also handle T::foo<X>
5471
5472
    // Track the innermost caller/callee relationship so we can tell if a
5473
    // nested expr is being called as a function.
5474
0
    bool VisitCallExpr(CallExpr *CE) {
5475
0
      Caller = CE;
5476
0
      Callee = CE->getCallee();
5477
0
      return true;
5478
0
    }
5479
5480
  private:
5481
0
    void addResult(Member &&M) {
5482
0
      auto R = Outer->Results.try_emplace(M.Name);
5483
0
      Member &O = R.first->second;
5484
      // Overwrite existing if the new member has more info.
5485
      // The preference of . vs :: vs -> is fairly arbitrary.
5486
0
      if (/*Inserted*/ R.second ||
5487
0
          std::make_tuple(M.ArgTypes.has_value(), M.ResultType != nullptr,
5488
0
                          M.Operator) > std::make_tuple(O.ArgTypes.has_value(),
5489
0
                                                        O.ResultType != nullptr,
5490
0
                                                        O.Operator))
5491
0
        O = std::move(M);
5492
0
    }
5493
5494
0
    void addType(const IdentifierInfo *Name) {
5495
0
      if (!Name)
5496
0
        return;
5497
0
      Member M;
5498
0
      M.Name = Name;
5499
0
      M.Operator = Member::Colons;
5500
0
      addResult(std::move(M));
5501
0
    }
5502
5503
    void addValue(Expr *E, DeclarationName Name,
5504
0
                  Member::AccessOperator Operator) {
5505
0
      if (!Name.isIdentifier())
5506
0
        return;
5507
0
      Member Result;
5508
0
      Result.Name = Name.getAsIdentifierInfo();
5509
0
      Result.Operator = Operator;
5510
      // If this is the callee of an immediately-enclosing CallExpr, then
5511
      // treat it as a method, otherwise it's a variable.
5512
0
      if (Caller != nullptr && Callee == E) {
5513
0
        Result.ArgTypes.emplace();
5514
0
        for (const auto *Arg : Caller->arguments())
5515
0
          Result.ArgTypes->push_back(Arg->getType());
5516
0
        if (Caller == OuterExpr) {
5517
0
          Result.ResultType = OuterType;
5518
0
        }
5519
0
      } else {
5520
0
        if (E == OuterExpr)
5521
0
          Result.ResultType = OuterType;
5522
0
      }
5523
0
      addResult(std::move(Result));
5524
0
    }
5525
  };
5526
5527
0
  static bool isApprox(const TemplateArgument &Arg, const Type *T) {
5528
0
    return Arg.getKind() == TemplateArgument::Type &&
5529
0
           isApprox(Arg.getAsType().getTypePtr(), T);
5530
0
  }
5531
5532
0
  static bool isApprox(const Type *T1, const Type *T2) {
5533
0
    return T1 && T2 &&
5534
0
           T1->getCanonicalTypeUnqualified() ==
5535
0
               T2->getCanonicalTypeUnqualified();
5536
0
  }
5537
5538
  // Returns the DeclContext immediately enclosed by the template parameter
5539
  // scope. For primary templates, this is the templated (e.g.) CXXRecordDecl.
5540
  // For specializations, this is e.g. ClassTemplatePartialSpecializationDecl.
5541
  static DeclContext *getTemplatedEntity(const TemplateTypeParmDecl *D,
5542
0
                                         Scope *S) {
5543
0
    if (D == nullptr)
5544
0
      return nullptr;
5545
0
    Scope *Inner = nullptr;
5546
0
    while (S) {
5547
0
      if (S->isTemplateParamScope() && S->isDeclScope(D))
5548
0
        return Inner ? Inner->getEntity() : nullptr;
5549
0
      Inner = S;
5550
0
      S = S->getParent();
5551
0
    }
5552
0
    return nullptr;
5553
0
  }
5554
5555
  // Gets all the type constraint expressions that might apply to the type
5556
  // variables associated with DC (as returned by getTemplatedEntity()).
5557
  static SmallVector<const Expr *, 1>
5558
0
  constraintsForTemplatedEntity(DeclContext *DC) {
5559
0
    SmallVector<const Expr *, 1> Result;
5560
0
    if (DC == nullptr)
5561
0
      return Result;
5562
    // Primary templates can have constraints.
5563
0
    if (const auto *TD = cast<Decl>(DC)->getDescribedTemplate())
5564
0
      TD->getAssociatedConstraints(Result);
5565
    // Partial specializations may have constraints.
5566
0
    if (const auto *CTPSD =
5567
0
            dyn_cast<ClassTemplatePartialSpecializationDecl>(DC))
5568
0
      CTPSD->getAssociatedConstraints(Result);
5569
0
    if (const auto *VTPSD = dyn_cast<VarTemplatePartialSpecializationDecl>(DC))
5570
0
      VTPSD->getAssociatedConstraints(Result);
5571
0
    return Result;
5572
0
  }
5573
5574
  // Attempt to find the unique type satisfying a constraint.
5575
  // This lets us show e.g. `int` instead of `std::same_as<int>`.
5576
0
  static QualType deduceType(const TypeConstraint &T) {
5577
    // Assume a same_as<T> return type constraint is std::same_as or equivalent.
5578
    // In this case the return type is T.
5579
0
    DeclarationName DN = T.getNamedConcept()->getDeclName();
5580
0
    if (DN.isIdentifier() && DN.getAsIdentifierInfo()->isStr("same_as"))
5581
0
      if (const auto *Args = T.getTemplateArgsAsWritten())
5582
0
        if (Args->getNumTemplateArgs() == 1) {
5583
0
          const auto &Arg = Args->arguments().front().getArgument();
5584
0
          if (Arg.getKind() == TemplateArgument::Type)
5585
0
            return Arg.getAsType();
5586
0
        }
5587
0
    return {};
5588
0
  }
5589
5590
  llvm::DenseMap<const IdentifierInfo *, Member> Results;
5591
};
5592
5593
// Returns a type for E that yields acceptable member completions.
5594
// In particular, when E->getType() is DependentTy, try to guess a likely type.
5595
// We accept some lossiness (like dropping parameters).
5596
// We only try to handle common expressions on the LHS of MemberExpr.
5597
0
QualType getApproximateType(const Expr *E) {
5598
0
  if (E->getType().isNull())
5599
0
    return QualType();
5600
0
  E = E->IgnoreParenImpCasts();
5601
0
  QualType Unresolved = E->getType();
5602
  // We only resolve DependentTy, or undeduced autos (including auto* etc).
5603
0
  if (!Unresolved->isSpecificBuiltinType(BuiltinType::Dependent)) {
5604
0
    AutoType *Auto = Unresolved->getContainedAutoType();
5605
0
    if (!Auto || !Auto->isUndeducedAutoType())
5606
0
      return Unresolved;
5607
0
  }
5608
  // A call: approximate-resolve callee to a function type, get its return type
5609
0
  if (const CallExpr *CE = llvm::dyn_cast<CallExpr>(E)) {
5610
0
    QualType Callee = getApproximateType(CE->getCallee());
5611
0
    if (Callee.isNull() ||
5612
0
        Callee->isSpecificPlaceholderType(BuiltinType::BoundMember))
5613
0
      Callee = Expr::findBoundMemberType(CE->getCallee());
5614
0
    if (Callee.isNull())
5615
0
      return Unresolved;
5616
5617
0
    if (const auto *FnTypePtr = Callee->getAs<PointerType>()) {
5618
0
      Callee = FnTypePtr->getPointeeType();
5619
0
    } else if (const auto *BPT = Callee->getAs<BlockPointerType>()) {
5620
0
      Callee = BPT->getPointeeType();
5621
0
    }
5622
0
    if (const FunctionType *FnType = Callee->getAs<FunctionType>())
5623
0
      return FnType->getReturnType().getNonReferenceType();
5624
5625
    // Unresolved call: try to guess the return type.
5626
0
    if (const auto *OE = llvm::dyn_cast<OverloadExpr>(CE->getCallee())) {
5627
      // If all candidates have the same approximate return type, use it.
5628
      // Discard references and const to allow more to be "the same".
5629
      // (In particular, if there's one candidate + ADL, resolve it).
5630
0
      const Type *Common = nullptr;
5631
0
      for (const auto *D : OE->decls()) {
5632
0
        QualType ReturnType;
5633
0
        if (const auto *FD = llvm::dyn_cast<FunctionDecl>(D))
5634
0
          ReturnType = FD->getReturnType();
5635
0
        else if (const auto *FTD = llvm::dyn_cast<FunctionTemplateDecl>(D))
5636
0
          ReturnType = FTD->getTemplatedDecl()->getReturnType();
5637
0
        if (ReturnType.isNull())
5638
0
          continue;
5639
0
        const Type *Candidate =
5640
0
            ReturnType.getNonReferenceType().getCanonicalType().getTypePtr();
5641
0
        if (Common && Common != Candidate)
5642
0
          return Unresolved; // Multiple candidates.
5643
0
        Common = Candidate;
5644
0
      }
5645
0
      if (Common != nullptr)
5646
0
        return QualType(Common, 0);
5647
0
    }
5648
0
  }
5649
  // A dependent member: approximate-resolve the base, then lookup.
5650
0
  if (const auto *CDSME = llvm::dyn_cast<CXXDependentScopeMemberExpr>(E)) {
5651
0
    QualType Base = CDSME->isImplicitAccess()
5652
0
                        ? CDSME->getBaseType()
5653
0
                        : getApproximateType(CDSME->getBase());
5654
0
    if (CDSME->isArrow() && !Base.isNull())
5655
0
      Base = Base->getPointeeType(); // could handle unique_ptr etc here?
5656
0
    auto *RD =
5657
0
        Base.isNull()
5658
0
            ? nullptr
5659
0
            : llvm::dyn_cast_or_null<CXXRecordDecl>(getAsRecordDecl(Base));
5660
0
    if (RD && RD->isCompleteDefinition()) {
5661
      // Look up member heuristically, including in bases.
5662
0
      for (const auto *Member : RD->lookupDependentName(
5663
0
               CDSME->getMember(), [](const NamedDecl *Member) {
5664
0
                 return llvm::isa<ValueDecl>(Member);
5665
0
               })) {
5666
0
        return llvm::cast<ValueDecl>(Member)->getType().getNonReferenceType();
5667
0
      }
5668
0
    }
5669
0
  }
5670
  // A reference to an `auto` variable: approximate-resolve its initializer.
5671
0
  if (const auto *DRE = llvm::dyn_cast<DeclRefExpr>(E)) {
5672
0
    if (const auto *VD = llvm::dyn_cast<VarDecl>(DRE->getDecl())) {
5673
0
      if (VD->hasInit())
5674
0
        return getApproximateType(VD->getInit());
5675
0
    }
5676
0
  }
5677
0
  return Unresolved;
5678
0
}
5679
5680
// If \p Base is ParenListExpr, assume a chain of comma operators and pick the
5681
// last expr. We expect other ParenListExprs to be resolved to e.g. constructor
5682
// calls before here. (So the ParenListExpr should be nonempty, but check just
5683
// in case)
5684
0
Expr *unwrapParenList(Expr *Base) {
5685
0
  if (auto *PLE = llvm::dyn_cast_or_null<ParenListExpr>(Base)) {
5686
0
    if (PLE->getNumExprs() == 0)
5687
0
      return nullptr;
5688
0
    Base = PLE->getExpr(PLE->getNumExprs() - 1);
5689
0
  }
5690
0
  return Base;
5691
0
}
5692
5693
} // namespace
5694
5695
void Sema::CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base,
5696
                                           Expr *OtherOpBase,
5697
                                           SourceLocation OpLoc, bool IsArrow,
5698
                                           bool IsBaseExprStatement,
5699
0
                                           QualType PreferredType) {
5700
0
  Base = unwrapParenList(Base);
5701
0
  OtherOpBase = unwrapParenList(OtherOpBase);
5702
0
  if (!Base || !CodeCompleter)
5703
0
    return;
5704
5705
0
  ExprResult ConvertedBase = PerformMemberExprBaseConversion(Base, IsArrow);
5706
0
  if (ConvertedBase.isInvalid())
5707
0
    return;
5708
0
  QualType ConvertedBaseType = getApproximateType(ConvertedBase.get());
5709
5710
0
  enum CodeCompletionContext::Kind contextKind;
5711
5712
0
  if (IsArrow) {
5713
0
    if (const auto *Ptr = ConvertedBaseType->getAs<PointerType>())
5714
0
      ConvertedBaseType = Ptr->getPointeeType();
5715
0
  }
5716
5717
0
  if (IsArrow) {
5718
0
    contextKind = CodeCompletionContext::CCC_ArrowMemberAccess;
5719
0
  } else {
5720
0
    if (ConvertedBaseType->isObjCObjectPointerType() ||
5721
0
        ConvertedBaseType->isObjCObjectOrInterfaceType()) {
5722
0
      contextKind = CodeCompletionContext::CCC_ObjCPropertyAccess;
5723
0
    } else {
5724
0
      contextKind = CodeCompletionContext::CCC_DotMemberAccess;
5725
0
    }
5726
0
  }
5727
5728
0
  CodeCompletionContext CCContext(contextKind, ConvertedBaseType);
5729
0
  CCContext.setPreferredType(PreferredType);
5730
0
  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5731
0
                        CodeCompleter->getCodeCompletionTUInfo(), CCContext,
5732
0
                        &ResultBuilder::IsMember);
5733
5734
0
  auto DoCompletion = [&](Expr *Base, bool IsArrow,
5735
0
                          std::optional<FixItHint> AccessOpFixIt) -> bool {
5736
0
    if (!Base)
5737
0
      return false;
5738
5739
0
    ExprResult ConvertedBase = PerformMemberExprBaseConversion(Base, IsArrow);
5740
0
    if (ConvertedBase.isInvalid())
5741
0
      return false;
5742
0
    Base = ConvertedBase.get();
5743
5744
0
    QualType BaseType = getApproximateType(Base);
5745
0
    if (BaseType.isNull())
5746
0
      return false;
5747
0
    ExprValueKind BaseKind = Base->getValueKind();
5748
5749
0
    if (IsArrow) {
5750
0
      if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
5751
0
        BaseType = Ptr->getPointeeType();
5752
0
        BaseKind = VK_LValue;
5753
0
      } else if (BaseType->isObjCObjectPointerType() ||
5754
0
                 BaseType->isTemplateTypeParmType()) {
5755
        // Both cases (dot/arrow) handled below.
5756
0
      } else {
5757
0
        return false;
5758
0
      }
5759
0
    }
5760
5761
0
    if (RecordDecl *RD = getAsRecordDecl(BaseType)) {
5762
0
      AddRecordMembersCompletionResults(*this, Results, S, BaseType, BaseKind,
5763
0
                                        RD, std::move(AccessOpFixIt));
5764
0
    } else if (const auto *TTPT =
5765
0
                   dyn_cast<TemplateTypeParmType>(BaseType.getTypePtr())) {
5766
0
      auto Operator =
5767
0
          IsArrow ? ConceptInfo::Member::Arrow : ConceptInfo::Member::Dot;
5768
0
      for (const auto &R : ConceptInfo(*TTPT, S).members()) {
5769
0
        if (R.Operator != Operator)
5770
0
          continue;
5771
0
        CodeCompletionResult Result(
5772
0
            R.render(*this, CodeCompleter->getAllocator(),
5773
0
                     CodeCompleter->getCodeCompletionTUInfo()));
5774
0
        if (AccessOpFixIt)
5775
0
          Result.FixIts.push_back(*AccessOpFixIt);
5776
0
        Results.AddResult(std::move(Result));
5777
0
      }
5778
0
    } else if (!IsArrow && BaseType->isObjCObjectPointerType()) {
5779
      // Objective-C property reference. Bail if we're performing fix-it code
5780
      // completion since Objective-C properties are normally backed by ivars,
5781
      // most Objective-C fix-its here would have little value.
5782
0
      if (AccessOpFixIt) {
5783
0
        return false;
5784
0
      }
5785
0
      AddedPropertiesSet AddedProperties;
5786
5787
0
      if (const ObjCObjectPointerType *ObjCPtr =
5788
0
              BaseType->getAsObjCInterfacePointerType()) {
5789
        // Add property results based on our interface.
5790
0
        assert(ObjCPtr && "Non-NULL pointer guaranteed above!");
5791
0
        AddObjCProperties(CCContext, ObjCPtr->getInterfaceDecl(), true,
5792
0
                          /*AllowNullaryMethods=*/true, CurContext,
5793
0
                          AddedProperties, Results, IsBaseExprStatement);
5794
0
      }
5795
5796
      // Add properties from the protocols in a qualified interface.
5797
0
      for (auto *I : BaseType->castAs<ObjCObjectPointerType>()->quals())
5798
0
        AddObjCProperties(CCContext, I, true, /*AllowNullaryMethods=*/true,
5799
0
                          CurContext, AddedProperties, Results,
5800
0
                          IsBaseExprStatement, /*IsClassProperty*/ false,
5801
0
                          /*InOriginalClass*/ false);
5802
0
    } else if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
5803
0
               (!IsArrow && BaseType->isObjCObjectType())) {
5804
      // Objective-C instance variable access. Bail if we're performing fix-it
5805
      // code completion since Objective-C properties are normally backed by
5806
      // ivars, most Objective-C fix-its here would have little value.
5807
0
      if (AccessOpFixIt) {
5808
0
        return false;
5809
0
      }
5810
0
      ObjCInterfaceDecl *Class = nullptr;
5811
0
      if (const ObjCObjectPointerType *ObjCPtr =
5812
0
              BaseType->getAs<ObjCObjectPointerType>())
5813
0
        Class = ObjCPtr->getInterfaceDecl();
5814
0
      else
5815
0
        Class = BaseType->castAs<ObjCObjectType>()->getInterface();
5816
5817
      // Add all ivars from this class and its superclasses.
5818
0
      if (Class) {
5819
0
        CodeCompletionDeclConsumer Consumer(Results, Class, BaseType);
5820
0
        Results.setFilter(&ResultBuilder::IsObjCIvar);
5821
0
        LookupVisibleDecls(
5822
0
            Class, LookupMemberName, Consumer, CodeCompleter->includeGlobals(),
5823
0
            /*IncludeDependentBases=*/false, CodeCompleter->loadExternal());
5824
0
      }
5825
0
    }
5826
5827
    // FIXME: How do we cope with isa?
5828
0
    return true;
5829
0
  };
5830
5831
0
  Results.EnterNewScope();
5832
5833
0
  bool CompletionSucceded = DoCompletion(Base, IsArrow, std::nullopt);
5834
0
  if (CodeCompleter->includeFixIts()) {
5835
0
    const CharSourceRange OpRange =
5836
0
        CharSourceRange::getTokenRange(OpLoc, OpLoc);
5837
0
    CompletionSucceded |= DoCompletion(
5838
0
        OtherOpBase, !IsArrow,
5839
0
        FixItHint::CreateReplacement(OpRange, IsArrow ? "." : "->"));
5840
0
  }
5841
5842
0
  Results.ExitScope();
5843
5844
0
  if (!CompletionSucceded)
5845
0
    return;
5846
5847
  // Hand off the results found for code completion.
5848
0
  HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
5849
0
                            Results.data(), Results.size());
5850
0
}
5851
5852
void Sema::CodeCompleteObjCClassPropertyRefExpr(Scope *S,
5853
                                                IdentifierInfo &ClassName,
5854
                                                SourceLocation ClassNameLoc,
5855
0
                                                bool IsBaseExprStatement) {
5856
0
  IdentifierInfo *ClassNamePtr = &ClassName;
5857
0
  ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(ClassNamePtr, ClassNameLoc);
5858
0
  if (!IFace)
5859
0
    return;
5860
0
  CodeCompletionContext CCContext(
5861
0
      CodeCompletionContext::CCC_ObjCPropertyAccess);
5862
0
  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5863
0
                        CodeCompleter->getCodeCompletionTUInfo(), CCContext,
5864
0
                        &ResultBuilder::IsMember);
5865
0
  Results.EnterNewScope();
5866
0
  AddedPropertiesSet AddedProperties;
5867
0
  AddObjCProperties(CCContext, IFace, true,
5868
0
                    /*AllowNullaryMethods=*/true, CurContext, AddedProperties,
5869
0
                    Results, IsBaseExprStatement,
5870
0
                    /*IsClassProperty=*/true);
5871
0
  Results.ExitScope();
5872
0
  HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
5873
0
                            Results.data(), Results.size());
5874
0
}
5875
5876
0
void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) {
5877
0
  if (!CodeCompleter)
5878
0
    return;
5879
5880
0
  ResultBuilder::LookupFilter Filter = nullptr;
5881
0
  enum CodeCompletionContext::Kind ContextKind =
5882
0
      CodeCompletionContext::CCC_Other;
5883
0
  switch ((DeclSpec::TST)TagSpec) {
5884
0
  case DeclSpec::TST_enum:
5885
0
    Filter = &ResultBuilder::IsEnum;
5886
0
    ContextKind = CodeCompletionContext::CCC_EnumTag;
5887
0
    break;
5888
5889
0
  case DeclSpec::TST_union:
5890
0
    Filter = &ResultBuilder::IsUnion;
5891
0
    ContextKind = CodeCompletionContext::CCC_UnionTag;
5892
0
    break;
5893
5894
0
  case DeclSpec::TST_struct:
5895
0
  case DeclSpec::TST_class:
5896
0
  case DeclSpec::TST_interface:
5897
0
    Filter = &ResultBuilder::IsClassOrStruct;
5898
0
    ContextKind = CodeCompletionContext::CCC_ClassOrStructTag;
5899
0
    break;
5900
5901
0
  default:
5902
0
    llvm_unreachable("Unknown type specifier kind in CodeCompleteTag");
5903
0
  }
5904
5905
0
  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5906
0
                        CodeCompleter->getCodeCompletionTUInfo(), ContextKind);
5907
0
  CodeCompletionDeclConsumer Consumer(Results, CurContext);
5908
5909
  // First pass: look for tags.
5910
0
  Results.setFilter(Filter);
5911
0
  LookupVisibleDecls(S, LookupTagName, Consumer,
5912
0
                     CodeCompleter->includeGlobals(),
5913
0
                     CodeCompleter->loadExternal());
5914
5915
0
  if (CodeCompleter->includeGlobals()) {
5916
    // Second pass: look for nested name specifiers.
5917
0
    Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
5918
0
    LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer,
5919
0
                       CodeCompleter->includeGlobals(),
5920
0
                       CodeCompleter->loadExternal());
5921
0
  }
5922
5923
0
  HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
5924
0
                            Results.data(), Results.size());
5925
0
}
5926
5927
static void AddTypeQualifierResults(DeclSpec &DS, ResultBuilder &Results,
5928
0
                                    const LangOptions &LangOpts) {
5929
0
  if (!(DS.getTypeQualifiers() & DeclSpec::TQ_const))
5930
0
    Results.AddResult("const");
5931
0
  if (!(DS.getTypeQualifiers() & DeclSpec::TQ_volatile))
5932
0
    Results.AddResult("volatile");
5933
0
  if (LangOpts.C99 && !(DS.getTypeQualifiers() & DeclSpec::TQ_restrict))
5934
0
    Results.AddResult("restrict");
5935
0
  if (LangOpts.C11 && !(DS.getTypeQualifiers() & DeclSpec::TQ_atomic))
5936
0
    Results.AddResult("_Atomic");
5937
0
  if (LangOpts.MSVCCompat && !(DS.getTypeQualifiers() & DeclSpec::TQ_unaligned))
5938
0
    Results.AddResult("__unaligned");
5939
0
}
5940
5941
0
void Sema::CodeCompleteTypeQualifiers(DeclSpec &DS) {
5942
0
  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5943
0
                        CodeCompleter->getCodeCompletionTUInfo(),
5944
0
                        CodeCompletionContext::CCC_TypeQualifiers);
5945
0
  Results.EnterNewScope();
5946
0
  AddTypeQualifierResults(DS, Results, LangOpts);
5947
0
  Results.ExitScope();
5948
0
  HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
5949
0
                            Results.data(), Results.size());
5950
0
}
5951
5952
void Sema::CodeCompleteFunctionQualifiers(DeclSpec &DS, Declarator &D,
5953
0
                                          const VirtSpecifiers *VS) {
5954
0
  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5955
0
                        CodeCompleter->getCodeCompletionTUInfo(),
5956
0
                        CodeCompletionContext::CCC_TypeQualifiers);
5957
0
  Results.EnterNewScope();
5958
0
  AddTypeQualifierResults(DS, Results, LangOpts);
5959
0
  if (LangOpts.CPlusPlus11) {
5960
0
    Results.AddResult("noexcept");
5961
0
    if (D.getContext() == DeclaratorContext::Member && !D.isCtorOrDtor() &&
5962
0
        !D.isStaticMember()) {
5963
0
      if (!VS || !VS->isFinalSpecified())
5964
0
        Results.AddResult("final");
5965
0
      if (!VS || !VS->isOverrideSpecified())
5966
0
        Results.AddResult("override");
5967
0
    }
5968
0
  }
5969
0
  Results.ExitScope();
5970
0
  HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
5971
0
                            Results.data(), Results.size());
5972
0
}
5973
5974
0
void Sema::CodeCompleteBracketDeclarator(Scope *S) {
5975
0
  CodeCompleteExpression(S, QualType(getASTContext().getSizeType()));
5976
0
}
5977
5978
0
void Sema::CodeCompleteCase(Scope *S) {
5979
0
  if (getCurFunction()->SwitchStack.empty() || !CodeCompleter)
5980
0
    return;
5981
5982
0
  SwitchStmt *Switch = getCurFunction()->SwitchStack.back().getPointer();
5983
  // Condition expression might be invalid, do not continue in this case.
5984
0
  if (!Switch->getCond())
5985
0
    return;
5986
0
  QualType type = Switch->getCond()->IgnoreImplicit()->getType();
5987
0
  if (!type->isEnumeralType()) {
5988
0
    CodeCompleteExpressionData Data(type);
5989
0
    Data.IntegralConstantExpression = true;
5990
0
    CodeCompleteExpression(S, Data);
5991
0
    return;
5992
0
  }
5993
5994
  // Code-complete the cases of a switch statement over an enumeration type
5995
  // by providing the list of
5996
0
  EnumDecl *Enum = type->castAs<EnumType>()->getDecl();
5997
0
  if (EnumDecl *Def = Enum->getDefinition())
5998
0
    Enum = Def;
5999
6000
  // Determine which enumerators we have already seen in the switch statement.
6001
  // FIXME: Ideally, we would also be able to look *past* the code-completion
6002
  // token, in case we are code-completing in the middle of the switch and not
6003
  // at the end. However, we aren't able to do so at the moment.
6004
0
  CoveredEnumerators Enumerators;
6005
0
  for (SwitchCase *SC = Switch->getSwitchCaseList(); SC;
6006
0
       SC = SC->getNextSwitchCase()) {
6007
0
    CaseStmt *Case = dyn_cast<CaseStmt>(SC);
6008
0
    if (!Case)
6009
0
      continue;
6010
6011
0
    Expr *CaseVal = Case->getLHS()->IgnoreParenCasts();
6012
0
    if (auto *DRE = dyn_cast<DeclRefExpr>(CaseVal))
6013
0
      if (auto *Enumerator =
6014
0
              dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
6015
        // We look into the AST of the case statement to determine which
6016
        // enumerator was named. Alternatively, we could compute the value of
6017
        // the integral constant expression, then compare it against the
6018
        // values of each enumerator. However, value-based approach would not
6019
        // work as well with C++ templates where enumerators declared within a
6020
        // template are type- and value-dependent.
6021
0
        Enumerators.Seen.insert(Enumerator);
6022
6023
        // If this is a qualified-id, keep track of the nested-name-specifier
6024
        // so that we can reproduce it as part of code completion, e.g.,
6025
        //
6026
        //   switch (TagD.getKind()) {
6027
        //     case TagDecl::TK_enum:
6028
        //       break;
6029
        //     case XXX
6030
        //
6031
        // At the XXX, our completions are TagDecl::TK_union,
6032
        // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
6033
        // TK_struct, and TK_class.
6034
0
        Enumerators.SuggestedQualifier = DRE->getQualifier();
6035
0
      }
6036
0
  }
6037
6038
  // Add any enumerators that have not yet been mentioned.
6039
0
  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6040
0
                        CodeCompleter->getCodeCompletionTUInfo(),
6041
0
                        CodeCompletionContext::CCC_Expression);
6042
0
  AddEnumerators(Results, Context, Enum, CurContext, Enumerators);
6043
6044
0
  if (CodeCompleter->includeMacros()) {
6045
0
    AddMacroResults(PP, Results, CodeCompleter->loadExternal(), false);
6046
0
  }
6047
0
  HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
6048
0
                            Results.data(), Results.size());
6049
0
}
6050
6051
0
static bool anyNullArguments(ArrayRef<Expr *> Args) {
6052
0
  if (Args.size() && !Args.data())
6053
0
    return true;
6054
6055
0
  for (unsigned I = 0; I != Args.size(); ++I)
6056
0
    if (!Args[I])
6057
0
      return true;
6058
6059
0
  return false;
6060
0
}
6061
6062
typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate;
6063
6064
static void mergeCandidatesWithResults(
6065
    Sema &SemaRef, SmallVectorImpl<ResultCandidate> &Results,
6066
0
    OverloadCandidateSet &CandidateSet, SourceLocation Loc, size_t ArgSize) {
6067
  // Sort the overload candidate set by placing the best overloads first.
6068
0
  llvm::stable_sort(CandidateSet, [&](const OverloadCandidate &X,
6069
0
                                      const OverloadCandidate &Y) {
6070
0
    return isBetterOverloadCandidate(SemaRef, X, Y, Loc,
6071
0
                                     CandidateSet.getKind());
6072
0
  });
6073
6074
  // Add the remaining viable overload candidates as code-completion results.
6075
0
  for (OverloadCandidate &Candidate : CandidateSet) {
6076
0
    if (Candidate.Function) {
6077
0
      if (Candidate.Function->isDeleted())
6078
0
        continue;
6079
0
      if (shouldEnforceArgLimit(/*PartialOverloading=*/true,
6080
0
                                Candidate.Function) &&
6081
0
          Candidate.Function->getNumParams() <= ArgSize &&
6082
          // Having zero args is annoying, normally we don't surface a function
6083
          // with 2 params, if you already have 2 params, because you are
6084
          // inserting the 3rd now. But with zero, it helps the user to figure
6085
          // out there are no overloads that take any arguments. Hence we are
6086
          // keeping the overload.
6087
0
          ArgSize > 0)
6088
0
        continue;
6089
0
    }
6090
0
    if (Candidate.Viable)
6091
0
      Results.push_back(ResultCandidate(Candidate.Function));
6092
0
  }
6093
0
}
6094
6095
/// Get the type of the Nth parameter from a given set of overload
6096
/// candidates.
6097
static QualType getParamType(Sema &SemaRef,
6098
0
                             ArrayRef<ResultCandidate> Candidates, unsigned N) {
6099
6100
  // Given the overloads 'Candidates' for a function call matching all arguments
6101
  // up to N, return the type of the Nth parameter if it is the same for all
6102
  // overload candidates.
6103
0
  QualType ParamType;
6104
0
  for (auto &Candidate : Candidates) {
6105
0
    QualType CandidateParamType = Candidate.getParamType(N);
6106
0
    if (CandidateParamType.isNull())
6107
0
      continue;
6108
0
    if (ParamType.isNull()) {
6109
0
      ParamType = CandidateParamType;
6110
0
      continue;
6111
0
    }
6112
0
    if (!SemaRef.Context.hasSameUnqualifiedType(
6113
0
            ParamType.getNonReferenceType(),
6114
0
            CandidateParamType.getNonReferenceType()))
6115
      // Two conflicting types, give up.
6116
0
      return QualType();
6117
0
  }
6118
6119
0
  return ParamType;
6120
0
}
6121
6122
static QualType
6123
ProduceSignatureHelp(Sema &SemaRef, MutableArrayRef<ResultCandidate> Candidates,
6124
                     unsigned CurrentArg, SourceLocation OpenParLoc,
6125
0
                     bool Braced) {
6126
0
  if (Candidates.empty())
6127
0
    return QualType();
6128
0
  if (SemaRef.getPreprocessor().isCodeCompletionReached())
6129
0
    SemaRef.CodeCompleter->ProcessOverloadCandidates(
6130
0
        SemaRef, CurrentArg, Candidates.data(), Candidates.size(), OpenParLoc,
6131
0
        Braced);
6132
0
  return getParamType(SemaRef, Candidates, CurrentArg);
6133
0
}
6134
6135
// Given a callee expression `Fn`, if the call is through a function pointer,
6136
// try to find the declaration of the corresponding function pointer type,
6137
// so that we can recover argument names from it.
6138
0
static FunctionProtoTypeLoc GetPrototypeLoc(Expr *Fn) {
6139
0
  TypeLoc Target;
6140
0
  if (const auto *T = Fn->getType().getTypePtr()->getAs<TypedefType>()) {
6141
0
    Target = T->getDecl()->getTypeSourceInfo()->getTypeLoc();
6142
6143
0
  } else if (const auto *DR = dyn_cast<DeclRefExpr>(Fn)) {
6144
0
    const auto *D = DR->getDecl();
6145
0
    if (const auto *const VD = dyn_cast<VarDecl>(D)) {
6146
0
      Target = VD->getTypeSourceInfo()->getTypeLoc();
6147
0
    }
6148
0
  }
6149
6150
0
  if (!Target)
6151
0
    return {};
6152
6153
  // Unwrap types that may be wrapping the function type
6154
0
  while (true) {
6155
0
    if (auto P = Target.getAs<PointerTypeLoc>()) {
6156
0
      Target = P.getPointeeLoc();
6157
0
      continue;
6158
0
    }
6159
0
    if (auto A = Target.getAs<AttributedTypeLoc>()) {
6160
0
      Target = A.getModifiedLoc();
6161
0
      continue;
6162
0
    }
6163
0
    if (auto P = Target.getAs<ParenTypeLoc>()) {
6164
0
      Target = P.getInnerLoc();
6165
0
      continue;
6166
0
    }
6167
0
    break;
6168
0
  }
6169
6170
0
  if (auto F = Target.getAs<FunctionProtoTypeLoc>()) {
6171
0
    return F;
6172
0
  }
6173
6174
0
  return {};
6175
0
}
6176
6177
QualType Sema::ProduceCallSignatureHelp(Expr *Fn, ArrayRef<Expr *> Args,
6178
0
                                        SourceLocation OpenParLoc) {
6179
0
  Fn = unwrapParenList(Fn);
6180
0
  if (!CodeCompleter || !Fn)
6181
0
    return QualType();
6182
6183
  // FIXME: Provide support for variadic template functions.
6184
  // Ignore type-dependent call expressions entirely.
6185
0
  if (Fn->isTypeDependent() || anyNullArguments(Args))
6186
0
    return QualType();
6187
  // In presence of dependent args we surface all possible signatures using the
6188
  // non-dependent args in the prefix. Afterwards we do a post filtering to make
6189
  // sure provided candidates satisfy parameter count restrictions.
6190
0
  auto ArgsWithoutDependentTypes =
6191
0
      Args.take_while([](Expr *Arg) { return !Arg->isTypeDependent(); });
6192
6193
0
  SmallVector<ResultCandidate, 8> Results;
6194
6195
0
  Expr *NakedFn = Fn->IgnoreParenCasts();
6196
  // Build an overload candidate set based on the functions we find.
6197
0
  SourceLocation Loc = Fn->getExprLoc();
6198
0
  OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
6199
6200
0
  if (auto ULE = dyn_cast<UnresolvedLookupExpr>(NakedFn)) {
6201
0
    AddOverloadedCallCandidates(ULE, ArgsWithoutDependentTypes, CandidateSet,
6202
0
                                /*PartialOverloading=*/true);
6203
0
  } else if (auto UME = dyn_cast<UnresolvedMemberExpr>(NakedFn)) {
6204
0
    TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
6205
0
    if (UME->hasExplicitTemplateArgs()) {
6206
0
      UME->copyTemplateArgumentsInto(TemplateArgsBuffer);
6207
0
      TemplateArgs = &TemplateArgsBuffer;
6208
0
    }
6209
6210
    // Add the base as first argument (use a nullptr if the base is implicit).
6211
0
    SmallVector<Expr *, 12> ArgExprs(
6212
0
        1, UME->isImplicitAccess() ? nullptr : UME->getBase());
6213
0
    ArgExprs.append(ArgsWithoutDependentTypes.begin(),
6214
0
                    ArgsWithoutDependentTypes.end());
6215
0
    UnresolvedSet<8> Decls;
6216
0
    Decls.append(UME->decls_begin(), UME->decls_end());
6217
0
    const bool FirstArgumentIsBase = !UME->isImplicitAccess() && UME->getBase();
6218
0
    AddFunctionCandidates(Decls, ArgExprs, CandidateSet, TemplateArgs,
6219
0
                          /*SuppressUserConversions=*/false,
6220
0
                          /*PartialOverloading=*/true, FirstArgumentIsBase);
6221
0
  } else {
6222
0
    FunctionDecl *FD = nullptr;
6223
0
    if (auto *MCE = dyn_cast<MemberExpr>(NakedFn))
6224
0
      FD = dyn_cast<FunctionDecl>(MCE->getMemberDecl());
6225
0
    else if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn))
6226
0
      FD = dyn_cast<FunctionDecl>(DRE->getDecl());
6227
0
    if (FD) { // We check whether it's a resolved function declaration.
6228
0
      if (!getLangOpts().CPlusPlus ||
6229
0
          !FD->getType()->getAs<FunctionProtoType>())
6230
0
        Results.push_back(ResultCandidate(FD));
6231
0
      else
6232
0
        AddOverloadCandidate(FD, DeclAccessPair::make(FD, FD->getAccess()),
6233
0
                             ArgsWithoutDependentTypes, CandidateSet,
6234
0
                             /*SuppressUserConversions=*/false,
6235
0
                             /*PartialOverloading=*/true);
6236
6237
0
    } else if (auto DC = NakedFn->getType()->getAsCXXRecordDecl()) {
6238
      // If expression's type is CXXRecordDecl, it may overload the function
6239
      // call operator, so we check if it does and add them as candidates.
6240
      // A complete type is needed to lookup for member function call operators.
6241
0
      if (isCompleteType(Loc, NakedFn->getType())) {
6242
0
        DeclarationName OpName =
6243
0
            Context.DeclarationNames.getCXXOperatorName(OO_Call);
6244
0
        LookupResult R(*this, OpName, Loc, LookupOrdinaryName);
6245
0
        LookupQualifiedName(R, DC);
6246
0
        R.suppressDiagnostics();
6247
0
        SmallVector<Expr *, 12> ArgExprs(1, NakedFn);
6248
0
        ArgExprs.append(ArgsWithoutDependentTypes.begin(),
6249
0
                        ArgsWithoutDependentTypes.end());
6250
0
        AddFunctionCandidates(R.asUnresolvedSet(), ArgExprs, CandidateSet,
6251
0
                              /*ExplicitArgs=*/nullptr,
6252
0
                              /*SuppressUserConversions=*/false,
6253
0
                              /*PartialOverloading=*/true);
6254
0
      }
6255
0
    } else {
6256
      // Lastly we check whether expression's type is function pointer or
6257
      // function.
6258
6259
0
      FunctionProtoTypeLoc P = GetPrototypeLoc(NakedFn);
6260
0
      QualType T = NakedFn->getType();
6261
0
      if (!T->getPointeeType().isNull())
6262
0
        T = T->getPointeeType();
6263
6264
0
      if (auto FP = T->getAs<FunctionProtoType>()) {
6265
0
        if (!TooManyArguments(FP->getNumParams(),
6266
0
                              ArgsWithoutDependentTypes.size(),
6267
0
                              /*PartialOverloading=*/true) ||
6268
0
            FP->isVariadic()) {
6269
0
          if (P) {
6270
0
            Results.push_back(ResultCandidate(P));
6271
0
          } else {
6272
0
            Results.push_back(ResultCandidate(FP));
6273
0
          }
6274
0
        }
6275
0
      } else if (auto FT = T->getAs<FunctionType>())
6276
        // No prototype and declaration, it may be a K & R style function.
6277
0
        Results.push_back(ResultCandidate(FT));
6278
0
    }
6279
0
  }
6280
0
  mergeCandidatesWithResults(*this, Results, CandidateSet, Loc, Args.size());
6281
0
  QualType ParamType = ProduceSignatureHelp(*this, Results, Args.size(),
6282
0
                                            OpenParLoc, /*Braced=*/false);
6283
0
  return !CandidateSet.empty() ? ParamType : QualType();
6284
0
}
6285
6286
// Determine which param to continue aggregate initialization from after
6287
// a designated initializer.
6288
//
6289
// Given struct S { int a,b,c,d,e; }:
6290
//   after `S{.b=1,`       we want to suggest c to continue
6291
//   after `S{.b=1, 2,`    we continue with d (this is legal C and ext in C++)
6292
//   after `S{.b=1, .a=2,` we continue with b (this is legal C and ext in C++)
6293
//
6294
// Possible outcomes:
6295
//   - we saw a designator for a field, and continue from the returned index.
6296
//     Only aggregate initialization is allowed.
6297
//   - we saw a designator, but it was complex or we couldn't find the field.
6298
//     Only aggregate initialization is possible, but we can't assist with it.
6299
//     Returns an out-of-range index.
6300
//   - we saw no designators, just positional arguments.
6301
//     Returns std::nullopt.
6302
static std::optional<unsigned>
6303
getNextAggregateIndexAfterDesignatedInit(const ResultCandidate &Aggregate,
6304
0
                                         ArrayRef<Expr *> Args) {
6305
0
  static constexpr unsigned Invalid = std::numeric_limits<unsigned>::max();
6306
0
  assert(Aggregate.getKind() == ResultCandidate::CK_Aggregate);
6307
6308
  // Look for designated initializers.
6309
  // They're in their syntactic form, not yet resolved to fields.
6310
0
  const IdentifierInfo *DesignatedFieldName = nullptr;
6311
0
  unsigned ArgsAfterDesignator = 0;
6312
0
  for (const Expr *Arg : Args) {
6313
0
    if (const auto *DIE = dyn_cast<DesignatedInitExpr>(Arg)) {
6314
0
      if (DIE->size() == 1 && DIE->getDesignator(0)->isFieldDesignator()) {
6315
0
        DesignatedFieldName = DIE->getDesignator(0)->getFieldName();
6316
0
        ArgsAfterDesignator = 0;
6317
0
      } else {
6318
0
        return Invalid; // Complicated designator.
6319
0
      }
6320
0
    } else if (isa<DesignatedInitUpdateExpr>(Arg)) {
6321
0
      return Invalid; // Unsupported.
6322
0
    } else {
6323
0
      ++ArgsAfterDesignator;
6324
0
    }
6325
0
  }
6326
0
  if (!DesignatedFieldName)
6327
0
    return std::nullopt;
6328
6329
  // Find the index within the class's fields.
6330
  // (Probing getParamDecl() directly would be quadratic in number of fields).
6331
0
  unsigned DesignatedIndex = 0;
6332
0
  const FieldDecl *DesignatedField = nullptr;
6333
0
  for (const auto *Field : Aggregate.getAggregate()->fields()) {
6334
0
    if (Field->getIdentifier() == DesignatedFieldName) {
6335
0
      DesignatedField = Field;
6336
0
      break;
6337
0
    }
6338
0
    ++DesignatedIndex;
6339
0
  }
6340
0
  if (!DesignatedField)
6341
0
    return Invalid; // Designator referred to a missing field, give up.
6342
6343
  // Find the index within the aggregate (which may have leading bases).
6344
0
  unsigned AggregateSize = Aggregate.getNumParams();
6345
0
  while (DesignatedIndex < AggregateSize &&
6346
0
         Aggregate.getParamDecl(DesignatedIndex) != DesignatedField)
6347
0
    ++DesignatedIndex;
6348
6349
  // Continue from the index after the last named field.
6350
0
  return DesignatedIndex + ArgsAfterDesignator + 1;
6351
0
}
6352
6353
QualType Sema::ProduceConstructorSignatureHelp(QualType Type,
6354
                                               SourceLocation Loc,
6355
                                               ArrayRef<Expr *> Args,
6356
                                               SourceLocation OpenParLoc,
6357
0
                                               bool Braced) {
6358
0
  if (!CodeCompleter)
6359
0
    return QualType();
6360
0
  SmallVector<ResultCandidate, 8> Results;
6361
6362
  // A complete type is needed to lookup for constructors.
6363
0
  RecordDecl *RD =
6364
0
      isCompleteType(Loc, Type) ? Type->getAsRecordDecl() : nullptr;
6365
0
  if (!RD)
6366
0
    return Type;
6367
0
  CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD);
6368
6369
  // Consider aggregate initialization.
6370
  // We don't check that types so far are correct.
6371
  // We also don't handle C99/C++17 brace-elision, we assume init-list elements
6372
  // are 1:1 with fields.
6373
  // FIXME: it would be nice to support "unwrapping" aggregates that contain
6374
  // a single subaggregate, like std::array<T, N> -> T __elements[N].
6375
0
  if (Braced && !RD->isUnion() &&
6376
0
      (!LangOpts.CPlusPlus || (CRD && CRD->isAggregate()))) {
6377
0
    ResultCandidate AggregateSig(RD);
6378
0
    unsigned AggregateSize = AggregateSig.getNumParams();
6379
6380
0
    if (auto NextIndex =
6381
0
            getNextAggregateIndexAfterDesignatedInit(AggregateSig, Args)) {
6382
      // A designator was used, only aggregate init is possible.
6383
0
      if (*NextIndex >= AggregateSize)
6384
0
        return Type;
6385
0
      Results.push_back(AggregateSig);
6386
0
      return ProduceSignatureHelp(*this, Results, *NextIndex, OpenParLoc,
6387
0
                                  Braced);
6388
0
    }
6389
6390
    // Describe aggregate initialization, but also constructors below.
6391
0
    if (Args.size() < AggregateSize)
6392
0
      Results.push_back(AggregateSig);
6393
0
  }
6394
6395
  // FIXME: Provide support for member initializers.
6396
  // FIXME: Provide support for variadic template constructors.
6397
6398
0
  if (CRD) {
6399
0
    OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
6400
0
    for (NamedDecl *C : LookupConstructors(CRD)) {
6401
0
      if (auto *FD = dyn_cast<FunctionDecl>(C)) {
6402
        // FIXME: we can't yet provide correct signature help for initializer
6403
        //        list constructors, so skip them entirely.
6404
0
        if (Braced && LangOpts.CPlusPlus && isInitListConstructor(FD))
6405
0
          continue;
6406
0
        AddOverloadCandidate(FD, DeclAccessPair::make(FD, C->getAccess()), Args,
6407
0
                             CandidateSet,
6408
0
                             /*SuppressUserConversions=*/false,
6409
0
                             /*PartialOverloading=*/true,
6410
0
                             /*AllowExplicit*/ true);
6411
0
      } else if (auto *FTD = dyn_cast<FunctionTemplateDecl>(C)) {
6412
0
        if (Braced && LangOpts.CPlusPlus &&
6413
0
            isInitListConstructor(FTD->getTemplatedDecl()))
6414
0
          continue;
6415
6416
0
        AddTemplateOverloadCandidate(
6417
0
            FTD, DeclAccessPair::make(FTD, C->getAccess()),
6418
0
            /*ExplicitTemplateArgs=*/nullptr, Args, CandidateSet,
6419
0
            /*SuppressUserConversions=*/false,
6420
0
            /*PartialOverloading=*/true);
6421
0
      }
6422
0
    }
6423
0
    mergeCandidatesWithResults(*this, Results, CandidateSet, Loc, Args.size());
6424
0
  }
6425
6426
0
  return ProduceSignatureHelp(*this, Results, Args.size(), OpenParLoc, Braced);
6427
0
}
6428
6429
QualType Sema::ProduceCtorInitMemberSignatureHelp(
6430
    Decl *ConstructorDecl, CXXScopeSpec SS, ParsedType TemplateTypeTy,
6431
    ArrayRef<Expr *> ArgExprs, IdentifierInfo *II, SourceLocation OpenParLoc,
6432
0
    bool Braced) {
6433
0
  if (!CodeCompleter)
6434
0
    return QualType();
6435
6436
0
  CXXConstructorDecl *Constructor =
6437
0
      dyn_cast<CXXConstructorDecl>(ConstructorDecl);
6438
0
  if (!Constructor)
6439
0
    return QualType();
6440
  // FIXME: Add support for Base class constructors as well.
6441
0
  if (ValueDecl *MemberDecl = tryLookupCtorInitMemberDecl(
6442
0
          Constructor->getParent(), SS, TemplateTypeTy, II))
6443
0
    return ProduceConstructorSignatureHelp(MemberDecl->getType(),
6444
0
                                           MemberDecl->getLocation(), ArgExprs,
6445
0
                                           OpenParLoc, Braced);
6446
0
  return QualType();
6447
0
}
6448
6449
static bool argMatchesTemplateParams(const ParsedTemplateArgument &Arg,
6450
                                     unsigned Index,
6451
0
                                     const TemplateParameterList &Params) {
6452
0
  const NamedDecl *Param;
6453
0
  if (Index < Params.size())
6454
0
    Param = Params.getParam(Index);
6455
0
  else if (Params.hasParameterPack())
6456
0
    Param = Params.asArray().back();
6457
0
  else
6458
0
    return false; // too many args
6459
6460
0
  switch (Arg.getKind()) {
6461
0
  case ParsedTemplateArgument::Type:
6462
0
    return llvm::isa<TemplateTypeParmDecl>(Param); // constraints not checked
6463
0
  case ParsedTemplateArgument::NonType:
6464
0
    return llvm::isa<NonTypeTemplateParmDecl>(Param); // type not checked
6465
0
  case ParsedTemplateArgument::Template:
6466
0
    return llvm::isa<TemplateTemplateParmDecl>(Param); // signature not checked
6467
0
  }
6468
0
  llvm_unreachable("Unhandled switch case");
6469
0
}
6470
6471
QualType Sema::ProduceTemplateArgumentSignatureHelp(
6472
    TemplateTy ParsedTemplate, ArrayRef<ParsedTemplateArgument> Args,
6473
0
    SourceLocation LAngleLoc) {
6474
0
  if (!CodeCompleter || !ParsedTemplate)
6475
0
    return QualType();
6476
6477
0
  SmallVector<ResultCandidate, 8> Results;
6478
0
  auto Consider = [&](const TemplateDecl *TD) {
6479
    // Only add if the existing args are compatible with the template.
6480
0
    bool Matches = true;
6481
0
    for (unsigned I = 0; I < Args.size(); ++I) {
6482
0
      if (!argMatchesTemplateParams(Args[I], I, *TD->getTemplateParameters())) {
6483
0
        Matches = false;
6484
0
        break;
6485
0
      }
6486
0
    }
6487
0
    if (Matches)
6488
0
      Results.emplace_back(TD);
6489
0
  };
6490
6491
0
  TemplateName Template = ParsedTemplate.get();
6492
0
  if (const auto *TD = Template.getAsTemplateDecl()) {
6493
0
    Consider(TD);
6494
0
  } else if (const auto *OTS = Template.getAsOverloadedTemplate()) {
6495
0
    for (const NamedDecl *ND : *OTS)
6496
0
      if (const auto *TD = llvm::dyn_cast<TemplateDecl>(ND))
6497
0
        Consider(TD);
6498
0
  }
6499
0
  return ProduceSignatureHelp(*this, Results, Args.size(), LAngleLoc,
6500
0
                              /*Braced=*/false);
6501
0
}
6502
6503
0
static QualType getDesignatedType(QualType BaseType, const Designation &Desig) {
6504
0
  for (unsigned I = 0; I < Desig.getNumDesignators(); ++I) {
6505
0
    if (BaseType.isNull())
6506
0
      break;
6507
0
    QualType NextType;
6508
0
    const auto &D = Desig.getDesignator(I);
6509
0
    if (D.isArrayDesignator() || D.isArrayRangeDesignator()) {
6510
0
      if (BaseType->isArrayType())
6511
0
        NextType = BaseType->getAsArrayTypeUnsafe()->getElementType();
6512
0
    } else {
6513
0
      assert(D.isFieldDesignator());
6514
0
      auto *RD = getAsRecordDecl(BaseType);
6515
0
      if (RD && RD->isCompleteDefinition()) {
6516
0
        for (const auto *Member : RD->lookup(D.getFieldDecl()))
6517
0
          if (const FieldDecl *FD = llvm::dyn_cast<FieldDecl>(Member)) {
6518
0
            NextType = FD->getType();
6519
0
            break;
6520
0
          }
6521
0
      }
6522
0
    }
6523
0
    BaseType = NextType;
6524
0
  }
6525
0
  return BaseType;
6526
0
}
6527
6528
void Sema::CodeCompleteDesignator(QualType BaseType,
6529
                                  llvm::ArrayRef<Expr *> InitExprs,
6530
0
                                  const Designation &D) {
6531
0
  BaseType = getDesignatedType(BaseType, D);
6532
0
  if (BaseType.isNull())
6533
0
    return;
6534
0
  const auto *RD = getAsRecordDecl(BaseType);
6535
0
  if (!RD || RD->fields().empty())
6536
0
    return;
6537
6538
0
  CodeCompletionContext CCC(CodeCompletionContext::CCC_DotMemberAccess,
6539
0
                            BaseType);
6540
0
  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6541
0
                        CodeCompleter->getCodeCompletionTUInfo(), CCC);
6542
6543
0
  Results.EnterNewScope();
6544
0
  for (const Decl *D : RD->decls()) {
6545
0
    const FieldDecl *FD;
6546
0
    if (auto *IFD = dyn_cast<IndirectFieldDecl>(D))
6547
0
      FD = IFD->getAnonField();
6548
0
    else if (auto *DFD = dyn_cast<FieldDecl>(D))
6549
0
      FD = DFD;
6550
0
    else
6551
0
      continue;
6552
6553
    // FIXME: Make use of previous designators to mark any fields before those
6554
    // inaccessible, and also compute the next initializer priority.
6555
0
    ResultBuilder::Result Result(FD, Results.getBasePriority(FD));
6556
0
    Results.AddResult(Result, CurContext, /*Hiding=*/nullptr);
6557
0
  }
6558
0
  Results.ExitScope();
6559
0
  HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
6560
0
                            Results.data(), Results.size());
6561
0
}
6562
6563
0
void Sema::CodeCompleteInitializer(Scope *S, Decl *D) {
6564
0
  ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
6565
0
  if (!VD) {
6566
0
    CodeCompleteOrdinaryName(S, PCC_Expression);
6567
0
    return;
6568
0
  }
6569
6570
0
  CodeCompleteExpressionData Data;
6571
0
  Data.PreferredType = VD->getType();
6572
  // Ignore VD to avoid completing the variable itself, e.g. in 'int foo = ^'.
6573
0
  Data.IgnoreDecls.push_back(VD);
6574
6575
0
  CodeCompleteExpression(S, Data);
6576
0
}
6577
6578
0
void Sema::CodeCompleteAfterIf(Scope *S, bool IsBracedThen) {
6579
0
  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6580
0
                        CodeCompleter->getCodeCompletionTUInfo(),
6581
0
                        mapCodeCompletionContext(*this, PCC_Statement));
6582
0
  Results.setFilter(&ResultBuilder::IsOrdinaryName);
6583
0
  Results.EnterNewScope();
6584
6585
0
  CodeCompletionDeclConsumer Consumer(Results, CurContext);
6586
0
  LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
6587
0
                     CodeCompleter->includeGlobals(),
6588
0
                     CodeCompleter->loadExternal());
6589
6590
0
  AddOrdinaryNameResults(PCC_Statement, S, *this, Results);
6591
6592
  // "else" block
6593
0
  CodeCompletionBuilder Builder(Results.getAllocator(),
6594
0
                                Results.getCodeCompletionTUInfo());
6595
6596
0
  auto AddElseBodyPattern = [&] {
6597
0
    if (IsBracedThen) {
6598
0
      Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6599
0
      Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
6600
0
      Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
6601
0
      Builder.AddPlaceholderChunk("statements");
6602
0
      Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
6603
0
      Builder.AddChunk(CodeCompletionString::CK_RightBrace);
6604
0
    } else {
6605
0
      Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
6606
0
      Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6607
0
      Builder.AddPlaceholderChunk("statement");
6608
0
      Builder.AddChunk(CodeCompletionString::CK_SemiColon);
6609
0
    }
6610
0
  };
6611
0
  Builder.AddTypedTextChunk("else");
6612
0
  if (Results.includeCodePatterns())
6613
0
    AddElseBodyPattern();
6614
0
  Results.AddResult(Builder.TakeString());
6615
6616
  // "else if" block
6617
0
  Builder.AddTypedTextChunk("else if");
6618
0
  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6619
0
  Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6620
0
  if (getLangOpts().CPlusPlus)
6621
0
    Builder.AddPlaceholderChunk("condition");
6622
0
  else
6623
0
    Builder.AddPlaceholderChunk("expression");
6624
0
  Builder.AddChunk(CodeCompletionString::CK_RightParen);
6625
0
  if (Results.includeCodePatterns()) {
6626
0
    AddElseBodyPattern();
6627
0
  }
6628
0
  Results.AddResult(Builder.TakeString());
6629
6630
0
  Results.ExitScope();
6631
6632
0
  if (S->getFnParent())
6633
0
    AddPrettyFunctionResults(getLangOpts(), Results);
6634
6635
0
  if (CodeCompleter->includeMacros())
6636
0
    AddMacroResults(PP, Results, CodeCompleter->loadExternal(), false);
6637
6638
0
  HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
6639
0
                            Results.data(), Results.size());
6640
0
}
6641
6642
void Sema::CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
6643
                                   bool EnteringContext,
6644
                                   bool IsUsingDeclaration, QualType BaseType,
6645
0
                                   QualType PreferredType) {
6646
0
  if (SS.isEmpty() || !CodeCompleter)
6647
0
    return;
6648
6649
0
  CodeCompletionContext CC(CodeCompletionContext::CCC_Symbol, PreferredType);
6650
0
  CC.setIsUsingDeclaration(IsUsingDeclaration);
6651
0
  CC.setCXXScopeSpecifier(SS);
6652
6653
  // We want to keep the scope specifier even if it's invalid (e.g. the scope
6654
  // "a::b::" is not corresponding to any context/namespace in the AST), since
6655
  // it can be useful for global code completion which have information about
6656
  // contexts/symbols that are not in the AST.
6657
0
  if (SS.isInvalid()) {
6658
    // As SS is invalid, we try to collect accessible contexts from the current
6659
    // scope with a dummy lookup so that the completion consumer can try to
6660
    // guess what the specified scope is.
6661
0
    ResultBuilder DummyResults(*this, CodeCompleter->getAllocator(),
6662
0
                               CodeCompleter->getCodeCompletionTUInfo(), CC);
6663
0
    if (!PreferredType.isNull())
6664
0
      DummyResults.setPreferredType(PreferredType);
6665
0
    if (S->getEntity()) {
6666
0
      CodeCompletionDeclConsumer Consumer(DummyResults, S->getEntity(),
6667
0
                                          BaseType);
6668
0
      LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
6669
0
                         /*IncludeGlobalScope=*/false,
6670
0
                         /*LoadExternal=*/false);
6671
0
    }
6672
0
    HandleCodeCompleteResults(this, CodeCompleter,
6673
0
                              DummyResults.getCompletionContext(), nullptr, 0);
6674
0
    return;
6675
0
  }
6676
  // Always pretend to enter a context to ensure that a dependent type
6677
  // resolves to a dependent record.
6678
0
  DeclContext *Ctx = computeDeclContext(SS, /*EnteringContext=*/true);
6679
6680
  // Try to instantiate any non-dependent declaration contexts before
6681
  // we look in them. Bail out if we fail.
6682
0
  NestedNameSpecifier *NNS = SS.getScopeRep();
6683
0
  if (NNS != nullptr && SS.isValid() && !NNS->isDependent()) {
6684
0
    if (Ctx == nullptr || RequireCompleteDeclContext(SS, Ctx))
6685
0
      return;
6686
0
  }
6687
6688
0
  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6689
0
                        CodeCompleter->getCodeCompletionTUInfo(), CC);
6690
0
  if (!PreferredType.isNull())
6691
0
    Results.setPreferredType(PreferredType);
6692
0
  Results.EnterNewScope();
6693
6694
  // The "template" keyword can follow "::" in the grammar, but only
6695
  // put it into the grammar if the nested-name-specifier is dependent.
6696
  // FIXME: results is always empty, this appears to be dead.
6697
0
  if (!Results.empty() && NNS && NNS->isDependent())
6698
0
    Results.AddResult("template");
6699
6700
  // If the scope is a concept-constrained type parameter, infer nested
6701
  // members based on the constraints.
6702
0
  if (const auto *TTPT =
6703
0
          dyn_cast_or_null<TemplateTypeParmType>(NNS->getAsType())) {
6704
0
    for (const auto &R : ConceptInfo(*TTPT, S).members()) {
6705
0
      if (R.Operator != ConceptInfo::Member::Colons)
6706
0
        continue;
6707
0
      Results.AddResult(CodeCompletionResult(
6708
0
          R.render(*this, CodeCompleter->getAllocator(),
6709
0
                   CodeCompleter->getCodeCompletionTUInfo())));
6710
0
    }
6711
0
  }
6712
6713
  // Add calls to overridden virtual functions, if there are any.
6714
  //
6715
  // FIXME: This isn't wonderful, because we don't know whether we're actually
6716
  // in a context that permits expressions. This is a general issue with
6717
  // qualified-id completions.
6718
0
  if (Ctx && !EnteringContext)
6719
0
    MaybeAddOverrideCalls(*this, Ctx, Results);
6720
0
  Results.ExitScope();
6721
6722
0
  if (Ctx &&
6723
0
      (CodeCompleter->includeNamespaceLevelDecls() || !Ctx->isFileContext())) {
6724
0
    CodeCompletionDeclConsumer Consumer(Results, Ctx, BaseType);
6725
0
    LookupVisibleDecls(Ctx, LookupOrdinaryName, Consumer,
6726
0
                       /*IncludeGlobalScope=*/true,
6727
0
                       /*IncludeDependentBases=*/true,
6728
0
                       CodeCompleter->loadExternal());
6729
0
  }
6730
6731
0
  HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
6732
0
                            Results.data(), Results.size());
6733
0
}
6734
6735
0
void Sema::CodeCompleteUsing(Scope *S) {
6736
0
  if (!CodeCompleter)
6737
0
    return;
6738
6739
  // This can be both a using alias or using declaration, in the former we
6740
  // expect a new name and a symbol in the latter case.
6741
0
  CodeCompletionContext Context(CodeCompletionContext::CCC_SymbolOrNewName);
6742
0
  Context.setIsUsingDeclaration(true);
6743
6744
0
  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6745
0
                        CodeCompleter->getCodeCompletionTUInfo(), Context,
6746
0
                        &ResultBuilder::IsNestedNameSpecifier);
6747
0
  Results.EnterNewScope();
6748
6749
  // If we aren't in class scope, we could see the "namespace" keyword.
6750
0
  if (!S->isClassScope())
6751
0
    Results.AddResult(CodeCompletionResult("namespace"));
6752
6753
  // After "using", we can see anything that would start a
6754
  // nested-name-specifier.
6755
0
  CodeCompletionDeclConsumer Consumer(Results, CurContext);
6756
0
  LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
6757
0
                     CodeCompleter->includeGlobals(),
6758
0
                     CodeCompleter->loadExternal());
6759
0
  Results.ExitScope();
6760
6761
0
  HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
6762
0
                            Results.data(), Results.size());
6763
0
}
6764
6765
0
void Sema::CodeCompleteUsingDirective(Scope *S) {
6766
0
  if (!CodeCompleter)
6767
0
    return;
6768
6769
  // After "using namespace", we expect to see a namespace name or namespace
6770
  // alias.
6771
0
  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6772
0
                        CodeCompleter->getCodeCompletionTUInfo(),
6773
0
                        CodeCompletionContext::CCC_Namespace,
6774
0
                        &ResultBuilder::IsNamespaceOrAlias);
6775
0
  Results.EnterNewScope();
6776
0
  CodeCompletionDeclConsumer Consumer(Results, CurContext);
6777
0
  LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
6778
0
                     CodeCompleter->includeGlobals(),
6779
0
                     CodeCompleter->loadExternal());
6780
0
  Results.ExitScope();
6781
0
  HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
6782
0
                            Results.data(), Results.size());
6783
0
}
6784
6785
0
void Sema::CodeCompleteNamespaceDecl(Scope *S) {
6786
0
  if (!CodeCompleter)
6787
0
    return;
6788
6789
0
  DeclContext *Ctx = S->getEntity();
6790
0
  if (!S->getParent())
6791
0
    Ctx = Context.getTranslationUnitDecl();
6792
6793
0
  bool SuppressedGlobalResults =
6794
0
      Ctx && !CodeCompleter->includeGlobals() && isa<TranslationUnitDecl>(Ctx);
6795
6796
0
  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6797
0
                        CodeCompleter->getCodeCompletionTUInfo(),
6798
0
                        SuppressedGlobalResults
6799
0
                            ? CodeCompletionContext::CCC_Namespace
6800
0
                            : CodeCompletionContext::CCC_Other,
6801
0
                        &ResultBuilder::IsNamespace);
6802
6803
0
  if (Ctx && Ctx->isFileContext() && !SuppressedGlobalResults) {
6804
    // We only want to see those namespaces that have already been defined
6805
    // within this scope, because its likely that the user is creating an
6806
    // extended namespace declaration. Keep track of the most recent
6807
    // definition of each namespace.
6808
0
    std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest;
6809
0
    for (DeclContext::specific_decl_iterator<NamespaceDecl>
6810
0
             NS(Ctx->decls_begin()),
6811
0
         NSEnd(Ctx->decls_end());
6812
0
         NS != NSEnd; ++NS)
6813
0
      OrigToLatest[NS->getOriginalNamespace()] = *NS;
6814
6815
    // Add the most recent definition (or extended definition) of each
6816
    // namespace to the list of results.
6817
0
    Results.EnterNewScope();
6818
0
    for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator
6819
0
             NS = OrigToLatest.begin(),
6820
0
             NSEnd = OrigToLatest.end();
6821
0
         NS != NSEnd; ++NS)
6822
0
      Results.AddResult(
6823
0
          CodeCompletionResult(NS->second, Results.getBasePriority(NS->second),
6824
0
                               nullptr),
6825
0
          CurContext, nullptr, false);
6826
0
    Results.ExitScope();
6827
0
  }
6828
6829
0
  HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
6830
0
                            Results.data(), Results.size());
6831
0
}
6832
6833
0
void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) {
6834
0
  if (!CodeCompleter)
6835
0
    return;
6836
6837
  // After "namespace", we expect to see a namespace or alias.
6838
0
  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6839
0
                        CodeCompleter->getCodeCompletionTUInfo(),
6840
0
                        CodeCompletionContext::CCC_Namespace,
6841
0
                        &ResultBuilder::IsNamespaceOrAlias);
6842
0
  CodeCompletionDeclConsumer Consumer(Results, CurContext);
6843
0
  LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
6844
0
                     CodeCompleter->includeGlobals(),
6845
0
                     CodeCompleter->loadExternal());
6846
0
  HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
6847
0
                            Results.data(), Results.size());
6848
0
}
6849
6850
0
void Sema::CodeCompleteOperatorName(Scope *S) {
6851
0
  if (!CodeCompleter)
6852
0
    return;
6853
6854
0
  typedef CodeCompletionResult Result;
6855
0
  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6856
0
                        CodeCompleter->getCodeCompletionTUInfo(),
6857
0
                        CodeCompletionContext::CCC_Type,
6858
0
                        &ResultBuilder::IsType);
6859
0
  Results.EnterNewScope();
6860
6861
  // Add the names of overloadable operators. Note that OO_Conditional is not
6862
  // actually overloadable.
6863
0
#define OVERLOADED_OPERATOR(Name, Spelling, Token, Unary, Binary, MemberOnly)  \
6864
0
  if (OO_##Name != OO_Conditional)                                             \
6865
0
    Results.AddResult(Result(Spelling));
6866
0
#include "clang/Basic/OperatorKinds.def"
6867
6868
  // Add any type names visible from the current scope
6869
0
  Results.allowNestedNameSpecifiers();
6870
0
  CodeCompletionDeclConsumer Consumer(Results, CurContext);
6871
0
  LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
6872
0
                     CodeCompleter->includeGlobals(),
6873
0
                     CodeCompleter->loadExternal());
6874
6875
  // Add any type specifiers
6876
0
  AddTypeSpecifierResults(getLangOpts(), Results);
6877
0
  Results.ExitScope();
6878
6879
0
  HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
6880
0
                            Results.data(), Results.size());
6881
0
}
6882
6883
void Sema::CodeCompleteConstructorInitializer(
6884
0
    Decl *ConstructorD, ArrayRef<CXXCtorInitializer *> Initializers) {
6885
0
  if (!ConstructorD)
6886
0
    return;
6887
6888
0
  AdjustDeclIfTemplate(ConstructorD);
6889
6890
0
  auto *Constructor = dyn_cast<CXXConstructorDecl>(ConstructorD);
6891
0
  if (!Constructor)
6892
0
    return;
6893
6894
0
  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6895
0
                        CodeCompleter->getCodeCompletionTUInfo(),
6896
0
                        CodeCompletionContext::CCC_Symbol);
6897
0
  Results.EnterNewScope();
6898
6899
  // Fill in any already-initialized fields or base classes.
6900
0
  llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields;
6901
0
  llvm::SmallPtrSet<CanQualType, 4> InitializedBases;
6902
0
  for (unsigned I = 0, E = Initializers.size(); I != E; ++I) {
6903
0
    if (Initializers[I]->isBaseInitializer())
6904
0
      InitializedBases.insert(Context.getCanonicalType(
6905
0
          QualType(Initializers[I]->getBaseClass(), 0)));
6906
0
    else
6907
0
      InitializedFields.insert(
6908
0
          cast<FieldDecl>(Initializers[I]->getAnyMember()));
6909
0
  }
6910
6911
  // Add completions for base classes.
6912
0
  PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
6913
0
  bool SawLastInitializer = Initializers.empty();
6914
0
  CXXRecordDecl *ClassDecl = Constructor->getParent();
6915
6916
0
  auto GenerateCCS = [&](const NamedDecl *ND, const char *Name) {
6917
0
    CodeCompletionBuilder Builder(Results.getAllocator(),
6918
0
                                  Results.getCodeCompletionTUInfo());
6919
0
    Builder.AddTypedTextChunk(Name);
6920
0
    Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6921
0
    if (const auto *Function = dyn_cast<FunctionDecl>(ND))
6922
0
      AddFunctionParameterChunks(PP, Policy, Function, Builder);
6923
0
    else if (const auto *FunTemplDecl = dyn_cast<FunctionTemplateDecl>(ND))
6924
0
      AddFunctionParameterChunks(PP, Policy, FunTemplDecl->getTemplatedDecl(),
6925
0
                                 Builder);
6926
0
    Builder.AddChunk(CodeCompletionString::CK_RightParen);
6927
0
    return Builder.TakeString();
6928
0
  };
6929
0
  auto AddDefaultCtorInit = [&](const char *Name, const char *Type,
6930
0
                                const NamedDecl *ND) {
6931
0
    CodeCompletionBuilder Builder(Results.getAllocator(),
6932
0
                                  Results.getCodeCompletionTUInfo());
6933
0
    Builder.AddTypedTextChunk(Name);
6934
0
    Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6935
0
    Builder.AddPlaceholderChunk(Type);
6936
0
    Builder.AddChunk(CodeCompletionString::CK_RightParen);
6937
0
    if (ND) {
6938
0
      auto CCR = CodeCompletionResult(
6939
0
          Builder.TakeString(), ND,
6940
0
          SawLastInitializer ? CCP_NextInitializer : CCP_MemberDeclaration);
6941
0
      if (isa<FieldDecl>(ND))
6942
0
        CCR.CursorKind = CXCursor_MemberRef;
6943
0
      return Results.AddResult(CCR);
6944
0
    }
6945
0
    return Results.AddResult(CodeCompletionResult(
6946
0
        Builder.TakeString(),
6947
0
        SawLastInitializer ? CCP_NextInitializer : CCP_MemberDeclaration));
6948
0
  };
6949
0
  auto AddCtorsWithName = [&](const CXXRecordDecl *RD, unsigned int Priority,
6950
0
                              const char *Name, const FieldDecl *FD) {
6951
0
    if (!RD)
6952
0
      return AddDefaultCtorInit(Name,
6953
0
                                FD ? Results.getAllocator().CopyString(
6954
0
                                         FD->getType().getAsString(Policy))
6955
0
                                   : Name,
6956
0
                                FD);
6957
0
    auto Ctors = getConstructors(Context, RD);
6958
0
    if (Ctors.begin() == Ctors.end())
6959
0
      return AddDefaultCtorInit(Name, Name, RD);
6960
0
    for (const NamedDecl *Ctor : Ctors) {
6961
0
      auto CCR = CodeCompletionResult(GenerateCCS(Ctor, Name), RD, Priority);
6962
0
      CCR.CursorKind = getCursorKindForDecl(Ctor);
6963
0
      Results.AddResult(CCR);
6964
0
    }
6965
0
  };
6966
0
  auto AddBase = [&](const CXXBaseSpecifier &Base) {
6967
0
    const char *BaseName =
6968
0
        Results.getAllocator().CopyString(Base.getType().getAsString(Policy));
6969
0
    const auto *RD = Base.getType()->getAsCXXRecordDecl();
6970
0
    AddCtorsWithName(
6971
0
        RD, SawLastInitializer ? CCP_NextInitializer : CCP_MemberDeclaration,
6972
0
        BaseName, nullptr);
6973
0
  };
6974
0
  auto AddField = [&](const FieldDecl *FD) {
6975
0
    const char *FieldName =
6976
0
        Results.getAllocator().CopyString(FD->getIdentifier()->getName());
6977
0
    const CXXRecordDecl *RD = FD->getType()->getAsCXXRecordDecl();
6978
0
    AddCtorsWithName(
6979
0
        RD, SawLastInitializer ? CCP_NextInitializer : CCP_MemberDeclaration,
6980
0
        FieldName, FD);
6981
0
  };
6982
6983
0
  for (const auto &Base : ClassDecl->bases()) {
6984
0
    if (!InitializedBases.insert(Context.getCanonicalType(Base.getType()))
6985
0
             .second) {
6986
0
      SawLastInitializer =
6987
0
          !Initializers.empty() && Initializers.back()->isBaseInitializer() &&
6988
0
          Context.hasSameUnqualifiedType(
6989
0
              Base.getType(), QualType(Initializers.back()->getBaseClass(), 0));
6990
0
      continue;
6991
0
    }
6992
6993
0
    AddBase(Base);
6994
0
    SawLastInitializer = false;
6995
0
  }
6996
6997
  // Add completions for virtual base classes.
6998
0
  for (const auto &Base : ClassDecl->vbases()) {
6999
0
    if (!InitializedBases.insert(Context.getCanonicalType(Base.getType()))
7000
0
             .second) {
7001
0
      SawLastInitializer =
7002
0
          !Initializers.empty() && Initializers.back()->isBaseInitializer() &&
7003
0
          Context.hasSameUnqualifiedType(
7004
0
              Base.getType(), QualType(Initializers.back()->getBaseClass(), 0));
7005
0
      continue;
7006
0
    }
7007
7008
0
    AddBase(Base);
7009
0
    SawLastInitializer = false;
7010
0
  }
7011
7012
  // Add completions for members.
7013
0
  for (auto *Field : ClassDecl->fields()) {
7014
0
    if (!InitializedFields.insert(cast<FieldDecl>(Field->getCanonicalDecl()))
7015
0
             .second) {
7016
0
      SawLastInitializer = !Initializers.empty() &&
7017
0
                           Initializers.back()->isAnyMemberInitializer() &&
7018
0
                           Initializers.back()->getAnyMember() == Field;
7019
0
      continue;
7020
0
    }
7021
7022
0
    if (!Field->getDeclName())
7023
0
      continue;
7024
7025
0
    AddField(Field);
7026
0
    SawLastInitializer = false;
7027
0
  }
7028
0
  Results.ExitScope();
7029
7030
0
  HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
7031
0
                            Results.data(), Results.size());
7032
0
}
7033
7034
/// Determine whether this scope denotes a namespace.
7035
0
static bool isNamespaceScope(Scope *S) {
7036
0
  DeclContext *DC = S->getEntity();
7037
0
  if (!DC)
7038
0
    return false;
7039
7040
0
  return DC->isFileContext();
7041
0
}
7042
7043
void Sema::CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro,
7044
0
                                        bool AfterAmpersand) {
7045
0
  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
7046
0
                        CodeCompleter->getCodeCompletionTUInfo(),
7047
0
                        CodeCompletionContext::CCC_Other);
7048
0
  Results.EnterNewScope();
7049
7050
  // Note what has already been captured.
7051
0
  llvm::SmallPtrSet<IdentifierInfo *, 4> Known;
7052
0
  bool IncludedThis = false;
7053
0
  for (const auto &C : Intro.Captures) {
7054
0
    if (C.Kind == LCK_This) {
7055
0
      IncludedThis = true;
7056
0
      continue;
7057
0
    }
7058
7059
0
    Known.insert(C.Id);
7060
0
  }
7061
7062
  // Look for other capturable variables.
7063
0
  for (; S && !isNamespaceScope(S); S = S->getParent()) {
7064
0
    for (const auto *D : S->decls()) {
7065
0
      const auto *Var = dyn_cast<VarDecl>(D);
7066
0
      if (!Var || !Var->hasLocalStorage() || Var->hasAttr<BlocksAttr>())
7067
0
        continue;
7068
7069
0
      if (Known.insert(Var->getIdentifier()).second)
7070
0
        Results.AddResult(CodeCompletionResult(Var, CCP_LocalDeclaration),
7071
0
                          CurContext, nullptr, false);
7072
0
    }
7073
0
  }
7074
7075
  // Add 'this', if it would be valid.
7076
0
  if (!IncludedThis && !AfterAmpersand && Intro.Default != LCD_ByCopy)
7077
0
    addThisCompletion(*this, Results);
7078
7079
0
  Results.ExitScope();
7080
7081
0
  HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
7082
0
                            Results.data(), Results.size());
7083
0
}
7084
7085
0
void Sema::CodeCompleteAfterFunctionEquals(Declarator &D) {
7086
0
  if (!LangOpts.CPlusPlus11)
7087
0
    return;
7088
0
  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
7089
0
                        CodeCompleter->getCodeCompletionTUInfo(),
7090
0
                        CodeCompletionContext::CCC_Other);
7091
0
  auto ShouldAddDefault = [&D, this]() {
7092
0
    if (!D.isFunctionDeclarator())
7093
0
      return false;
7094
0
    auto &Id = D.getName();
7095
0
    if (Id.getKind() == UnqualifiedIdKind::IK_DestructorName)
7096
0
      return true;
7097
    // FIXME(liuhui): Ideally, we should check the constructor parameter list to
7098
    // verify that it is the default, copy or move constructor?
7099
0
    if (Id.getKind() == UnqualifiedIdKind::IK_ConstructorName &&
7100
0
        D.getFunctionTypeInfo().NumParams <= 1)
7101
0
      return true;
7102
0
    if (Id.getKind() == UnqualifiedIdKind::IK_OperatorFunctionId) {
7103
0
      auto Op = Id.OperatorFunctionId.Operator;
7104
      // FIXME(liuhui): Ideally, we should check the function parameter list to
7105
      // verify that it is the copy or move assignment?
7106
0
      if (Op == OverloadedOperatorKind::OO_Equal)
7107
0
        return true;
7108
0
      if (LangOpts.CPlusPlus20 &&
7109
0
          (Op == OverloadedOperatorKind::OO_EqualEqual ||
7110
0
           Op == OverloadedOperatorKind::OO_ExclaimEqual ||
7111
0
           Op == OverloadedOperatorKind::OO_Less ||
7112
0
           Op == OverloadedOperatorKind::OO_LessEqual ||
7113
0
           Op == OverloadedOperatorKind::OO_Greater ||
7114
0
           Op == OverloadedOperatorKind::OO_GreaterEqual ||
7115
0
           Op == OverloadedOperatorKind::OO_Spaceship))
7116
0
        return true;
7117
0
    }
7118
0
    return false;
7119
0
  };
7120
7121
0
  Results.EnterNewScope();
7122
0
  if (ShouldAddDefault())
7123
0
    Results.AddResult("default");
7124
  // FIXME(liuhui): Ideally, we should only provide `delete` completion for the
7125
  // first function declaration.
7126
0
  Results.AddResult("delete");
7127
0
  Results.ExitScope();
7128
0
  HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
7129
0
                            Results.data(), Results.size());
7130
0
}
7131
7132
/// Macro that optionally prepends an "@" to the string literal passed in via
7133
/// Keyword, depending on whether NeedAt is true or false.
7134
0
#define OBJC_AT_KEYWORD_NAME(NeedAt, Keyword) ((NeedAt) ? "@" Keyword : Keyword)
7135
7136
static void AddObjCImplementationResults(const LangOptions &LangOpts,
7137
0
                                         ResultBuilder &Results, bool NeedAt) {
7138
0
  typedef CodeCompletionResult Result;
7139
  // Since we have an implementation, we can end it.
7140
0
  Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "end")));
7141
7142
0
  CodeCompletionBuilder Builder(Results.getAllocator(),
7143
0
                                Results.getCodeCompletionTUInfo());
7144
0
  if (LangOpts.ObjC) {
7145
    // @dynamic
7146
0
    Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "dynamic"));
7147
0
    Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7148
0
    Builder.AddPlaceholderChunk("property");
7149
0
    Results.AddResult(Result(Builder.TakeString()));
7150
7151
    // @synthesize
7152
0
    Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "synthesize"));
7153
0
    Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7154
0
    Builder.AddPlaceholderChunk("property");
7155
0
    Results.AddResult(Result(Builder.TakeString()));
7156
0
  }
7157
0
}
7158
7159
static void AddObjCInterfaceResults(const LangOptions &LangOpts,
7160
0
                                    ResultBuilder &Results, bool NeedAt) {
7161
0
  typedef CodeCompletionResult Result;
7162
7163
  // Since we have an interface or protocol, we can end it.
7164
0
  Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "end")));
7165
7166
0
  if (LangOpts.ObjC) {
7167
    // @property
7168
0
    Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "property")));
7169
7170
    // @required
7171
0
    Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "required")));
7172
7173
    // @optional
7174
0
    Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "optional")));
7175
0
  }
7176
0
}
7177
7178
0
static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt) {
7179
0
  typedef CodeCompletionResult Result;
7180
0
  CodeCompletionBuilder Builder(Results.getAllocator(),
7181
0
                                Results.getCodeCompletionTUInfo());
7182
7183
  // @class name ;
7184
0
  Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "class"));
7185
0
  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7186
0
  Builder.AddPlaceholderChunk("name");
7187
0
  Results.AddResult(Result(Builder.TakeString()));
7188
7189
0
  if (Results.includeCodePatterns()) {
7190
    // @interface name
7191
    // FIXME: Could introduce the whole pattern, including superclasses and
7192
    // such.
7193
0
    Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "interface"));
7194
0
    Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7195
0
    Builder.AddPlaceholderChunk("class");
7196
0
    Results.AddResult(Result(Builder.TakeString()));
7197
7198
    // @protocol name
7199
0
    Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "protocol"));
7200
0
    Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7201
0
    Builder.AddPlaceholderChunk("protocol");
7202
0
    Results.AddResult(Result(Builder.TakeString()));
7203
7204
    // @implementation name
7205
0
    Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "implementation"));
7206
0
    Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7207
0
    Builder.AddPlaceholderChunk("class");
7208
0
    Results.AddResult(Result(Builder.TakeString()));
7209
0
  }
7210
7211
  // @compatibility_alias name
7212
0
  Builder.AddTypedTextChunk(
7213
0
      OBJC_AT_KEYWORD_NAME(NeedAt, "compatibility_alias"));
7214
0
  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7215
0
  Builder.AddPlaceholderChunk("alias");
7216
0
  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7217
0
  Builder.AddPlaceholderChunk("class");
7218
0
  Results.AddResult(Result(Builder.TakeString()));
7219
7220
0
  if (Results.getSema().getLangOpts().Modules) {
7221
    // @import name
7222
0
    Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "import"));
7223
0
    Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7224
0
    Builder.AddPlaceholderChunk("module");
7225
0
    Results.AddResult(Result(Builder.TakeString()));
7226
0
  }
7227
0
}
7228
7229
0
void Sema::CodeCompleteObjCAtDirective(Scope *S) {
7230
0
  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
7231
0
                        CodeCompleter->getCodeCompletionTUInfo(),
7232
0
                        CodeCompletionContext::CCC_Other);
7233
0
  Results.EnterNewScope();
7234
0
  if (isa<ObjCImplDecl>(CurContext))
7235
0
    AddObjCImplementationResults(getLangOpts(), Results, false);
7236
0
  else if (CurContext->isObjCContainer())
7237
0
    AddObjCInterfaceResults(getLangOpts(), Results, false);
7238
0
  else
7239
0
    AddObjCTopLevelResults(Results, false);
7240
0
  Results.ExitScope();
7241
0
  HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
7242
0
                            Results.data(), Results.size());
7243
0
}
7244
7245
0
static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt) {
7246
0
  typedef CodeCompletionResult Result;
7247
0
  CodeCompletionBuilder Builder(Results.getAllocator(),
7248
0
                                Results.getCodeCompletionTUInfo());
7249
7250
  // @encode ( type-name )
7251
0
  const char *EncodeType = "char[]";
7252
0
  if (Results.getSema().getLangOpts().CPlusPlus ||
7253
0
      Results.getSema().getLangOpts().ConstStrings)
7254
0
    EncodeType = "const char[]";
7255
0
  Builder.AddResultTypeChunk(EncodeType);
7256
0
  Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "encode"));
7257
0
  Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7258
0
  Builder.AddPlaceholderChunk("type-name");
7259
0
  Builder.AddChunk(CodeCompletionString::CK_RightParen);
7260
0
  Results.AddResult(Result(Builder.TakeString()));
7261
7262
  // @protocol ( protocol-name )
7263
0
  Builder.AddResultTypeChunk("Protocol *");
7264
0
  Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "protocol"));
7265
0
  Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7266
0
  Builder.AddPlaceholderChunk("protocol-name");
7267
0
  Builder.AddChunk(CodeCompletionString::CK_RightParen);
7268
0
  Results.AddResult(Result(Builder.TakeString()));
7269
7270
  // @selector ( selector )
7271
0
  Builder.AddResultTypeChunk("SEL");
7272
0
  Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "selector"));
7273
0
  Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7274
0
  Builder.AddPlaceholderChunk("selector");
7275
0
  Builder.AddChunk(CodeCompletionString::CK_RightParen);
7276
0
  Results.AddResult(Result(Builder.TakeString()));
7277
7278
  // @"string"
7279
0
  Builder.AddResultTypeChunk("NSString *");
7280
0
  Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "\""));
7281
0
  Builder.AddPlaceholderChunk("string");
7282
0
  Builder.AddTextChunk("\"");
7283
0
  Results.AddResult(Result(Builder.TakeString()));
7284
7285
  // @[objects, ...]
7286
0
  Builder.AddResultTypeChunk("NSArray *");
7287
0
  Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "["));
7288
0
  Builder.AddPlaceholderChunk("objects, ...");
7289
0
  Builder.AddChunk(CodeCompletionString::CK_RightBracket);
7290
0
  Results.AddResult(Result(Builder.TakeString()));
7291
7292
  // @{key : object, ...}
7293
0
  Builder.AddResultTypeChunk("NSDictionary *");
7294
0
  Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "{"));
7295
0
  Builder.AddPlaceholderChunk("key");
7296
0
  Builder.AddChunk(CodeCompletionString::CK_Colon);
7297
0
  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7298
0
  Builder.AddPlaceholderChunk("object, ...");
7299
0
  Builder.AddChunk(CodeCompletionString::CK_RightBrace);
7300
0
  Results.AddResult(Result(Builder.TakeString()));
7301
7302
  // @(expression)
7303
0
  Builder.AddResultTypeChunk("id");
7304
0
  Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "("));
7305
0
  Builder.AddPlaceholderChunk("expression");
7306
0
  Builder.AddChunk(CodeCompletionString::CK_RightParen);
7307
0
  Results.AddResult(Result(Builder.TakeString()));
7308
0
}
7309
7310
0
static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt) {
7311
0
  typedef CodeCompletionResult Result;
7312
0
  CodeCompletionBuilder Builder(Results.getAllocator(),
7313
0
                                Results.getCodeCompletionTUInfo());
7314
7315
0
  if (Results.includeCodePatterns()) {
7316
    // @try { statements } @catch ( declaration ) { statements } @finally
7317
    //   { statements }
7318
0
    Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "try"));
7319
0
    Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
7320
0
    Builder.AddPlaceholderChunk("statements");
7321
0
    Builder.AddChunk(CodeCompletionString::CK_RightBrace);
7322
0
    Builder.AddTextChunk("@catch");
7323
0
    Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7324
0
    Builder.AddPlaceholderChunk("parameter");
7325
0
    Builder.AddChunk(CodeCompletionString::CK_RightParen);
7326
0
    Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
7327
0
    Builder.AddPlaceholderChunk("statements");
7328
0
    Builder.AddChunk(CodeCompletionString::CK_RightBrace);
7329
0
    Builder.AddTextChunk("@finally");
7330
0
    Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
7331
0
    Builder.AddPlaceholderChunk("statements");
7332
0
    Builder.AddChunk(CodeCompletionString::CK_RightBrace);
7333
0
    Results.AddResult(Result(Builder.TakeString()));
7334
0
  }
7335
7336
  // @throw
7337
0
  Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "throw"));
7338
0
  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7339
0
  Builder.AddPlaceholderChunk("expression");
7340
0
  Results.AddResult(Result(Builder.TakeString()));
7341
7342
0
  if (Results.includeCodePatterns()) {
7343
    // @synchronized ( expression ) { statements }
7344
0
    Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "synchronized"));
7345
0
    Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7346
0
    Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7347
0
    Builder.AddPlaceholderChunk("expression");
7348
0
    Builder.AddChunk(CodeCompletionString::CK_RightParen);
7349
0
    Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
7350
0
    Builder.AddPlaceholderChunk("statements");
7351
0
    Builder.AddChunk(CodeCompletionString::CK_RightBrace);
7352
0
    Results.AddResult(Result(Builder.TakeString()));
7353
0
  }
7354
0
}
7355
7356
static void AddObjCVisibilityResults(const LangOptions &LangOpts,
7357
0
                                     ResultBuilder &Results, bool NeedAt) {
7358
0
  typedef CodeCompletionResult Result;
7359
0
  Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "private")));
7360
0
  Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "protected")));
7361
0
  Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "public")));
7362
0
  if (LangOpts.ObjC)
7363
0
    Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "package")));
7364
0
}
7365
7366
0
void Sema::CodeCompleteObjCAtVisibility(Scope *S) {
7367
0
  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
7368
0
                        CodeCompleter->getCodeCompletionTUInfo(),
7369
0
                        CodeCompletionContext::CCC_Other);
7370
0
  Results.EnterNewScope();
7371
0
  AddObjCVisibilityResults(getLangOpts(), Results, false);
7372
0
  Results.ExitScope();
7373
0
  HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
7374
0
                            Results.data(), Results.size());
7375
0
}
7376
7377
0
void Sema::CodeCompleteObjCAtStatement(Scope *S) {
7378
0
  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
7379
0
                        CodeCompleter->getCodeCompletionTUInfo(),
7380
0
                        CodeCompletionContext::CCC_Other);
7381
0
  Results.EnterNewScope();
7382
0
  AddObjCStatementResults(Results, false);
7383
0
  AddObjCExpressionResults(Results, false);
7384
0
  Results.ExitScope();
7385
0
  HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
7386
0
                            Results.data(), Results.size());
7387
0
}
7388
7389
0
void Sema::CodeCompleteObjCAtExpression(Scope *S) {
7390
0
  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
7391
0
                        CodeCompleter->getCodeCompletionTUInfo(),
7392
0
                        CodeCompletionContext::CCC_Other);
7393
0
  Results.EnterNewScope();
7394
0
  AddObjCExpressionResults(Results, false);
7395
0
  Results.ExitScope();
7396
0
  HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
7397
0
                            Results.data(), Results.size());
7398
0
}
7399
7400
/// Determine whether the addition of the given flag to an Objective-C
7401
/// property's attributes will cause a conflict.
7402
0
static bool ObjCPropertyFlagConflicts(unsigned Attributes, unsigned NewFlag) {
7403
  // Check if we've already added this flag.
7404
0
  if (Attributes & NewFlag)
7405
0
    return true;
7406
7407
0
  Attributes |= NewFlag;
7408
7409
  // Check for collisions with "readonly".
7410
0
  if ((Attributes & ObjCPropertyAttribute::kind_readonly) &&
7411
0
      (Attributes & ObjCPropertyAttribute::kind_readwrite))
7412
0
    return true;
7413
7414
  // Check for more than one of { assign, copy, retain, strong, weak }.
7415
0
  unsigned AssignCopyRetMask =
7416
0
      Attributes &
7417
0
      (ObjCPropertyAttribute::kind_assign |
7418
0
       ObjCPropertyAttribute::kind_unsafe_unretained |
7419
0
       ObjCPropertyAttribute::kind_copy | ObjCPropertyAttribute::kind_retain |
7420
0
       ObjCPropertyAttribute::kind_strong | ObjCPropertyAttribute::kind_weak);
7421
0
  if (AssignCopyRetMask &&
7422
0
      AssignCopyRetMask != ObjCPropertyAttribute::kind_assign &&
7423
0
      AssignCopyRetMask != ObjCPropertyAttribute::kind_unsafe_unretained &&
7424
0
      AssignCopyRetMask != ObjCPropertyAttribute::kind_copy &&
7425
0
      AssignCopyRetMask != ObjCPropertyAttribute::kind_retain &&
7426
0
      AssignCopyRetMask != ObjCPropertyAttribute::kind_strong &&
7427
0
      AssignCopyRetMask != ObjCPropertyAttribute::kind_weak)
7428
0
    return true;
7429
7430
0
  return false;
7431
0
}
7432
7433
0
void Sema::CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS) {
7434
0
  if (!CodeCompleter)
7435
0
    return;
7436
7437
0
  unsigned Attributes = ODS.getPropertyAttributes();
7438
7439
0
  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
7440
0
                        CodeCompleter->getCodeCompletionTUInfo(),
7441
0
                        CodeCompletionContext::CCC_Other);
7442
0
  Results.EnterNewScope();
7443
0
  if (!ObjCPropertyFlagConflicts(Attributes,
7444
0
                                 ObjCPropertyAttribute::kind_readonly))
7445
0
    Results.AddResult(CodeCompletionResult("readonly"));
7446
0
  if (!ObjCPropertyFlagConflicts(Attributes,
7447
0
                                 ObjCPropertyAttribute::kind_assign))
7448
0
    Results.AddResult(CodeCompletionResult("assign"));
7449
0
  if (!ObjCPropertyFlagConflicts(Attributes,
7450
0
                                 ObjCPropertyAttribute::kind_unsafe_unretained))
7451
0
    Results.AddResult(CodeCompletionResult("unsafe_unretained"));
7452
0
  if (!ObjCPropertyFlagConflicts(Attributes,
7453
0
                                 ObjCPropertyAttribute::kind_readwrite))
7454
0
    Results.AddResult(CodeCompletionResult("readwrite"));
7455
0
  if (!ObjCPropertyFlagConflicts(Attributes,
7456
0
                                 ObjCPropertyAttribute::kind_retain))
7457
0
    Results.AddResult(CodeCompletionResult("retain"));
7458
0
  if (!ObjCPropertyFlagConflicts(Attributes,
7459
0
                                 ObjCPropertyAttribute::kind_strong))
7460
0
    Results.AddResult(CodeCompletionResult("strong"));
7461
0
  if (!ObjCPropertyFlagConflicts(Attributes, ObjCPropertyAttribute::kind_copy))
7462
0
    Results.AddResult(CodeCompletionResult("copy"));
7463
0
  if (!ObjCPropertyFlagConflicts(Attributes,
7464
0
                                 ObjCPropertyAttribute::kind_nonatomic))
7465
0
    Results.AddResult(CodeCompletionResult("nonatomic"));
7466
0
  if (!ObjCPropertyFlagConflicts(Attributes,
7467
0
                                 ObjCPropertyAttribute::kind_atomic))
7468
0
    Results.AddResult(CodeCompletionResult("atomic"));
7469
7470
  // Only suggest "weak" if we're compiling for ARC-with-weak-references or GC.
7471
0
  if (getLangOpts().ObjCWeak || getLangOpts().getGC() != LangOptions::NonGC)
7472
0
    if (!ObjCPropertyFlagConflicts(Attributes,
7473
0
                                   ObjCPropertyAttribute::kind_weak))
7474
0
      Results.AddResult(CodeCompletionResult("weak"));
7475
7476
0
  if (!ObjCPropertyFlagConflicts(Attributes,
7477
0
                                 ObjCPropertyAttribute::kind_setter)) {
7478
0
    CodeCompletionBuilder Setter(Results.getAllocator(),
7479
0
                                 Results.getCodeCompletionTUInfo());
7480
0
    Setter.AddTypedTextChunk("setter");
7481
0
    Setter.AddTextChunk("=");
7482
0
    Setter.AddPlaceholderChunk("method");
7483
0
    Results.AddResult(CodeCompletionResult(Setter.TakeString()));
7484
0
  }
7485
0
  if (!ObjCPropertyFlagConflicts(Attributes,
7486
0
                                 ObjCPropertyAttribute::kind_getter)) {
7487
0
    CodeCompletionBuilder Getter(Results.getAllocator(),
7488
0
                                 Results.getCodeCompletionTUInfo());
7489
0
    Getter.AddTypedTextChunk("getter");
7490
0
    Getter.AddTextChunk("=");
7491
0
    Getter.AddPlaceholderChunk("method");
7492
0
    Results.AddResult(CodeCompletionResult(Getter.TakeString()));
7493
0
  }
7494
0
  if (!ObjCPropertyFlagConflicts(Attributes,
7495
0
                                 ObjCPropertyAttribute::kind_nullability)) {
7496
0
    Results.AddResult(CodeCompletionResult("nonnull"));
7497
0
    Results.AddResult(CodeCompletionResult("nullable"));
7498
0
    Results.AddResult(CodeCompletionResult("null_unspecified"));
7499
0
    Results.AddResult(CodeCompletionResult("null_resettable"));
7500
0
  }
7501
0
  Results.ExitScope();
7502
0
  HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
7503
0
                            Results.data(), Results.size());
7504
0
}
7505
7506
/// Describes the kind of Objective-C method that we want to find
7507
/// via code completion.
7508
enum ObjCMethodKind {
7509
  MK_Any, ///< Any kind of method, provided it means other specified criteria.
7510
  MK_ZeroArgSelector, ///< Zero-argument (unary) selector.
7511
  MK_OneArgSelector   ///< One-argument selector.
7512
};
7513
7514
static bool isAcceptableObjCSelector(Selector Sel, ObjCMethodKind WantKind,
7515
                                     ArrayRef<IdentifierInfo *> SelIdents,
7516
0
                                     bool AllowSameLength = true) {
7517
0
  unsigned NumSelIdents = SelIdents.size();
7518
0
  if (NumSelIdents > Sel.getNumArgs())
7519
0
    return false;
7520
7521
0
  switch (WantKind) {
7522
0
  case MK_Any:
7523
0
    break;
7524
0
  case MK_ZeroArgSelector:
7525
0
    return Sel.isUnarySelector();
7526
0
  case MK_OneArgSelector:
7527
0
    return Sel.getNumArgs() == 1;
7528
0
  }
7529
7530
0
  if (!AllowSameLength && NumSelIdents && NumSelIdents == Sel.getNumArgs())
7531
0
    return false;
7532
7533
0
  for (unsigned I = 0; I != NumSelIdents; ++I)
7534
0
    if (SelIdents[I] != Sel.getIdentifierInfoForSlot(I))
7535
0
      return false;
7536
7537
0
  return true;
7538
0
}
7539
7540
static bool isAcceptableObjCMethod(ObjCMethodDecl *Method,
7541
                                   ObjCMethodKind WantKind,
7542
                                   ArrayRef<IdentifierInfo *> SelIdents,
7543
0
                                   bool AllowSameLength = true) {
7544
0
  return isAcceptableObjCSelector(Method->getSelector(), WantKind, SelIdents,
7545
0
                                  AllowSameLength);
7546
0
}
7547
7548
/// A set of selectors, which is used to avoid introducing multiple
7549
/// completions with the same selector into the result set.
7550
typedef llvm::SmallPtrSet<Selector, 16> VisitedSelectorSet;
7551
7552
/// Add all of the Objective-C methods in the given Objective-C
7553
/// container to the set of results.
7554
///
7555
/// The container will be a class, protocol, category, or implementation of
7556
/// any of the above. This mether will recurse to include methods from
7557
/// the superclasses of classes along with their categories, protocols, and
7558
/// implementations.
7559
///
7560
/// \param Container the container in which we'll look to find methods.
7561
///
7562
/// \param WantInstanceMethods Whether to add instance methods (only); if
7563
/// false, this routine will add factory methods (only).
7564
///
7565
/// \param CurContext the context in which we're performing the lookup that
7566
/// finds methods.
7567
///
7568
/// \param AllowSameLength Whether we allow a method to be added to the list
7569
/// when it has the same number of parameters as we have selector identifiers.
7570
///
7571
/// \param Results the structure into which we'll add results.
7572
static void AddObjCMethods(ObjCContainerDecl *Container,
7573
                           bool WantInstanceMethods, ObjCMethodKind WantKind,
7574
                           ArrayRef<IdentifierInfo *> SelIdents,
7575
                           DeclContext *CurContext,
7576
                           VisitedSelectorSet &Selectors, bool AllowSameLength,
7577
                           ResultBuilder &Results, bool InOriginalClass = true,
7578
0
                           bool IsRootClass = false) {
7579
0
  typedef CodeCompletionResult Result;
7580
0
  Container = getContainerDef(Container);
7581
0
  ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container);
7582
0
  IsRootClass = IsRootClass || (IFace && !IFace->getSuperClass());
7583
0
  for (ObjCMethodDecl *M : Container->methods()) {
7584
    // The instance methods on the root class can be messaged via the
7585
    // metaclass.
7586
0
    if (M->isInstanceMethod() == WantInstanceMethods ||
7587
0
        (IsRootClass && !WantInstanceMethods)) {
7588
      // Check whether the selector identifiers we've been given are a
7589
      // subset of the identifiers for this particular method.
7590
0
      if (!isAcceptableObjCMethod(M, WantKind, SelIdents, AllowSameLength))
7591
0
        continue;
7592
7593
0
      if (!Selectors.insert(M->getSelector()).second)
7594
0
        continue;
7595
7596
0
      Result R = Result(M, Results.getBasePriority(M), nullptr);
7597
0
      R.StartParameter = SelIdents.size();
7598
0
      R.AllParametersAreInformative = (WantKind != MK_Any);
7599
0
      if (!InOriginalClass)
7600
0
        setInBaseClass(R);
7601
0
      Results.MaybeAddResult(R, CurContext);
7602
0
    }
7603
0
  }
7604
7605
  // Visit the protocols of protocols.
7606
0
  if (const auto *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
7607
0
    if (Protocol->hasDefinition()) {
7608
0
      const ObjCList<ObjCProtocolDecl> &Protocols =
7609
0
          Protocol->getReferencedProtocols();
7610
0
      for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
7611
0
                                                E = Protocols.end();
7612
0
           I != E; ++I)
7613
0
        AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, CurContext,
7614
0
                       Selectors, AllowSameLength, Results, false, IsRootClass);
7615
0
    }
7616
0
  }
7617
7618
0
  if (!IFace || !IFace->hasDefinition())
7619
0
    return;
7620
7621
  // Add methods in protocols.
7622
0
  for (ObjCProtocolDecl *I : IFace->protocols())
7623
0
    AddObjCMethods(I, WantInstanceMethods, WantKind, SelIdents, CurContext,
7624
0
                   Selectors, AllowSameLength, Results, false, IsRootClass);
7625
7626
  // Add methods in categories.
7627
0
  for (ObjCCategoryDecl *CatDecl : IFace->known_categories()) {
7628
0
    AddObjCMethods(CatDecl, WantInstanceMethods, WantKind, SelIdents,
7629
0
                   CurContext, Selectors, AllowSameLength, Results,
7630
0
                   InOriginalClass, IsRootClass);
7631
7632
    // Add a categories protocol methods.
7633
0
    const ObjCList<ObjCProtocolDecl> &Protocols =
7634
0
        CatDecl->getReferencedProtocols();
7635
0
    for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
7636
0
                                              E = Protocols.end();
7637
0
         I != E; ++I)
7638
0
      AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, CurContext,
7639
0
                     Selectors, AllowSameLength, Results, false, IsRootClass);
7640
7641
    // Add methods in category implementations.
7642
0
    if (ObjCCategoryImplDecl *Impl = CatDecl->getImplementation())
7643
0
      AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents, CurContext,
7644
0
                     Selectors, AllowSameLength, Results, InOriginalClass,
7645
0
                     IsRootClass);
7646
0
  }
7647
7648
  // Add methods in superclass.
7649
  // Avoid passing in IsRootClass since root classes won't have super classes.
7650
0
  if (IFace->getSuperClass())
7651
0
    AddObjCMethods(IFace->getSuperClass(), WantInstanceMethods, WantKind,
7652
0
                   SelIdents, CurContext, Selectors, AllowSameLength, Results,
7653
0
                   /*IsRootClass=*/false);
7654
7655
  // Add methods in our implementation, if any.
7656
0
  if (ObjCImplementationDecl *Impl = IFace->getImplementation())
7657
0
    AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents, CurContext,
7658
0
                   Selectors, AllowSameLength, Results, InOriginalClass,
7659
0
                   IsRootClass);
7660
0
}
7661
7662
0
void Sema::CodeCompleteObjCPropertyGetter(Scope *S) {
7663
  // Try to find the interface where getters might live.
7664
0
  ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext);
7665
0
  if (!Class) {
7666
0
    if (ObjCCategoryDecl *Category =
7667
0
            dyn_cast_or_null<ObjCCategoryDecl>(CurContext))
7668
0
      Class = Category->getClassInterface();
7669
7670
0
    if (!Class)
7671
0
      return;
7672
0
  }
7673
7674
  // Find all of the potential getters.
7675
0
  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
7676
0
                        CodeCompleter->getCodeCompletionTUInfo(),
7677
0
                        CodeCompletionContext::CCC_Other);
7678
0
  Results.EnterNewScope();
7679
7680
0
  VisitedSelectorSet Selectors;
7681
0
  AddObjCMethods(Class, true, MK_ZeroArgSelector, std::nullopt, CurContext,
7682
0
                 Selectors,
7683
0
                 /*AllowSameLength=*/true, Results);
7684
0
  Results.ExitScope();
7685
0
  HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
7686
0
                            Results.data(), Results.size());
7687
0
}
7688
7689
0
void Sema::CodeCompleteObjCPropertySetter(Scope *S) {
7690
  // Try to find the interface where setters might live.
7691
0
  ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext);
7692
0
  if (!Class) {
7693
0
    if (ObjCCategoryDecl *Category =
7694
0
            dyn_cast_or_null<ObjCCategoryDecl>(CurContext))
7695
0
      Class = Category->getClassInterface();
7696
7697
0
    if (!Class)
7698
0
      return;
7699
0
  }
7700
7701
  // Find all of the potential getters.
7702
0
  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
7703
0
                        CodeCompleter->getCodeCompletionTUInfo(),
7704
0
                        CodeCompletionContext::CCC_Other);
7705
0
  Results.EnterNewScope();
7706
7707
0
  VisitedSelectorSet Selectors;
7708
0
  AddObjCMethods(Class, true, MK_OneArgSelector, std::nullopt, CurContext,
7709
0
                 Selectors,
7710
0
                 /*AllowSameLength=*/true, Results);
7711
7712
0
  Results.ExitScope();
7713
0
  HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
7714
0
                            Results.data(), Results.size());
7715
0
}
7716
7717
void Sema::CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
7718
0
                                       bool IsParameter) {
7719
0
  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
7720
0
                        CodeCompleter->getCodeCompletionTUInfo(),
7721
0
                        CodeCompletionContext::CCC_Type);
7722
0
  Results.EnterNewScope();
7723
7724
  // Add context-sensitive, Objective-C parameter-passing keywords.
7725
0
  bool AddedInOut = false;
7726
0
  if ((DS.getObjCDeclQualifier() &
7727
0
       (ObjCDeclSpec::DQ_In | ObjCDeclSpec::DQ_Inout)) == 0) {
7728
0
    Results.AddResult("in");
7729
0
    Results.AddResult("inout");
7730
0
    AddedInOut = true;
7731
0
  }
7732
0
  if ((DS.getObjCDeclQualifier() &
7733
0
       (ObjCDeclSpec::DQ_Out | ObjCDeclSpec::DQ_Inout)) == 0) {
7734
0
    Results.AddResult("out");
7735
0
    if (!AddedInOut)
7736
0
      Results.AddResult("inout");
7737
0
  }
7738
0
  if ((DS.getObjCDeclQualifier() &
7739
0
       (ObjCDeclSpec::DQ_Bycopy | ObjCDeclSpec::DQ_Byref |
7740
0
        ObjCDeclSpec::DQ_Oneway)) == 0) {
7741
0
    Results.AddResult("bycopy");
7742
0
    Results.AddResult("byref");
7743
0
    Results.AddResult("oneway");
7744
0
  }
7745
0
  if ((DS.getObjCDeclQualifier() & ObjCDeclSpec::DQ_CSNullability) == 0) {
7746
0
    Results.AddResult("nonnull");
7747
0
    Results.AddResult("nullable");
7748
0
    Results.AddResult("null_unspecified");
7749
0
  }
7750
7751
  // If we're completing the return type of an Objective-C method and the
7752
  // identifier IBAction refers to a macro, provide a completion item for
7753
  // an action, e.g.,
7754
  //   IBAction)<#selector#>:(id)sender
7755
0
  if (DS.getObjCDeclQualifier() == 0 && !IsParameter &&
7756
0
      PP.isMacroDefined("IBAction")) {
7757
0
    CodeCompletionBuilder Builder(Results.getAllocator(),
7758
0
                                  Results.getCodeCompletionTUInfo(),
7759
0
                                  CCP_CodePattern, CXAvailability_Available);
7760
0
    Builder.AddTypedTextChunk("IBAction");
7761
0
    Builder.AddChunk(CodeCompletionString::CK_RightParen);
7762
0
    Builder.AddPlaceholderChunk("selector");
7763
0
    Builder.AddChunk(CodeCompletionString::CK_Colon);
7764
0
    Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7765
0
    Builder.AddTextChunk("id");
7766
0
    Builder.AddChunk(CodeCompletionString::CK_RightParen);
7767
0
    Builder.AddTextChunk("sender");
7768
0
    Results.AddResult(CodeCompletionResult(Builder.TakeString()));
7769
0
  }
7770
7771
  // If we're completing the return type, provide 'instancetype'.
7772
0
  if (!IsParameter) {
7773
0
    Results.AddResult(CodeCompletionResult("instancetype"));
7774
0
  }
7775
7776
  // Add various builtin type names and specifiers.
7777
0
  AddOrdinaryNameResults(PCC_Type, S, *this, Results);
7778
0
  Results.ExitScope();
7779
7780
  // Add the various type names
7781
0
  Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
7782
0
  CodeCompletionDeclConsumer Consumer(Results, CurContext);
7783
0
  LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
7784
0
                     CodeCompleter->includeGlobals(),
7785
0
                     CodeCompleter->loadExternal());
7786
7787
0
  if (CodeCompleter->includeMacros())
7788
0
    AddMacroResults(PP, Results, CodeCompleter->loadExternal(), false);
7789
7790
0
  HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
7791
0
                            Results.data(), Results.size());
7792
0
}
7793
7794
/// When we have an expression with type "id", we may assume
7795
/// that it has some more-specific class type based on knowledge of
7796
/// common uses of Objective-C. This routine returns that class type,
7797
/// or NULL if no better result could be determined.
7798
0
static ObjCInterfaceDecl *GetAssumedMessageSendExprType(Expr *E) {
7799
0
  auto *Msg = dyn_cast_or_null<ObjCMessageExpr>(E);
7800
0
  if (!Msg)
7801
0
    return nullptr;
7802
7803
0
  Selector Sel = Msg->getSelector();
7804
0
  if (Sel.isNull())
7805
0
    return nullptr;
7806
7807
0
  IdentifierInfo *Id = Sel.getIdentifierInfoForSlot(0);
7808
0
  if (!Id)
7809
0
    return nullptr;
7810
7811
0
  ObjCMethodDecl *Method = Msg->getMethodDecl();
7812
0
  if (!Method)
7813
0
    return nullptr;
7814
7815
  // Determine the class that we're sending the message to.
7816
0
  ObjCInterfaceDecl *IFace = nullptr;
7817
0
  switch (Msg->getReceiverKind()) {
7818
0
  case ObjCMessageExpr::Class:
7819
0
    if (const ObjCObjectType *ObjType =
7820
0
            Msg->getClassReceiver()->getAs<ObjCObjectType>())
7821
0
      IFace = ObjType->getInterface();
7822
0
    break;
7823
7824
0
  case ObjCMessageExpr::Instance: {
7825
0
    QualType T = Msg->getInstanceReceiver()->getType();
7826
0
    if (const ObjCObjectPointerType *Ptr = T->getAs<ObjCObjectPointerType>())
7827
0
      IFace = Ptr->getInterfaceDecl();
7828
0
    break;
7829
0
  }
7830
7831
0
  case ObjCMessageExpr::SuperInstance:
7832
0
  case ObjCMessageExpr::SuperClass:
7833
0
    break;
7834
0
  }
7835
7836
0
  if (!IFace)
7837
0
    return nullptr;
7838
7839
0
  ObjCInterfaceDecl *Super = IFace->getSuperClass();
7840
0
  if (Method->isInstanceMethod())
7841
0
    return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
7842
0
        .Case("retain", IFace)
7843
0
        .Case("strong", IFace)
7844
0
        .Case("autorelease", IFace)
7845
0
        .Case("copy", IFace)
7846
0
        .Case("copyWithZone", IFace)
7847
0
        .Case("mutableCopy", IFace)
7848
0
        .Case("mutableCopyWithZone", IFace)
7849
0
        .Case("awakeFromCoder", IFace)
7850
0
        .Case("replacementObjectFromCoder", IFace)
7851
0
        .Case("class", IFace)
7852
0
        .Case("classForCoder", IFace)
7853
0
        .Case("superclass", Super)
7854
0
        .Default(nullptr);
7855
7856
0
  return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
7857
0
      .Case("new", IFace)
7858
0
      .Case("alloc", IFace)
7859
0
      .Case("allocWithZone", IFace)
7860
0
      .Case("class", IFace)
7861
0
      .Case("superclass", Super)
7862
0
      .Default(nullptr);
7863
0
}
7864
7865
// Add a special completion for a message send to "super", which fills in the
7866
// most likely case of forwarding all of our arguments to the superclass
7867
// function.
7868
///
7869
/// \param S The semantic analysis object.
7870
///
7871
/// \param NeedSuperKeyword Whether we need to prefix this completion with
7872
/// the "super" keyword. Otherwise, we just need to provide the arguments.
7873
///
7874
/// \param SelIdents The identifiers in the selector that have already been
7875
/// provided as arguments for a send to "super".
7876
///
7877
/// \param Results The set of results to augment.
7878
///
7879
/// \returns the Objective-C method declaration that would be invoked by
7880
/// this "super" completion. If NULL, no completion was added.
7881
static ObjCMethodDecl *
7882
AddSuperSendCompletion(Sema &S, bool NeedSuperKeyword,
7883
                       ArrayRef<IdentifierInfo *> SelIdents,
7884
0
                       ResultBuilder &Results) {
7885
0
  ObjCMethodDecl *CurMethod = S.getCurMethodDecl();
7886
0
  if (!CurMethod)
7887
0
    return nullptr;
7888
7889
0
  ObjCInterfaceDecl *Class = CurMethod->getClassInterface();
7890
0
  if (!Class)
7891
0
    return nullptr;
7892
7893
  // Try to find a superclass method with the same selector.
7894
0
  ObjCMethodDecl *SuperMethod = nullptr;
7895
0
  while ((Class = Class->getSuperClass()) && !SuperMethod) {
7896
    // Check in the class
7897
0
    SuperMethod = Class->getMethod(CurMethod->getSelector(),
7898
0
                                   CurMethod->isInstanceMethod());
7899
7900
    // Check in categories or class extensions.
7901
0
    if (!SuperMethod) {
7902
0
      for (const auto *Cat : Class->known_categories()) {
7903
0
        if ((SuperMethod = Cat->getMethod(CurMethod->getSelector(),
7904
0
                                          CurMethod->isInstanceMethod())))
7905
0
          break;
7906
0
      }
7907
0
    }
7908
0
  }
7909
7910
0
  if (!SuperMethod)
7911
0
    return nullptr;
7912
7913
  // Check whether the superclass method has the same signature.
7914
0
  if (CurMethod->param_size() != SuperMethod->param_size() ||
7915
0
      CurMethod->isVariadic() != SuperMethod->isVariadic())
7916
0
    return nullptr;
7917
7918
0
  for (ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin(),
7919
0
                                      CurPEnd = CurMethod->param_end(),
7920
0
                                      SuperP = SuperMethod->param_begin();
7921
0
       CurP != CurPEnd; ++CurP, ++SuperP) {
7922
    // Make sure the parameter types are compatible.
7923
0
    if (!S.Context.hasSameUnqualifiedType((*CurP)->getType(),
7924
0
                                          (*SuperP)->getType()))
7925
0
      return nullptr;
7926
7927
    // Make sure we have a parameter name to forward!
7928
0
    if (!(*CurP)->getIdentifier())
7929
0
      return nullptr;
7930
0
  }
7931
7932
  // We have a superclass method. Now, form the send-to-super completion.
7933
0
  CodeCompletionBuilder Builder(Results.getAllocator(),
7934
0
                                Results.getCodeCompletionTUInfo());
7935
7936
  // Give this completion a return type.
7937
0
  AddResultTypeChunk(S.Context, getCompletionPrintingPolicy(S), SuperMethod,
7938
0
                     Results.getCompletionContext().getBaseType(), Builder);
7939
7940
  // If we need the "super" keyword, add it (plus some spacing).
7941
0
  if (NeedSuperKeyword) {
7942
0
    Builder.AddTypedTextChunk("super");
7943
0
    Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7944
0
  }
7945
7946
0
  Selector Sel = CurMethod->getSelector();
7947
0
  if (Sel.isUnarySelector()) {
7948
0
    if (NeedSuperKeyword)
7949
0
      Builder.AddTextChunk(
7950
0
          Builder.getAllocator().CopyString(Sel.getNameForSlot(0)));
7951
0
    else
7952
0
      Builder.AddTypedTextChunk(
7953
0
          Builder.getAllocator().CopyString(Sel.getNameForSlot(0)));
7954
0
  } else {
7955
0
    ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin();
7956
0
    for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I, ++CurP) {
7957
0
      if (I > SelIdents.size())
7958
0
        Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7959
7960
0
      if (I < SelIdents.size())
7961
0
        Builder.AddInformativeChunk(
7962
0
            Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":"));
7963
0
      else if (NeedSuperKeyword || I > SelIdents.size()) {
7964
0
        Builder.AddTextChunk(
7965
0
            Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":"));
7966
0
        Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
7967
0
            (*CurP)->getIdentifier()->getName()));
7968
0
      } else {
7969
0
        Builder.AddTypedTextChunk(
7970
0
            Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":"));
7971
0
        Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
7972
0
            (*CurP)->getIdentifier()->getName()));
7973
0
      }
7974
0
    }
7975
0
  }
7976
7977
0
  Results.AddResult(CodeCompletionResult(Builder.TakeString(), SuperMethod,
7978
0
                                         CCP_SuperCompletion));
7979
0
  return SuperMethod;
7980
0
}
7981
7982
0
void Sema::CodeCompleteObjCMessageReceiver(Scope *S) {
7983
0
  typedef CodeCompletionResult Result;
7984
0
  ResultBuilder Results(
7985
0
      *this, CodeCompleter->getAllocator(),
7986
0
      CodeCompleter->getCodeCompletionTUInfo(),
7987
0
      CodeCompletionContext::CCC_ObjCMessageReceiver,
7988
0
      getLangOpts().CPlusPlus11
7989
0
          ? &ResultBuilder::IsObjCMessageReceiverOrLambdaCapture
7990
0
          : &ResultBuilder::IsObjCMessageReceiver);
7991
7992
0
  CodeCompletionDeclConsumer Consumer(Results, CurContext);
7993
0
  Results.EnterNewScope();
7994
0
  LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
7995
0
                     CodeCompleter->includeGlobals(),
7996
0
                     CodeCompleter->loadExternal());
7997
7998
  // If we are in an Objective-C method inside a class that has a superclass,
7999
  // add "super" as an option.
8000
0
  if (ObjCMethodDecl *Method = getCurMethodDecl())
8001
0
    if (ObjCInterfaceDecl *Iface = Method->getClassInterface())
8002
0
      if (Iface->getSuperClass()) {
8003
0
        Results.AddResult(Result("super"));
8004
8005
0
        AddSuperSendCompletion(*this, /*NeedSuperKeyword=*/true, std::nullopt,
8006
0
                               Results);
8007
0
      }
8008
8009
0
  if (getLangOpts().CPlusPlus11)
8010
0
    addThisCompletion(*this, Results);
8011
8012
0
  Results.ExitScope();
8013
8014
0
  if (CodeCompleter->includeMacros())
8015
0
    AddMacroResults(PP, Results, CodeCompleter->loadExternal(), false);
8016
0
  HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
8017
0
                            Results.data(), Results.size());
8018
0
}
8019
8020
void Sema::CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
8021
                                        ArrayRef<IdentifierInfo *> SelIdents,
8022
0
                                        bool AtArgumentExpression) {
8023
0
  ObjCInterfaceDecl *CDecl = nullptr;
8024
0
  if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
8025
    // Figure out which interface we're in.
8026
0
    CDecl = CurMethod->getClassInterface();
8027
0
    if (!CDecl)
8028
0
      return;
8029
8030
    // Find the superclass of this class.
8031
0
    CDecl = CDecl->getSuperClass();
8032
0
    if (!CDecl)
8033
0
      return;
8034
8035
0
    if (CurMethod->isInstanceMethod()) {
8036
      // We are inside an instance method, which means that the message
8037
      // send [super ...] is actually calling an instance method on the
8038
      // current object.
8039
0
      return CodeCompleteObjCInstanceMessage(S, nullptr, SelIdents,
8040
0
                                             AtArgumentExpression, CDecl);
8041
0
    }
8042
8043
    // Fall through to send to the superclass in CDecl.
8044
0
  } else {
8045
    // "super" may be the name of a type or variable. Figure out which
8046
    // it is.
8047
0
    IdentifierInfo *Super = getSuperIdentifier();
8048
0
    NamedDecl *ND = LookupSingleName(S, Super, SuperLoc, LookupOrdinaryName);
8049
0
    if ((CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(ND))) {
8050
      // "super" names an interface. Use it.
8051
0
    } else if (TypeDecl *TD = dyn_cast_or_null<TypeDecl>(ND)) {
8052
0
      if (const ObjCObjectType *Iface =
8053
0
              Context.getTypeDeclType(TD)->getAs<ObjCObjectType>())
8054
0
        CDecl = Iface->getInterface();
8055
0
    } else if (ND && isa<UnresolvedUsingTypenameDecl>(ND)) {
8056
      // "super" names an unresolved type; we can't be more specific.
8057
0
    } else {
8058
      // Assume that "super" names some kind of value and parse that way.
8059
0
      CXXScopeSpec SS;
8060
0
      SourceLocation TemplateKWLoc;
8061
0
      UnqualifiedId id;
8062
0
      id.setIdentifier(Super, SuperLoc);
8063
0
      ExprResult SuperExpr = ActOnIdExpression(S, SS, TemplateKWLoc, id,
8064
0
                                               /*HasTrailingLParen=*/false,
8065
0
                                               /*IsAddressOfOperand=*/false);
8066
0
      return CodeCompleteObjCInstanceMessage(S, (Expr *)SuperExpr.get(),
8067
0
                                             SelIdents, AtArgumentExpression);
8068
0
    }
8069
8070
    // Fall through
8071
0
  }
8072
8073
0
  ParsedType Receiver;
8074
0
  if (CDecl)
8075
0
    Receiver = ParsedType::make(Context.getObjCInterfaceType(CDecl));
8076
0
  return CodeCompleteObjCClassMessage(S, Receiver, SelIdents,
8077
0
                                      AtArgumentExpression,
8078
0
                                      /*IsSuper=*/true);
8079
0
}
8080
8081
/// Given a set of code-completion results for the argument of a message
8082
/// send, determine the preferred type (if any) for that argument expression.
8083
static QualType getPreferredArgumentTypeForMessageSend(ResultBuilder &Results,
8084
0
                                                       unsigned NumSelIdents) {
8085
0
  typedef CodeCompletionResult Result;
8086
0
  ASTContext &Context = Results.getSema().Context;
8087
8088
0
  QualType PreferredType;
8089
0
  unsigned BestPriority = CCP_Unlikely * 2;
8090
0
  Result *ResultsData = Results.data();
8091
0
  for (unsigned I = 0, N = Results.size(); I != N; ++I) {
8092
0
    Result &R = ResultsData[I];
8093
0
    if (R.Kind == Result::RK_Declaration &&
8094
0
        isa<ObjCMethodDecl>(R.Declaration)) {
8095
0
      if (R.Priority <= BestPriority) {
8096
0
        const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(R.Declaration);
8097
0
        if (NumSelIdents <= Method->param_size()) {
8098
0
          QualType MyPreferredType =
8099
0
              Method->parameters()[NumSelIdents - 1]->getType();
8100
0
          if (R.Priority < BestPriority || PreferredType.isNull()) {
8101
0
            BestPriority = R.Priority;
8102
0
            PreferredType = MyPreferredType;
8103
0
          } else if (!Context.hasSameUnqualifiedType(PreferredType,
8104
0
                                                     MyPreferredType)) {
8105
0
            PreferredType = QualType();
8106
0
          }
8107
0
        }
8108
0
      }
8109
0
    }
8110
0
  }
8111
8112
0
  return PreferredType;
8113
0
}
8114
8115
static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
8116
                                       ParsedType Receiver,
8117
                                       ArrayRef<IdentifierInfo *> SelIdents,
8118
                                       bool AtArgumentExpression, bool IsSuper,
8119
0
                                       ResultBuilder &Results) {
8120
0
  typedef CodeCompletionResult Result;
8121
0
  ObjCInterfaceDecl *CDecl = nullptr;
8122
8123
  // If the given name refers to an interface type, retrieve the
8124
  // corresponding declaration.
8125
0
  if (Receiver) {
8126
0
    QualType T = SemaRef.GetTypeFromParser(Receiver, nullptr);
8127
0
    if (!T.isNull())
8128
0
      if (const ObjCObjectType *Interface = T->getAs<ObjCObjectType>())
8129
0
        CDecl = Interface->getInterface();
8130
0
  }
8131
8132
  // Add all of the factory methods in this Objective-C class, its protocols,
8133
  // superclasses, categories, implementation, etc.
8134
0
  Results.EnterNewScope();
8135
8136
  // If this is a send-to-super, try to add the special "super" send
8137
  // completion.
8138
0
  if (IsSuper) {
8139
0
    if (ObjCMethodDecl *SuperMethod =
8140
0
            AddSuperSendCompletion(SemaRef, false, SelIdents, Results))
8141
0
      Results.Ignore(SuperMethod);
8142
0
  }
8143
8144
  // If we're inside an Objective-C method definition, prefer its selector to
8145
  // others.
8146
0
  if (ObjCMethodDecl *CurMethod = SemaRef.getCurMethodDecl())
8147
0
    Results.setPreferredSelector(CurMethod->getSelector());
8148
8149
0
  VisitedSelectorSet Selectors;
8150
0
  if (CDecl)
8151
0
    AddObjCMethods(CDecl, false, MK_Any, SelIdents, SemaRef.CurContext,
8152
0
                   Selectors, AtArgumentExpression, Results);
8153
0
  else {
8154
    // We're messaging "id" as a type; provide all class/factory methods.
8155
8156
    // If we have an external source, load the entire class method
8157
    // pool from the AST file.
8158
0
    if (SemaRef.getExternalSource()) {
8159
0
      for (uint32_t I = 0,
8160
0
                    N = SemaRef.getExternalSource()->GetNumExternalSelectors();
8161
0
           I != N; ++I) {
8162
0
        Selector Sel = SemaRef.getExternalSource()->GetExternalSelector(I);
8163
0
        if (Sel.isNull() || SemaRef.MethodPool.count(Sel))
8164
0
          continue;
8165
8166
0
        SemaRef.ReadMethodPool(Sel);
8167
0
      }
8168
0
    }
8169
8170
0
    for (Sema::GlobalMethodPool::iterator M = SemaRef.MethodPool.begin(),
8171
0
                                          MEnd = SemaRef.MethodPool.end();
8172
0
         M != MEnd; ++M) {
8173
0
      for (ObjCMethodList *MethList = &M->second.second;
8174
0
           MethList && MethList->getMethod(); MethList = MethList->getNext()) {
8175
0
        if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents))
8176
0
          continue;
8177
8178
0
        Result R(MethList->getMethod(),
8179
0
                 Results.getBasePriority(MethList->getMethod()), nullptr);
8180
0
        R.StartParameter = SelIdents.size();
8181
0
        R.AllParametersAreInformative = false;
8182
0
        Results.MaybeAddResult(R, SemaRef.CurContext);
8183
0
      }
8184
0
    }
8185
0
  }
8186
8187
0
  Results.ExitScope();
8188
0
}
8189
8190
void Sema::CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
8191
                                        ArrayRef<IdentifierInfo *> SelIdents,
8192
                                        bool AtArgumentExpression,
8193
0
                                        bool IsSuper) {
8194
8195
0
  QualType T = this->GetTypeFromParser(Receiver);
8196
8197
0
  ResultBuilder Results(
8198
0
      *this, CodeCompleter->getAllocator(),
8199
0
      CodeCompleter->getCodeCompletionTUInfo(),
8200
0
      CodeCompletionContext(CodeCompletionContext::CCC_ObjCClassMessage, T,
8201
0
                            SelIdents));
8202
8203
0
  AddClassMessageCompletions(*this, S, Receiver, SelIdents,
8204
0
                             AtArgumentExpression, IsSuper, Results);
8205
8206
  // If we're actually at the argument expression (rather than prior to the
8207
  // selector), we're actually performing code completion for an expression.
8208
  // Determine whether we have a single, best method. If so, we can
8209
  // code-complete the expression using the corresponding parameter type as
8210
  // our preferred type, improving completion results.
8211
0
  if (AtArgumentExpression) {
8212
0
    QualType PreferredType =
8213
0
        getPreferredArgumentTypeForMessageSend(Results, SelIdents.size());
8214
0
    if (PreferredType.isNull())
8215
0
      CodeCompleteOrdinaryName(S, PCC_Expression);
8216
0
    else
8217
0
      CodeCompleteExpression(S, PreferredType);
8218
0
    return;
8219
0
  }
8220
8221
0
  HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
8222
0
                            Results.data(), Results.size());
8223
0
}
8224
8225
void Sema::CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
8226
                                           ArrayRef<IdentifierInfo *> SelIdents,
8227
                                           bool AtArgumentExpression,
8228
0
                                           ObjCInterfaceDecl *Super) {
8229
0
  typedef CodeCompletionResult Result;
8230
8231
0
  Expr *RecExpr = static_cast<Expr *>(Receiver);
8232
8233
  // If necessary, apply function/array conversion to the receiver.
8234
  // C99 6.7.5.3p[7,8].
8235
0
  if (RecExpr) {
8236
0
    ExprResult Conv = DefaultFunctionArrayLvalueConversion(RecExpr);
8237
0
    if (Conv.isInvalid()) // conversion failed. bail.
8238
0
      return;
8239
0
    RecExpr = Conv.get();
8240
0
  }
8241
0
  QualType ReceiverType = RecExpr
8242
0
                              ? RecExpr->getType()
8243
0
                              : Super ? Context.getObjCObjectPointerType(
8244
0
                                            Context.getObjCInterfaceType(Super))
8245
0
                                      : Context.getObjCIdType();
8246
8247
  // If we're messaging an expression with type "id" or "Class", check
8248
  // whether we know something special about the receiver that allows
8249
  // us to assume a more-specific receiver type.
8250
0
  if (ReceiverType->isObjCIdType() || ReceiverType->isObjCClassType()) {
8251
0
    if (ObjCInterfaceDecl *IFace = GetAssumedMessageSendExprType(RecExpr)) {
8252
0
      if (ReceiverType->isObjCClassType())
8253
0
        return CodeCompleteObjCClassMessage(
8254
0
            S, ParsedType::make(Context.getObjCInterfaceType(IFace)), SelIdents,
8255
0
            AtArgumentExpression, Super);
8256
8257
0
      ReceiverType =
8258
0
          Context.getObjCObjectPointerType(Context.getObjCInterfaceType(IFace));
8259
0
    }
8260
0
  } else if (RecExpr && getLangOpts().CPlusPlus) {
8261
0
    ExprResult Conv = PerformContextuallyConvertToObjCPointer(RecExpr);
8262
0
    if (Conv.isUsable()) {
8263
0
      RecExpr = Conv.get();
8264
0
      ReceiverType = RecExpr->getType();
8265
0
    }
8266
0
  }
8267
8268
  // Build the set of methods we can see.
8269
0
  ResultBuilder Results(
8270
0
      *this, CodeCompleter->getAllocator(),
8271
0
      CodeCompleter->getCodeCompletionTUInfo(),
8272
0
      CodeCompletionContext(CodeCompletionContext::CCC_ObjCInstanceMessage,
8273
0
                            ReceiverType, SelIdents));
8274
8275
0
  Results.EnterNewScope();
8276
8277
  // If this is a send-to-super, try to add the special "super" send
8278
  // completion.
8279
0
  if (Super) {
8280
0
    if (ObjCMethodDecl *SuperMethod =
8281
0
            AddSuperSendCompletion(*this, false, SelIdents, Results))
8282
0
      Results.Ignore(SuperMethod);
8283
0
  }
8284
8285
  // If we're inside an Objective-C method definition, prefer its selector to
8286
  // others.
8287
0
  if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
8288
0
    Results.setPreferredSelector(CurMethod->getSelector());
8289
8290
  // Keep track of the selectors we've already added.
8291
0
  VisitedSelectorSet Selectors;
8292
8293
  // Handle messages to Class. This really isn't a message to an instance
8294
  // method, so we treat it the same way we would treat a message send to a
8295
  // class method.
8296
0
  if (ReceiverType->isObjCClassType() ||
8297
0
      ReceiverType->isObjCQualifiedClassType()) {
8298
0
    if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
8299
0
      if (ObjCInterfaceDecl *ClassDecl = CurMethod->getClassInterface())
8300
0
        AddObjCMethods(ClassDecl, false, MK_Any, SelIdents, CurContext,
8301
0
                       Selectors, AtArgumentExpression, Results);
8302
0
    }
8303
0
  }
8304
  // Handle messages to a qualified ID ("id<foo>").
8305
0
  else if (const ObjCObjectPointerType *QualID =
8306
0
               ReceiverType->getAsObjCQualifiedIdType()) {
8307
    // Search protocols for instance methods.
8308
0
    for (auto *I : QualID->quals())
8309
0
      AddObjCMethods(I, true, MK_Any, SelIdents, CurContext, Selectors,
8310
0
                     AtArgumentExpression, Results);
8311
0
  }
8312
  // Handle messages to a pointer to interface type.
8313
0
  else if (const ObjCObjectPointerType *IFacePtr =
8314
0
               ReceiverType->getAsObjCInterfacePointerType()) {
8315
    // Search the class, its superclasses, etc., for instance methods.
8316
0
    AddObjCMethods(IFacePtr->getInterfaceDecl(), true, MK_Any, SelIdents,
8317
0
                   CurContext, Selectors, AtArgumentExpression, Results);
8318
8319
    // Search protocols for instance methods.
8320
0
    for (auto *I : IFacePtr->quals())
8321
0
      AddObjCMethods(I, true, MK_Any, SelIdents, CurContext, Selectors,
8322
0
                     AtArgumentExpression, Results);
8323
0
  }
8324
  // Handle messages to "id".
8325
0
  else if (ReceiverType->isObjCIdType()) {
8326
    // We're messaging "id", so provide all instance methods we know
8327
    // about as code-completion results.
8328
8329
    // If we have an external source, load the entire class method
8330
    // pool from the AST file.
8331
0
    if (ExternalSource) {
8332
0
      for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
8333
0
           I != N; ++I) {
8334
0
        Selector Sel = ExternalSource->GetExternalSelector(I);
8335
0
        if (Sel.isNull() || MethodPool.count(Sel))
8336
0
          continue;
8337
8338
0
        ReadMethodPool(Sel);
8339
0
      }
8340
0
    }
8341
8342
0
    for (GlobalMethodPool::iterator M = MethodPool.begin(),
8343
0
                                    MEnd = MethodPool.end();
8344
0
         M != MEnd; ++M) {
8345
0
      for (ObjCMethodList *MethList = &M->second.first;
8346
0
           MethList && MethList->getMethod(); MethList = MethList->getNext()) {
8347
0
        if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents))
8348
0
          continue;
8349
8350
0
        if (!Selectors.insert(MethList->getMethod()->getSelector()).second)
8351
0
          continue;
8352
8353
0
        Result R(MethList->getMethod(),
8354
0
                 Results.getBasePriority(MethList->getMethod()), nullptr);
8355
0
        R.StartParameter = SelIdents.size();
8356
0
        R.AllParametersAreInformative = false;
8357
0
        Results.MaybeAddResult(R, CurContext);
8358
0
      }
8359
0
    }
8360
0
  }
8361
0
  Results.ExitScope();
8362
8363
  // If we're actually at the argument expression (rather than prior to the
8364
  // selector), we're actually performing code completion for an expression.
8365
  // Determine whether we have a single, best method. If so, we can
8366
  // code-complete the expression using the corresponding parameter type as
8367
  // our preferred type, improving completion results.
8368
0
  if (AtArgumentExpression) {
8369
0
    QualType PreferredType =
8370
0
        getPreferredArgumentTypeForMessageSend(Results, SelIdents.size());
8371
0
    if (PreferredType.isNull())
8372
0
      CodeCompleteOrdinaryName(S, PCC_Expression);
8373
0
    else
8374
0
      CodeCompleteExpression(S, PreferredType);
8375
0
    return;
8376
0
  }
8377
8378
0
  HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
8379
0
                            Results.data(), Results.size());
8380
0
}
8381
8382
void Sema::CodeCompleteObjCForCollection(Scope *S,
8383
0
                                         DeclGroupPtrTy IterationVar) {
8384
0
  CodeCompleteExpressionData Data;
8385
0
  Data.ObjCCollection = true;
8386
8387
0
  if (IterationVar.getAsOpaquePtr()) {
8388
0
    DeclGroupRef DG = IterationVar.get();
8389
0
    for (DeclGroupRef::iterator I = DG.begin(), End = DG.end(); I != End; ++I) {
8390
0
      if (*I)
8391
0
        Data.IgnoreDecls.push_back(*I);
8392
0
    }
8393
0
  }
8394
8395
0
  CodeCompleteExpression(S, Data);
8396
0
}
8397
8398
void Sema::CodeCompleteObjCSelector(Scope *S,
8399
0
                                    ArrayRef<IdentifierInfo *> SelIdents) {
8400
  // If we have an external source, load the entire class method
8401
  // pool from the AST file.
8402
0
  if (ExternalSource) {
8403
0
    for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors(); I != N;
8404
0
         ++I) {
8405
0
      Selector Sel = ExternalSource->GetExternalSelector(I);
8406
0
      if (Sel.isNull() || MethodPool.count(Sel))
8407
0
        continue;
8408
8409
0
      ReadMethodPool(Sel);
8410
0
    }
8411
0
  }
8412
8413
0
  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
8414
0
                        CodeCompleter->getCodeCompletionTUInfo(),
8415
0
                        CodeCompletionContext::CCC_SelectorName);
8416
0
  Results.EnterNewScope();
8417
0
  for (GlobalMethodPool::iterator M = MethodPool.begin(),
8418
0
                                  MEnd = MethodPool.end();
8419
0
       M != MEnd; ++M) {
8420
8421
0
    Selector Sel = M->first;
8422
0
    if (!isAcceptableObjCSelector(Sel, MK_Any, SelIdents))
8423
0
      continue;
8424
8425
0
    CodeCompletionBuilder Builder(Results.getAllocator(),
8426
0
                                  Results.getCodeCompletionTUInfo());
8427
0
    if (Sel.isUnarySelector()) {
8428
0
      Builder.AddTypedTextChunk(
8429
0
          Builder.getAllocator().CopyString(Sel.getNameForSlot(0)));
8430
0
      Results.AddResult(Builder.TakeString());
8431
0
      continue;
8432
0
    }
8433
8434
0
    std::string Accumulator;
8435
0
    for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I) {
8436
0
      if (I == SelIdents.size()) {
8437
0
        if (!Accumulator.empty()) {
8438
0
          Builder.AddInformativeChunk(
8439
0
              Builder.getAllocator().CopyString(Accumulator));
8440
0
          Accumulator.clear();
8441
0
        }
8442
0
      }
8443
8444
0
      Accumulator += Sel.getNameForSlot(I);
8445
0
      Accumulator += ':';
8446
0
    }
8447
0
    Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(Accumulator));
8448
0
    Results.AddResult(Builder.TakeString());
8449
0
  }
8450
0
  Results.ExitScope();
8451
8452
0
  HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
8453
0
                            Results.data(), Results.size());
8454
0
}
8455
8456
/// Add all of the protocol declarations that we find in the given
8457
/// (translation unit) context.
8458
static void AddProtocolResults(DeclContext *Ctx, DeclContext *CurContext,
8459
                               bool OnlyForwardDeclarations,
8460
0
                               ResultBuilder &Results) {
8461
0
  typedef CodeCompletionResult Result;
8462
8463
0
  for (const auto *D : Ctx->decls()) {
8464
    // Record any protocols we find.
8465
0
    if (const auto *Proto = dyn_cast<ObjCProtocolDecl>(D))
8466
0
      if (!OnlyForwardDeclarations || !Proto->hasDefinition())
8467
0
        Results.AddResult(
8468
0
            Result(Proto, Results.getBasePriority(Proto), nullptr), CurContext,
8469
0
            nullptr, false);
8470
0
  }
8471
0
}
8472
8473
void Sema::CodeCompleteObjCProtocolReferences(
8474
0
    ArrayRef<IdentifierLocPair> Protocols) {
8475
0
  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
8476
0
                        CodeCompleter->getCodeCompletionTUInfo(),
8477
0
                        CodeCompletionContext::CCC_ObjCProtocolName);
8478
8479
0
  if (CodeCompleter->includeGlobals()) {
8480
0
    Results.EnterNewScope();
8481
8482
    // Tell the result set to ignore all of the protocols we have
8483
    // already seen.
8484
    // FIXME: This doesn't work when caching code-completion results.
8485
0
    for (const IdentifierLocPair &Pair : Protocols)
8486
0
      if (ObjCProtocolDecl *Protocol = LookupProtocol(Pair.first, Pair.second))
8487
0
        Results.Ignore(Protocol);
8488
8489
    // Add all protocols.
8490
0
    AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, false,
8491
0
                       Results);
8492
8493
0
    Results.ExitScope();
8494
0
  }
8495
8496
0
  HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
8497
0
                            Results.data(), Results.size());
8498
0
}
8499
8500
0
void Sema::CodeCompleteObjCProtocolDecl(Scope *) {
8501
0
  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
8502
0
                        CodeCompleter->getCodeCompletionTUInfo(),
8503
0
                        CodeCompletionContext::CCC_ObjCProtocolName);
8504
8505
0
  if (CodeCompleter->includeGlobals()) {
8506
0
    Results.EnterNewScope();
8507
8508
    // Add all protocols.
8509
0
    AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, true,
8510
0
                       Results);
8511
8512
0
    Results.ExitScope();
8513
0
  }
8514
8515
0
  HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
8516
0
                            Results.data(), Results.size());
8517
0
}
8518
8519
/// Add all of the Objective-C interface declarations that we find in
8520
/// the given (translation unit) context.
8521
static void AddInterfaceResults(DeclContext *Ctx, DeclContext *CurContext,
8522
                                bool OnlyForwardDeclarations,
8523
                                bool OnlyUnimplemented,
8524
0
                                ResultBuilder &Results) {
8525
0
  typedef CodeCompletionResult Result;
8526
8527
0
  for (const auto *D : Ctx->decls()) {
8528
    // Record any interfaces we find.
8529
0
    if (const auto *Class = dyn_cast<ObjCInterfaceDecl>(D))
8530
0
      if ((!OnlyForwardDeclarations || !Class->hasDefinition()) &&
8531
0
          (!OnlyUnimplemented || !Class->getImplementation()))
8532
0
        Results.AddResult(
8533
0
            Result(Class, Results.getBasePriority(Class), nullptr), CurContext,
8534
0
            nullptr, false);
8535
0
  }
8536
0
}
8537
8538
0
void Sema::CodeCompleteObjCInterfaceDecl(Scope *S) {
8539
0
  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
8540
0
                        CodeCompleter->getCodeCompletionTUInfo(),
8541
0
                        CodeCompletionContext::CCC_ObjCInterfaceName);
8542
0
  Results.EnterNewScope();
8543
8544
0
  if (CodeCompleter->includeGlobals()) {
8545
    // Add all classes.
8546
0
    AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
8547
0
                        false, Results);
8548
0
  }
8549
8550
0
  Results.ExitScope();
8551
8552
0
  HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
8553
0
                            Results.data(), Results.size());
8554
0
}
8555
8556
0
void Sema::CodeCompleteObjCClassForwardDecl(Scope *S) {
8557
0
  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
8558
0
                        CodeCompleter->getCodeCompletionTUInfo(),
8559
0
                        CodeCompletionContext::CCC_ObjCClassForwardDecl);
8560
0
  Results.EnterNewScope();
8561
8562
0
  if (CodeCompleter->includeGlobals()) {
8563
    // Add all classes.
8564
0
    AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
8565
0
                        false, Results);
8566
0
  }
8567
8568
0
  Results.ExitScope();
8569
8570
0
  HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
8571
0
                            Results.data(), Results.size());
8572
0
}
8573
8574
void Sema::CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName,
8575
0
                                      SourceLocation ClassNameLoc) {
8576
0
  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
8577
0
                        CodeCompleter->getCodeCompletionTUInfo(),
8578
0
                        CodeCompletionContext::CCC_ObjCInterfaceName);
8579
0
  Results.EnterNewScope();
8580
8581
  // Make sure that we ignore the class we're currently defining.
8582
0
  NamedDecl *CurClass =
8583
0
      LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
8584
0
  if (CurClass && isa<ObjCInterfaceDecl>(CurClass))
8585
0
    Results.Ignore(CurClass);
8586
8587
0
  if (CodeCompleter->includeGlobals()) {
8588
    // Add all classes.
8589
0
    AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
8590
0
                        false, Results);
8591
0
  }
8592
8593
0
  Results.ExitScope();
8594
8595
0
  HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
8596
0
                            Results.data(), Results.size());
8597
0
}
8598
8599
0
void Sema::CodeCompleteObjCImplementationDecl(Scope *S) {
8600
0
  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
8601
0
                        CodeCompleter->getCodeCompletionTUInfo(),
8602
0
                        CodeCompletionContext::CCC_ObjCImplementation);
8603
0
  Results.EnterNewScope();
8604
8605
0
  if (CodeCompleter->includeGlobals()) {
8606
    // Add all unimplemented classes.
8607
0
    AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
8608
0
                        true, Results);
8609
0
  }
8610
8611
0
  Results.ExitScope();
8612
8613
0
  HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
8614
0
                            Results.data(), Results.size());
8615
0
}
8616
8617
void Sema::CodeCompleteObjCInterfaceCategory(Scope *S,
8618
                                             IdentifierInfo *ClassName,
8619
0
                                             SourceLocation ClassNameLoc) {
8620
0
  typedef CodeCompletionResult Result;
8621
8622
0
  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
8623
0
                        CodeCompleter->getCodeCompletionTUInfo(),
8624
0
                        CodeCompletionContext::CCC_ObjCCategoryName);
8625
8626
  // Ignore any categories we find that have already been implemented by this
8627
  // interface.
8628
0
  llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
8629
0
  NamedDecl *CurClass =
8630
0
      LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
8631
0
  if (ObjCInterfaceDecl *Class =
8632
0
          dyn_cast_or_null<ObjCInterfaceDecl>(CurClass)) {
8633
0
    for (const auto *Cat : Class->visible_categories())
8634
0
      CategoryNames.insert(Cat->getIdentifier());
8635
0
  }
8636
8637
  // Add all of the categories we know about.
8638
0
  Results.EnterNewScope();
8639
0
  TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
8640
0
  for (const auto *D : TU->decls())
8641
0
    if (const auto *Category = dyn_cast<ObjCCategoryDecl>(D))
8642
0
      if (CategoryNames.insert(Category->getIdentifier()).second)
8643
0
        Results.AddResult(
8644
0
            Result(Category, Results.getBasePriority(Category), nullptr),
8645
0
            CurContext, nullptr, false);
8646
0
  Results.ExitScope();
8647
8648
0
  HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
8649
0
                            Results.data(), Results.size());
8650
0
}
8651
8652
void Sema::CodeCompleteObjCImplementationCategory(Scope *S,
8653
                                                  IdentifierInfo *ClassName,
8654
0
                                                  SourceLocation ClassNameLoc) {
8655
0
  typedef CodeCompletionResult Result;
8656
8657
  // Find the corresponding interface. If we couldn't find the interface, the
8658
  // program itself is ill-formed. However, we'll try to be helpful still by
8659
  // providing the list of all of the categories we know about.
8660
0
  NamedDecl *CurClass =
8661
0
      LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
8662
0
  ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass);
8663
0
  if (!Class)
8664
0
    return CodeCompleteObjCInterfaceCategory(S, ClassName, ClassNameLoc);
8665
8666
0
  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
8667
0
                        CodeCompleter->getCodeCompletionTUInfo(),
8668
0
                        CodeCompletionContext::CCC_ObjCCategoryName);
8669
8670
  // Add all of the categories that have corresponding interface
8671
  // declarations in this class and any of its superclasses, except for
8672
  // already-implemented categories in the class itself.
8673
0
  llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
8674
0
  Results.EnterNewScope();
8675
0
  bool IgnoreImplemented = true;
8676
0
  while (Class) {
8677
0
    for (const auto *Cat : Class->visible_categories()) {
8678
0
      if ((!IgnoreImplemented || !Cat->getImplementation()) &&
8679
0
          CategoryNames.insert(Cat->getIdentifier()).second)
8680
0
        Results.AddResult(Result(Cat, Results.getBasePriority(Cat), nullptr),
8681
0
                          CurContext, nullptr, false);
8682
0
    }
8683
8684
0
    Class = Class->getSuperClass();
8685
0
    IgnoreImplemented = false;
8686
0
  }
8687
0
  Results.ExitScope();
8688
8689
0
  HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
8690
0
                            Results.data(), Results.size());
8691
0
}
8692
8693
0
void Sema::CodeCompleteObjCPropertyDefinition(Scope *S) {
8694
0
  CodeCompletionContext CCContext(CodeCompletionContext::CCC_Other);
8695
0
  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
8696
0
                        CodeCompleter->getCodeCompletionTUInfo(), CCContext);
8697
8698
  // Figure out where this @synthesize lives.
8699
0
  ObjCContainerDecl *Container =
8700
0
      dyn_cast_or_null<ObjCContainerDecl>(CurContext);
8701
0
  if (!Container || (!isa<ObjCImplementationDecl>(Container) &&
8702
0
                     !isa<ObjCCategoryImplDecl>(Container)))
8703
0
    return;
8704
8705
  // Ignore any properties that have already been implemented.
8706
0
  Container = getContainerDef(Container);
8707
0
  for (const auto *D : Container->decls())
8708
0
    if (const auto *PropertyImpl = dyn_cast<ObjCPropertyImplDecl>(D))
8709
0
      Results.Ignore(PropertyImpl->getPropertyDecl());
8710
8711
  // Add any properties that we find.
8712
0
  AddedPropertiesSet AddedProperties;
8713
0
  Results.EnterNewScope();
8714
0
  if (ObjCImplementationDecl *ClassImpl =
8715
0
          dyn_cast<ObjCImplementationDecl>(Container))
8716
0
    AddObjCProperties(CCContext, ClassImpl->getClassInterface(), false,
8717
0
                      /*AllowNullaryMethods=*/false, CurContext,
8718
0
                      AddedProperties, Results);
8719
0
  else
8720
0
    AddObjCProperties(CCContext,
8721
0
                      cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl(),
8722
0
                      false, /*AllowNullaryMethods=*/false, CurContext,
8723
0
                      AddedProperties, Results);
8724
0
  Results.ExitScope();
8725
8726
0
  HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
8727
0
                            Results.data(), Results.size());
8728
0
}
8729
8730
void Sema::CodeCompleteObjCPropertySynthesizeIvar(
8731
0
    Scope *S, IdentifierInfo *PropertyName) {
8732
0
  typedef CodeCompletionResult Result;
8733
0
  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
8734
0
                        CodeCompleter->getCodeCompletionTUInfo(),
8735
0
                        CodeCompletionContext::CCC_Other);
8736
8737
  // Figure out where this @synthesize lives.
8738
0
  ObjCContainerDecl *Container =
8739
0
      dyn_cast_or_null<ObjCContainerDecl>(CurContext);
8740
0
  if (!Container || (!isa<ObjCImplementationDecl>(Container) &&
8741
0
                     !isa<ObjCCategoryImplDecl>(Container)))
8742
0
    return;
8743
8744
  // Figure out which interface we're looking into.
8745
0
  ObjCInterfaceDecl *Class = nullptr;
8746
0
  if (ObjCImplementationDecl *ClassImpl =
8747
0
          dyn_cast<ObjCImplementationDecl>(Container))
8748
0
    Class = ClassImpl->getClassInterface();
8749
0
  else
8750
0
    Class = cast<ObjCCategoryImplDecl>(Container)
8751
0
                ->getCategoryDecl()
8752
0
                ->getClassInterface();
8753
8754
  // Determine the type of the property we're synthesizing.
8755
0
  QualType PropertyType = Context.getObjCIdType();
8756
0
  if (Class) {
8757
0
    if (ObjCPropertyDecl *Property = Class->FindPropertyDeclaration(
8758
0
            PropertyName, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
8759
0
      PropertyType =
8760
0
          Property->getType().getNonReferenceType().getUnqualifiedType();
8761
8762
      // Give preference to ivars
8763
0
      Results.setPreferredType(PropertyType);
8764
0
    }
8765
0
  }
8766
8767
  // Add all of the instance variables in this class and its superclasses.
8768
0
  Results.EnterNewScope();
8769
0
  bool SawSimilarlyNamedIvar = false;
8770
0
  std::string NameWithPrefix;
8771
0
  NameWithPrefix += '_';
8772
0
  NameWithPrefix += PropertyName->getName();
8773
0
  std::string NameWithSuffix = PropertyName->getName().str();
8774
0
  NameWithSuffix += '_';
8775
0
  for (; Class; Class = Class->getSuperClass()) {
8776
0
    for (ObjCIvarDecl *Ivar = Class->all_declared_ivar_begin(); Ivar;
8777
0
         Ivar = Ivar->getNextIvar()) {
8778
0
      Results.AddResult(Result(Ivar, Results.getBasePriority(Ivar), nullptr),
8779
0
                        CurContext, nullptr, false);
8780
8781
      // Determine whether we've seen an ivar with a name similar to the
8782
      // property.
8783
0
      if ((PropertyName == Ivar->getIdentifier() ||
8784
0
           NameWithPrefix == Ivar->getName() ||
8785
0
           NameWithSuffix == Ivar->getName())) {
8786
0
        SawSimilarlyNamedIvar = true;
8787
8788
        // Reduce the priority of this result by one, to give it a slight
8789
        // advantage over other results whose names don't match so closely.
8790
0
        if (Results.size() &&
8791
0
            Results.data()[Results.size() - 1].Kind ==
8792
0
                CodeCompletionResult::RK_Declaration &&
8793
0
            Results.data()[Results.size() - 1].Declaration == Ivar)
8794
0
          Results.data()[Results.size() - 1].Priority--;
8795
0
      }
8796
0
    }
8797
0
  }
8798
8799
0
  if (!SawSimilarlyNamedIvar) {
8800
    // Create ivar result _propName, that the user can use to synthesize
8801
    // an ivar of the appropriate type.
8802
0
    unsigned Priority = CCP_MemberDeclaration + 1;
8803
0
    typedef CodeCompletionResult Result;
8804
0
    CodeCompletionAllocator &Allocator = Results.getAllocator();
8805
0
    CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo(),
8806
0
                                  Priority, CXAvailability_Available);
8807
8808
0
    PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
8809
0
    Builder.AddResultTypeChunk(
8810
0
        GetCompletionTypeString(PropertyType, Context, Policy, Allocator));
8811
0
    Builder.AddTypedTextChunk(Allocator.CopyString(NameWithPrefix));
8812
0
    Results.AddResult(
8813
0
        Result(Builder.TakeString(), Priority, CXCursor_ObjCIvarDecl));
8814
0
  }
8815
8816
0
  Results.ExitScope();
8817
8818
0
  HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
8819
0
                            Results.data(), Results.size());
8820
0
}
8821
8822
// Mapping from selectors to the methods that implement that selector, along
8823
// with the "in original class" flag.
8824
typedef llvm::DenseMap<Selector,
8825
                       llvm::PointerIntPair<ObjCMethodDecl *, 1, bool>>
8826
    KnownMethodsMap;
8827
8828
/// Find all of the methods that reside in the given container
8829
/// (and its superclasses, protocols, etc.) that meet the given
8830
/// criteria. Insert those methods into the map of known methods,
8831
/// indexed by selector so they can be easily found.
8832
static void FindImplementableMethods(ASTContext &Context,
8833
                                     ObjCContainerDecl *Container,
8834
                                     std::optional<bool> WantInstanceMethods,
8835
                                     QualType ReturnType,
8836
                                     KnownMethodsMap &KnownMethods,
8837
0
                                     bool InOriginalClass = true) {
8838
0
  if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)) {
8839
    // Make sure we have a definition; that's what we'll walk.
8840
0
    if (!IFace->hasDefinition())
8841
0
      return;
8842
8843
0
    IFace = IFace->getDefinition();
8844
0
    Container = IFace;
8845
8846
0
    const ObjCList<ObjCProtocolDecl> &Protocols =
8847
0
        IFace->getReferencedProtocols();
8848
0
    for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
8849
0
                                              E = Protocols.end();
8850
0
         I != E; ++I)
8851
0
      FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
8852
0
                               KnownMethods, InOriginalClass);
8853
8854
    // Add methods from any class extensions and categories.
8855
0
    for (auto *Cat : IFace->visible_categories()) {
8856
0
      FindImplementableMethods(Context, Cat, WantInstanceMethods, ReturnType,
8857
0
                               KnownMethods, false);
8858
0
    }
8859
8860
    // Visit the superclass.
8861
0
    if (IFace->getSuperClass())
8862
0
      FindImplementableMethods(Context, IFace->getSuperClass(),
8863
0
                               WantInstanceMethods, ReturnType, KnownMethods,
8864
0
                               false);
8865
0
  }
8866
8867
0
  if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
8868
    // Recurse into protocols.
8869
0
    const ObjCList<ObjCProtocolDecl> &Protocols =
8870
0
        Category->getReferencedProtocols();
8871
0
    for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
8872
0
                                              E = Protocols.end();
8873
0
         I != E; ++I)
8874
0
      FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
8875
0
                               KnownMethods, InOriginalClass);
8876
8877
    // If this category is the original class, jump to the interface.
8878
0
    if (InOriginalClass && Category->getClassInterface())
8879
0
      FindImplementableMethods(Context, Category->getClassInterface(),
8880
0
                               WantInstanceMethods, ReturnType, KnownMethods,
8881
0
                               false);
8882
0
  }
8883
8884
0
  if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
8885
    // Make sure we have a definition; that's what we'll walk.
8886
0
    if (!Protocol->hasDefinition())
8887
0
      return;
8888
0
    Protocol = Protocol->getDefinition();
8889
0
    Container = Protocol;
8890
8891
    // Recurse into protocols.
8892
0
    const ObjCList<ObjCProtocolDecl> &Protocols =
8893
0
        Protocol->getReferencedProtocols();
8894
0
    for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
8895
0
                                              E = Protocols.end();
8896
0
         I != E; ++I)
8897
0
      FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
8898
0
                               KnownMethods, false);
8899
0
  }
8900
8901
  // Add methods in this container. This operation occurs last because
8902
  // we want the methods from this container to override any methods
8903
  // we've previously seen with the same selector.
8904
0
  for (auto *M : Container->methods()) {
8905
0
    if (!WantInstanceMethods || M->isInstanceMethod() == *WantInstanceMethods) {
8906
0
      if (!ReturnType.isNull() &&
8907
0
          !Context.hasSameUnqualifiedType(ReturnType, M->getReturnType()))
8908
0
        continue;
8909
8910
0
      KnownMethods[M->getSelector()] =
8911
0
          KnownMethodsMap::mapped_type(M, InOriginalClass);
8912
0
    }
8913
0
  }
8914
0
}
8915
8916
/// Add the parenthesized return or parameter type chunk to a code
8917
/// completion string.
8918
static void AddObjCPassingTypeChunk(QualType Type, unsigned ObjCDeclQuals,
8919
                                    ASTContext &Context,
8920
                                    const PrintingPolicy &Policy,
8921
0
                                    CodeCompletionBuilder &Builder) {
8922
0
  Builder.AddChunk(CodeCompletionString::CK_LeftParen);
8923
0
  std::string Quals = formatObjCParamQualifiers(ObjCDeclQuals, Type);
8924
0
  if (!Quals.empty())
8925
0
    Builder.AddTextChunk(Builder.getAllocator().CopyString(Quals));
8926
0
  Builder.AddTextChunk(
8927
0
      GetCompletionTypeString(Type, Context, Policy, Builder.getAllocator()));
8928
0
  Builder.AddChunk(CodeCompletionString::CK_RightParen);
8929
0
}
8930
8931
/// Determine whether the given class is or inherits from a class by
8932
/// the given name.
8933
0
static bool InheritsFromClassNamed(ObjCInterfaceDecl *Class, StringRef Name) {
8934
0
  if (!Class)
8935
0
    return false;
8936
8937
0
  if (Class->getIdentifier() && Class->getIdentifier()->getName() == Name)
8938
0
    return true;
8939
8940
0
  return InheritsFromClassNamed(Class->getSuperClass(), Name);
8941
0
}
8942
8943
/// Add code completions for Objective-C Key-Value Coding (KVC) and
8944
/// Key-Value Observing (KVO).
8945
static void AddObjCKeyValueCompletions(ObjCPropertyDecl *Property,
8946
                                       bool IsInstanceMethod,
8947
                                       QualType ReturnType, ASTContext &Context,
8948
                                       VisitedSelectorSet &KnownSelectors,
8949
0
                                       ResultBuilder &Results) {
8950
0
  IdentifierInfo *PropName = Property->getIdentifier();
8951
0
  if (!PropName || PropName->getLength() == 0)
8952
0
    return;
8953
8954
0
  PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema());
8955
8956
  // Builder that will create each code completion.
8957
0
  typedef CodeCompletionResult Result;
8958
0
  CodeCompletionAllocator &Allocator = Results.getAllocator();
8959
0
  CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
8960
8961
  // The selector table.
8962
0
  SelectorTable &Selectors = Context.Selectors;
8963
8964
  // The property name, copied into the code completion allocation region
8965
  // on demand.
8966
0
  struct KeyHolder {
8967
0
    CodeCompletionAllocator &Allocator;
8968
0
    StringRef Key;
8969
0
    const char *CopiedKey;
8970
8971
0
    KeyHolder(CodeCompletionAllocator &Allocator, StringRef Key)
8972
0
        : Allocator(Allocator), Key(Key), CopiedKey(nullptr) {}
8973
8974
0
    operator const char *() {
8975
0
      if (CopiedKey)
8976
0
        return CopiedKey;
8977
8978
0
      return CopiedKey = Allocator.CopyString(Key);
8979
0
    }
8980
0
  } Key(Allocator, PropName->getName());
8981
8982
  // The uppercased name of the property name.
8983
0
  std::string UpperKey = std::string(PropName->getName());
8984
0
  if (!UpperKey.empty())
8985
0
    UpperKey[0] = toUppercase(UpperKey[0]);
8986
8987
0
  bool ReturnTypeMatchesProperty =
8988
0
      ReturnType.isNull() ||
8989
0
      Context.hasSameUnqualifiedType(ReturnType.getNonReferenceType(),
8990
0
                                     Property->getType());
8991
0
  bool ReturnTypeMatchesVoid = ReturnType.isNull() || ReturnType->isVoidType();
8992
8993
  // Add the normal accessor -(type)key.
8994
0
  if (IsInstanceMethod &&
8995
0
      KnownSelectors.insert(Selectors.getNullarySelector(PropName)).second &&
8996
0
      ReturnTypeMatchesProperty && !Property->getGetterMethodDecl()) {
8997
0
    if (ReturnType.isNull())
8998
0
      AddObjCPassingTypeChunk(Property->getType(), /*Quals=*/0, Context, Policy,
8999
0
                              Builder);
9000
9001
0
    Builder.AddTypedTextChunk(Key);
9002
0
    Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
9003
0
                             CXCursor_ObjCInstanceMethodDecl));
9004
0
  }
9005
9006
  // If we have an integral or boolean property (or the user has provided
9007
  // an integral or boolean return type), add the accessor -(type)isKey.
9008
0
  if (IsInstanceMethod &&
9009
0
      ((!ReturnType.isNull() &&
9010
0
        (ReturnType->isIntegerType() || ReturnType->isBooleanType())) ||
9011
0
       (ReturnType.isNull() && (Property->getType()->isIntegerType() ||
9012
0
                                Property->getType()->isBooleanType())))) {
9013
0
    std::string SelectorName = (Twine("is") + UpperKey).str();
9014
0
    IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
9015
0
    if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
9016
0
            .second) {
9017
0
      if (ReturnType.isNull()) {
9018
0
        Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9019
0
        Builder.AddTextChunk("BOOL");
9020
0
        Builder.AddChunk(CodeCompletionString::CK_RightParen);
9021
0
      }
9022
9023
0
      Builder.AddTypedTextChunk(Allocator.CopyString(SelectorId->getName()));
9024
0
      Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
9025
0
                               CXCursor_ObjCInstanceMethodDecl));
9026
0
    }
9027
0
  }
9028
9029
  // Add the normal mutator.
9030
0
  if (IsInstanceMethod && ReturnTypeMatchesVoid &&
9031
0
      !Property->getSetterMethodDecl()) {
9032
0
    std::string SelectorName = (Twine("set") + UpperKey).str();
9033
0
    IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
9034
0
    if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
9035
0
      if (ReturnType.isNull()) {
9036
0
        Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9037
0
        Builder.AddTextChunk("void");
9038
0
        Builder.AddChunk(CodeCompletionString::CK_RightParen);
9039
0
      }
9040
9041
0
      Builder.AddTypedTextChunk(
9042
0
          Allocator.CopyString(SelectorId->getName() + ":"));
9043
0
      AddObjCPassingTypeChunk(Property->getType(), /*Quals=*/0, Context, Policy,
9044
0
                              Builder);
9045
0
      Builder.AddTextChunk(Key);
9046
0
      Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
9047
0
                               CXCursor_ObjCInstanceMethodDecl));
9048
0
    }
9049
0
  }
9050
9051
  // Indexed and unordered accessors
9052
0
  unsigned IndexedGetterPriority = CCP_CodePattern;
9053
0
  unsigned IndexedSetterPriority = CCP_CodePattern;
9054
0
  unsigned UnorderedGetterPriority = CCP_CodePattern;
9055
0
  unsigned UnorderedSetterPriority = CCP_CodePattern;
9056
0
  if (const auto *ObjCPointer =
9057
0
          Property->getType()->getAs<ObjCObjectPointerType>()) {
9058
0
    if (ObjCInterfaceDecl *IFace = ObjCPointer->getInterfaceDecl()) {
9059
      // If this interface type is not provably derived from a known
9060
      // collection, penalize the corresponding completions.
9061
0
      if (!InheritsFromClassNamed(IFace, "NSMutableArray")) {
9062
0
        IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
9063
0
        if (!InheritsFromClassNamed(IFace, "NSArray"))
9064
0
          IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
9065
0
      }
9066
9067
0
      if (!InheritsFromClassNamed(IFace, "NSMutableSet")) {
9068
0
        UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
9069
0
        if (!InheritsFromClassNamed(IFace, "NSSet"))
9070
0
          UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
9071
0
      }
9072
0
    }
9073
0
  } else {
9074
0
    IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
9075
0
    IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
9076
0
    UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
9077
0
    UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
9078
0
  }
9079
9080
  // Add -(NSUInteger)countOf<key>
9081
0
  if (IsInstanceMethod &&
9082
0
      (ReturnType.isNull() || ReturnType->isIntegerType())) {
9083
0
    std::string SelectorName = (Twine("countOf") + UpperKey).str();
9084
0
    IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
9085
0
    if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
9086
0
            .second) {
9087
0
      if (ReturnType.isNull()) {
9088
0
        Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9089
0
        Builder.AddTextChunk("NSUInteger");
9090
0
        Builder.AddChunk(CodeCompletionString::CK_RightParen);
9091
0
      }
9092
9093
0
      Builder.AddTypedTextChunk(Allocator.CopyString(SelectorId->getName()));
9094
0
      Results.AddResult(
9095
0
          Result(Builder.TakeString(),
9096
0
                 std::min(IndexedGetterPriority, UnorderedGetterPriority),
9097
0
                 CXCursor_ObjCInstanceMethodDecl));
9098
0
    }
9099
0
  }
9100
9101
  // Indexed getters
9102
  // Add -(id)objectInKeyAtIndex:(NSUInteger)index
9103
0
  if (IsInstanceMethod &&
9104
0
      (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
9105
0
    std::string SelectorName = (Twine("objectIn") + UpperKey + "AtIndex").str();
9106
0
    IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
9107
0
    if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
9108
0
      if (ReturnType.isNull()) {
9109
0
        Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9110
0
        Builder.AddTextChunk("id");
9111
0
        Builder.AddChunk(CodeCompletionString::CK_RightParen);
9112
0
      }
9113
9114
0
      Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
9115
0
      Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9116
0
      Builder.AddTextChunk("NSUInteger");
9117
0
      Builder.AddChunk(CodeCompletionString::CK_RightParen);
9118
0
      Builder.AddTextChunk("index");
9119
0
      Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
9120
0
                               CXCursor_ObjCInstanceMethodDecl));
9121
0
    }
9122
0
  }
9123
9124
  // Add -(NSArray *)keyAtIndexes:(NSIndexSet *)indexes
9125
0
  if (IsInstanceMethod &&
9126
0
      (ReturnType.isNull() ||
9127
0
       (ReturnType->isObjCObjectPointerType() &&
9128
0
        ReturnType->castAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
9129
0
        ReturnType->castAs<ObjCObjectPointerType>()
9130
0
                ->getInterfaceDecl()
9131
0
                ->getName() == "NSArray"))) {
9132
0
    std::string SelectorName = (Twine(Property->getName()) + "AtIndexes").str();
9133
0
    IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
9134
0
    if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
9135
0
      if (ReturnType.isNull()) {
9136
0
        Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9137
0
        Builder.AddTextChunk("NSArray *");
9138
0
        Builder.AddChunk(CodeCompletionString::CK_RightParen);
9139
0
      }
9140
9141
0
      Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
9142
0
      Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9143
0
      Builder.AddTextChunk("NSIndexSet *");
9144
0
      Builder.AddChunk(CodeCompletionString::CK_RightParen);
9145
0
      Builder.AddTextChunk("indexes");
9146
0
      Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
9147
0
                               CXCursor_ObjCInstanceMethodDecl));
9148
0
    }
9149
0
  }
9150
9151
  // Add -(void)getKey:(type **)buffer range:(NSRange)inRange
9152
0
  if (IsInstanceMethod && ReturnTypeMatchesVoid) {
9153
0
    std::string SelectorName = (Twine("get") + UpperKey).str();
9154
0
    IdentifierInfo *SelectorIds[2] = {&Context.Idents.get(SelectorName),
9155
0
                                      &Context.Idents.get("range")};
9156
9157
0
    if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
9158
0
      if (ReturnType.isNull()) {
9159
0
        Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9160
0
        Builder.AddTextChunk("void");
9161
0
        Builder.AddChunk(CodeCompletionString::CK_RightParen);
9162
0
      }
9163
9164
0
      Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
9165
0
      Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9166
0
      Builder.AddPlaceholderChunk("object-type");
9167
0
      Builder.AddTextChunk(" **");
9168
0
      Builder.AddChunk(CodeCompletionString::CK_RightParen);
9169
0
      Builder.AddTextChunk("buffer");
9170
0
      Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9171
0
      Builder.AddTypedTextChunk("range:");
9172
0
      Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9173
0
      Builder.AddTextChunk("NSRange");
9174
0
      Builder.AddChunk(CodeCompletionString::CK_RightParen);
9175
0
      Builder.AddTextChunk("inRange");
9176
0
      Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
9177
0
                               CXCursor_ObjCInstanceMethodDecl));
9178
0
    }
9179
0
  }
9180
9181
  // Mutable indexed accessors
9182
9183
  // - (void)insertObject:(type *)object inKeyAtIndex:(NSUInteger)index
9184
0
  if (IsInstanceMethod && ReturnTypeMatchesVoid) {
9185
0
    std::string SelectorName = (Twine("in") + UpperKey + "AtIndex").str();
9186
0
    IdentifierInfo *SelectorIds[2] = {&Context.Idents.get("insertObject"),
9187
0
                                      &Context.Idents.get(SelectorName)};
9188
9189
0
    if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
9190
0
      if (ReturnType.isNull()) {
9191
0
        Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9192
0
        Builder.AddTextChunk("void");
9193
0
        Builder.AddChunk(CodeCompletionString::CK_RightParen);
9194
0
      }
9195
9196
0
      Builder.AddTypedTextChunk("insertObject:");
9197
0
      Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9198
0
      Builder.AddPlaceholderChunk("object-type");
9199
0
      Builder.AddTextChunk(" *");
9200
0
      Builder.AddChunk(CodeCompletionString::CK_RightParen);
9201
0
      Builder.AddTextChunk("object");
9202
0
      Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9203
0
      Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
9204
0
      Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9205
0
      Builder.AddPlaceholderChunk("NSUInteger");
9206
0
      Builder.AddChunk(CodeCompletionString::CK_RightParen);
9207
0
      Builder.AddTextChunk("index");
9208
0
      Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
9209
0
                               CXCursor_ObjCInstanceMethodDecl));
9210
0
    }
9211
0
  }
9212
9213
  // - (void)insertKey:(NSArray *)array atIndexes:(NSIndexSet *)indexes
9214
0
  if (IsInstanceMethod && ReturnTypeMatchesVoid) {
9215
0
    std::string SelectorName = (Twine("insert") + UpperKey).str();
9216
0
    IdentifierInfo *SelectorIds[2] = {&Context.Idents.get(SelectorName),
9217
0
                                      &Context.Idents.get("atIndexes")};
9218
9219
0
    if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
9220
0
      if (ReturnType.isNull()) {
9221
0
        Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9222
0
        Builder.AddTextChunk("void");
9223
0
        Builder.AddChunk(CodeCompletionString::CK_RightParen);
9224
0
      }
9225
9226
0
      Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
9227
0
      Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9228
0
      Builder.AddTextChunk("NSArray *");
9229
0
      Builder.AddChunk(CodeCompletionString::CK_RightParen);
9230
0
      Builder.AddTextChunk("array");
9231
0
      Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9232
0
      Builder.AddTypedTextChunk("atIndexes:");
9233
0
      Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9234
0
      Builder.AddPlaceholderChunk("NSIndexSet *");
9235
0
      Builder.AddChunk(CodeCompletionString::CK_RightParen);
9236
0
      Builder.AddTextChunk("indexes");
9237
0
      Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
9238
0
                               CXCursor_ObjCInstanceMethodDecl));
9239
0
    }
9240
0
  }
9241
9242
  // -(void)removeObjectFromKeyAtIndex:(NSUInteger)index
9243
0
  if (IsInstanceMethod && ReturnTypeMatchesVoid) {
9244
0
    std::string SelectorName =
9245
0
        (Twine("removeObjectFrom") + UpperKey + "AtIndex").str();
9246
0
    IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
9247
0
    if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
9248
0
      if (ReturnType.isNull()) {
9249
0
        Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9250
0
        Builder.AddTextChunk("void");
9251
0
        Builder.AddChunk(CodeCompletionString::CK_RightParen);
9252
0
      }
9253
9254
0
      Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
9255
0
      Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9256
0
      Builder.AddTextChunk("NSUInteger");
9257
0
      Builder.AddChunk(CodeCompletionString::CK_RightParen);
9258
0
      Builder.AddTextChunk("index");
9259
0
      Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
9260
0
                               CXCursor_ObjCInstanceMethodDecl));
9261
0
    }
9262
0
  }
9263
9264
  // -(void)removeKeyAtIndexes:(NSIndexSet *)indexes
9265
0
  if (IsInstanceMethod && ReturnTypeMatchesVoid) {
9266
0
    std::string SelectorName = (Twine("remove") + UpperKey + "AtIndexes").str();
9267
0
    IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
9268
0
    if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
9269
0
      if (ReturnType.isNull()) {
9270
0
        Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9271
0
        Builder.AddTextChunk("void");
9272
0
        Builder.AddChunk(CodeCompletionString::CK_RightParen);
9273
0
      }
9274
9275
0
      Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
9276
0
      Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9277
0
      Builder.AddTextChunk("NSIndexSet *");
9278
0
      Builder.AddChunk(CodeCompletionString::CK_RightParen);
9279
0
      Builder.AddTextChunk("indexes");
9280
0
      Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
9281
0
                               CXCursor_ObjCInstanceMethodDecl));
9282
0
    }
9283
0
  }
9284
9285
  // - (void)replaceObjectInKeyAtIndex:(NSUInteger)index withObject:(id)object
9286
0
  if (IsInstanceMethod && ReturnTypeMatchesVoid) {
9287
0
    std::string SelectorName =
9288
0
        (Twine("replaceObjectIn") + UpperKey + "AtIndex").str();
9289
0
    IdentifierInfo *SelectorIds[2] = {&Context.Idents.get(SelectorName),
9290
0
                                      &Context.Idents.get("withObject")};
9291
9292
0
    if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
9293
0
      if (ReturnType.isNull()) {
9294
0
        Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9295
0
        Builder.AddTextChunk("void");
9296
0
        Builder.AddChunk(CodeCompletionString::CK_RightParen);
9297
0
      }
9298
9299
0
      Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
9300
0
      Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9301
0
      Builder.AddPlaceholderChunk("NSUInteger");
9302
0
      Builder.AddChunk(CodeCompletionString::CK_RightParen);
9303
0
      Builder.AddTextChunk("index");
9304
0
      Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9305
0
      Builder.AddTypedTextChunk("withObject:");
9306
0
      Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9307
0
      Builder.AddTextChunk("id");
9308
0
      Builder.AddChunk(CodeCompletionString::CK_RightParen);
9309
0
      Builder.AddTextChunk("object");
9310
0
      Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
9311
0
                               CXCursor_ObjCInstanceMethodDecl));
9312
0
    }
9313
0
  }
9314
9315
  // - (void)replaceKeyAtIndexes:(NSIndexSet *)indexes withKey:(NSArray *)array
9316
0
  if (IsInstanceMethod && ReturnTypeMatchesVoid) {
9317
0
    std::string SelectorName1 =
9318
0
        (Twine("replace") + UpperKey + "AtIndexes").str();
9319
0
    std::string SelectorName2 = (Twine("with") + UpperKey).str();
9320
0
    IdentifierInfo *SelectorIds[2] = {&Context.Idents.get(SelectorName1),
9321
0
                                      &Context.Idents.get(SelectorName2)};
9322
9323
0
    if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
9324
0
      if (ReturnType.isNull()) {
9325
0
        Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9326
0
        Builder.AddTextChunk("void");
9327
0
        Builder.AddChunk(CodeCompletionString::CK_RightParen);
9328
0
      }
9329
9330
0
      Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName1 + ":"));
9331
0
      Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9332
0
      Builder.AddPlaceholderChunk("NSIndexSet *");
9333
0
      Builder.AddChunk(CodeCompletionString::CK_RightParen);
9334
0
      Builder.AddTextChunk("indexes");
9335
0
      Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9336
0
      Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName2 + ":"));
9337
0
      Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9338
0
      Builder.AddTextChunk("NSArray *");
9339
0
      Builder.AddChunk(CodeCompletionString::CK_RightParen);
9340
0
      Builder.AddTextChunk("array");
9341
0
      Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
9342
0
                               CXCursor_ObjCInstanceMethodDecl));
9343
0
    }
9344
0
  }
9345
9346
  // Unordered getters
9347
  // - (NSEnumerator *)enumeratorOfKey
9348
0
  if (IsInstanceMethod &&
9349
0
      (ReturnType.isNull() ||
9350
0
       (ReturnType->isObjCObjectPointerType() &&
9351
0
        ReturnType->castAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
9352
0
        ReturnType->castAs<ObjCObjectPointerType>()
9353
0
                ->getInterfaceDecl()
9354
0
                ->getName() == "NSEnumerator"))) {
9355
0
    std::string SelectorName = (Twine("enumeratorOf") + UpperKey).str();
9356
0
    IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
9357
0
    if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
9358
0
            .second) {
9359
0
      if (ReturnType.isNull()) {
9360
0
        Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9361
0
        Builder.AddTextChunk("NSEnumerator *");
9362
0
        Builder.AddChunk(CodeCompletionString::CK_RightParen);
9363
0
      }
9364
9365
0
      Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
9366
0
      Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
9367
0
                               CXCursor_ObjCInstanceMethodDecl));
9368
0
    }
9369
0
  }
9370
9371
  // - (type *)memberOfKey:(type *)object
9372
0
  if (IsInstanceMethod &&
9373
0
      (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
9374
0
    std::string SelectorName = (Twine("memberOf") + UpperKey).str();
9375
0
    IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
9376
0
    if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
9377
0
      if (ReturnType.isNull()) {
9378
0
        Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9379
0
        Builder.AddPlaceholderChunk("object-type");
9380
0
        Builder.AddTextChunk(" *");
9381
0
        Builder.AddChunk(CodeCompletionString::CK_RightParen);
9382
0
      }
9383
9384
0
      Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
9385
0
      Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9386
0
      if (ReturnType.isNull()) {
9387
0
        Builder.AddPlaceholderChunk("object-type");
9388
0
        Builder.AddTextChunk(" *");
9389
0
      } else {
9390
0
        Builder.AddTextChunk(GetCompletionTypeString(
9391
0
            ReturnType, Context, Policy, Builder.getAllocator()));
9392
0
      }
9393
0
      Builder.AddChunk(CodeCompletionString::CK_RightParen);
9394
0
      Builder.AddTextChunk("object");
9395
0
      Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
9396
0
                               CXCursor_ObjCInstanceMethodDecl));
9397
0
    }
9398
0
  }
9399
9400
  // Mutable unordered accessors
9401
  // - (void)addKeyObject:(type *)object
9402
0
  if (IsInstanceMethod && ReturnTypeMatchesVoid) {
9403
0
    std::string SelectorName =
9404
0
        (Twine("add") + UpperKey + Twine("Object")).str();
9405
0
    IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
9406
0
    if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
9407
0
      if (ReturnType.isNull()) {
9408
0
        Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9409
0
        Builder.AddTextChunk("void");
9410
0
        Builder.AddChunk(CodeCompletionString::CK_RightParen);
9411
0
      }
9412
9413
0
      Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
9414
0
      Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9415
0
      Builder.AddPlaceholderChunk("object-type");
9416
0
      Builder.AddTextChunk(" *");
9417
0
      Builder.AddChunk(CodeCompletionString::CK_RightParen);
9418
0
      Builder.AddTextChunk("object");
9419
0
      Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
9420
0
                               CXCursor_ObjCInstanceMethodDecl));
9421
0
    }
9422
0
  }
9423
9424
  // - (void)addKey:(NSSet *)objects
9425
0
  if (IsInstanceMethod && ReturnTypeMatchesVoid) {
9426
0
    std::string SelectorName = (Twine("add") + UpperKey).str();
9427
0
    IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
9428
0
    if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
9429
0
      if (ReturnType.isNull()) {
9430
0
        Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9431
0
        Builder.AddTextChunk("void");
9432
0
        Builder.AddChunk(CodeCompletionString::CK_RightParen);
9433
0
      }
9434
9435
0
      Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
9436
0
      Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9437
0
      Builder.AddTextChunk("NSSet *");
9438
0
      Builder.AddChunk(CodeCompletionString::CK_RightParen);
9439
0
      Builder.AddTextChunk("objects");
9440
0
      Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
9441
0
                               CXCursor_ObjCInstanceMethodDecl));
9442
0
    }
9443
0
  }
9444
9445
  // - (void)removeKeyObject:(type *)object
9446
0
  if (IsInstanceMethod && ReturnTypeMatchesVoid) {
9447
0
    std::string SelectorName =
9448
0
        (Twine("remove") + UpperKey + Twine("Object")).str();
9449
0
    IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
9450
0
    if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
9451
0
      if (ReturnType.isNull()) {
9452
0
        Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9453
0
        Builder.AddTextChunk("void");
9454
0
        Builder.AddChunk(CodeCompletionString::CK_RightParen);
9455
0
      }
9456
9457
0
      Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
9458
0
      Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9459
0
      Builder.AddPlaceholderChunk("object-type");
9460
0
      Builder.AddTextChunk(" *");
9461
0
      Builder.AddChunk(CodeCompletionString::CK_RightParen);
9462
0
      Builder.AddTextChunk("object");
9463
0
      Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
9464
0
                               CXCursor_ObjCInstanceMethodDecl));
9465
0
    }
9466
0
  }
9467
9468
  // - (void)removeKey:(NSSet *)objects
9469
0
  if (IsInstanceMethod && ReturnTypeMatchesVoid) {
9470
0
    std::string SelectorName = (Twine("remove") + UpperKey).str();
9471
0
    IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
9472
0
    if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
9473
0
      if (ReturnType.isNull()) {
9474
0
        Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9475
0
        Builder.AddTextChunk("void");
9476
0
        Builder.AddChunk(CodeCompletionString::CK_RightParen);
9477
0
      }
9478
9479
0
      Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
9480
0
      Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9481
0
      Builder.AddTextChunk("NSSet *");
9482
0
      Builder.AddChunk(CodeCompletionString::CK_RightParen);
9483
0
      Builder.AddTextChunk("objects");
9484
0
      Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
9485
0
                               CXCursor_ObjCInstanceMethodDecl));
9486
0
    }
9487
0
  }
9488
9489
  // - (void)intersectKey:(NSSet *)objects
9490
0
  if (IsInstanceMethod && ReturnTypeMatchesVoid) {
9491
0
    std::string SelectorName = (Twine("intersect") + UpperKey).str();
9492
0
    IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
9493
0
    if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
9494
0
      if (ReturnType.isNull()) {
9495
0
        Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9496
0
        Builder.AddTextChunk("void");
9497
0
        Builder.AddChunk(CodeCompletionString::CK_RightParen);
9498
0
      }
9499
9500
0
      Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
9501
0
      Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9502
0
      Builder.AddTextChunk("NSSet *");
9503
0
      Builder.AddChunk(CodeCompletionString::CK_RightParen);
9504
0
      Builder.AddTextChunk("objects");
9505
0
      Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
9506
0
                               CXCursor_ObjCInstanceMethodDecl));
9507
0
    }
9508
0
  }
9509
9510
  // Key-Value Observing
9511
  // + (NSSet *)keyPathsForValuesAffectingKey
9512
0
  if (!IsInstanceMethod &&
9513
0
      (ReturnType.isNull() ||
9514
0
       (ReturnType->isObjCObjectPointerType() &&
9515
0
        ReturnType->castAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
9516
0
        ReturnType->castAs<ObjCObjectPointerType>()
9517
0
                ->getInterfaceDecl()
9518
0
                ->getName() == "NSSet"))) {
9519
0
    std::string SelectorName =
9520
0
        (Twine("keyPathsForValuesAffecting") + UpperKey).str();
9521
0
    IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
9522
0
    if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
9523
0
            .second) {
9524
0
      if (ReturnType.isNull()) {
9525
0
        Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9526
0
        Builder.AddTextChunk("NSSet<NSString *> *");
9527
0
        Builder.AddChunk(CodeCompletionString::CK_RightParen);
9528
0
      }
9529
9530
0
      Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
9531
0
      Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
9532
0
                               CXCursor_ObjCClassMethodDecl));
9533
0
    }
9534
0
  }
9535
9536
  // + (BOOL)automaticallyNotifiesObserversForKey
9537
0
  if (!IsInstanceMethod &&
9538
0
      (ReturnType.isNull() || ReturnType->isIntegerType() ||
9539
0
       ReturnType->isBooleanType())) {
9540
0
    std::string SelectorName =
9541
0
        (Twine("automaticallyNotifiesObserversOf") + UpperKey).str();
9542
0
    IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
9543
0
    if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
9544
0
            .second) {
9545
0
      if (ReturnType.isNull()) {
9546
0
        Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9547
0
        Builder.AddTextChunk("BOOL");
9548
0
        Builder.AddChunk(CodeCompletionString::CK_RightParen);
9549
0
      }
9550
9551
0
      Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
9552
0
      Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
9553
0
                               CXCursor_ObjCClassMethodDecl));
9554
0
    }
9555
0
  }
9556
0
}
9557
9558
void Sema::CodeCompleteObjCMethodDecl(Scope *S,
9559
                                      std::optional<bool> IsInstanceMethod,
9560
0
                                      ParsedType ReturnTy) {
9561
  // Determine the return type of the method we're declaring, if
9562
  // provided.
9563
0
  QualType ReturnType = GetTypeFromParser(ReturnTy);
9564
0
  Decl *IDecl = nullptr;
9565
0
  if (CurContext->isObjCContainer()) {
9566
0
    ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext);
9567
0
    IDecl = OCD;
9568
0
  }
9569
  // Determine where we should start searching for methods.
9570
0
  ObjCContainerDecl *SearchDecl = nullptr;
9571
0
  bool IsInImplementation = false;
9572
0
  if (Decl *D = IDecl) {
9573
0
    if (ObjCImplementationDecl *Impl = dyn_cast<ObjCImplementationDecl>(D)) {
9574
0
      SearchDecl = Impl->getClassInterface();
9575
0
      IsInImplementation = true;
9576
0
    } else if (ObjCCategoryImplDecl *CatImpl =
9577
0
                   dyn_cast<ObjCCategoryImplDecl>(D)) {
9578
0
      SearchDecl = CatImpl->getCategoryDecl();
9579
0
      IsInImplementation = true;
9580
0
    } else
9581
0
      SearchDecl = dyn_cast<ObjCContainerDecl>(D);
9582
0
  }
9583
9584
0
  if (!SearchDecl && S) {
9585
0
    if (DeclContext *DC = S->getEntity())
9586
0
      SearchDecl = dyn_cast<ObjCContainerDecl>(DC);
9587
0
  }
9588
9589
0
  if (!SearchDecl) {
9590
0
    HandleCodeCompleteResults(this, CodeCompleter,
9591
0
                              CodeCompletionContext::CCC_Other, nullptr, 0);
9592
0
    return;
9593
0
  }
9594
9595
  // Find all of the methods that we could declare/implement here.
9596
0
  KnownMethodsMap KnownMethods;
9597
0
  FindImplementableMethods(Context, SearchDecl, IsInstanceMethod, ReturnType,
9598
0
                           KnownMethods);
9599
9600
  // Add declarations or definitions for each of the known methods.
9601
0
  typedef CodeCompletionResult Result;
9602
0
  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
9603
0
                        CodeCompleter->getCodeCompletionTUInfo(),
9604
0
                        CodeCompletionContext::CCC_Other);
9605
0
  Results.EnterNewScope();
9606
0
  PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
9607
0
  for (KnownMethodsMap::iterator M = KnownMethods.begin(),
9608
0
                                 MEnd = KnownMethods.end();
9609
0
       M != MEnd; ++M) {
9610
0
    ObjCMethodDecl *Method = M->second.getPointer();
9611
0
    CodeCompletionBuilder Builder(Results.getAllocator(),
9612
0
                                  Results.getCodeCompletionTUInfo());
9613
9614
    // Add the '-'/'+' prefix if it wasn't provided yet.
9615
0
    if (!IsInstanceMethod) {
9616
0
      Builder.AddTextChunk(Method->isInstanceMethod() ? "-" : "+");
9617
0
      Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9618
0
    }
9619
9620
    // If the result type was not already provided, add it to the
9621
    // pattern as (type).
9622
0
    if (ReturnType.isNull()) {
9623
0
      QualType ResTy = Method->getSendResultType().stripObjCKindOfType(Context);
9624
0
      AttributedType::stripOuterNullability(ResTy);
9625
0
      AddObjCPassingTypeChunk(ResTy, Method->getObjCDeclQualifier(), Context,
9626
0
                              Policy, Builder);
9627
0
    }
9628
9629
0
    Selector Sel = Method->getSelector();
9630
9631
0
    if (Sel.isUnarySelector()) {
9632
      // Unary selectors have no arguments.
9633
0
      Builder.AddTypedTextChunk(
9634
0
          Builder.getAllocator().CopyString(Sel.getNameForSlot(0)));
9635
0
    } else {
9636
      // Add all parameters to the pattern.
9637
0
      unsigned I = 0;
9638
0
      for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
9639
0
                                          PEnd = Method->param_end();
9640
0
           P != PEnd; (void)++P, ++I) {
9641
        // Add the part of the selector name.
9642
0
        if (I == 0)
9643
0
          Builder.AddTypedTextChunk(
9644
0
              Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":"));
9645
0
        else if (I < Sel.getNumArgs()) {
9646
0
          Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9647
0
          Builder.AddTypedTextChunk(
9648
0
              Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":"));
9649
0
        } else
9650
0
          break;
9651
9652
        // Add the parameter type.
9653
0
        QualType ParamType;
9654
0
        if ((*P)->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
9655
0
          ParamType = (*P)->getType();
9656
0
        else
9657
0
          ParamType = (*P)->getOriginalType();
9658
0
        ParamType = ParamType.substObjCTypeArgs(
9659
0
            Context, {}, ObjCSubstitutionContext::Parameter);
9660
0
        AttributedType::stripOuterNullability(ParamType);
9661
0
        AddObjCPassingTypeChunk(ParamType, (*P)->getObjCDeclQualifier(),
9662
0
                                Context, Policy, Builder);
9663
9664
0
        if (IdentifierInfo *Id = (*P)->getIdentifier())
9665
0
          Builder.AddTextChunk(
9666
0
              Builder.getAllocator().CopyString(Id->getName()));
9667
0
      }
9668
0
    }
9669
9670
0
    if (Method->isVariadic()) {
9671
0
      if (Method->param_size() > 0)
9672
0
        Builder.AddChunk(CodeCompletionString::CK_Comma);
9673
0
      Builder.AddTextChunk("...");
9674
0
    }
9675
9676
0
    if (IsInImplementation && Results.includeCodePatterns()) {
9677
      // We will be defining the method here, so add a compound statement.
9678
0
      Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9679
0
      Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
9680
0
      Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
9681
0
      if (!Method->getReturnType()->isVoidType()) {
9682
        // If the result type is not void, add a return clause.
9683
0
        Builder.AddTextChunk("return");
9684
0
        Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9685
0
        Builder.AddPlaceholderChunk("expression");
9686
0
        Builder.AddChunk(CodeCompletionString::CK_SemiColon);
9687
0
      } else
9688
0
        Builder.AddPlaceholderChunk("statements");
9689
9690
0
      Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
9691
0
      Builder.AddChunk(CodeCompletionString::CK_RightBrace);
9692
0
    }
9693
9694
0
    unsigned Priority = CCP_CodePattern;
9695
0
    auto R = Result(Builder.TakeString(), Method, Priority);
9696
0
    if (!M->second.getInt())
9697
0
      setInBaseClass(R);
9698
0
    Results.AddResult(std::move(R));
9699
0
  }
9700
9701
  // Add Key-Value-Coding and Key-Value-Observing accessor methods for all of
9702
  // the properties in this class and its categories.
9703
0
  if (Context.getLangOpts().ObjC) {
9704
0
    SmallVector<ObjCContainerDecl *, 4> Containers;
9705
0
    Containers.push_back(SearchDecl);
9706
9707
0
    VisitedSelectorSet KnownSelectors;
9708
0
    for (KnownMethodsMap::iterator M = KnownMethods.begin(),
9709
0
                                   MEnd = KnownMethods.end();
9710
0
         M != MEnd; ++M)
9711
0
      KnownSelectors.insert(M->first);
9712
9713
0
    ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(SearchDecl);
9714
0
    if (!IFace)
9715
0
      if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(SearchDecl))
9716
0
        IFace = Category->getClassInterface();
9717
9718
0
    if (IFace)
9719
0
      llvm::append_range(Containers, IFace->visible_categories());
9720
9721
0
    if (IsInstanceMethod) {
9722
0
      for (unsigned I = 0, N = Containers.size(); I != N; ++I)
9723
0
        for (auto *P : Containers[I]->instance_properties())
9724
0
          AddObjCKeyValueCompletions(P, *IsInstanceMethod, ReturnType, Context,
9725
0
                                     KnownSelectors, Results);
9726
0
    }
9727
0
  }
9728
9729
0
  Results.ExitScope();
9730
9731
0
  HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
9732
0
                            Results.data(), Results.size());
9733
0
}
9734
9735
void Sema::CodeCompleteObjCMethodDeclSelector(
9736
    Scope *S, bool IsInstanceMethod, bool AtParameterName, ParsedType ReturnTy,
9737
0
    ArrayRef<IdentifierInfo *> SelIdents) {
9738
  // If we have an external source, load the entire class method
9739
  // pool from the AST file.
9740
0
  if (ExternalSource) {
9741
0
    for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors(); I != N;
9742
0
         ++I) {
9743
0
      Selector Sel = ExternalSource->GetExternalSelector(I);
9744
0
      if (Sel.isNull() || MethodPool.count(Sel))
9745
0
        continue;
9746
9747
0
      ReadMethodPool(Sel);
9748
0
    }
9749
0
  }
9750
9751
  // Build the set of methods we can see.
9752
0
  typedef CodeCompletionResult Result;
9753
0
  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
9754
0
                        CodeCompleter->getCodeCompletionTUInfo(),
9755
0
                        CodeCompletionContext::CCC_Other);
9756
9757
0
  if (ReturnTy)
9758
0
    Results.setPreferredType(GetTypeFromParser(ReturnTy).getNonReferenceType());
9759
9760
0
  Results.EnterNewScope();
9761
0
  for (GlobalMethodPool::iterator M = MethodPool.begin(),
9762
0
                                  MEnd = MethodPool.end();
9763
0
       M != MEnd; ++M) {
9764
0
    for (ObjCMethodList *MethList = IsInstanceMethod ? &M->second.first
9765
0
                                                     : &M->second.second;
9766
0
         MethList && MethList->getMethod(); MethList = MethList->getNext()) {
9767
0
      if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents))
9768
0
        continue;
9769
9770
0
      if (AtParameterName) {
9771
        // Suggest parameter names we've seen before.
9772
0
        unsigned NumSelIdents = SelIdents.size();
9773
0
        if (NumSelIdents &&
9774
0
            NumSelIdents <= MethList->getMethod()->param_size()) {
9775
0
          ParmVarDecl *Param =
9776
0
              MethList->getMethod()->parameters()[NumSelIdents - 1];
9777
0
          if (Param->getIdentifier()) {
9778
0
            CodeCompletionBuilder Builder(Results.getAllocator(),
9779
0
                                          Results.getCodeCompletionTUInfo());
9780
0
            Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
9781
0
                Param->getIdentifier()->getName()));
9782
0
            Results.AddResult(Builder.TakeString());
9783
0
          }
9784
0
        }
9785
9786
0
        continue;
9787
0
      }
9788
9789
0
      Result R(MethList->getMethod(),
9790
0
               Results.getBasePriority(MethList->getMethod()), nullptr);
9791
0
      R.StartParameter = SelIdents.size();
9792
0
      R.AllParametersAreInformative = false;
9793
0
      R.DeclaringEntity = true;
9794
0
      Results.MaybeAddResult(R, CurContext);
9795
0
    }
9796
0
  }
9797
9798
0
  Results.ExitScope();
9799
9800
0
  if (!AtParameterName && !SelIdents.empty() &&
9801
0
      SelIdents.front()->getName().starts_with("init")) {
9802
0
    for (const auto &M : PP.macros()) {
9803
0
      if (M.first->getName() != "NS_DESIGNATED_INITIALIZER")
9804
0
        continue;
9805
0
      Results.EnterNewScope();
9806
0
      CodeCompletionBuilder Builder(Results.getAllocator(),
9807
0
                                    Results.getCodeCompletionTUInfo());
9808
0
      Builder.AddTypedTextChunk(
9809
0
          Builder.getAllocator().CopyString(M.first->getName()));
9810
0
      Results.AddResult(CodeCompletionResult(Builder.TakeString(), CCP_Macro,
9811
0
                                             CXCursor_MacroDefinition));
9812
0
      Results.ExitScope();
9813
0
    }
9814
0
  }
9815
9816
0
  HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
9817
0
                            Results.data(), Results.size());
9818
0
}
9819
9820
0
void Sema::CodeCompletePreprocessorDirective(bool InConditional) {
9821
0
  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
9822
0
                        CodeCompleter->getCodeCompletionTUInfo(),
9823
0
                        CodeCompletionContext::CCC_PreprocessorDirective);
9824
0
  Results.EnterNewScope();
9825
9826
  // #if <condition>
9827
0
  CodeCompletionBuilder Builder(Results.getAllocator(),
9828
0
                                Results.getCodeCompletionTUInfo());
9829
0
  Builder.AddTypedTextChunk("if");
9830
0
  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9831
0
  Builder.AddPlaceholderChunk("condition");
9832
0
  Results.AddResult(Builder.TakeString());
9833
9834
  // #ifdef <macro>
9835
0
  Builder.AddTypedTextChunk("ifdef");
9836
0
  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9837
0
  Builder.AddPlaceholderChunk("macro");
9838
0
  Results.AddResult(Builder.TakeString());
9839
9840
  // #ifndef <macro>
9841
0
  Builder.AddTypedTextChunk("ifndef");
9842
0
  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9843
0
  Builder.AddPlaceholderChunk("macro");
9844
0
  Results.AddResult(Builder.TakeString());
9845
9846
0
  if (InConditional) {
9847
    // #elif <condition>
9848
0
    Builder.AddTypedTextChunk("elif");
9849
0
    Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9850
0
    Builder.AddPlaceholderChunk("condition");
9851
0
    Results.AddResult(Builder.TakeString());
9852
9853
    // #elifdef <macro>
9854
0
    Builder.AddTypedTextChunk("elifdef");
9855
0
    Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9856
0
    Builder.AddPlaceholderChunk("macro");
9857
0
    Results.AddResult(Builder.TakeString());
9858
9859
    // #elifndef <macro>
9860
0
    Builder.AddTypedTextChunk("elifndef");
9861
0
    Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9862
0
    Builder.AddPlaceholderChunk("macro");
9863
0
    Results.AddResult(Builder.TakeString());
9864
9865
    // #else
9866
0
    Builder.AddTypedTextChunk("else");
9867
0
    Results.AddResult(Builder.TakeString());
9868
9869
    // #endif
9870
0
    Builder.AddTypedTextChunk("endif");
9871
0
    Results.AddResult(Builder.TakeString());
9872
0
  }
9873
9874
  // #include "header"
9875
0
  Builder.AddTypedTextChunk("include");
9876
0
  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9877
0
  Builder.AddTextChunk("\"");
9878
0
  Builder.AddPlaceholderChunk("header");
9879
0
  Builder.AddTextChunk("\"");
9880
0
  Results.AddResult(Builder.TakeString());
9881
9882
  // #include <header>
9883
0
  Builder.AddTypedTextChunk("include");
9884
0
  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9885
0
  Builder.AddTextChunk("<");
9886
0
  Builder.AddPlaceholderChunk("header");
9887
0
  Builder.AddTextChunk(">");
9888
0
  Results.AddResult(Builder.TakeString());
9889
9890
  // #define <macro>
9891
0
  Builder.AddTypedTextChunk("define");
9892
0
  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9893
0
  Builder.AddPlaceholderChunk("macro");
9894
0
  Results.AddResult(Builder.TakeString());
9895
9896
  // #define <macro>(<args>)
9897
0
  Builder.AddTypedTextChunk("define");
9898
0
  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9899
0
  Builder.AddPlaceholderChunk("macro");
9900
0
  Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9901
0
  Builder.AddPlaceholderChunk("args");
9902
0
  Builder.AddChunk(CodeCompletionString::CK_RightParen);
9903
0
  Results.AddResult(Builder.TakeString());
9904
9905
  // #undef <macro>
9906
0
  Builder.AddTypedTextChunk("undef");
9907
0
  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9908
0
  Builder.AddPlaceholderChunk("macro");
9909
0
  Results.AddResult(Builder.TakeString());
9910
9911
  // #line <number>
9912
0
  Builder.AddTypedTextChunk("line");
9913
0
  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9914
0
  Builder.AddPlaceholderChunk("number");
9915
0
  Results.AddResult(Builder.TakeString());
9916
9917
  // #line <number> "filename"
9918
0
  Builder.AddTypedTextChunk("line");
9919
0
  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9920
0
  Builder.AddPlaceholderChunk("number");
9921
0
  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9922
0
  Builder.AddTextChunk("\"");
9923
0
  Builder.AddPlaceholderChunk("filename");
9924
0
  Builder.AddTextChunk("\"");
9925
0
  Results.AddResult(Builder.TakeString());
9926
9927
  // #error <message>
9928
0
  Builder.AddTypedTextChunk("error");
9929
0
  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9930
0
  Builder.AddPlaceholderChunk("message");
9931
0
  Results.AddResult(Builder.TakeString());
9932
9933
  // #pragma <arguments>
9934
0
  Builder.AddTypedTextChunk("pragma");
9935
0
  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9936
0
  Builder.AddPlaceholderChunk("arguments");
9937
0
  Results.AddResult(Builder.TakeString());
9938
9939
0
  if (getLangOpts().ObjC) {
9940
    // #import "header"
9941
0
    Builder.AddTypedTextChunk("import");
9942
0
    Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9943
0
    Builder.AddTextChunk("\"");
9944
0
    Builder.AddPlaceholderChunk("header");
9945
0
    Builder.AddTextChunk("\"");
9946
0
    Results.AddResult(Builder.TakeString());
9947
9948
    // #import <header>
9949
0
    Builder.AddTypedTextChunk("import");
9950
0
    Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9951
0
    Builder.AddTextChunk("<");
9952
0
    Builder.AddPlaceholderChunk("header");
9953
0
    Builder.AddTextChunk(">");
9954
0
    Results.AddResult(Builder.TakeString());
9955
0
  }
9956
9957
  // #include_next "header"
9958
0
  Builder.AddTypedTextChunk("include_next");
9959
0
  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9960
0
  Builder.AddTextChunk("\"");
9961
0
  Builder.AddPlaceholderChunk("header");
9962
0
  Builder.AddTextChunk("\"");
9963
0
  Results.AddResult(Builder.TakeString());
9964
9965
  // #include_next <header>
9966
0
  Builder.AddTypedTextChunk("include_next");
9967
0
  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9968
0
  Builder.AddTextChunk("<");
9969
0
  Builder.AddPlaceholderChunk("header");
9970
0
  Builder.AddTextChunk(">");
9971
0
  Results.AddResult(Builder.TakeString());
9972
9973
  // #warning <message>
9974
0
  Builder.AddTypedTextChunk("warning");
9975
0
  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9976
0
  Builder.AddPlaceholderChunk("message");
9977
0
  Results.AddResult(Builder.TakeString());
9978
9979
  // Note: #ident and #sccs are such crazy anachronisms that we don't provide
9980
  // completions for them. And __include_macros is a Clang-internal extension
9981
  // that we don't want to encourage anyone to use.
9982
9983
  // FIXME: we don't support #assert or #unassert, so don't suggest them.
9984
0
  Results.ExitScope();
9985
9986
0
  HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
9987
0
                            Results.data(), Results.size());
9988
0
}
9989
9990
0
void Sema::CodeCompleteInPreprocessorConditionalExclusion(Scope *S) {
9991
0
  CodeCompleteOrdinaryName(S, S->getFnParent() ? Sema::PCC_RecoveryInFunction
9992
0
                                               : Sema::PCC_Namespace);
9993
0
}
9994
9995
0
void Sema::CodeCompletePreprocessorMacroName(bool IsDefinition) {
9996
0
  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
9997
0
                        CodeCompleter->getCodeCompletionTUInfo(),
9998
0
                        IsDefinition ? CodeCompletionContext::CCC_MacroName
9999
0
                                     : CodeCompletionContext::CCC_MacroNameUse);
10000
0
  if (!IsDefinition && CodeCompleter->includeMacros()) {
10001
    // Add just the names of macros, not their arguments.
10002
0
    CodeCompletionBuilder Builder(Results.getAllocator(),
10003
0
                                  Results.getCodeCompletionTUInfo());
10004
0
    Results.EnterNewScope();
10005
0
    for (Preprocessor::macro_iterator M = PP.macro_begin(),
10006
0
                                      MEnd = PP.macro_end();
10007
0
         M != MEnd; ++M) {
10008
0
      Builder.AddTypedTextChunk(
10009
0
          Builder.getAllocator().CopyString(M->first->getName()));
10010
0
      Results.AddResult(CodeCompletionResult(
10011
0
          Builder.TakeString(), CCP_CodePattern, CXCursor_MacroDefinition));
10012
0
    }
10013
0
    Results.ExitScope();
10014
0
  } else if (IsDefinition) {
10015
    // FIXME: Can we detect when the user just wrote an include guard above?
10016
0
  }
10017
10018
0
  HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
10019
0
                            Results.data(), Results.size());
10020
0
}
10021
10022
0
void Sema::CodeCompletePreprocessorExpression() {
10023
0
  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
10024
0
                        CodeCompleter->getCodeCompletionTUInfo(),
10025
0
                        CodeCompletionContext::CCC_PreprocessorExpression);
10026
10027
0
  if (CodeCompleter->includeMacros())
10028
0
    AddMacroResults(PP, Results, CodeCompleter->loadExternal(), true);
10029
10030
  // defined (<macro>)
10031
0
  Results.EnterNewScope();
10032
0
  CodeCompletionBuilder Builder(Results.getAllocator(),
10033
0
                                Results.getCodeCompletionTUInfo());
10034
0
  Builder.AddTypedTextChunk("defined");
10035
0
  Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
10036
0
  Builder.AddChunk(CodeCompletionString::CK_LeftParen);
10037
0
  Builder.AddPlaceholderChunk("macro");
10038
0
  Builder.AddChunk(CodeCompletionString::CK_RightParen);
10039
0
  Results.AddResult(Builder.TakeString());
10040
0
  Results.ExitScope();
10041
10042
0
  HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
10043
0
                            Results.data(), Results.size());
10044
0
}
10045
10046
void Sema::CodeCompletePreprocessorMacroArgument(Scope *S,
10047
                                                 IdentifierInfo *Macro,
10048
                                                 MacroInfo *MacroInfo,
10049
0
                                                 unsigned Argument) {
10050
  // FIXME: In the future, we could provide "overload" results, much like we
10051
  // do for function calls.
10052
10053
  // Now just ignore this. There will be another code-completion callback
10054
  // for the expanded tokens.
10055
0
}
10056
10057
// This handles completion inside an #include filename, e.g. #include <foo/ba
10058
// We look for the directory "foo" under each directory on the include path,
10059
// list its files, and reassemble the appropriate #include.
10060
0
void Sema::CodeCompleteIncludedFile(llvm::StringRef Dir, bool Angled) {
10061
  // RelDir should use /, but unescaped \ is possible on windows!
10062
  // Our completions will normalize to / for simplicity, this case is rare.
10063
0
  std::string RelDir = llvm::sys::path::convert_to_slash(Dir);
10064
  // We need the native slashes for the actual file system interactions.
10065
0
  SmallString<128> NativeRelDir = StringRef(RelDir);
10066
0
  llvm::sys::path::native(NativeRelDir);
10067
0
  llvm::vfs::FileSystem &FS =
10068
0
      getSourceManager().getFileManager().getVirtualFileSystem();
10069
10070
0
  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
10071
0
                        CodeCompleter->getCodeCompletionTUInfo(),
10072
0
                        CodeCompletionContext::CCC_IncludedFile);
10073
0
  llvm::DenseSet<StringRef> SeenResults; // To deduplicate results.
10074
10075
  // Helper: adds one file or directory completion result.
10076
0
  auto AddCompletion = [&](StringRef Filename, bool IsDirectory) {
10077
0
    SmallString<64> TypedChunk = Filename;
10078
    // Directory completion is up to the slash, e.g. <sys/
10079
0
    TypedChunk.push_back(IsDirectory ? '/' : Angled ? '>' : '"');
10080
0
    auto R = SeenResults.insert(TypedChunk);
10081
0
    if (R.second) { // New completion
10082
0
      const char *InternedTyped = Results.getAllocator().CopyString(TypedChunk);
10083
0
      *R.first = InternedTyped; // Avoid dangling StringRef.
10084
0
      CodeCompletionBuilder Builder(CodeCompleter->getAllocator(),
10085
0
                                    CodeCompleter->getCodeCompletionTUInfo());
10086
0
      Builder.AddTypedTextChunk(InternedTyped);
10087
      // The result is a "Pattern", which is pretty opaque.
10088
      // We may want to include the real filename to allow smart ranking.
10089
0
      Results.AddResult(CodeCompletionResult(Builder.TakeString()));
10090
0
    }
10091
0
  };
10092
10093
  // Helper: scans IncludeDir for nice files, and adds results for each.
10094
0
  auto AddFilesFromIncludeDir = [&](StringRef IncludeDir,
10095
0
                                    bool IsSystem,
10096
0
                                    DirectoryLookup::LookupType_t LookupType) {
10097
0
    llvm::SmallString<128> Dir = IncludeDir;
10098
0
    if (!NativeRelDir.empty()) {
10099
0
      if (LookupType == DirectoryLookup::LT_Framework) {
10100
        // For a framework dir, #include <Foo/Bar/> actually maps to
10101
        // a path of Foo.framework/Headers/Bar/.
10102
0
        auto Begin = llvm::sys::path::begin(NativeRelDir);
10103
0
        auto End = llvm::sys::path::end(NativeRelDir);
10104
10105
0
        llvm::sys::path::append(Dir, *Begin + ".framework", "Headers");
10106
0
        llvm::sys::path::append(Dir, ++Begin, End);
10107
0
      } else {
10108
0
        llvm::sys::path::append(Dir, NativeRelDir);
10109
0
      }
10110
0
    }
10111
10112
0
    const StringRef &Dirname = llvm::sys::path::filename(Dir);
10113
0
    const bool isQt = Dirname.starts_with("Qt") || Dirname == "ActiveQt";
10114
0
    const bool ExtensionlessHeaders =
10115
0
        IsSystem || isQt || Dir.ends_with(".framework/Headers");
10116
0
    std::error_code EC;
10117
0
    unsigned Count = 0;
10118
0
    for (auto It = FS.dir_begin(Dir, EC);
10119
0
         !EC && It != llvm::vfs::directory_iterator(); It.increment(EC)) {
10120
0
      if (++Count == 2500) // If we happen to hit a huge directory,
10121
0
        break;             // bail out early so we're not too slow.
10122
0
      StringRef Filename = llvm::sys::path::filename(It->path());
10123
10124
      // To know whether a symlink should be treated as file or a directory, we
10125
      // have to stat it. This should be cheap enough as there shouldn't be many
10126
      // symlinks.
10127
0
      llvm::sys::fs::file_type Type = It->type();
10128
0
      if (Type == llvm::sys::fs::file_type::symlink_file) {
10129
0
        if (auto FileStatus = FS.status(It->path()))
10130
0
          Type = FileStatus->getType();
10131
0
      }
10132
0
      switch (Type) {
10133
0
      case llvm::sys::fs::file_type::directory_file:
10134
        // All entries in a framework directory must have a ".framework" suffix,
10135
        // but the suffix does not appear in the source code's include/import.
10136
0
        if (LookupType == DirectoryLookup::LT_Framework &&
10137
0
            NativeRelDir.empty() && !Filename.consume_back(".framework"))
10138
0
          break;
10139
10140
0
        AddCompletion(Filename, /*IsDirectory=*/true);
10141
0
        break;
10142
0
      case llvm::sys::fs::file_type::regular_file: {
10143
        // Only files that really look like headers. (Except in special dirs).
10144
0
        const bool IsHeader = Filename.ends_with_insensitive(".h") ||
10145
0
                              Filename.ends_with_insensitive(".hh") ||
10146
0
                              Filename.ends_with_insensitive(".hpp") ||
10147
0
                              Filename.ends_with_insensitive(".hxx") ||
10148
0
                              Filename.ends_with_insensitive(".inc") ||
10149
0
                              (ExtensionlessHeaders && !Filename.contains('.'));
10150
0
        if (!IsHeader)
10151
0
          break;
10152
0
        AddCompletion(Filename, /*IsDirectory=*/false);
10153
0
        break;
10154
0
      }
10155
0
      default:
10156
0
        break;
10157
0
      }
10158
0
    }
10159
0
  };
10160
10161
  // Helper: adds results relative to IncludeDir, if possible.
10162
0
  auto AddFilesFromDirLookup = [&](const DirectoryLookup &IncludeDir,
10163
0
                                   bool IsSystem) {
10164
0
    switch (IncludeDir.getLookupType()) {
10165
0
    case DirectoryLookup::LT_HeaderMap:
10166
      // header maps are not (currently) enumerable.
10167
0
      break;
10168
0
    case DirectoryLookup::LT_NormalDir:
10169
0
      AddFilesFromIncludeDir(IncludeDir.getDirRef()->getName(), IsSystem,
10170
0
                             DirectoryLookup::LT_NormalDir);
10171
0
      break;
10172
0
    case DirectoryLookup::LT_Framework:
10173
0
      AddFilesFromIncludeDir(IncludeDir.getFrameworkDirRef()->getName(),
10174
0
                             IsSystem, DirectoryLookup::LT_Framework);
10175
0
      break;
10176
0
    }
10177
0
  };
10178
10179
  // Finally with all our helpers, we can scan the include path.
10180
  // Do this in standard order so deduplication keeps the right file.
10181
  // (In case we decide to add more details to the results later).
10182
0
  const auto &S = PP.getHeaderSearchInfo();
10183
0
  using llvm::make_range;
10184
0
  if (!Angled) {
10185
    // The current directory is on the include path for "quoted" includes.
10186
0
    if (auto CurFile = PP.getCurrentFileLexer()->getFileEntry())
10187
0
      AddFilesFromIncludeDir(CurFile->getDir().getName(), false,
10188
0
                             DirectoryLookup::LT_NormalDir);
10189
0
    for (const auto &D : make_range(S.quoted_dir_begin(), S.quoted_dir_end()))
10190
0
      AddFilesFromDirLookup(D, false);
10191
0
  }
10192
0
  for (const auto &D : make_range(S.angled_dir_begin(), S.angled_dir_end()))
10193
0
    AddFilesFromDirLookup(D, false);
10194
0
  for (const auto &D : make_range(S.system_dir_begin(), S.system_dir_end()))
10195
0
    AddFilesFromDirLookup(D, true);
10196
10197
0
  HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
10198
0
                            Results.data(), Results.size());
10199
0
}
10200
10201
0
void Sema::CodeCompleteNaturalLanguage() {
10202
0
  HandleCodeCompleteResults(this, CodeCompleter,
10203
0
                            CodeCompletionContext::CCC_NaturalLanguage, nullptr,
10204
0
                            0);
10205
0
}
10206
10207
0
void Sema::CodeCompleteAvailabilityPlatformName() {
10208
0
  ResultBuilder Results(*this, CodeCompleter->getAllocator(),
10209
0
                        CodeCompleter->getCodeCompletionTUInfo(),
10210
0
                        CodeCompletionContext::CCC_Other);
10211
0
  Results.EnterNewScope();
10212
0
  static const char *Platforms[] = {"macOS", "iOS", "watchOS", "tvOS"};
10213
0
  for (const char *Platform : llvm::ArrayRef(Platforms)) {
10214
0
    Results.AddResult(CodeCompletionResult(Platform));
10215
0
    Results.AddResult(CodeCompletionResult(Results.getAllocator().CopyString(
10216
0
        Twine(Platform) + "ApplicationExtension")));
10217
0
  }
10218
0
  Results.ExitScope();
10219
0
  HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
10220
0
                            Results.data(), Results.size());
10221
0
}
10222
10223
void Sema::GatherGlobalCodeCompletions(
10224
    CodeCompletionAllocator &Allocator, CodeCompletionTUInfo &CCTUInfo,
10225
0
    SmallVectorImpl<CodeCompletionResult> &Results) {
10226
0
  ResultBuilder Builder(*this, Allocator, CCTUInfo,
10227
0
                        CodeCompletionContext::CCC_Recovery);
10228
0
  if (!CodeCompleter || CodeCompleter->includeGlobals()) {
10229
0
    CodeCompletionDeclConsumer Consumer(Builder,
10230
0
                                        Context.getTranslationUnitDecl());
10231
0
    LookupVisibleDecls(Context.getTranslationUnitDecl(), LookupAnyName,
10232
0
                       Consumer,
10233
0
                       !CodeCompleter || CodeCompleter->loadExternal());
10234
0
  }
10235
10236
0
  if (!CodeCompleter || CodeCompleter->includeMacros())
10237
0
    AddMacroResults(PP, Builder,
10238
0
                    !CodeCompleter || CodeCompleter->loadExternal(), true);
10239
10240
0
  Results.clear();
10241
0
  Results.insert(Results.end(), Builder.data(),
10242
0
                 Builder.data() + Builder.size());
10243
0
}