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