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