1 //===---------------- SemaCodeComplete.cpp - Code Completion ----*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
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"
63 using namespace clang;
67 /// A container of code-completion results.
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;
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;
104 ShadowMapEntry() : SingleDeclIndex(0) {}
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;
115 void Add(const NamedDecl *ND, unsigned Index) {
116 if (DeclOrVector.isNull()) {
117 // 0 - > 1 elements: just set the single element information.
119 SingleDeclIndex = Index;
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));
132 // Add the new element to the end of the vector.
133 DeclOrVector.get<DeclIndexPairVector *>()->push_back(
134 DeclIndexPair(ND, Index));
138 if (DeclIndexPairVector *Vec =
139 DeclOrVector.dyn_cast<DeclIndexPairVector *>()) {
141 DeclOrVector = ((NamedDecl *)nullptr);
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
154 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
156 /// The semantic analysis object for which results are being
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.
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
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>
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
206 ObjCImplementationDecl *ObjCImplementation;
208 void AdjustResultPriorityForDecl(Result &R);
210 void MaybeAddConstructorResults(Result R);
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_Recovery:
229 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl())
230 if (Method->isInstanceMethod())
231 if (ObjCInterfaceDecl *Interface = Method->getClassInterface())
232 ObjCImplementation = Interface->getImplementation();
240 /// Determine the priority for a reference to the given declaration.
241 unsigned getBasePriority(const NamedDecl *D);
243 /// Whether we should include code patterns in the completion
245 bool includeCodePatterns() const {
246 return SemaRef.CodeCompleter &&
247 SemaRef.CodeCompleter->includeCodePatterns();
250 /// Set the filter used for code-completion results.
251 void setFilter(LookupFilter Filter) { this->Filter = Filter; }
253 Result *data() { return Results.empty() ? nullptr : &Results.front(); }
254 unsigned size() const { return Results.size(); }
255 bool empty() const { return Results.empty(); }
257 /// Specify the preferred type.
258 void setPreferredType(QualType T) {
259 PreferredType = SemaRef.Context.getCanonicalType(T);
262 /// Set the cv-qualifiers on the object type, for us in filtering
263 /// calls to member functions.
265 /// When there are qualifiers in this set, they will be used to filter
266 /// out member functions that aren't available (because there will be a
267 /// cv-qualifier mismatch) or prefer functions with an exact qualifier
269 void setObjectTypeQualifiers(Qualifiers Quals, ExprValueKind Kind) {
270 ObjectTypeQualifiers = Quals;
272 HasObjectTypeQualifiers = true;
275 /// Set the preferred selector.
277 /// When an Objective-C method declaration result is added, and that
278 /// method's selector matches this preferred selector, we give that method
279 /// a slight priority boost.
280 void setPreferredSelector(Selector Sel) { PreferredSelector = Sel; }
282 /// Retrieve the code-completion context for which results are
284 const CodeCompletionContext &getCompletionContext() const {
285 return CompletionContext;
288 /// Specify whether nested-name-specifiers are allowed.
289 void allowNestedNameSpecifiers(bool Allow = true) {
290 AllowNestedNameSpecifiers = Allow;
293 /// Return the semantic analysis object for which we are collecting
294 /// code completion results.
295 Sema &getSema() const { return SemaRef; }
297 /// Retrieve the allocator used to allocate code completion strings.
298 CodeCompletionAllocator &getAllocator() const { return Allocator; }
300 CodeCompletionTUInfo &getCodeCompletionTUInfo() const { return CCTUInfo; }
302 /// Determine whether the given declaration is at all interesting
303 /// as a code-completion result.
305 /// \param ND the declaration that we are inspecting.
307 /// \param AsNestedNameSpecifier will be set true if this declaration is
308 /// only interesting when it is a nested-name-specifier.
309 bool isInterestingDecl(const NamedDecl *ND,
310 bool &AsNestedNameSpecifier) const;
312 /// Check whether the result is hidden by the Hiding declaration.
314 /// \returns true if the result is hidden and cannot be found, false if
315 /// the hidden result could still be found. When false, \p R may be
316 /// modified to describe how the result can be found (e.g., via extra
318 bool CheckHiddenResult(Result &R, DeclContext *CurContext,
319 const NamedDecl *Hiding);
321 /// Add a new result to this result set (if it isn't already in one
322 /// of the shadow maps), or replace an existing result (for, e.g., a
325 /// \param R the result to add (if it is unique).
327 /// \param CurContext the context in which this result will be named.
328 void MaybeAddResult(Result R, DeclContext *CurContext = nullptr);
330 /// Add a new result to this result set, where we already know
331 /// the hiding declaration (if any).
333 /// \param R the result to add (if it is unique).
335 /// \param CurContext the context in which this result will be named.
337 /// \param Hiding the declaration that hides the result.
339 /// \param InBaseClass whether the result was found in a base
340 /// class of the searched context.
341 void AddResult(Result R, DeclContext *CurContext, NamedDecl *Hiding,
344 /// Add a new non-declaration result to this result set.
345 void AddResult(Result R);
347 /// Enter into a new scope.
348 void EnterNewScope();
350 /// Exit from the current scope.
353 /// Ignore this declaration, if it is seen again.
354 void Ignore(const Decl *D) { AllDeclsFound.insert(D->getCanonicalDecl()); }
356 /// Add a visited context.
357 void addVisitedContext(DeclContext *Ctx) {
358 CompletionContext.addVisitedContext(Ctx);
361 /// \name Name lookup predicates
363 /// These predicates can be passed to the name lookup functions to filter the
364 /// results of name lookup. All of the predicates have the same type, so that
367 bool IsOrdinaryName(const NamedDecl *ND) const;
368 bool IsOrdinaryNonTypeName(const NamedDecl *ND) const;
369 bool IsIntegralConstantValue(const NamedDecl *ND) const;
370 bool IsOrdinaryNonValueName(const NamedDecl *ND) const;
371 bool IsNestedNameSpecifier(const NamedDecl *ND) const;
372 bool IsEnum(const NamedDecl *ND) const;
373 bool IsClassOrStruct(const NamedDecl *ND) const;
374 bool IsUnion(const NamedDecl *ND) const;
375 bool IsNamespace(const NamedDecl *ND) const;
376 bool IsNamespaceOrAlias(const NamedDecl *ND) const;
377 bool IsType(const NamedDecl *ND) const;
378 bool IsMember(const NamedDecl *ND) const;
379 bool IsObjCIvar(const NamedDecl *ND) const;
380 bool IsObjCMessageReceiver(const NamedDecl *ND) const;
381 bool IsObjCMessageReceiverOrLambdaCapture(const NamedDecl *ND) const;
382 bool IsObjCCollection(const NamedDecl *ND) const;
383 bool IsImpossibleToSatisfy(const NamedDecl *ND) const;
388 void PreferredTypeBuilder::enterReturn(Sema &S, SourceLocation Tok) {
391 if (isa<BlockDecl>(S.CurContext)) {
392 if (sema::BlockScopeInfo *BSI = S.getCurBlock()) {
393 ComputeType = nullptr;
394 Type = BSI->ReturnType;
397 } else if (const auto *Function = dyn_cast<FunctionDecl>(S.CurContext)) {
398 ComputeType = nullptr;
399 Type = Function->getReturnType();
401 } else if (const auto *Method = dyn_cast<ObjCMethodDecl>(S.CurContext)) {
402 ComputeType = nullptr;
403 Type = Method->getReturnType();
408 void PreferredTypeBuilder::enterVariableInit(SourceLocation Tok, Decl *D) {
411 auto *VD = llvm::dyn_cast_or_null<ValueDecl>(D);
412 ComputeType = nullptr;
413 Type = VD ? VD->getType() : QualType();
417 static QualType getDesignatedType(QualType BaseType, const Designation &Desig);
419 void PreferredTypeBuilder::enterDesignatedInitializer(SourceLocation Tok,
421 const Designation &D) {
424 ComputeType = nullptr;
425 Type = getDesignatedType(BaseType, D);
429 void PreferredTypeBuilder::enterFunctionArgument(
430 SourceLocation Tok, llvm::function_ref<QualType()> ComputeType) {
433 this->ComputeType = ComputeType;
438 void PreferredTypeBuilder::enterParenExpr(SourceLocation Tok,
439 SourceLocation LParLoc) {
442 // expected type for parenthesized expression does not change.
443 if (ExpectedLoc == LParLoc)
447 static QualType getPreferredTypeOfBinaryRHS(Sema &S, Expr *LHS,
452 QualType LHSType = LHS->getType();
453 if (LHSType->isPointerType()) {
454 if (Op == tok::plus || Op == tok::plusequal || Op == tok::minusequal)
455 return S.getASTContext().getPointerDiffType();
456 // Pointer difference is more common than subtracting an int from a pointer.
457 if (Op == tok::minus)
462 // No way to infer the type of RHS from LHS.
465 // Prefer the type of the left operand for all of these.
466 // Arithmetic operations.
470 case tok::minusequal:
472 case tok::percentequal:
474 case tok::slashequal:
479 // Comparison operators.
480 case tok::equalequal:
481 case tok::exclaimequal:
485 case tok::greaterequal:
487 return LHS->getType();
488 // Binary shifts are often overloaded, so don't try to guess those.
489 case tok::greatergreater:
490 case tok::greatergreaterequal:
492 case tok::lesslessequal:
493 if (LHSType->isIntegralOrEnumerationType())
494 return S.getASTContext().IntTy;
496 // Logical operators, assume we want bool.
499 case tok::caretcaret:
500 return S.getASTContext().BoolTy;
501 // Operators often used for bit manipulation are typically used with the type
502 // of the left argument.
506 case tok::caretequal:
509 if (LHSType->isIntegralOrEnumerationType())
512 // RHS should be a pointer to a member of the 'LHS' type, but we can't give
513 // any particular type here.
514 case tok::periodstar:
518 // FIXME(ibiryukov): handle the missing op, re-add the assertion.
519 // assert(false && "unhandled binary op");
524 /// Get preferred type for an argument of an unary expression. \p ContextType is
525 /// preferred type of the whole unary expression.
526 static QualType getPreferredTypeOfUnaryArg(Sema &S, QualType ContextType,
530 return S.getASTContext().BoolTy;
532 if (!ContextType.isNull() && ContextType->isPointerType())
533 return ContextType->getPointeeType();
536 if (ContextType.isNull())
538 return S.getASTContext().getPointerType(ContextType.getNonReferenceType());
542 case tok::minusminus:
544 if (ContextType.isNull())
545 return S.getASTContext().IntTy;
546 // leave as is, these operators typically return the same type.
552 assert(false && "unhandled unary op");
557 void PreferredTypeBuilder::enterBinary(Sema &S, SourceLocation Tok, Expr *LHS,
561 ComputeType = nullptr;
562 Type = getPreferredTypeOfBinaryRHS(S, LHS, Op);
566 void PreferredTypeBuilder::enterMemAccess(Sema &S, SourceLocation Tok,
568 if (!Enabled || !Base)
570 // Do we have expected type for Base?
571 if (ExpectedLoc != Base->getBeginLoc())
573 // Keep the expected type, only update the location.
577 void PreferredTypeBuilder::enterUnary(Sema &S, SourceLocation Tok,
578 tok::TokenKind OpKind,
579 SourceLocation OpLoc) {
582 ComputeType = nullptr;
583 Type = getPreferredTypeOfUnaryArg(S, this->get(OpLoc), OpKind);
587 void PreferredTypeBuilder::enterSubscript(Sema &S, SourceLocation Tok,
591 ComputeType = nullptr;
592 Type = S.getASTContext().IntTy;
596 void PreferredTypeBuilder::enterTypeCast(SourceLocation Tok,
600 ComputeType = nullptr;
601 Type = !CastType.isNull() ? CastType.getCanonicalType() : QualType();
605 void PreferredTypeBuilder::enterCondition(Sema &S, SourceLocation Tok) {
608 ComputeType = nullptr;
609 Type = S.getASTContext().BoolTy;
613 class ResultBuilder::ShadowMapEntry::iterator {
614 llvm::PointerUnion<const NamedDecl *, const DeclIndexPair *> DeclOrIterator;
615 unsigned SingleDeclIndex;
618 typedef DeclIndexPair value_type;
619 typedef value_type reference;
620 typedef std::ptrdiff_t difference_type;
621 typedef std::input_iterator_tag iterator_category;
627 pointer(const DeclIndexPair &Value) : Value(Value) {}
629 const DeclIndexPair *operator->() const { return &Value; }
632 iterator() : DeclOrIterator((NamedDecl *)nullptr), SingleDeclIndex(0) {}
634 iterator(const NamedDecl *SingleDecl, unsigned Index)
635 : DeclOrIterator(SingleDecl), SingleDeclIndex(Index) {}
637 iterator(const DeclIndexPair *Iterator)
638 : DeclOrIterator(Iterator), SingleDeclIndex(0) {}
640 iterator &operator++() {
641 if (DeclOrIterator.is<const NamedDecl *>()) {
642 DeclOrIterator = (NamedDecl *)nullptr;
647 const DeclIndexPair *I = DeclOrIterator.get<const DeclIndexPair *>();
653 /*iterator operator++(int) {
659 reference operator*() const {
660 if (const NamedDecl *ND = DeclOrIterator.dyn_cast<const NamedDecl *>())
661 return reference(ND, SingleDeclIndex);
663 return *DeclOrIterator.get<const DeclIndexPair *>();
666 pointer operator->() const { return pointer(**this); }
668 friend bool operator==(const iterator &X, const iterator &Y) {
669 return X.DeclOrIterator.getOpaqueValue() ==
670 Y.DeclOrIterator.getOpaqueValue() &&
671 X.SingleDeclIndex == Y.SingleDeclIndex;
674 friend bool operator!=(const iterator &X, const iterator &Y) {
679 ResultBuilder::ShadowMapEntry::iterator
680 ResultBuilder::ShadowMapEntry::begin() const {
681 if (DeclOrVector.isNull())
684 if (const NamedDecl *ND = DeclOrVector.dyn_cast<const NamedDecl *>())
685 return iterator(ND, SingleDeclIndex);
687 return iterator(DeclOrVector.get<DeclIndexPairVector *>()->begin());
690 ResultBuilder::ShadowMapEntry::iterator
691 ResultBuilder::ShadowMapEntry::end() const {
692 if (DeclOrVector.is<const NamedDecl *>() || DeclOrVector.isNull())
695 return iterator(DeclOrVector.get<DeclIndexPairVector *>()->end());
698 /// Compute the qualification required to get from the current context
699 /// (\p CurContext) to the target context (\p TargetContext).
701 /// \param Context the AST context in which the qualification will be used.
703 /// \param CurContext the context where an entity is being named, which is
704 /// typically based on the current scope.
706 /// \param TargetContext the context in which the named entity actually
709 /// \returns a nested name specifier that refers into the target context, or
710 /// NULL if no qualification is needed.
711 static NestedNameSpecifier *
712 getRequiredQualification(ASTContext &Context, const DeclContext *CurContext,
713 const DeclContext *TargetContext) {
714 SmallVector<const DeclContext *, 4> TargetParents;
716 for (const DeclContext *CommonAncestor = TargetContext;
717 CommonAncestor && !CommonAncestor->Encloses(CurContext);
718 CommonAncestor = CommonAncestor->getLookupParent()) {
719 if (CommonAncestor->isTransparentContext() ||
720 CommonAncestor->isFunctionOrMethod())
723 TargetParents.push_back(CommonAncestor);
726 NestedNameSpecifier *Result = nullptr;
727 while (!TargetParents.empty()) {
728 const DeclContext *Parent = TargetParents.pop_back_val();
730 if (const auto *Namespace = dyn_cast<NamespaceDecl>(Parent)) {
731 if (!Namespace->getIdentifier())
734 Result = NestedNameSpecifier::Create(Context, Result, Namespace);
735 } else if (const auto *TD = dyn_cast<TagDecl>(Parent))
736 Result = NestedNameSpecifier::Create(
737 Context, Result, false, Context.getTypeDeclType(TD).getTypePtr());
742 // Some declarations have reserved names that we don't want to ever show.
743 // Filter out names reserved for the implementation if they come from a
745 static bool shouldIgnoreDueToReservedName(const NamedDecl *ND, Sema &SemaRef) {
746 ReservedIdentifierStatus Status = ND->isReserved(SemaRef.getLangOpts());
747 // Ignore reserved names for compiler provided decls.
748 if (isReservedInAllContexts(Status) && ND->getLocation().isInvalid())
751 // For system headers ignore only double-underscore names.
752 // This allows for system headers providing private symbols with a single
754 if (Status == ReservedIdentifierStatus::StartsWithDoubleUnderscore &&
755 SemaRef.SourceMgr.isInSystemHeader(
756 SemaRef.SourceMgr.getSpellingLoc(ND->getLocation())))
762 bool ResultBuilder::isInterestingDecl(const NamedDecl *ND,
763 bool &AsNestedNameSpecifier) const {
764 AsNestedNameSpecifier = false;
767 ND = ND->getUnderlyingDecl();
769 // Skip unnamed entities.
770 if (!ND->getDeclName())
773 // Friend declarations and declarations introduced due to friends are never
775 if (ND->getFriendObjectKind() == Decl::FOK_Undeclared)
778 // Class template (partial) specializations are never added as results.
779 if (isa<ClassTemplateSpecializationDecl>(ND) ||
780 isa<ClassTemplatePartialSpecializationDecl>(ND))
783 // Using declarations themselves are never added as results.
784 if (isa<UsingDecl>(ND))
787 if (shouldIgnoreDueToReservedName(ND, SemaRef))
790 if (Filter == &ResultBuilder::IsNestedNameSpecifier ||
791 (isa<NamespaceDecl>(ND) && Filter != &ResultBuilder::IsNamespace &&
792 Filter != &ResultBuilder::IsNamespaceOrAlias && Filter != nullptr))
793 AsNestedNameSpecifier = true;
795 // Filter out any unwanted results.
796 if (Filter && !(this->*Filter)(Named)) {
797 // Check whether it is interesting as a nested-name-specifier.
798 if (AllowNestedNameSpecifiers && SemaRef.getLangOpts().CPlusPlus &&
799 IsNestedNameSpecifier(ND) &&
800 (Filter != &ResultBuilder::IsMember ||
801 (isa<CXXRecordDecl>(ND) &&
802 cast<CXXRecordDecl>(ND)->isInjectedClassName()))) {
803 AsNestedNameSpecifier = true;
809 // ... then it must be interesting!
813 bool ResultBuilder::CheckHiddenResult(Result &R, DeclContext *CurContext,
814 const NamedDecl *Hiding) {
815 // In C, there is no way to refer to a hidden name.
816 // FIXME: This isn't true; we can find a tag name hidden by an ordinary
817 // name if we introduce the tag type.
818 if (!SemaRef.getLangOpts().CPlusPlus)
821 const DeclContext *HiddenCtx =
822 R.Declaration->getDeclContext()->getRedeclContext();
824 // There is no way to qualify a name declared in a function or method.
825 if (HiddenCtx->isFunctionOrMethod())
828 if (HiddenCtx == Hiding->getDeclContext()->getRedeclContext())
831 // We can refer to the result with the appropriate qualification. Do it.
833 R.QualifierIsInformative = false;
836 R.Qualifier = getRequiredQualification(SemaRef.Context, CurContext,
837 R.Declaration->getDeclContext());
841 /// A simplified classification of types used to determine whether two
842 /// types are "similar enough" when adjusting priorities.
843 SimplifiedTypeClass clang::getSimplifiedTypeClass(CanQualType T) {
844 switch (T->getTypeClass()) {
846 switch (cast<BuiltinType>(T)->getKind()) {
847 case BuiltinType::Void:
850 case BuiltinType::NullPtr:
853 case BuiltinType::Overload:
854 case BuiltinType::Dependent:
857 case BuiltinType::ObjCId:
858 case BuiltinType::ObjCClass:
859 case BuiltinType::ObjCSel:
860 return STC_ObjectiveC;
863 return STC_Arithmetic;
867 return STC_Arithmetic;
872 case Type::BlockPointer:
875 case Type::LValueReference:
876 case Type::RValueReference:
877 return getSimplifiedTypeClass(T->getAs<ReferenceType>()->getPointeeType());
879 case Type::ConstantArray:
880 case Type::IncompleteArray:
881 case Type::VariableArray:
882 case Type::DependentSizedArray:
885 case Type::DependentSizedExtVector:
887 case Type::ExtVector:
888 return STC_Arithmetic;
890 case Type::FunctionProto:
891 case Type::FunctionNoProto:
898 return STC_Arithmetic;
900 case Type::ObjCObject:
901 case Type::ObjCInterface:
902 case Type::ObjCObjectPointer:
903 return STC_ObjectiveC;
910 /// Get the type that a given expression will have if this declaration
911 /// is used as an expression in its "typical" code-completion form.
912 QualType clang::getDeclUsageType(ASTContext &C, const NamedDecl *ND) {
913 ND = ND->getUnderlyingDecl();
915 if (const auto *Type = dyn_cast<TypeDecl>(ND))
916 return C.getTypeDeclType(Type);
917 if (const auto *Iface = dyn_cast<ObjCInterfaceDecl>(ND))
918 return C.getObjCInterfaceType(Iface);
921 if (const FunctionDecl *Function = ND->getAsFunction())
922 T = Function->getCallResultType();
923 else if (const auto *Method = dyn_cast<ObjCMethodDecl>(ND))
924 T = Method->getSendResultType();
925 else if (const auto *Enumerator = dyn_cast<EnumConstantDecl>(ND))
926 T = C.getTypeDeclType(cast<EnumDecl>(Enumerator->getDeclContext()));
927 else if (const auto *Property = dyn_cast<ObjCPropertyDecl>(ND))
928 T = Property->getType();
929 else if (const auto *Value = dyn_cast<ValueDecl>(ND))
930 T = Value->getType();
935 // Dig through references, function pointers, and block pointers to
936 // get down to the likely type of an expression when the entity is
939 if (const auto *Ref = T->getAs<ReferenceType>()) {
940 T = Ref->getPointeeType();
944 if (const auto *Pointer = T->getAs<PointerType>()) {
945 if (Pointer->getPointeeType()->isFunctionType()) {
946 T = Pointer->getPointeeType();
953 if (const auto *Block = T->getAs<BlockPointerType>()) {
954 T = Block->getPointeeType();
958 if (const auto *Function = T->getAs<FunctionType>()) {
959 T = Function->getReturnType();
969 unsigned ResultBuilder::getBasePriority(const NamedDecl *ND) {
973 // Context-based decisions.
974 const DeclContext *LexicalDC = ND->getLexicalDeclContext();
975 if (LexicalDC->isFunctionOrMethod()) {
976 // _cmd is relatively rare
977 if (const auto *ImplicitParam = dyn_cast<ImplicitParamDecl>(ND))
978 if (ImplicitParam->getIdentifier() &&
979 ImplicitParam->getIdentifier()->isStr("_cmd"))
982 return CCP_LocalDeclaration;
985 const DeclContext *DC = ND->getDeclContext()->getRedeclContext();
986 if (DC->isRecord() || isa<ObjCContainerDecl>(DC)) {
987 // Explicit destructor calls are very rare.
988 if (isa<CXXDestructorDecl>(ND))
990 // Explicit operator and conversion function calls are also very rare.
991 auto DeclNameKind = ND->getDeclName().getNameKind();
992 if (DeclNameKind == DeclarationName::CXXOperatorName ||
993 DeclNameKind == DeclarationName::CXXLiteralOperatorName ||
994 DeclNameKind == DeclarationName::CXXConversionFunctionName)
996 return CCP_MemberDeclaration;
999 // Content-based decisions.
1000 if (isa<EnumConstantDecl>(ND))
1001 return CCP_Constant;
1003 // Use CCP_Type for type declarations unless we're in a statement, Objective-C
1004 // message receiver, or parenthesized expression context. There, it's as
1005 // likely that the user will want to write a type as other declarations.
1006 if ((isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) &&
1007 !(CompletionContext.getKind() == CodeCompletionContext::CCC_Statement ||
1008 CompletionContext.getKind() ==
1009 CodeCompletionContext::CCC_ObjCMessageReceiver ||
1010 CompletionContext.getKind() ==
1011 CodeCompletionContext::CCC_ParenthesizedExpression))
1014 return CCP_Declaration;
1017 void ResultBuilder::AdjustResultPriorityForDecl(Result &R) {
1018 // If this is an Objective-C method declaration whose selector matches our
1019 // preferred selector, give it a priority boost.
1020 if (!PreferredSelector.isNull())
1021 if (const auto *Method = dyn_cast<ObjCMethodDecl>(R.Declaration))
1022 if (PreferredSelector == Method->getSelector())
1023 R.Priority += CCD_SelectorMatch;
1025 // If we have a preferred type, adjust the priority for results with exactly-
1026 // matching or nearly-matching types.
1027 if (!PreferredType.isNull()) {
1028 QualType T = getDeclUsageType(SemaRef.Context, R.Declaration);
1030 CanQualType TC = SemaRef.Context.getCanonicalType(T);
1031 // Check for exactly-matching types (modulo qualifiers).
1032 if (SemaRef.Context.hasSameUnqualifiedType(PreferredType, TC))
1033 R.Priority /= CCF_ExactTypeMatch;
1034 // Check for nearly-matching types, based on classification of each.
1035 else if ((getSimplifiedTypeClass(PreferredType) ==
1036 getSimplifiedTypeClass(TC)) &&
1037 !(PreferredType->isEnumeralType() && TC->isEnumeralType()))
1038 R.Priority /= CCF_SimilarTypeMatch;
1043 static DeclContext::lookup_result getConstructors(ASTContext &Context,
1044 const CXXRecordDecl *Record) {
1045 QualType RecordTy = Context.getTypeDeclType(Record);
1046 DeclarationName ConstructorName =
1047 Context.DeclarationNames.getCXXConstructorName(
1048 Context.getCanonicalType(RecordTy));
1049 return Record->lookup(ConstructorName);
1052 void ResultBuilder::MaybeAddConstructorResults(Result R) {
1053 if (!SemaRef.getLangOpts().CPlusPlus || !R.Declaration ||
1054 !CompletionContext.wantConstructorResults())
1057 const NamedDecl *D = R.Declaration;
1058 const CXXRecordDecl *Record = nullptr;
1059 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D))
1060 Record = ClassTemplate->getTemplatedDecl();
1061 else if ((Record = dyn_cast<CXXRecordDecl>(D))) {
1062 // Skip specializations and partial specializations.
1063 if (isa<ClassTemplateSpecializationDecl>(Record))
1066 // There are no constructors here.
1070 Record = Record->getDefinition();
1074 for (NamedDecl *Ctor : getConstructors(SemaRef.Context, Record)) {
1075 R.Declaration = Ctor;
1076 R.CursorKind = getCursorKindForDecl(R.Declaration);
1077 Results.push_back(R);
1081 static bool isConstructor(const Decl *ND) {
1082 if (const auto *Tmpl = dyn_cast<FunctionTemplateDecl>(ND))
1083 ND = Tmpl->getTemplatedDecl();
1084 return isa<CXXConstructorDecl>(ND);
1087 void ResultBuilder::MaybeAddResult(Result R, DeclContext *CurContext) {
1088 assert(!ShadowMaps.empty() && "Must enter into a results scope");
1090 if (R.Kind != Result::RK_Declaration) {
1091 // For non-declaration results, just add the result.
1092 Results.push_back(R);
1096 // Look through using declarations.
1097 if (const UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
1098 CodeCompletionResult Result(Using->getTargetDecl(),
1099 getBasePriority(Using->getTargetDecl()),
1101 (R.Availability == CXAvailability_Available ||
1102 R.Availability == CXAvailability_Deprecated),
1103 std::move(R.FixIts));
1104 Result.ShadowDecl = Using;
1105 MaybeAddResult(Result, CurContext);
1109 const Decl *CanonDecl = R.Declaration->getCanonicalDecl();
1110 unsigned IDNS = CanonDecl->getIdentifierNamespace();
1112 bool AsNestedNameSpecifier = false;
1113 if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
1116 // C++ constructors are never found by name lookup.
1117 if (isConstructor(R.Declaration))
1120 ShadowMap &SMap = ShadowMaps.back();
1121 ShadowMapEntry::iterator I, IEnd;
1122 ShadowMap::iterator NamePos = SMap.find(R.Declaration->getDeclName());
1123 if (NamePos != SMap.end()) {
1124 I = NamePos->second.begin();
1125 IEnd = NamePos->second.end();
1128 for (; I != IEnd; ++I) {
1129 const NamedDecl *ND = I->first;
1130 unsigned Index = I->second;
1131 if (ND->getCanonicalDecl() == CanonDecl) {
1132 // This is a redeclaration. Always pick the newer declaration.
1133 Results[Index].Declaration = R.Declaration;
1140 // This is a new declaration in this scope. However, check whether this
1141 // declaration name is hidden by a similarly-named declaration in an outer
1143 std::list<ShadowMap>::iterator SM, SMEnd = ShadowMaps.end();
1145 for (SM = ShadowMaps.begin(); SM != SMEnd; ++SM) {
1146 ShadowMapEntry::iterator I, IEnd;
1147 ShadowMap::iterator NamePos = SM->find(R.Declaration->getDeclName());
1148 if (NamePos != SM->end()) {
1149 I = NamePos->second.begin();
1150 IEnd = NamePos->second.end();
1152 for (; I != IEnd; ++I) {
1153 // A tag declaration does not hide a non-tag declaration.
1154 if (I->first->hasTagIdentifierNamespace() &&
1155 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
1156 Decl::IDNS_LocalExtern | Decl::IDNS_ObjCProtocol)))
1159 // Protocols are in distinct namespaces from everything else.
1160 if (((I->first->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol) ||
1161 (IDNS & Decl::IDNS_ObjCProtocol)) &&
1162 I->first->getIdentifierNamespace() != IDNS)
1165 // The newly-added result is hidden by an entry in the shadow map.
1166 if (CheckHiddenResult(R, CurContext, I->first))
1173 // Make sure that any given declaration only shows up in the result set once.
1174 if (!AllDeclsFound.insert(CanonDecl).second)
1177 // If the filter is for nested-name-specifiers, then this result starts a
1178 // nested-name-specifier.
1179 if (AsNestedNameSpecifier) {
1180 R.StartsNestedNameSpecifier = true;
1181 R.Priority = CCP_NestedNameSpecifier;
1183 AdjustResultPriorityForDecl(R);
1185 // If this result is supposed to have an informative qualifier, add one.
1186 if (R.QualifierIsInformative && !R.Qualifier &&
1187 !R.StartsNestedNameSpecifier) {
1188 const DeclContext *Ctx = R.Declaration->getDeclContext();
1189 if (const NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
1191 NestedNameSpecifier::Create(SemaRef.Context, nullptr, Namespace);
1192 else if (const TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
1193 R.Qualifier = NestedNameSpecifier::Create(
1194 SemaRef.Context, nullptr, false,
1195 SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
1197 R.QualifierIsInformative = false;
1200 // Insert this result into the set of results and into the current shadow
1202 SMap[R.Declaration->getDeclName()].Add(R.Declaration, Results.size());
1203 Results.push_back(R);
1205 if (!AsNestedNameSpecifier)
1206 MaybeAddConstructorResults(R);
1209 static void setInBaseClass(ResultBuilder::Result &R) {
1210 R.Priority += CCD_InBaseClass;
1211 R.InBaseClass = true;
1214 enum class OverloadCompare { BothViable, Dominates, Dominated };
1215 // Will Candidate ever be called on the object, when overloaded with Incumbent?
1216 // Returns Dominates if Candidate is always called, Dominated if Incumbent is
1217 // always called, BothViable if either may be called depending on arguments.
1218 // Precondition: must actually be overloads!
1219 static OverloadCompare compareOverloads(const CXXMethodDecl &Candidate,
1220 const CXXMethodDecl &Incumbent,
1221 const Qualifiers &ObjectQuals,
1222 ExprValueKind ObjectKind) {
1223 // Base/derived shadowing is handled elsewhere.
1224 if (Candidate.getDeclContext() != Incumbent.getDeclContext())
1225 return OverloadCompare::BothViable;
1226 if (Candidate.isVariadic() != Incumbent.isVariadic() ||
1227 Candidate.getNumParams() != Incumbent.getNumParams() ||
1228 Candidate.getMinRequiredArguments() !=
1229 Incumbent.getMinRequiredArguments())
1230 return OverloadCompare::BothViable;
1231 for (unsigned I = 0, E = Candidate.getNumParams(); I != E; ++I)
1232 if (Candidate.parameters()[I]->getType().getCanonicalType() !=
1233 Incumbent.parameters()[I]->getType().getCanonicalType())
1234 return OverloadCompare::BothViable;
1235 if (!Candidate.specific_attrs<EnableIfAttr>().empty() ||
1236 !Incumbent.specific_attrs<EnableIfAttr>().empty())
1237 return OverloadCompare::BothViable;
1238 // At this point, we know calls can't pick one or the other based on
1239 // arguments, so one of the two must win. (Or both fail, handled elsewhere).
1240 RefQualifierKind CandidateRef = Candidate.getRefQualifier();
1241 RefQualifierKind IncumbentRef = Incumbent.getRefQualifier();
1242 if (CandidateRef != IncumbentRef) {
1243 // If the object kind is LValue/RValue, there's one acceptable ref-qualifier
1244 // and it can't be mixed with ref-unqualified overloads (in valid code).
1246 // For xvalue objects, we prefer the rvalue overload even if we have to
1247 // add qualifiers (which is rare, because const&& is rare).
1248 if (ObjectKind == clang::VK_XValue)
1249 return CandidateRef == RQ_RValue ? OverloadCompare::Dominates
1250 : OverloadCompare::Dominated;
1252 // Now the ref qualifiers are the same (or we're in some invalid state).
1253 // So make some decision based on the qualifiers.
1254 Qualifiers CandidateQual = Candidate.getMethodQualifiers();
1255 Qualifiers IncumbentQual = Incumbent.getMethodQualifiers();
1256 bool CandidateSuperset = CandidateQual.compatiblyIncludes(IncumbentQual);
1257 bool IncumbentSuperset = IncumbentQual.compatiblyIncludes(CandidateQual);
1258 if (CandidateSuperset == IncumbentSuperset)
1259 return OverloadCompare::BothViable;
1260 return IncumbentSuperset ? OverloadCompare::Dominates
1261 : OverloadCompare::Dominated;
1264 void ResultBuilder::AddResult(Result R, DeclContext *CurContext,
1265 NamedDecl *Hiding, bool InBaseClass = false) {
1266 if (R.Kind != Result::RK_Declaration) {
1267 // For non-declaration results, just add the result.
1268 Results.push_back(R);
1272 // Look through using declarations.
1273 if (const auto *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
1274 CodeCompletionResult Result(Using->getTargetDecl(),
1275 getBasePriority(Using->getTargetDecl()),
1277 (R.Availability == CXAvailability_Available ||
1278 R.Availability == CXAvailability_Deprecated),
1279 std::move(R.FixIts));
1280 Result.ShadowDecl = Using;
1281 AddResult(Result, CurContext, Hiding);
1285 bool AsNestedNameSpecifier = false;
1286 if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
1289 // C++ constructors are never found by name lookup.
1290 if (isConstructor(R.Declaration))
1293 if (Hiding && CheckHiddenResult(R, CurContext, Hiding))
1296 // Make sure that any given declaration only shows up in the result set once.
1297 if (!AllDeclsFound.insert(R.Declaration->getCanonicalDecl()).second)
1300 // If the filter is for nested-name-specifiers, then this result starts a
1301 // nested-name-specifier.
1302 if (AsNestedNameSpecifier) {
1303 R.StartsNestedNameSpecifier = true;
1304 R.Priority = CCP_NestedNameSpecifier;
1305 } else if (Filter == &ResultBuilder::IsMember && !R.Qualifier &&
1308 R.Declaration->getDeclContext()->getRedeclContext()))
1309 R.QualifierIsInformative = true;
1311 // If this result is supposed to have an informative qualifier, add one.
1312 if (R.QualifierIsInformative && !R.Qualifier &&
1313 !R.StartsNestedNameSpecifier) {
1314 const DeclContext *Ctx = R.Declaration->getDeclContext();
1315 if (const auto *Namespace = dyn_cast<NamespaceDecl>(Ctx))
1317 NestedNameSpecifier::Create(SemaRef.Context, nullptr, Namespace);
1318 else if (const auto *Tag = dyn_cast<TagDecl>(Ctx))
1319 R.Qualifier = NestedNameSpecifier::Create(
1320 SemaRef.Context, nullptr, false,
1321 SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
1323 R.QualifierIsInformative = false;
1326 // Adjust the priority if this result comes from a base class.
1330 AdjustResultPriorityForDecl(R);
1332 if (HasObjectTypeQualifiers)
1333 if (const auto *Method = dyn_cast<CXXMethodDecl>(R.Declaration))
1334 if (Method->isInstance()) {
1335 Qualifiers MethodQuals = Method->getMethodQualifiers();
1336 if (ObjectTypeQualifiers == MethodQuals)
1337 R.Priority += CCD_ObjectQualifierMatch;
1338 else if (ObjectTypeQualifiers - MethodQuals) {
1339 // The method cannot be invoked, because doing so would drop
1343 // Detect cases where a ref-qualified method cannot be invoked.
1344 switch (Method->getRefQualifier()) {
1346 if (ObjectKind != VK_LValue && !MethodQuals.hasConst())
1350 if (ObjectKind == VK_LValue)
1357 /// Check whether this dominates another overloaded method, which should
1358 /// be suppressed (or vice versa).
1359 /// Motivating case is const_iterator begin() const vs iterator begin().
1360 auto &OverloadSet = OverloadMap[std::make_pair(
1361 CurContext, Method->getDeclName().getAsOpaqueInteger())];
1362 for (const DeclIndexPair Entry : OverloadSet) {
1363 Result &Incumbent = Results[Entry.second];
1364 switch (compareOverloads(*Method,
1365 *cast<CXXMethodDecl>(Incumbent.Declaration),
1366 ObjectTypeQualifiers, ObjectKind)) {
1367 case OverloadCompare::Dominates:
1368 // Replace the dominated overload with this one.
1369 // FIXME: if the overload dominates multiple incumbents then we
1370 // should remove all. But two overloads is by far the common case.
1371 Incumbent = std::move(R);
1373 case OverloadCompare::Dominated:
1374 // This overload can't be called, drop it.
1376 case OverloadCompare::BothViable:
1380 OverloadSet.Add(Method, Results.size());
1383 // When completing a non-static member function (and not via
1384 // dot/arrow member access) and we're not inside that class' scope,
1385 // it can't be a call.
1386 if (CompletionContext.getKind() == clang::CodeCompletionContext::CCC_Symbol) {
1387 const auto *Method = dyn_cast<CXXMethodDecl>(R.getDeclaration());
1388 if (Method && !Method->isStatic()) {
1389 // Find the class scope that we're currently in.
1390 // We could e.g. be inside a lambda, so walk up the DeclContext until we
1391 // find a CXXMethodDecl.
1392 const auto *CurrentClassScope = [&]() -> const CXXRecordDecl * {
1393 for (DeclContext *Ctx = SemaRef.CurContext; Ctx;
1394 Ctx = Ctx->getParent()) {
1395 const auto *CtxMethod = llvm::dyn_cast<CXXMethodDecl>(Ctx);
1396 if (CtxMethod && !CtxMethod->getParent()->isLambda()) {
1397 return CtxMethod->getParent();
1403 R.FunctionCanBeCall =
1404 CurrentClassScope &&
1405 (CurrentClassScope == Method->getParent() ||
1406 CurrentClassScope->isDerivedFrom(Method->getParent()));
1410 // Insert this result into the set of results.
1411 Results.push_back(R);
1413 if (!AsNestedNameSpecifier)
1414 MaybeAddConstructorResults(R);
1417 void ResultBuilder::AddResult(Result R) {
1418 assert(R.Kind != Result::RK_Declaration &&
1419 "Declaration results need more context");
1420 Results.push_back(R);
1423 /// Enter into a new scope.
1424 void ResultBuilder::EnterNewScope() { ShadowMaps.emplace_back(); }
1426 /// Exit from the current scope.
1427 void ResultBuilder::ExitScope() {
1428 ShadowMaps.pop_back();
1431 /// Determines whether this given declaration will be found by
1432 /// ordinary name lookup.
1433 bool ResultBuilder::IsOrdinaryName(const NamedDecl *ND) const {
1434 ND = ND->getUnderlyingDecl();
1436 // If name lookup finds a local extern declaration, then we are in a
1437 // context where it behaves like an ordinary name.
1438 unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_LocalExtern;
1439 if (SemaRef.getLangOpts().CPlusPlus)
1440 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
1441 else if (SemaRef.getLangOpts().ObjC) {
1442 if (isa<ObjCIvarDecl>(ND))
1446 return ND->getIdentifierNamespace() & IDNS;
1449 /// Determines whether this given declaration will be found by
1450 /// ordinary name lookup but is not a type name.
1451 bool ResultBuilder::IsOrdinaryNonTypeName(const NamedDecl *ND) const {
1452 ND = ND->getUnderlyingDecl();
1453 if (isa<TypeDecl>(ND))
1455 // Objective-C interfaces names are not filtered by this method because they
1456 // can be used in a class property expression. We can still filter out
1457 // @class declarations though.
1458 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND)) {
1459 if (!ID->getDefinition())
1463 unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_LocalExtern;
1464 if (SemaRef.getLangOpts().CPlusPlus)
1465 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
1466 else if (SemaRef.getLangOpts().ObjC) {
1467 if (isa<ObjCIvarDecl>(ND))
1471 return ND->getIdentifierNamespace() & IDNS;
1474 bool ResultBuilder::IsIntegralConstantValue(const NamedDecl *ND) const {
1475 if (!IsOrdinaryNonTypeName(ND))
1478 if (const auto *VD = dyn_cast<ValueDecl>(ND->getUnderlyingDecl()))
1479 if (VD->getType()->isIntegralOrEnumerationType())
1485 /// Determines whether this given declaration will be found by
1486 /// ordinary name lookup.
1487 bool ResultBuilder::IsOrdinaryNonValueName(const NamedDecl *ND) const {
1488 ND = ND->getUnderlyingDecl();
1490 unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_LocalExtern;
1491 if (SemaRef.getLangOpts().CPlusPlus)
1492 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace;
1494 return (ND->getIdentifierNamespace() & IDNS) && !isa<ValueDecl>(ND) &&
1495 !isa<FunctionTemplateDecl>(ND) && !isa<ObjCPropertyDecl>(ND);
1498 /// Determines whether the given declaration is suitable as the
1499 /// start of a C++ nested-name-specifier, e.g., a class or namespace.
1500 bool ResultBuilder::IsNestedNameSpecifier(const NamedDecl *ND) const {
1501 // Allow us to find class templates, too.
1502 if (const auto *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
1503 ND = ClassTemplate->getTemplatedDecl();
1505 return SemaRef.isAcceptableNestedNameSpecifier(ND);
1508 /// Determines whether the given declaration is an enumeration.
1509 bool ResultBuilder::IsEnum(const NamedDecl *ND) const {
1510 return isa<EnumDecl>(ND);
1513 /// Determines whether the given declaration is a class or struct.
1514 bool ResultBuilder::IsClassOrStruct(const NamedDecl *ND) const {
1515 // Allow us to find class templates, too.
1516 if (const auto *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
1517 ND = ClassTemplate->getTemplatedDecl();
1519 // For purposes of this check, interfaces match too.
1520 if (const auto *RD = dyn_cast<RecordDecl>(ND))
1521 return RD->getTagKind() == TTK_Class || RD->getTagKind() == TTK_Struct ||
1522 RD->getTagKind() == TTK_Interface;
1527 /// Determines whether the given declaration is a union.
1528 bool ResultBuilder::IsUnion(const NamedDecl *ND) const {
1529 // Allow us to find class templates, too.
1530 if (const auto *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
1531 ND = ClassTemplate->getTemplatedDecl();
1533 if (const auto *RD = dyn_cast<RecordDecl>(ND))
1534 return RD->getTagKind() == TTK_Union;
1539 /// Determines whether the given declaration is a namespace.
1540 bool ResultBuilder::IsNamespace(const NamedDecl *ND) const {
1541 return isa<NamespaceDecl>(ND);
1544 /// Determines whether the given declaration is a namespace or
1545 /// namespace alias.
1546 bool ResultBuilder::IsNamespaceOrAlias(const NamedDecl *ND) const {
1547 return isa<NamespaceDecl>(ND->getUnderlyingDecl());
1550 /// Determines whether the given declaration is a type.
1551 bool ResultBuilder::IsType(const NamedDecl *ND) const {
1552 ND = ND->getUnderlyingDecl();
1553 return isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
1556 /// Determines which members of a class should be visible via
1557 /// "." or "->". Only value declarations, nested name specifiers, and
1558 /// using declarations thereof should show up.
1559 bool ResultBuilder::IsMember(const NamedDecl *ND) const {
1560 ND = ND->getUnderlyingDecl();
1561 return isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND) ||
1562 isa<ObjCPropertyDecl>(ND);
1565 static bool isObjCReceiverType(ASTContext &C, QualType T) {
1566 T = C.getCanonicalType(T);
1567 switch (T->getTypeClass()) {
1568 case Type::ObjCObject:
1569 case Type::ObjCInterface:
1570 case Type::ObjCObjectPointer:
1574 switch (cast<BuiltinType>(T)->getKind()) {
1575 case BuiltinType::ObjCId:
1576 case BuiltinType::ObjCClass:
1577 case BuiltinType::ObjCSel:
1589 if (!C.getLangOpts().CPlusPlus)
1592 // FIXME: We could perform more analysis here to determine whether a
1593 // particular class type has any conversions to Objective-C types. For now,
1594 // just accept all class types.
1595 return T->isDependentType() || T->isRecordType();
1598 bool ResultBuilder::IsObjCMessageReceiver(const NamedDecl *ND) const {
1599 QualType T = getDeclUsageType(SemaRef.Context, ND);
1603 T = SemaRef.Context.getBaseElementType(T);
1604 return isObjCReceiverType(SemaRef.Context, T);
1607 bool ResultBuilder::IsObjCMessageReceiverOrLambdaCapture(
1608 const NamedDecl *ND) const {
1609 if (IsObjCMessageReceiver(ND))
1612 const auto *Var = dyn_cast<VarDecl>(ND);
1616 return Var->hasLocalStorage() && !Var->hasAttr<BlocksAttr>();
1619 bool ResultBuilder::IsObjCCollection(const NamedDecl *ND) const {
1620 if ((SemaRef.getLangOpts().CPlusPlus && !IsOrdinaryName(ND)) ||
1621 (!SemaRef.getLangOpts().CPlusPlus && !IsOrdinaryNonTypeName(ND)))
1624 QualType T = getDeclUsageType(SemaRef.Context, ND);
1628 T = SemaRef.Context.getBaseElementType(T);
1629 return T->isObjCObjectType() || T->isObjCObjectPointerType() ||
1630 T->isObjCIdType() ||
1631 (SemaRef.getLangOpts().CPlusPlus && T->isRecordType());
1634 bool ResultBuilder::IsImpossibleToSatisfy(const NamedDecl *ND) const {
1638 /// Determines whether the given declaration is an Objective-C
1639 /// instance variable.
1640 bool ResultBuilder::IsObjCIvar(const NamedDecl *ND) const {
1641 return isa<ObjCIvarDecl>(ND);
1646 /// Visible declaration consumer that adds a code-completion result
1647 /// for each visible declaration.
1648 class CodeCompletionDeclConsumer : public VisibleDeclConsumer {
1649 ResultBuilder &Results;
1650 DeclContext *InitialLookupCtx;
1651 // NamingClass and BaseType are used for access-checking. See
1652 // Sema::IsSimplyAccessible for details.
1653 CXXRecordDecl *NamingClass;
1655 std::vector<FixItHint> FixIts;
1658 CodeCompletionDeclConsumer(
1659 ResultBuilder &Results, DeclContext *InitialLookupCtx,
1660 QualType BaseType = QualType(),
1661 std::vector<FixItHint> FixIts = std::vector<FixItHint>())
1662 : Results(Results), InitialLookupCtx(InitialLookupCtx),
1663 FixIts(std::move(FixIts)) {
1664 NamingClass = llvm::dyn_cast<CXXRecordDecl>(InitialLookupCtx);
1665 // If BaseType was not provided explicitly, emulate implicit 'this->'.
1666 if (BaseType.isNull()) {
1667 auto ThisType = Results.getSema().getCurrentThisType();
1668 if (!ThisType.isNull()) {
1669 assert(ThisType->isPointerType());
1670 BaseType = ThisType->getPointeeType();
1672 NamingClass = BaseType->getAsCXXRecordDecl();
1675 this->BaseType = BaseType;
1678 void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
1679 bool InBaseClass) override {
1680 ResultBuilder::Result Result(ND, Results.getBasePriority(ND), nullptr,
1681 false, IsAccessible(ND, Ctx), FixIts);
1682 Results.AddResult(Result, InitialLookupCtx, Hiding, InBaseClass);
1685 void EnteredContext(DeclContext *Ctx) override {
1686 Results.addVisitedContext(Ctx);
1690 bool IsAccessible(NamedDecl *ND, DeclContext *Ctx) {
1691 // Naming class to use for access check. In most cases it was provided
1692 // explicitly (e.g. member access (lhs.foo) or qualified lookup (X::)),
1693 // for unqualified lookup we fallback to the \p Ctx in which we found the
1695 auto *NamingClass = this->NamingClass;
1696 QualType BaseType = this->BaseType;
1697 if (auto *Cls = llvm::dyn_cast_or_null<CXXRecordDecl>(Ctx)) {
1700 // When we emulate implicit 'this->' in an unqualified lookup, we might
1701 // end up with an invalid naming class. In that case, we avoid emulating
1702 // 'this->' qualifier to satisfy preconditions of the access checking.
1703 if (NamingClass->getCanonicalDecl() != Cls->getCanonicalDecl() &&
1704 !NamingClass->isDerivedFrom(Cls)) {
1706 BaseType = QualType();
1709 // The decl was found outside the C++ class, so only ObjC access checks
1710 // apply. Those do not rely on NamingClass and BaseType, so we clear them
1712 NamingClass = nullptr;
1713 BaseType = QualType();
1715 return Results.getSema().IsSimplyAccessible(ND, NamingClass, BaseType);
1720 /// Add type specifiers for the current language as keyword results.
1721 static void AddTypeSpecifierResults(const LangOptions &LangOpts,
1722 ResultBuilder &Results) {
1723 typedef CodeCompletionResult Result;
1724 Results.AddResult(Result("short", CCP_Type));
1725 Results.AddResult(Result("long", CCP_Type));
1726 Results.AddResult(Result("signed", CCP_Type));
1727 Results.AddResult(Result("unsigned", CCP_Type));
1728 Results.AddResult(Result("void", CCP_Type));
1729 Results.AddResult(Result("char", CCP_Type));
1730 Results.AddResult(Result("int", CCP_Type));
1731 Results.AddResult(Result("float", CCP_Type));
1732 Results.AddResult(Result("double", CCP_Type));
1733 Results.AddResult(Result("enum", CCP_Type));
1734 Results.AddResult(Result("struct", CCP_Type));
1735 Results.AddResult(Result("union", CCP_Type));
1736 Results.AddResult(Result("const", CCP_Type));
1737 Results.AddResult(Result("volatile", CCP_Type));
1741 Results.AddResult(Result("_Complex", CCP_Type));
1742 Results.AddResult(Result("_Imaginary", CCP_Type));
1743 Results.AddResult(Result("_Bool", CCP_Type));
1744 Results.AddResult(Result("restrict", CCP_Type));
1747 CodeCompletionBuilder Builder(Results.getAllocator(),
1748 Results.getCodeCompletionTUInfo());
1749 if (LangOpts.CPlusPlus) {
1752 Result("bool", CCP_Type + (LangOpts.ObjC ? CCD_bool_in_ObjC : 0)));
1753 Results.AddResult(Result("class", CCP_Type));
1754 Results.AddResult(Result("wchar_t", CCP_Type));
1757 Builder.AddTypedTextChunk("typename");
1758 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1759 Builder.AddPlaceholderChunk("name");
1760 Results.AddResult(Result(Builder.TakeString()));
1762 if (LangOpts.CPlusPlus11) {
1763 Results.AddResult(Result("auto", CCP_Type));
1764 Results.AddResult(Result("char16_t", CCP_Type));
1765 Results.AddResult(Result("char32_t", CCP_Type));
1767 Builder.AddTypedTextChunk("decltype");
1768 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1769 Builder.AddPlaceholderChunk("expression");
1770 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1771 Results.AddResult(Result(Builder.TakeString()));
1774 Results.AddResult(Result("__auto_type", CCP_Type));
1777 if (LangOpts.GNUKeywords) {
1778 // FIXME: Enable when we actually support decimal floating point.
1779 // Results.AddResult(Result("_Decimal32"));
1780 // Results.AddResult(Result("_Decimal64"));
1781 // Results.AddResult(Result("_Decimal128"));
1783 Builder.AddTypedTextChunk("typeof");
1784 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1785 Builder.AddPlaceholderChunk("expression");
1786 Results.AddResult(Result(Builder.TakeString()));
1788 Builder.AddTypedTextChunk("typeof");
1789 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1790 Builder.AddPlaceholderChunk("type");
1791 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1792 Results.AddResult(Result(Builder.TakeString()));
1796 Results.AddResult(Result("_Nonnull", CCP_Type));
1797 Results.AddResult(Result("_Null_unspecified", CCP_Type));
1798 Results.AddResult(Result("_Nullable", CCP_Type));
1801 static void AddStorageSpecifiers(Sema::ParserCompletionContext CCC,
1802 const LangOptions &LangOpts,
1803 ResultBuilder &Results) {
1804 typedef CodeCompletionResult Result;
1805 // Note: we don't suggest either "auto" or "register", because both
1806 // are pointless as storage specifiers. Elsewhere, we suggest "auto"
1807 // in C++0x as a type specifier.
1808 Results.AddResult(Result("extern"));
1809 Results.AddResult(Result("static"));
1811 if (LangOpts.CPlusPlus11) {
1812 CodeCompletionAllocator &Allocator = Results.getAllocator();
1813 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
1816 Builder.AddTypedTextChunk("alignas");
1817 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1818 Builder.AddPlaceholderChunk("expression");
1819 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1820 Results.AddResult(Result(Builder.TakeString()));
1822 Results.AddResult(Result("constexpr"));
1823 Results.AddResult(Result("thread_local"));
1827 static void AddFunctionSpecifiers(Sema::ParserCompletionContext CCC,
1828 const LangOptions &LangOpts,
1829 ResultBuilder &Results) {
1830 typedef CodeCompletionResult Result;
1832 case Sema::PCC_Class:
1833 case Sema::PCC_MemberTemplate:
1834 if (LangOpts.CPlusPlus) {
1835 Results.AddResult(Result("explicit"));
1836 Results.AddResult(Result("friend"));
1837 Results.AddResult(Result("mutable"));
1838 Results.AddResult(Result("virtual"));
1842 case Sema::PCC_ObjCInterface:
1843 case Sema::PCC_ObjCImplementation:
1844 case Sema::PCC_Namespace:
1845 case Sema::PCC_Template:
1846 if (LangOpts.CPlusPlus || LangOpts.C99)
1847 Results.AddResult(Result("inline"));
1850 case Sema::PCC_ObjCInstanceVariableList:
1851 case Sema::PCC_Expression:
1852 case Sema::PCC_Statement:
1853 case Sema::PCC_ForInit:
1854 case Sema::PCC_Condition:
1855 case Sema::PCC_RecoveryInFunction:
1856 case Sema::PCC_Type:
1857 case Sema::PCC_ParenthesizedExpression:
1858 case Sema::PCC_LocalDeclarationSpecifiers:
1863 static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt);
1864 static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt);
1865 static void AddObjCVisibilityResults(const LangOptions &LangOpts,
1866 ResultBuilder &Results, bool NeedAt);
1867 static void AddObjCImplementationResults(const LangOptions &LangOpts,
1868 ResultBuilder &Results, bool NeedAt);
1869 static void AddObjCInterfaceResults(const LangOptions &LangOpts,
1870 ResultBuilder &Results, bool NeedAt);
1871 static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt);
1873 static void AddTypedefResult(ResultBuilder &Results) {
1874 CodeCompletionBuilder Builder(Results.getAllocator(),
1875 Results.getCodeCompletionTUInfo());
1876 Builder.AddTypedTextChunk("typedef");
1877 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1878 Builder.AddPlaceholderChunk("type");
1879 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1880 Builder.AddPlaceholderChunk("name");
1881 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
1882 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
1885 // using name = type
1886 static void AddUsingAliasResult(CodeCompletionBuilder &Builder,
1887 ResultBuilder &Results) {
1888 Builder.AddTypedTextChunk("using");
1889 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1890 Builder.AddPlaceholderChunk("name");
1891 Builder.AddChunk(CodeCompletionString::CK_Equal);
1892 Builder.AddPlaceholderChunk("type");
1893 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
1894 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
1897 static bool WantTypesInContext(Sema::ParserCompletionContext CCC,
1898 const LangOptions &LangOpts) {
1900 case Sema::PCC_Namespace:
1901 case Sema::PCC_Class:
1902 case Sema::PCC_ObjCInstanceVariableList:
1903 case Sema::PCC_Template:
1904 case Sema::PCC_MemberTemplate:
1905 case Sema::PCC_Statement:
1906 case Sema::PCC_RecoveryInFunction:
1907 case Sema::PCC_Type:
1908 case Sema::PCC_ParenthesizedExpression:
1909 case Sema::PCC_LocalDeclarationSpecifiers:
1912 case Sema::PCC_Expression:
1913 case Sema::PCC_Condition:
1914 return LangOpts.CPlusPlus;
1916 case Sema::PCC_ObjCInterface:
1917 case Sema::PCC_ObjCImplementation:
1920 case Sema::PCC_ForInit:
1921 return LangOpts.CPlusPlus || LangOpts.ObjC || LangOpts.C99;
1924 llvm_unreachable("Invalid ParserCompletionContext!");
1927 static PrintingPolicy getCompletionPrintingPolicy(const ASTContext &Context,
1928 const Preprocessor &PP) {
1929 PrintingPolicy Policy = Sema::getPrintingPolicy(Context, PP);
1930 Policy.AnonymousTagLocations = false;
1931 Policy.SuppressStrongLifetime = true;
1932 Policy.SuppressUnwrittenScope = true;
1933 Policy.SuppressScope = true;
1934 Policy.CleanUglifiedParameters = true;
1938 /// Retrieve a printing policy suitable for code completion.
1939 static PrintingPolicy getCompletionPrintingPolicy(Sema &S) {
1940 return getCompletionPrintingPolicy(S.Context, S.PP);
1943 /// Retrieve the string representation of the given type as a string
1944 /// that has the appropriate lifetime for code completion.
1946 /// This routine provides a fast path where we provide constant strings for
1947 /// common type names.
1948 static const char *GetCompletionTypeString(QualType T, ASTContext &Context,
1949 const PrintingPolicy &Policy,
1950 CodeCompletionAllocator &Allocator) {
1951 if (!T.getLocalQualifiers()) {
1952 // Built-in type names are constant strings.
1953 if (const BuiltinType *BT = dyn_cast<BuiltinType>(T))
1954 return BT->getNameAsCString(Policy);
1956 // Anonymous tag types are constant strings.
1957 if (const TagType *TagT = dyn_cast<TagType>(T))
1958 if (TagDecl *Tag = TagT->getDecl())
1959 if (!Tag->hasNameForLinkage()) {
1960 switch (Tag->getTagKind()) {
1962 return "struct <anonymous>";
1964 return "__interface <anonymous>";
1966 return "class <anonymous>";
1968 return "union <anonymous>";
1970 return "enum <anonymous>";
1975 // Slow path: format the type as a string.
1977 T.getAsStringInternal(Result, Policy);
1978 return Allocator.CopyString(Result);
1981 /// Add a completion for "this", if we're in a member function.
1982 static void addThisCompletion(Sema &S, ResultBuilder &Results) {
1983 QualType ThisTy = S.getCurrentThisType();
1984 if (ThisTy.isNull())
1987 CodeCompletionAllocator &Allocator = Results.getAllocator();
1988 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
1989 PrintingPolicy Policy = getCompletionPrintingPolicy(S);
1990 Builder.AddResultTypeChunk(
1991 GetCompletionTypeString(ThisTy, S.Context, Policy, Allocator));
1992 Builder.AddTypedTextChunk("this");
1993 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
1996 static void AddStaticAssertResult(CodeCompletionBuilder &Builder,
1997 ResultBuilder &Results,
1998 const LangOptions &LangOpts) {
1999 if (!LangOpts.CPlusPlus11)
2002 Builder.AddTypedTextChunk("static_assert");
2003 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2004 Builder.AddPlaceholderChunk("expression");
2005 Builder.AddChunk(CodeCompletionString::CK_Comma);
2006 Builder.AddPlaceholderChunk("message");
2007 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2008 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2009 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
2012 static void AddOverrideResults(ResultBuilder &Results,
2013 const CodeCompletionContext &CCContext,
2014 CodeCompletionBuilder &Builder) {
2015 Sema &S = Results.getSema();
2016 const auto *CR = llvm::dyn_cast<CXXRecordDecl>(S.CurContext);
2017 // If not inside a class/struct/union return empty.
2020 // First store overrides within current class.
2021 // These are stored by name to make querying fast in the later step.
2022 llvm::StringMap<std::vector<FunctionDecl *>> Overrides;
2023 for (auto *Method : CR->methods()) {
2024 if (!Method->isVirtual() || !Method->getIdentifier())
2026 Overrides[Method->getName()].push_back(Method);
2029 for (const auto &Base : CR->bases()) {
2030 const auto *BR = Base.getType().getTypePtr()->getAsCXXRecordDecl();
2033 for (auto *Method : BR->methods()) {
2034 if (!Method->isVirtual() || !Method->getIdentifier())
2036 const auto it = Overrides.find(Method->getName());
2037 bool IsOverriden = false;
2038 if (it != Overrides.end()) {
2039 for (auto *MD : it->second) {
2040 // If the method in current body is not an overload of this virtual
2041 // function, then it overrides this one.
2042 if (!S.IsOverload(MD, Method, false)) {
2049 // Generates a new CodeCompletionResult by taking this function and
2050 // converting it into an override declaration with only one chunk in the
2051 // final CodeCompletionString as a TypedTextChunk.
2052 std::string OverrideSignature;
2053 llvm::raw_string_ostream OS(OverrideSignature);
2054 CodeCompletionResult CCR(Method, 0);
2055 PrintingPolicy Policy =
2056 getCompletionPrintingPolicy(S.getASTContext(), S.getPreprocessor());
2057 auto *CCS = CCR.createCodeCompletionStringForOverride(
2058 S.getPreprocessor(), S.getASTContext(), Builder,
2059 /*IncludeBriefComments=*/false, CCContext, Policy);
2060 Results.AddResult(CodeCompletionResult(CCS, Method, CCP_CodePattern));
2066 /// Add language constructs that show up for "ordinary" names.
2067 static void AddOrdinaryNameResults(Sema::ParserCompletionContext CCC, Scope *S,
2068 Sema &SemaRef, ResultBuilder &Results) {
2069 CodeCompletionAllocator &Allocator = Results.getAllocator();
2070 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
2072 typedef CodeCompletionResult Result;
2074 case Sema::PCC_Namespace:
2075 if (SemaRef.getLangOpts().CPlusPlus) {
2076 if (Results.includeCodePatterns()) {
2077 // namespace <identifier> { declarations }
2078 Builder.AddTypedTextChunk("namespace");
2079 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2080 Builder.AddPlaceholderChunk("identifier");
2081 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2082 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
2083 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2084 Builder.AddPlaceholderChunk("declarations");
2085 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2086 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
2087 Results.AddResult(Result(Builder.TakeString()));
2090 // namespace identifier = identifier ;
2091 Builder.AddTypedTextChunk("namespace");
2092 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2093 Builder.AddPlaceholderChunk("name");
2094 Builder.AddChunk(CodeCompletionString::CK_Equal);
2095 Builder.AddPlaceholderChunk("namespace");
2096 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2097 Results.AddResult(Result(Builder.TakeString()));
2100 Builder.AddTypedTextChunk("using namespace");
2101 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2102 Builder.AddPlaceholderChunk("identifier");
2103 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2104 Results.AddResult(Result(Builder.TakeString()));
2106 // asm(string-literal)
2107 Builder.AddTypedTextChunk("asm");
2108 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2109 Builder.AddPlaceholderChunk("string-literal");
2110 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2111 Results.AddResult(Result(Builder.TakeString()));
2113 if (Results.includeCodePatterns()) {
2114 // Explicit template instantiation
2115 Builder.AddTypedTextChunk("template");
2116 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2117 Builder.AddPlaceholderChunk("declaration");
2118 Results.AddResult(Result(Builder.TakeString()));
2120 Results.AddResult(Result("template", CodeCompletionResult::RK_Keyword));
2124 if (SemaRef.getLangOpts().ObjC)
2125 AddObjCTopLevelResults(Results, true);
2127 AddTypedefResult(Results);
2130 case Sema::PCC_Class:
2131 if (SemaRef.getLangOpts().CPlusPlus) {
2132 // Using declaration
2133 Builder.AddTypedTextChunk("using");
2134 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2135 Builder.AddPlaceholderChunk("qualifier");
2136 Builder.AddTextChunk("::");
2137 Builder.AddPlaceholderChunk("name");
2138 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2139 Results.AddResult(Result(Builder.TakeString()));
2141 if (SemaRef.getLangOpts().CPlusPlus11)
2142 AddUsingAliasResult(Builder, Results);
2144 // using typename qualifier::name (only in a dependent context)
2145 if (SemaRef.CurContext->isDependentContext()) {
2146 Builder.AddTypedTextChunk("using typename");
2147 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2148 Builder.AddPlaceholderChunk("qualifier");
2149 Builder.AddTextChunk("::");
2150 Builder.AddPlaceholderChunk("name");
2151 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2152 Results.AddResult(Result(Builder.TakeString()));
2155 AddStaticAssertResult(Builder, Results, SemaRef.getLangOpts());
2157 if (CCC == Sema::PCC_Class) {
2158 AddTypedefResult(Results);
2160 bool IsNotInheritanceScope = !S->isClassInheritanceScope();
2162 Builder.AddTypedTextChunk("public");
2163 if (IsNotInheritanceScope && Results.includeCodePatterns())
2164 Builder.AddChunk(CodeCompletionString::CK_Colon);
2165 Results.AddResult(Result(Builder.TakeString()));
2168 Builder.AddTypedTextChunk("protected");
2169 if (IsNotInheritanceScope && Results.includeCodePatterns())
2170 Builder.AddChunk(CodeCompletionString::CK_Colon);
2171 Results.AddResult(Result(Builder.TakeString()));
2174 Builder.AddTypedTextChunk("private");
2175 if (IsNotInheritanceScope && Results.includeCodePatterns())
2176 Builder.AddChunk(CodeCompletionString::CK_Colon);
2177 Results.AddResult(Result(Builder.TakeString()));
2179 // FIXME: This adds override results only if we are at the first word of
2180 // the declaration/definition. Also call this from other sides to have
2182 AddOverrideResults(Results, CodeCompletionContext::CCC_ClassStructUnion,
2188 case Sema::PCC_Template:
2189 case Sema::PCC_MemberTemplate:
2190 if (SemaRef.getLangOpts().CPlusPlus && Results.includeCodePatterns()) {
2191 // template < parameters >
2192 Builder.AddTypedTextChunk("template");
2193 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
2194 Builder.AddPlaceholderChunk("parameters");
2195 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
2196 Results.AddResult(Result(Builder.TakeString()));
2198 Results.AddResult(Result("template", CodeCompletionResult::RK_Keyword));
2201 AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
2202 AddFunctionSpecifiers(CCC, SemaRef.getLangOpts(), Results);
2205 case Sema::PCC_ObjCInterface:
2206 AddObjCInterfaceResults(SemaRef.getLangOpts(), Results, true);
2207 AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
2208 AddFunctionSpecifiers(CCC, SemaRef.getLangOpts(), Results);
2211 case Sema::PCC_ObjCImplementation:
2212 AddObjCImplementationResults(SemaRef.getLangOpts(), Results, true);
2213 AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
2214 AddFunctionSpecifiers(CCC, SemaRef.getLangOpts(), Results);
2217 case Sema::PCC_ObjCInstanceVariableList:
2218 AddObjCVisibilityResults(SemaRef.getLangOpts(), Results, true);
2221 case Sema::PCC_RecoveryInFunction:
2222 case Sema::PCC_Statement: {
2223 if (SemaRef.getLangOpts().CPlusPlus11)
2224 AddUsingAliasResult(Builder, Results);
2226 AddTypedefResult(Results);
2228 if (SemaRef.getLangOpts().CPlusPlus && Results.includeCodePatterns() &&
2229 SemaRef.getLangOpts().CXXExceptions) {
2230 Builder.AddTypedTextChunk("try");
2231 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2232 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
2233 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2234 Builder.AddPlaceholderChunk("statements");
2235 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2236 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
2237 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2238 Builder.AddTextChunk("catch");
2239 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2240 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2241 Builder.AddPlaceholderChunk("declaration");
2242 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2243 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2244 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
2245 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2246 Builder.AddPlaceholderChunk("statements");
2247 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2248 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
2249 Results.AddResult(Result(Builder.TakeString()));
2251 if (SemaRef.getLangOpts().ObjC)
2252 AddObjCStatementResults(Results, true);
2254 if (Results.includeCodePatterns()) {
2255 // if (condition) { statements }
2256 Builder.AddTypedTextChunk("if");
2257 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2258 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2259 if (SemaRef.getLangOpts().CPlusPlus)
2260 Builder.AddPlaceholderChunk("condition");
2262 Builder.AddPlaceholderChunk("expression");
2263 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2264 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2265 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
2266 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2267 Builder.AddPlaceholderChunk("statements");
2268 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2269 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
2270 Results.AddResult(Result(Builder.TakeString()));
2272 // switch (condition) { }
2273 Builder.AddTypedTextChunk("switch");
2274 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2275 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2276 if (SemaRef.getLangOpts().CPlusPlus)
2277 Builder.AddPlaceholderChunk("condition");
2279 Builder.AddPlaceholderChunk("expression");
2280 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2281 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2282 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
2283 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2284 Builder.AddPlaceholderChunk("cases");
2285 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2286 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
2287 Results.AddResult(Result(Builder.TakeString()));
2290 // Switch-specific statements.
2291 if (SemaRef.getCurFunction() &&
2292 !SemaRef.getCurFunction()->SwitchStack.empty()) {
2294 Builder.AddTypedTextChunk("case");
2295 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2296 Builder.AddPlaceholderChunk("expression");
2297 Builder.AddChunk(CodeCompletionString::CK_Colon);
2298 Results.AddResult(Result(Builder.TakeString()));
2301 Builder.AddTypedTextChunk("default");
2302 Builder.AddChunk(CodeCompletionString::CK_Colon);
2303 Results.AddResult(Result(Builder.TakeString()));
2306 if (Results.includeCodePatterns()) {
2307 /// while (condition) { statements }
2308 Builder.AddTypedTextChunk("while");
2309 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2310 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2311 if (SemaRef.getLangOpts().CPlusPlus)
2312 Builder.AddPlaceholderChunk("condition");
2314 Builder.AddPlaceholderChunk("expression");
2315 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2316 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2317 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
2318 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2319 Builder.AddPlaceholderChunk("statements");
2320 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2321 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
2322 Results.AddResult(Result(Builder.TakeString()));
2324 // do { statements } while ( expression );
2325 Builder.AddTypedTextChunk("do");
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 Builder.AddTextChunk("while");
2333 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2334 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2335 Builder.AddPlaceholderChunk("expression");
2336 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2337 Results.AddResult(Result(Builder.TakeString()));
2339 // for ( for-init-statement ; condition ; expression ) { statements }
2340 Builder.AddTypedTextChunk("for");
2341 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2342 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2343 if (SemaRef.getLangOpts().CPlusPlus || SemaRef.getLangOpts().C99)
2344 Builder.AddPlaceholderChunk("init-statement");
2346 Builder.AddPlaceholderChunk("init-expression");
2347 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2348 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2349 Builder.AddPlaceholderChunk("condition");
2350 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2351 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2352 Builder.AddPlaceholderChunk("inc-expression");
2353 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2354 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2355 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
2356 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2357 Builder.AddPlaceholderChunk("statements");
2358 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2359 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
2360 Results.AddResult(Result(Builder.TakeString()));
2362 if (SemaRef.getLangOpts().CPlusPlus11 || SemaRef.getLangOpts().ObjC) {
2363 // for ( range_declaration (:|in) range_expression ) { statements }
2364 Builder.AddTypedTextChunk("for");
2365 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2366 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2367 Builder.AddPlaceholderChunk("range-declaration");
2368 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2369 if (SemaRef.getLangOpts().ObjC)
2370 Builder.AddTextChunk("in");
2372 Builder.AddChunk(CodeCompletionString::CK_Colon);
2373 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2374 Builder.AddPlaceholderChunk("range-expression");
2375 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2376 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2377 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
2378 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2379 Builder.AddPlaceholderChunk("statements");
2380 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2381 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
2382 Results.AddResult(Result(Builder.TakeString()));
2386 if (S->getContinueParent()) {
2388 Builder.AddTypedTextChunk("continue");
2389 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2390 Results.AddResult(Result(Builder.TakeString()));
2393 if (S->getBreakParent()) {
2395 Builder.AddTypedTextChunk("break");
2396 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2397 Results.AddResult(Result(Builder.TakeString()));
2400 // "return expression ;" or "return ;", depending on the return type.
2401 QualType ReturnType;
2402 if (const auto *Function = dyn_cast<FunctionDecl>(SemaRef.CurContext))
2403 ReturnType = Function->getReturnType();
2404 else if (const auto *Method = dyn_cast<ObjCMethodDecl>(SemaRef.CurContext))
2405 ReturnType = Method->getReturnType();
2406 else if (SemaRef.getCurBlock() &&
2407 !SemaRef.getCurBlock()->ReturnType.isNull())
2408 ReturnType = SemaRef.getCurBlock()->ReturnType;;
2409 if (ReturnType.isNull() || ReturnType->isVoidType()) {
2410 Builder.AddTypedTextChunk("return");
2411 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2412 Results.AddResult(Result(Builder.TakeString()));
2414 assert(!ReturnType.isNull());
2415 // "return expression ;"
2416 Builder.AddTypedTextChunk("return");
2417 Builder.AddChunk(clang::CodeCompletionString::CK_HorizontalSpace);
2418 Builder.AddPlaceholderChunk("expression");
2419 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2420 Results.AddResult(Result(Builder.TakeString()));
2421 // When boolean, also add 'return true;' and 'return false;'.
2422 if (ReturnType->isBooleanType()) {
2423 Builder.AddTypedTextChunk("return true");
2424 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2425 Results.AddResult(Result(Builder.TakeString()));
2427 Builder.AddTypedTextChunk("return false");
2428 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2429 Results.AddResult(Result(Builder.TakeString()));
2431 // For pointers, suggest 'return nullptr' in C++.
2432 if (SemaRef.getLangOpts().CPlusPlus11 &&
2433 (ReturnType->isPointerType() || ReturnType->isMemberPointerType())) {
2434 Builder.AddTypedTextChunk("return nullptr");
2435 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2436 Results.AddResult(Result(Builder.TakeString()));
2440 // goto identifier ;
2441 Builder.AddTypedTextChunk("goto");
2442 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2443 Builder.AddPlaceholderChunk("label");
2444 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2445 Results.AddResult(Result(Builder.TakeString()));
2448 Builder.AddTypedTextChunk("using namespace");
2449 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2450 Builder.AddPlaceholderChunk("identifier");
2451 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2452 Results.AddResult(Result(Builder.TakeString()));
2454 AddStaticAssertResult(Builder, Results, SemaRef.getLangOpts());
2458 // Fall through (for statement expressions).
2459 case Sema::PCC_ForInit:
2460 case Sema::PCC_Condition:
2461 AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
2462 // Fall through: conditions and statements can have expressions.
2465 case Sema::PCC_ParenthesizedExpression:
2466 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
2467 CCC == Sema::PCC_ParenthesizedExpression) {
2468 // (__bridge <type>)<expression>
2469 Builder.AddTypedTextChunk("__bridge");
2470 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2471 Builder.AddPlaceholderChunk("type");
2472 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2473 Builder.AddPlaceholderChunk("expression");
2474 Results.AddResult(Result(Builder.TakeString()));
2476 // (__bridge_transfer <Objective-C type>)<expression>
2477 Builder.AddTypedTextChunk("__bridge_transfer");
2478 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2479 Builder.AddPlaceholderChunk("Objective-C type");
2480 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2481 Builder.AddPlaceholderChunk("expression");
2482 Results.AddResult(Result(Builder.TakeString()));
2484 // (__bridge_retained <CF type>)<expression>
2485 Builder.AddTypedTextChunk("__bridge_retained");
2486 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2487 Builder.AddPlaceholderChunk("CF type");
2488 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2489 Builder.AddPlaceholderChunk("expression");
2490 Results.AddResult(Result(Builder.TakeString()));
2495 case Sema::PCC_Expression: {
2496 if (SemaRef.getLangOpts().CPlusPlus) {
2497 // 'this', if we're in a non-static member function.
2498 addThisCompletion(SemaRef, Results);
2501 Builder.AddResultTypeChunk("bool");
2502 Builder.AddTypedTextChunk("true");
2503 Results.AddResult(Result(Builder.TakeString()));
2506 Builder.AddResultTypeChunk("bool");
2507 Builder.AddTypedTextChunk("false");
2508 Results.AddResult(Result(Builder.TakeString()));
2510 if (SemaRef.getLangOpts().RTTI) {
2511 // dynamic_cast < type-id > ( expression )
2512 Builder.AddTypedTextChunk("dynamic_cast");
2513 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
2514 Builder.AddPlaceholderChunk("type");
2515 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
2516 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2517 Builder.AddPlaceholderChunk("expression");
2518 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2519 Results.AddResult(Result(Builder.TakeString()));
2522 // static_cast < type-id > ( expression )
2523 Builder.AddTypedTextChunk("static_cast");
2524 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
2525 Builder.AddPlaceholderChunk("type");
2526 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
2527 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2528 Builder.AddPlaceholderChunk("expression");
2529 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2530 Results.AddResult(Result(Builder.TakeString()));
2532 // reinterpret_cast < type-id > ( expression )
2533 Builder.AddTypedTextChunk("reinterpret_cast");
2534 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
2535 Builder.AddPlaceholderChunk("type");
2536 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
2537 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2538 Builder.AddPlaceholderChunk("expression");
2539 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2540 Results.AddResult(Result(Builder.TakeString()));
2542 // const_cast < type-id > ( expression )
2543 Builder.AddTypedTextChunk("const_cast");
2544 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
2545 Builder.AddPlaceholderChunk("type");
2546 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
2547 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2548 Builder.AddPlaceholderChunk("expression");
2549 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2550 Results.AddResult(Result(Builder.TakeString()));
2552 if (SemaRef.getLangOpts().RTTI) {
2553 // typeid ( expression-or-type )
2554 Builder.AddResultTypeChunk("std::type_info");
2555 Builder.AddTypedTextChunk("typeid");
2556 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2557 Builder.AddPlaceholderChunk("expression-or-type");
2558 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2559 Results.AddResult(Result(Builder.TakeString()));
2563 Builder.AddTypedTextChunk("new");
2564 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2565 Builder.AddPlaceholderChunk("type");
2566 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2567 Builder.AddPlaceholderChunk("expressions");
2568 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2569 Results.AddResult(Result(Builder.TakeString()));
2571 // new T [ ] ( ... )
2572 Builder.AddTypedTextChunk("new");
2573 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2574 Builder.AddPlaceholderChunk("type");
2575 Builder.AddChunk(CodeCompletionString::CK_LeftBracket);
2576 Builder.AddPlaceholderChunk("size");
2577 Builder.AddChunk(CodeCompletionString::CK_RightBracket);
2578 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2579 Builder.AddPlaceholderChunk("expressions");
2580 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2581 Results.AddResult(Result(Builder.TakeString()));
2583 // delete expression
2584 Builder.AddResultTypeChunk("void");
2585 Builder.AddTypedTextChunk("delete");
2586 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2587 Builder.AddPlaceholderChunk("expression");
2588 Results.AddResult(Result(Builder.TakeString()));
2590 // delete [] expression
2591 Builder.AddResultTypeChunk("void");
2592 Builder.AddTypedTextChunk("delete");
2593 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2594 Builder.AddChunk(CodeCompletionString::CK_LeftBracket);
2595 Builder.AddChunk(CodeCompletionString::CK_RightBracket);
2596 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2597 Builder.AddPlaceholderChunk("expression");
2598 Results.AddResult(Result(Builder.TakeString()));
2600 if (SemaRef.getLangOpts().CXXExceptions) {
2602 Builder.AddResultTypeChunk("void");
2603 Builder.AddTypedTextChunk("throw");
2604 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2605 Builder.AddPlaceholderChunk("expression");
2606 Results.AddResult(Result(Builder.TakeString()));
2611 if (SemaRef.getLangOpts().CPlusPlus11) {
2613 Builder.AddResultTypeChunk("std::nullptr_t");
2614 Builder.AddTypedTextChunk("nullptr");
2615 Results.AddResult(Result(Builder.TakeString()));
2618 Builder.AddResultTypeChunk("size_t");
2619 Builder.AddTypedTextChunk("alignof");
2620 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2621 Builder.AddPlaceholderChunk("type");
2622 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2623 Results.AddResult(Result(Builder.TakeString()));
2626 Builder.AddResultTypeChunk("bool");
2627 Builder.AddTypedTextChunk("noexcept");
2628 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2629 Builder.AddPlaceholderChunk("expression");
2630 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2631 Results.AddResult(Result(Builder.TakeString()));
2633 // sizeof... expression
2634 Builder.AddResultTypeChunk("size_t");
2635 Builder.AddTypedTextChunk("sizeof...");
2636 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2637 Builder.AddPlaceholderChunk("parameter-pack");
2638 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2639 Results.AddResult(Result(Builder.TakeString()));
2643 if (SemaRef.getLangOpts().ObjC) {
2644 // Add "super", if we're in an Objective-C class with a superclass.
2645 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
2646 // The interface can be NULL.
2647 if (ObjCInterfaceDecl *ID = Method->getClassInterface())
2648 if (ID->getSuperClass()) {
2649 std::string SuperType;
2650 SuperType = ID->getSuperClass()->getNameAsString();
2651 if (Method->isInstanceMethod())
2654 Builder.AddResultTypeChunk(Allocator.CopyString(SuperType));
2655 Builder.AddTypedTextChunk("super");
2656 Results.AddResult(Result(Builder.TakeString()));
2660 AddObjCExpressionResults(Results, true);
2663 if (SemaRef.getLangOpts().C11) {
2665 Builder.AddResultTypeChunk("size_t");
2666 if (SemaRef.PP.isMacroDefined("alignof"))
2667 Builder.AddTypedTextChunk("alignof");
2669 Builder.AddTypedTextChunk("_Alignof");
2670 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2671 Builder.AddPlaceholderChunk("type");
2672 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2673 Results.AddResult(Result(Builder.TakeString()));
2676 if (SemaRef.getLangOpts().C2x) {
2678 Builder.AddResultTypeChunk("nullptr_t");
2679 Builder.AddTypedTextChunk("nullptr");
2680 Results.AddResult(Result(Builder.TakeString()));
2683 // sizeof expression
2684 Builder.AddResultTypeChunk("size_t");
2685 Builder.AddTypedTextChunk("sizeof");
2686 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2687 Builder.AddPlaceholderChunk("expression-or-type");
2688 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2689 Results.AddResult(Result(Builder.TakeString()));
2693 case Sema::PCC_Type:
2694 case Sema::PCC_LocalDeclarationSpecifiers:
2698 if (WantTypesInContext(CCC, SemaRef.getLangOpts()))
2699 AddTypeSpecifierResults(SemaRef.getLangOpts(), Results);
2701 if (SemaRef.getLangOpts().CPlusPlus && CCC != Sema::PCC_Type)
2702 Results.AddResult(Result("operator"));
2705 /// If the given declaration has an associated type, add it as a result
2707 static void AddResultTypeChunk(ASTContext &Context,
2708 const PrintingPolicy &Policy,
2709 const NamedDecl *ND, QualType BaseType,
2710 CodeCompletionBuilder &Result) {
2714 // Skip constructors and conversion functions, which have their return types
2715 // built into their names.
2716 if (isConstructor(ND) || isa<CXXConversionDecl>(ND))
2719 // Determine the type of the declaration (if it has a type).
2721 if (const FunctionDecl *Function = ND->getAsFunction())
2722 T = Function->getReturnType();
2723 else if (const auto *Method = dyn_cast<ObjCMethodDecl>(ND)) {
2724 if (!BaseType.isNull())
2725 T = Method->getSendResultType(BaseType);
2727 T = Method->getReturnType();
2728 } else if (const auto *Enumerator = dyn_cast<EnumConstantDecl>(ND)) {
2729 T = Context.getTypeDeclType(cast<TypeDecl>(Enumerator->getDeclContext()));
2730 T = clang::TypeName::getFullyQualifiedType(T, Context);
2731 } else if (isa<UnresolvedUsingValueDecl>(ND)) {
2732 /* Do nothing: ignore unresolved using declarations*/
2733 } else if (const auto *Ivar = dyn_cast<ObjCIvarDecl>(ND)) {
2734 if (!BaseType.isNull())
2735 T = Ivar->getUsageType(BaseType);
2737 T = Ivar->getType();
2738 } else if (const auto *Value = dyn_cast<ValueDecl>(ND)) {
2739 T = Value->getType();
2740 } else if (const auto *Property = dyn_cast<ObjCPropertyDecl>(ND)) {
2741 if (!BaseType.isNull())
2742 T = Property->getUsageType(BaseType);
2744 T = Property->getType();
2747 if (T.isNull() || Context.hasSameType(T, Context.DependentTy))
2750 Result.AddResultTypeChunk(
2751 GetCompletionTypeString(T, Context, Policy, Result.getAllocator()));
2754 static void MaybeAddSentinel(Preprocessor &PP,
2755 const NamedDecl *FunctionOrMethod,
2756 CodeCompletionBuilder &Result) {
2757 if (SentinelAttr *Sentinel = FunctionOrMethod->getAttr<SentinelAttr>())
2758 if (Sentinel->getSentinel() == 0) {
2759 if (PP.getLangOpts().ObjC && PP.isMacroDefined("nil"))
2760 Result.AddTextChunk(", nil");
2761 else if (PP.isMacroDefined("NULL"))
2762 Result.AddTextChunk(", NULL");
2764 Result.AddTextChunk(", (void*)0");
2768 static std::string formatObjCParamQualifiers(unsigned ObjCQuals,
2771 if (ObjCQuals & Decl::OBJC_TQ_In)
2773 else if (ObjCQuals & Decl::OBJC_TQ_Inout)
2775 else if (ObjCQuals & Decl::OBJC_TQ_Out)
2777 if (ObjCQuals & Decl::OBJC_TQ_Bycopy)
2778 Result += "bycopy ";
2779 else if (ObjCQuals & Decl::OBJC_TQ_Byref)
2781 if (ObjCQuals & Decl::OBJC_TQ_Oneway)
2782 Result += "oneway ";
2783 if (ObjCQuals & Decl::OBJC_TQ_CSNullability) {
2784 if (auto nullability = AttributedType::stripOuterNullability(Type)) {
2785 switch (*nullability) {
2786 case NullabilityKind::NonNull:
2787 Result += "nonnull ";
2790 case NullabilityKind::Nullable:
2791 Result += "nullable ";
2794 case NullabilityKind::Unspecified:
2795 Result += "null_unspecified ";
2798 case NullabilityKind::NullableResult:
2799 llvm_unreachable("Not supported as a context-sensitive keyword!");
2807 /// Tries to find the most appropriate type location for an Objective-C
2808 /// block placeholder.
2810 /// This function ignores things like typedefs and qualifiers in order to
2811 /// present the most relevant and accurate block placeholders in code completion
2813 static void findTypeLocationForBlockDecl(const TypeSourceInfo *TSInfo,
2814 FunctionTypeLoc &Block,
2815 FunctionProtoTypeLoc &BlockProto,
2816 bool SuppressBlock = false) {
2819 TypeLoc TL = TSInfo->getTypeLoc().getUnqualifiedLoc();
2821 // Look through typedefs.
2822 if (!SuppressBlock) {
2823 if (TypedefTypeLoc TypedefTL = TL.getAsAdjusted<TypedefTypeLoc>()) {
2824 if (TypeSourceInfo *InnerTSInfo =
2825 TypedefTL.getTypedefNameDecl()->getTypeSourceInfo()) {
2826 TL = InnerTSInfo->getTypeLoc().getUnqualifiedLoc();
2831 // Look through qualified types
2832 if (QualifiedTypeLoc QualifiedTL = TL.getAs<QualifiedTypeLoc>()) {
2833 TL = QualifiedTL.getUnqualifiedLoc();
2837 if (AttributedTypeLoc AttrTL = TL.getAs<AttributedTypeLoc>()) {
2838 TL = AttrTL.getModifiedLoc();
2843 // Try to get the function prototype behind the block pointer type,
2845 if (BlockPointerTypeLoc BlockPtr = TL.getAs<BlockPointerTypeLoc>()) {
2846 TL = BlockPtr.getPointeeLoc().IgnoreParens();
2847 Block = TL.getAs<FunctionTypeLoc>();
2848 BlockProto = TL.getAs<FunctionProtoTypeLoc>();
2854 static std::string formatBlockPlaceholder(
2855 const PrintingPolicy &Policy, const NamedDecl *BlockDecl,
2856 FunctionTypeLoc &Block, FunctionProtoTypeLoc &BlockProto,
2857 bool SuppressBlockName = false, bool SuppressBlock = false,
2858 std::optional<ArrayRef<QualType>> ObjCSubsts = std::nullopt);
2860 static std::string FormatFunctionParameter(
2861 const PrintingPolicy &Policy, const DeclaratorDecl *Param,
2862 bool SuppressName = false, bool SuppressBlock = false,
2863 std::optional<ArrayRef<QualType>> ObjCSubsts = std::nullopt) {
2864 // Params are unavailable in FunctionTypeLoc if the FunctionType is invalid.
2865 // It would be better to pass in the param Type, which is usually available.
2866 // But this case is rare, so just pretend we fell back to int as elsewhere.
2869 Decl::ObjCDeclQualifier ObjCQual = Decl::OBJC_TQ_None;
2870 if (const auto *PVD = dyn_cast<ParmVarDecl>(Param))
2871 ObjCQual = PVD->getObjCDeclQualifier();
2872 bool ObjCMethodParam = isa<ObjCMethodDecl>(Param->getDeclContext());
2873 if (Param->getType()->isDependentType() ||
2874 !Param->getType()->isBlockPointerType()) {
2875 // The argument for a dependent or non-block parameter is a placeholder
2876 // containing that parameter's type.
2879 if (Param->getIdentifier() && !ObjCMethodParam && !SuppressName)
2880 Result = std::string(Param->getIdentifier()->deuglifiedName());
2882 QualType Type = Param->getType();
2884 Type = Type.substObjCTypeArgs(Param->getASTContext(), *ObjCSubsts,
2885 ObjCSubstitutionContext::Parameter);
2886 if (ObjCMethodParam) {
2887 Result = "(" + formatObjCParamQualifiers(ObjCQual, Type);
2888 Result += Type.getAsString(Policy) + ")";
2889 if (Param->getIdentifier() && !SuppressName)
2890 Result += Param->getIdentifier()->deuglifiedName();
2892 Type.getAsStringInternal(Result, Policy);
2897 // The argument for a block pointer parameter is a block literal with
2898 // the appropriate type.
2899 FunctionTypeLoc Block;
2900 FunctionProtoTypeLoc BlockProto;
2901 findTypeLocationForBlockDecl(Param->getTypeSourceInfo(), Block, BlockProto,
2903 // Try to retrieve the block type information from the property if this is a
2904 // parameter in a setter.
2905 if (!Block && ObjCMethodParam &&
2906 cast<ObjCMethodDecl>(Param->getDeclContext())->isPropertyAccessor()) {
2907 if (const auto *PD = cast<ObjCMethodDecl>(Param->getDeclContext())
2908 ->findPropertyDecl(/*CheckOverrides=*/false))
2909 findTypeLocationForBlockDecl(PD->getTypeSourceInfo(), Block, BlockProto,
2914 // We were unable to find a FunctionProtoTypeLoc with parameter names
2915 // for the block; just use the parameter type as a placeholder.
2917 if (!ObjCMethodParam && Param->getIdentifier())
2918 Result = std::string(Param->getIdentifier()->deuglifiedName());
2920 QualType Type = Param->getType().getUnqualifiedType();
2922 if (ObjCMethodParam) {
2923 Result = Type.getAsString(Policy);
2924 std::string Quals = formatObjCParamQualifiers(ObjCQual, Type);
2926 Result = "(" + Quals + " " + Result + ")";
2927 if (Result.back() != ')')
2929 if (Param->getIdentifier())
2930 Result += Param->getIdentifier()->deuglifiedName();
2932 Type.getAsStringInternal(Result, Policy);
2938 // We have the function prototype behind the block pointer type, as it was
2939 // written in the source.
2940 return formatBlockPlaceholder(Policy, Param, Block, BlockProto,
2941 /*SuppressBlockName=*/false, SuppressBlock,
2945 /// Returns a placeholder string that corresponds to an Objective-C block
2948 /// \param BlockDecl A declaration with an Objective-C block type.
2950 /// \param Block The most relevant type location for that block type.
2952 /// \param SuppressBlockName Determines whether or not the name of the block
2953 /// declaration is included in the resulting string.
2955 formatBlockPlaceholder(const PrintingPolicy &Policy, const NamedDecl *BlockDecl,
2956 FunctionTypeLoc &Block, FunctionProtoTypeLoc &BlockProto,
2957 bool SuppressBlockName, bool SuppressBlock,
2958 std::optional<ArrayRef<QualType>> ObjCSubsts) {
2960 QualType ResultType = Block.getTypePtr()->getReturnType();
2963 ResultType.substObjCTypeArgs(BlockDecl->getASTContext(), *ObjCSubsts,
2964 ObjCSubstitutionContext::Result);
2965 if (!ResultType->isVoidType() || SuppressBlock)
2966 ResultType.getAsStringInternal(Result, Policy);
2968 // Format the parameter list.
2970 if (!BlockProto || Block.getNumParams() == 0) {
2971 if (BlockProto && BlockProto.getTypePtr()->isVariadic())
2977 for (unsigned I = 0, N = Block.getNumParams(); I != N; ++I) {
2980 Params += FormatFunctionParameter(Policy, Block.getParam(I),
2981 /*SuppressName=*/false,
2982 /*SuppressBlock=*/true, ObjCSubsts);
2984 if (I == N - 1 && BlockProto.getTypePtr()->isVariadic())
2990 if (SuppressBlock) {
2991 // Format as a parameter.
2992 Result = Result + " (^";
2993 if (!SuppressBlockName && BlockDecl->getIdentifier())
2994 Result += BlockDecl->getIdentifier()->getName();
2998 // Format as a block literal argument.
2999 Result = '^' + Result;
3002 if (!SuppressBlockName && BlockDecl->getIdentifier())
3003 Result += BlockDecl->getIdentifier()->getName();
3009 static std::string GetDefaultValueString(const ParmVarDecl *Param,
3010 const SourceManager &SM,
3011 const LangOptions &LangOpts) {
3012 const SourceRange SrcRange = Param->getDefaultArgRange();
3013 CharSourceRange CharSrcRange = CharSourceRange::getTokenRange(SrcRange);
3014 bool Invalid = CharSrcRange.isInvalid();
3018 Lexer::getSourceText(CharSrcRange, SM, LangOpts, &Invalid);
3022 if (srcText.empty() || srcText == "=") {
3023 // Lexer can't determine the value.
3024 // This happens if the code is incorrect (for example class is forward
3028 std::string DefValue(srcText.str());
3029 // FIXME: remove this check if the Lexer::getSourceText value is fixed and
3030 // this value always has (or always does not have) '=' in front of it
3031 if (DefValue.at(0) != '=') {
3032 // If we don't have '=' in front of value.
3033 // Lexer returns built-in types values without '=' and user-defined types
3035 return " = " + DefValue;
3037 return " " + DefValue;
3040 /// Add function parameter chunks to the given code completion string.
3041 static void AddFunctionParameterChunks(Preprocessor &PP,
3042 const PrintingPolicy &Policy,
3043 const FunctionDecl *Function,
3044 CodeCompletionBuilder &Result,
3046 bool InOptional = false) {
3047 bool FirstParameter = true;
3049 for (unsigned P = Start, N = Function->getNumParams(); P != N; ++P) {
3050 const ParmVarDecl *Param = Function->getParamDecl(P);
3052 if (Param->hasDefaultArg() && !InOptional) {
3053 // When we see an optional default argument, put that argument and
3054 // the remaining default arguments into a new, optional string.
3055 CodeCompletionBuilder Opt(Result.getAllocator(),
3056 Result.getCodeCompletionTUInfo());
3057 if (!FirstParameter)
3058 Opt.AddChunk(CodeCompletionString::CK_Comma);
3059 AddFunctionParameterChunks(PP, Policy, Function, Opt, P, true);
3060 Result.AddOptionalChunk(Opt.TakeString());
3065 FirstParameter = false;
3067 Result.AddChunk(CodeCompletionString::CK_Comma);
3071 // Format the placeholder string.
3072 std::string PlaceholderStr = FormatFunctionParameter(Policy, Param);
3073 if (Param->hasDefaultArg())
3075 GetDefaultValueString(Param, PP.getSourceManager(), PP.getLangOpts());
3077 if (Function->isVariadic() && P == N - 1)
3078 PlaceholderStr += ", ...";
3080 // Add the placeholder string.
3081 Result.AddPlaceholderChunk(
3082 Result.getAllocator().CopyString(PlaceholderStr));
3085 if (const auto *Proto = Function->getType()->getAs<FunctionProtoType>())
3086 if (Proto->isVariadic()) {
3087 if (Proto->getNumParams() == 0)
3088 Result.AddPlaceholderChunk("...");
3090 MaybeAddSentinel(PP, Function, Result);
3094 /// Add template parameter chunks to the given code completion string.
3095 static void AddTemplateParameterChunks(
3096 ASTContext &Context, const PrintingPolicy &Policy,
3097 const TemplateDecl *Template, CodeCompletionBuilder &Result,
3098 unsigned MaxParameters = 0, unsigned Start = 0, bool InDefaultArg = false) {
3099 bool FirstParameter = true;
3101 // Prefer to take the template parameter names from the first declaration of
3103 Template = cast<TemplateDecl>(Template->getCanonicalDecl());
3105 TemplateParameterList *Params = Template->getTemplateParameters();
3106 TemplateParameterList::iterator PEnd = Params->end();
3108 PEnd = Params->begin() + MaxParameters;
3109 for (TemplateParameterList::iterator P = Params->begin() + Start; P != PEnd;
3111 bool HasDefaultArg = false;
3112 std::string PlaceholderStr;
3113 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
3114 if (TTP->wasDeclaredWithTypename())
3115 PlaceholderStr = "typename";
3116 else if (const auto *TC = TTP->getTypeConstraint()) {
3117 llvm::raw_string_ostream OS(PlaceholderStr);
3118 TC->print(OS, Policy);
3121 PlaceholderStr = "class";
3123 if (TTP->getIdentifier()) {
3124 PlaceholderStr += ' ';
3125 PlaceholderStr += TTP->getIdentifier()->deuglifiedName();
3128 HasDefaultArg = TTP->hasDefaultArgument();
3129 } else if (NonTypeTemplateParmDecl *NTTP =
3130 dyn_cast<NonTypeTemplateParmDecl>(*P)) {
3131 if (NTTP->getIdentifier())
3132 PlaceholderStr = std::string(NTTP->getIdentifier()->deuglifiedName());
3133 NTTP->getType().getAsStringInternal(PlaceholderStr, Policy);
3134 HasDefaultArg = NTTP->hasDefaultArgument();
3136 assert(isa<TemplateTemplateParmDecl>(*P));
3137 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
3139 // Since putting the template argument list into the placeholder would
3140 // be very, very long, we just use an abbreviation.
3141 PlaceholderStr = "template<...> class";
3142 if (TTP->getIdentifier()) {
3143 PlaceholderStr += ' ';
3144 PlaceholderStr += TTP->getIdentifier()->deuglifiedName();
3147 HasDefaultArg = TTP->hasDefaultArgument();
3150 if (HasDefaultArg && !InDefaultArg) {
3151 // When we see an optional default argument, put that argument and
3152 // the remaining default arguments into a new, optional string.
3153 CodeCompletionBuilder Opt(Result.getAllocator(),
3154 Result.getCodeCompletionTUInfo());
3155 if (!FirstParameter)
3156 Opt.AddChunk(CodeCompletionString::CK_Comma);
3157 AddTemplateParameterChunks(Context, Policy, Template, Opt, MaxParameters,
3158 P - Params->begin(), true);
3159 Result.AddOptionalChunk(Opt.TakeString());
3163 InDefaultArg = false;
3166 FirstParameter = false;
3168 Result.AddChunk(CodeCompletionString::CK_Comma);
3170 // Add the placeholder string.
3171 Result.AddPlaceholderChunk(
3172 Result.getAllocator().CopyString(PlaceholderStr));
3176 /// Add a qualifier to the given code-completion string, if the
3177 /// provided nested-name-specifier is non-NULL.
3178 static void AddQualifierToCompletionString(CodeCompletionBuilder &Result,
3179 NestedNameSpecifier *Qualifier,
3180 bool QualifierIsInformative,
3181 ASTContext &Context,
3182 const PrintingPolicy &Policy) {
3186 std::string PrintedNNS;
3188 llvm::raw_string_ostream OS(PrintedNNS);
3189 Qualifier->print(OS, Policy);
3191 if (QualifierIsInformative)
3192 Result.AddInformativeChunk(Result.getAllocator().CopyString(PrintedNNS));
3194 Result.AddTextChunk(Result.getAllocator().CopyString(PrintedNNS));
3198 AddFunctionTypeQualsToCompletionString(CodeCompletionBuilder &Result,
3199 const FunctionDecl *Function) {
3200 const auto *Proto = Function->getType()->getAs<FunctionProtoType>();
3201 if (!Proto || !Proto->getMethodQuals())
3204 // FIXME: Add ref-qualifier!
3206 // Handle single qualifiers without copying
3207 if (Proto->getMethodQuals().hasOnlyConst()) {
3208 Result.AddInformativeChunk(" const");
3212 if (Proto->getMethodQuals().hasOnlyVolatile()) {
3213 Result.AddInformativeChunk(" volatile");
3217 if (Proto->getMethodQuals().hasOnlyRestrict()) {
3218 Result.AddInformativeChunk(" restrict");
3222 // Handle multiple qualifiers.
3223 std::string QualsStr;
3224 if (Proto->isConst())
3225 QualsStr += " const";
3226 if (Proto->isVolatile())
3227 QualsStr += " volatile";
3228 if (Proto->isRestrict())
3229 QualsStr += " restrict";
3230 Result.AddInformativeChunk(Result.getAllocator().CopyString(QualsStr));
3233 /// Add the name of the given declaration
3234 static void AddTypedNameChunk(ASTContext &Context, const PrintingPolicy &Policy,
3235 const NamedDecl *ND,
3236 CodeCompletionBuilder &Result) {
3237 DeclarationName Name = ND->getDeclName();
3241 switch (Name.getNameKind()) {
3242 case DeclarationName::CXXOperatorName: {
3243 const char *OperatorName = nullptr;
3244 switch (Name.getCXXOverloadedOperator()) {
3246 case OO_Conditional:
3247 case NUM_OVERLOADED_OPERATORS:
3248 OperatorName = "operator";
3251 #define OVERLOADED_OPERATOR(Name, Spelling, Token, Unary, Binary, MemberOnly) \
3253 OperatorName = "operator" Spelling; \
3255 #define OVERLOADED_OPERATOR_MULTI(Name, Spelling, Unary, Binary, MemberOnly)
3256 #include "clang/Basic/OperatorKinds.def"
3259 OperatorName = "operator new";
3262 OperatorName = "operator delete";
3265 OperatorName = "operator new[]";
3267 case OO_Array_Delete:
3268 OperatorName = "operator delete[]";
3271 OperatorName = "operator()";
3274 OperatorName = "operator[]";
3277 Result.AddTypedTextChunk(OperatorName);
3281 case DeclarationName::Identifier:
3282 case DeclarationName::CXXConversionFunctionName:
3283 case DeclarationName::CXXDestructorName:
3284 case DeclarationName::CXXLiteralOperatorName:
3285 Result.AddTypedTextChunk(
3286 Result.getAllocator().CopyString(ND->getNameAsString()));
3289 case DeclarationName::CXXDeductionGuideName:
3290 case DeclarationName::CXXUsingDirective:
3291 case DeclarationName::ObjCZeroArgSelector:
3292 case DeclarationName::ObjCOneArgSelector:
3293 case DeclarationName::ObjCMultiArgSelector:
3296 case DeclarationName::CXXConstructorName: {
3297 CXXRecordDecl *Record = nullptr;
3298 QualType Ty = Name.getCXXNameType();
3299 if (const auto *RecordTy = Ty->getAs<RecordType>())
3300 Record = cast<CXXRecordDecl>(RecordTy->getDecl());
3301 else if (const auto *InjectedTy = Ty->getAs<InjectedClassNameType>())
3302 Record = InjectedTy->getDecl();
3304 Result.AddTypedTextChunk(
3305 Result.getAllocator().CopyString(ND->getNameAsString()));
3309 Result.AddTypedTextChunk(
3310 Result.getAllocator().CopyString(Record->getNameAsString()));
3311 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) {
3312 Result.AddChunk(CodeCompletionString::CK_LeftAngle);
3313 AddTemplateParameterChunks(Context, Policy, Template, Result);
3314 Result.AddChunk(CodeCompletionString::CK_RightAngle);
3321 CodeCompletionString *CodeCompletionResult::CreateCodeCompletionString(
3322 Sema &S, const CodeCompletionContext &CCContext,
3323 CodeCompletionAllocator &Allocator, CodeCompletionTUInfo &CCTUInfo,
3324 bool IncludeBriefComments) {
3325 return CreateCodeCompletionString(S.Context, S.PP, CCContext, Allocator,
3326 CCTUInfo, IncludeBriefComments);
3329 CodeCompletionString *CodeCompletionResult::CreateCodeCompletionStringForMacro(
3330 Preprocessor &PP, CodeCompletionAllocator &Allocator,
3331 CodeCompletionTUInfo &CCTUInfo) {
3332 assert(Kind == RK_Macro);
3333 CodeCompletionBuilder Result(Allocator, CCTUInfo, Priority, Availability);
3334 const MacroInfo *MI = PP.getMacroInfo(Macro);
3335 Result.AddTypedTextChunk(Result.getAllocator().CopyString(Macro->getName()));
3337 if (!MI || !MI->isFunctionLike())
3338 return Result.TakeString();
3340 // Format a function-like macro with placeholders for the arguments.
3341 Result.AddChunk(CodeCompletionString::CK_LeftParen);
3342 MacroInfo::param_iterator A = MI->param_begin(), AEnd = MI->param_end();
3344 // C99 variadic macros add __VA_ARGS__ at the end. Skip it.
3345 if (MI->isC99Varargs()) {
3349 Result.AddPlaceholderChunk("...");
3353 for (MacroInfo::param_iterator A = MI->param_begin(); A != AEnd; ++A) {
3354 if (A != MI->param_begin())
3355 Result.AddChunk(CodeCompletionString::CK_Comma);
3357 if (MI->isVariadic() && (A + 1) == AEnd) {
3358 SmallString<32> Arg = (*A)->getName();
3359 if (MI->isC99Varargs())
3363 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
3367 // Non-variadic macros are simple.
3368 Result.AddPlaceholderChunk(
3369 Result.getAllocator().CopyString((*A)->getName()));
3371 Result.AddChunk(CodeCompletionString::CK_RightParen);
3372 return Result.TakeString();
3375 /// If possible, create a new code completion string for the given
3378 /// \returns Either a new, heap-allocated code completion string describing
3379 /// how to use this result, or NULL to indicate that the string or name of the
3380 /// result is all that is needed.
3381 CodeCompletionString *CodeCompletionResult::CreateCodeCompletionString(
3382 ASTContext &Ctx, Preprocessor &PP, const CodeCompletionContext &CCContext,
3383 CodeCompletionAllocator &Allocator, CodeCompletionTUInfo &CCTUInfo,
3384 bool IncludeBriefComments) {
3385 if (Kind == RK_Macro)
3386 return CreateCodeCompletionStringForMacro(PP, Allocator, CCTUInfo);
3388 CodeCompletionBuilder Result(Allocator, CCTUInfo, Priority, Availability);
3390 PrintingPolicy Policy = getCompletionPrintingPolicy(Ctx, PP);
3391 if (Kind == RK_Pattern) {
3392 Pattern->Priority = Priority;
3393 Pattern->Availability = Availability;
3396 Result.addParentContext(Declaration->getDeclContext());
3397 Pattern->ParentName = Result.getParentName();
3398 if (const RawComment *RC =
3399 getPatternCompletionComment(Ctx, Declaration)) {
3400 Result.addBriefComment(RC->getBriefText(Ctx));
3401 Pattern->BriefComment = Result.getBriefComment();
3408 if (Kind == RK_Keyword) {
3409 Result.AddTypedTextChunk(Keyword);
3410 return Result.TakeString();
3412 assert(Kind == RK_Declaration && "Missed a result kind?");
3413 return createCodeCompletionStringForDecl(
3414 PP, Ctx, Result, IncludeBriefComments, CCContext, Policy);
3417 static void printOverrideString(const CodeCompletionString &CCS,
3418 std::string &BeforeName,
3419 std::string &NameAndSignature) {
3420 bool SeenTypedChunk = false;
3421 for (auto &Chunk : CCS) {
3422 if (Chunk.Kind == CodeCompletionString::CK_Optional) {
3423 assert(SeenTypedChunk && "optional parameter before name");
3424 // Note that we put all chunks inside into NameAndSignature.
3425 printOverrideString(*Chunk.Optional, NameAndSignature, NameAndSignature);
3428 SeenTypedChunk |= Chunk.Kind == CodeCompletionString::CK_TypedText;
3430 NameAndSignature += Chunk.Text;
3432 BeforeName += Chunk.Text;
3436 CodeCompletionString *
3437 CodeCompletionResult::createCodeCompletionStringForOverride(
3438 Preprocessor &PP, ASTContext &Ctx, CodeCompletionBuilder &Result,
3439 bool IncludeBriefComments, const CodeCompletionContext &CCContext,
3440 PrintingPolicy &Policy) {
3441 auto *CCS = createCodeCompletionStringForDecl(PP, Ctx, Result,
3442 /*IncludeBriefComments=*/false,
3444 std::string BeforeName;
3445 std::string NameAndSignature;
3446 // For overrides all chunks go into the result, none are informative.
3447 printOverrideString(*CCS, BeforeName, NameAndSignature);
3448 NameAndSignature += " override";
3450 Result.AddTextChunk(Result.getAllocator().CopyString(BeforeName));
3451 Result.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3452 Result.AddTypedTextChunk(Result.getAllocator().CopyString(NameAndSignature));
3453 return Result.TakeString();
3456 // FIXME: Right now this works well with lambdas. Add support for other functor
3457 // types like std::function.
3458 static const NamedDecl *extractFunctorCallOperator(const NamedDecl *ND) {
3459 const auto *VD = dyn_cast<VarDecl>(ND);
3462 const auto *RecordDecl = VD->getType()->getAsCXXRecordDecl();
3463 if (!RecordDecl || !RecordDecl->isLambda())
3465 return RecordDecl->getLambdaCallOperator();
3468 CodeCompletionString *CodeCompletionResult::createCodeCompletionStringForDecl(
3469 Preprocessor &PP, ASTContext &Ctx, CodeCompletionBuilder &Result,
3470 bool IncludeBriefComments, const CodeCompletionContext &CCContext,
3471 PrintingPolicy &Policy) {
3472 const NamedDecl *ND = Declaration;
3473 Result.addParentContext(ND->getDeclContext());
3475 if (IncludeBriefComments) {
3476 // Add documentation comment, if it exists.
3477 if (const RawComment *RC = getCompletionComment(Ctx, Declaration)) {
3478 Result.addBriefComment(RC->getBriefText(Ctx));
3482 if (StartsNestedNameSpecifier) {
3483 Result.AddTypedTextChunk(
3484 Result.getAllocator().CopyString(ND->getNameAsString()));
3485 Result.AddTextChunk("::");
3486 return Result.TakeString();
3489 for (const auto *I : ND->specific_attrs<AnnotateAttr>())
3490 Result.AddAnnotation(Result.getAllocator().CopyString(I->getAnnotation()));
3492 auto AddFunctionTypeAndResult = [&](const FunctionDecl *Function) {
3493 AddResultTypeChunk(Ctx, Policy, Function, CCContext.getBaseType(), Result);
3494 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
3496 AddTypedNameChunk(Ctx, Policy, ND, Result);
3497 Result.AddChunk(CodeCompletionString::CK_LeftParen);
3498 AddFunctionParameterChunks(PP, Policy, Function, Result);
3499 Result.AddChunk(CodeCompletionString::CK_RightParen);
3500 AddFunctionTypeQualsToCompletionString(Result, Function);
3503 if (const auto *Function = dyn_cast<FunctionDecl>(ND)) {
3504 AddFunctionTypeAndResult(Function);
3505 return Result.TakeString();
3508 if (const auto *CallOperator =
3509 dyn_cast_or_null<FunctionDecl>(extractFunctorCallOperator(ND))) {
3510 AddFunctionTypeAndResult(CallOperator);
3511 return Result.TakeString();
3514 AddResultTypeChunk(Ctx, Policy, ND, CCContext.getBaseType(), Result);
3516 if (const FunctionTemplateDecl *FunTmpl =
3517 dyn_cast<FunctionTemplateDecl>(ND)) {
3518 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
3520 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
3521 AddTypedNameChunk(Ctx, Policy, Function, Result);
3523 // Figure out which template parameters are deduced (or have default
3525 llvm::SmallBitVector Deduced;
3526 Sema::MarkDeducedTemplateParameters(Ctx, FunTmpl, Deduced);
3527 unsigned LastDeducibleArgument;
3528 for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0;
3529 --LastDeducibleArgument) {
3530 if (!Deduced[LastDeducibleArgument - 1]) {
3531 // C++0x: Figure out if the template argument has a default. If so,
3532 // the user doesn't need to type this argument.
3533 // FIXME: We need to abstract template parameters better!
3534 bool HasDefaultArg = false;
3535 NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam(
3536 LastDeducibleArgument - 1);
3537 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
3538 HasDefaultArg = TTP->hasDefaultArgument();
3539 else if (NonTypeTemplateParmDecl *NTTP =
3540 dyn_cast<NonTypeTemplateParmDecl>(Param))
3541 HasDefaultArg = NTTP->hasDefaultArgument();
3543 assert(isa<TemplateTemplateParmDecl>(Param));
3545 cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument();
3553 if (LastDeducibleArgument) {
3554 // Some of the function template arguments cannot be deduced from a
3555 // function call, so we introduce an explicit template argument list
3556 // containing all of the arguments up to the first deducible argument.
3557 Result.AddChunk(CodeCompletionString::CK_LeftAngle);
3558 AddTemplateParameterChunks(Ctx, Policy, FunTmpl, Result,
3559 LastDeducibleArgument);
3560 Result.AddChunk(CodeCompletionString::CK_RightAngle);
3563 // Add the function parameters
3564 Result.AddChunk(CodeCompletionString::CK_LeftParen);
3565 AddFunctionParameterChunks(PP, Policy, Function, Result);
3566 Result.AddChunk(CodeCompletionString::CK_RightParen);
3567 AddFunctionTypeQualsToCompletionString(Result, Function);
3568 return Result.TakeString();
3571 if (const auto *Template = dyn_cast<TemplateDecl>(ND)) {
3572 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
3574 Result.AddTypedTextChunk(
3575 Result.getAllocator().CopyString(Template->getNameAsString()));
3576 Result.AddChunk(CodeCompletionString::CK_LeftAngle);
3577 AddTemplateParameterChunks(Ctx, Policy, Template, Result);
3578 Result.AddChunk(CodeCompletionString::CK_RightAngle);
3579 return Result.TakeString();
3582 if (const auto *Method = dyn_cast<ObjCMethodDecl>(ND)) {
3583 Selector Sel = Method->getSelector();
3584 if (Sel.isUnarySelector()) {
3585 Result.AddTypedTextChunk(
3586 Result.getAllocator().CopyString(Sel.getNameForSlot(0)));
3587 return Result.TakeString();
3590 std::string SelName = Sel.getNameForSlot(0).str();
3592 if (StartParameter == 0)
3593 Result.AddTypedTextChunk(Result.getAllocator().CopyString(SelName));
3595 Result.AddInformativeChunk(Result.getAllocator().CopyString(SelName));
3597 // If there is only one parameter, and we're past it, add an empty
3598 // typed-text chunk since there is nothing to type.
3599 if (Method->param_size() == 1)
3600 Result.AddTypedTextChunk("");
3603 // The extra Idx < Sel.getNumArgs() check is needed due to legacy C-style
3604 // method parameters.
3605 for (ObjCMethodDecl::param_const_iterator P = Method->param_begin(),
3606 PEnd = Method->param_end();
3607 P != PEnd && Idx < Sel.getNumArgs(); (void)++P, ++Idx) {
3609 std::string Keyword;
3610 if (Idx > StartParameter)
3611 Result.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3612 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(Idx))
3613 Keyword += II->getName();
3615 if (Idx < StartParameter || AllParametersAreInformative)
3616 Result.AddInformativeChunk(Result.getAllocator().CopyString(Keyword));
3618 Result.AddTypedTextChunk(Result.getAllocator().CopyString(Keyword));
3621 // If we're before the starting parameter, skip the placeholder.
3622 if (Idx < StartParameter)
3626 QualType ParamType = (*P)->getType();
3627 std::optional<ArrayRef<QualType>> ObjCSubsts;
3628 if (!CCContext.getBaseType().isNull())
3629 ObjCSubsts = CCContext.getBaseType()->getObjCSubstitutions(Method);
3631 if (ParamType->isBlockPointerType() && !DeclaringEntity)
3632 Arg = FormatFunctionParameter(Policy, *P, true,
3633 /*SuppressBlock=*/false, ObjCSubsts);
3636 ParamType = ParamType.substObjCTypeArgs(
3637 Ctx, *ObjCSubsts, ObjCSubstitutionContext::Parameter);
3638 Arg = "(" + formatObjCParamQualifiers((*P)->getObjCDeclQualifier(),
3640 Arg += ParamType.getAsString(Policy) + ")";
3641 if (IdentifierInfo *II = (*P)->getIdentifier())
3642 if (DeclaringEntity || AllParametersAreInformative)
3643 Arg += II->getName();
3646 if (Method->isVariadic() && (P + 1) == PEnd)
3649 if (DeclaringEntity)
3650 Result.AddTextChunk(Result.getAllocator().CopyString(Arg));
3651 else if (AllParametersAreInformative)
3652 Result.AddInformativeChunk(Result.getAllocator().CopyString(Arg));
3654 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
3657 if (Method->isVariadic()) {
3658 if (Method->param_size() == 0) {
3659 if (DeclaringEntity)
3660 Result.AddTextChunk(", ...");
3661 else if (AllParametersAreInformative)
3662 Result.AddInformativeChunk(", ...");
3664 Result.AddPlaceholderChunk(", ...");
3667 MaybeAddSentinel(PP, Method, Result);
3670 return Result.TakeString();
3674 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
3677 Result.AddTypedTextChunk(
3678 Result.getAllocator().CopyString(ND->getNameAsString()));
3679 return Result.TakeString();
3682 const RawComment *clang::getCompletionComment(const ASTContext &Ctx,
3683 const NamedDecl *ND) {
3686 if (auto *RC = Ctx.getRawCommentForAnyRedecl(ND))
3689 // Try to find comment from a property for ObjC methods.
3690 const auto *M = dyn_cast<ObjCMethodDecl>(ND);
3693 const ObjCPropertyDecl *PDecl = M->findPropertyDecl();
3697 return Ctx.getRawCommentForAnyRedecl(PDecl);
3700 const RawComment *clang::getPatternCompletionComment(const ASTContext &Ctx,
3701 const NamedDecl *ND) {
3702 const auto *M = dyn_cast_or_null<ObjCMethodDecl>(ND);
3703 if (!M || !M->isPropertyAccessor())
3706 // Provide code completion comment for self.GetterName where
3707 // GetterName is the getter method for a property with name
3708 // different from the property name (declared via a property
3709 // getter attribute.
3710 const ObjCPropertyDecl *PDecl = M->findPropertyDecl();
3713 if (PDecl->getGetterName() == M->getSelector() &&
3714 PDecl->getIdentifier() != M->getIdentifier()) {
3715 if (auto *RC = Ctx.getRawCommentForAnyRedecl(M))
3717 if (auto *RC = Ctx.getRawCommentForAnyRedecl(PDecl))
3723 const RawComment *clang::getParameterComment(
3724 const ASTContext &Ctx,
3725 const CodeCompleteConsumer::OverloadCandidate &Result, unsigned ArgIndex) {
3726 auto FDecl = Result.getFunction();
3729 if (ArgIndex < FDecl->getNumParams())
3730 return Ctx.getRawCommentForAnyRedecl(FDecl->getParamDecl(ArgIndex));
3734 static void AddOverloadAggregateChunks(const RecordDecl *RD,
3735 const PrintingPolicy &Policy,
3736 CodeCompletionBuilder &Result,
3737 unsigned CurrentArg) {
3738 unsigned ChunkIndex = 0;
3739 auto AddChunk = [&](llvm::StringRef Placeholder) {
3741 Result.AddChunk(CodeCompletionString::CK_Comma);
3742 const char *Copy = Result.getAllocator().CopyString(Placeholder);
3743 if (ChunkIndex == CurrentArg)
3744 Result.AddCurrentParameterChunk(Copy);
3746 Result.AddPlaceholderChunk(Copy);
3749 // Aggregate initialization has all bases followed by all fields.
3750 // (Bases are not legal in C++11 but in that case we never get here).
3751 if (auto *CRD = llvm::dyn_cast<CXXRecordDecl>(RD)) {
3752 for (const auto &Base : CRD->bases())
3753 AddChunk(Base.getType().getAsString(Policy));
3755 for (const auto &Field : RD->fields())
3756 AddChunk(FormatFunctionParameter(Policy, Field));
3759 /// Add function overload parameter chunks to the given code completion
3761 static void AddOverloadParameterChunks(
3762 ASTContext &Context, const PrintingPolicy &Policy,
3763 const FunctionDecl *Function, const FunctionProtoType *Prototype,
3764 FunctionProtoTypeLoc PrototypeLoc, CodeCompletionBuilder &Result,
3765 unsigned CurrentArg, unsigned Start = 0, bool InOptional = false) {
3766 if (!Function && !Prototype) {
3767 Result.AddChunk(CodeCompletionString::CK_CurrentParameter, "...");
3771 bool FirstParameter = true;
3772 unsigned NumParams =
3773 Function ? Function->getNumParams() : Prototype->getNumParams();
3775 for (unsigned P = Start; P != NumParams; ++P) {
3776 if (Function && Function->getParamDecl(P)->hasDefaultArg() && !InOptional) {
3777 // When we see an optional default argument, put that argument and
3778 // the remaining default arguments into a new, optional string.
3779 CodeCompletionBuilder Opt(Result.getAllocator(),
3780 Result.getCodeCompletionTUInfo());
3781 if (!FirstParameter)
3782 Opt.AddChunk(CodeCompletionString::CK_Comma);
3783 // Optional sections are nested.
3784 AddOverloadParameterChunks(Context, Policy, Function, Prototype,
3785 PrototypeLoc, Opt, CurrentArg, P,
3786 /*InOptional=*/true);
3787 Result.AddOptionalChunk(Opt.TakeString());
3792 FirstParameter = false;
3794 Result.AddChunk(CodeCompletionString::CK_Comma);
3798 // Format the placeholder string.
3799 std::string Placeholder;
3800 assert(P < Prototype->getNumParams());
3801 if (Function || PrototypeLoc) {
3802 const ParmVarDecl *Param =
3803 Function ? Function->getParamDecl(P) : PrototypeLoc.getParam(P);
3804 Placeholder = FormatFunctionParameter(Policy, Param);
3805 if (Param->hasDefaultArg())
3806 Placeholder += GetDefaultValueString(Param, Context.getSourceManager(),
3807 Context.getLangOpts());
3809 Placeholder = Prototype->getParamType(P).getAsString(Policy);
3812 if (P == CurrentArg)
3813 Result.AddCurrentParameterChunk(
3814 Result.getAllocator().CopyString(Placeholder));
3816 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Placeholder));
3819 if (Prototype && Prototype->isVariadic()) {
3820 CodeCompletionBuilder Opt(Result.getAllocator(),
3821 Result.getCodeCompletionTUInfo());
3822 if (!FirstParameter)
3823 Opt.AddChunk(CodeCompletionString::CK_Comma);
3825 if (CurrentArg < NumParams)
3826 Opt.AddPlaceholderChunk("...");
3828 Opt.AddCurrentParameterChunk("...");
3830 Result.AddOptionalChunk(Opt.TakeString());
3835 formatTemplateParameterPlaceholder(const NamedDecl *Param, bool &Optional,
3836 const PrintingPolicy &Policy) {
3837 if (const auto *Type = dyn_cast<TemplateTypeParmDecl>(Param)) {
3838 Optional = Type->hasDefaultArgument();
3839 } else if (const auto *NonType = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3840 Optional = NonType->hasDefaultArgument();
3841 } else if (const auto *Template = dyn_cast<TemplateTemplateParmDecl>(Param)) {
3842 Optional = Template->hasDefaultArgument();
3845 llvm::raw_string_ostream OS(Result);
3846 Param->print(OS, Policy);
3850 static std::string templateResultType(const TemplateDecl *TD,
3851 const PrintingPolicy &Policy) {
3852 if (const auto *CTD = dyn_cast<ClassTemplateDecl>(TD))
3853 return CTD->getTemplatedDecl()->getKindName().str();
3854 if (const auto *VTD = dyn_cast<VarTemplateDecl>(TD))
3855 return VTD->getTemplatedDecl()->getType().getAsString(Policy);
3856 if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(TD))
3857 return FTD->getTemplatedDecl()->getReturnType().getAsString(Policy);
3858 if (isa<TypeAliasTemplateDecl>(TD))
3860 if (isa<TemplateTemplateParmDecl>(TD))
3862 if (isa<ConceptDecl>(TD))
3867 static CodeCompletionString *createTemplateSignatureString(
3868 const TemplateDecl *TD, CodeCompletionBuilder &Builder, unsigned CurrentArg,
3869 const PrintingPolicy &Policy) {
3870 llvm::ArrayRef<NamedDecl *> Params = TD->getTemplateParameters()->asArray();
3871 CodeCompletionBuilder OptionalBuilder(Builder.getAllocator(),
3872 Builder.getCodeCompletionTUInfo());
3873 std::string ResultType = templateResultType(TD, Policy);
3874 if (!ResultType.empty())
3875 Builder.AddResultTypeChunk(Builder.getAllocator().CopyString(ResultType));
3876 Builder.AddTextChunk(
3877 Builder.getAllocator().CopyString(TD->getNameAsString()));
3878 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
3879 // Initially we're writing into the main string. Once we see an optional arg
3880 // (with default), we're writing into the nested optional chunk.
3881 CodeCompletionBuilder *Current = &Builder;
3882 for (unsigned I = 0; I < Params.size(); ++I) {
3883 bool Optional = false;
3884 std::string Placeholder =
3885 formatTemplateParameterPlaceholder(Params[I], Optional, Policy);
3887 Current = &OptionalBuilder;
3889 Current->AddChunk(CodeCompletionString::CK_Comma);
3890 Current->AddChunk(I == CurrentArg
3891 ? CodeCompletionString::CK_CurrentParameter
3892 : CodeCompletionString::CK_Placeholder,
3893 Current->getAllocator().CopyString(Placeholder));
3895 // Add the optional chunk to the main string if we ever used it.
3896 if (Current == &OptionalBuilder)
3897 Builder.AddOptionalChunk(OptionalBuilder.TakeString());
3898 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
3899 // For function templates, ResultType was the function's return type.
3900 // Give some clue this is a function. (Don't show the possibly-bulky params).
3901 if (isa<FunctionTemplateDecl>(TD))
3902 Builder.AddInformativeChunk("()");
3903 return Builder.TakeString();
3906 CodeCompletionString *
3907 CodeCompleteConsumer::OverloadCandidate::CreateSignatureString(
3908 unsigned CurrentArg, Sema &S, CodeCompletionAllocator &Allocator,
3909 CodeCompletionTUInfo &CCTUInfo, bool IncludeBriefComments,
3910 bool Braced) const {
3911 PrintingPolicy Policy = getCompletionPrintingPolicy(S);
3912 // Show signatures of constructors as they are declared:
3913 // vector(int n) rather than vector<string>(int n)
3914 // This is less noisy without being less clear, and avoids tricky cases.
3915 Policy.SuppressTemplateArgsInCXXConstructors = true;
3917 // FIXME: Set priority, availability appropriately.
3918 CodeCompletionBuilder Result(Allocator, CCTUInfo, 1,
3919 CXAvailability_Available);
3921 if (getKind() == CK_Template)
3922 return createTemplateSignatureString(getTemplate(), Result, CurrentArg,
3925 FunctionDecl *FDecl = getFunction();
3926 const FunctionProtoType *Proto =
3927 dyn_cast_or_null<FunctionProtoType>(getFunctionType());
3929 // First, the name/type of the callee.
3930 if (getKind() == CK_Aggregate) {
3931 Result.AddTextChunk(
3932 Result.getAllocator().CopyString(getAggregate()->getName()));
3934 if (IncludeBriefComments) {
3935 if (auto RC = getParameterComment(S.getASTContext(), *this, CurrentArg))
3936 Result.addBriefComment(RC->getBriefText(S.getASTContext()));
3938 AddResultTypeChunk(S.Context, Policy, FDecl, QualType(), Result);
3941 llvm::raw_string_ostream OS(Name);
3942 FDecl->getDeclName().print(OS, Policy);
3943 Result.AddTextChunk(Result.getAllocator().CopyString(OS.str()));
3945 // Function without a declaration. Just give the return type.
3946 Result.AddResultTypeChunk(Result.getAllocator().CopyString(
3947 getFunctionType()->getReturnType().getAsString(Policy)));
3950 // Next, the brackets and parameters.
3951 Result.AddChunk(Braced ? CodeCompletionString::CK_LeftBrace
3952 : CodeCompletionString::CK_LeftParen);
3953 if (getKind() == CK_Aggregate)
3954 AddOverloadAggregateChunks(getAggregate(), Policy, Result, CurrentArg);
3956 AddOverloadParameterChunks(S.getASTContext(), Policy, FDecl, Proto,
3957 getFunctionProtoTypeLoc(), Result, CurrentArg);
3958 Result.AddChunk(Braced ? CodeCompletionString::CK_RightBrace
3959 : CodeCompletionString::CK_RightParen);
3961 return Result.TakeString();
3964 unsigned clang::getMacroUsagePriority(StringRef MacroName,
3965 const LangOptions &LangOpts,
3966 bool PreferredTypeIsPointer) {
3967 unsigned Priority = CCP_Macro;
3969 // Treat the "nil", "Nil" and "NULL" macros as null pointer constants.
3970 if (MacroName.equals("nil") || MacroName.equals("NULL") ||
3971 MacroName.equals("Nil")) {
3972 Priority = CCP_Constant;
3973 if (PreferredTypeIsPointer)
3974 Priority = Priority / CCF_SimilarTypeMatch;
3976 // Treat "YES", "NO", "true", and "false" as constants.
3977 else if (MacroName.equals("YES") || MacroName.equals("NO") ||
3978 MacroName.equals("true") || MacroName.equals("false"))
3979 Priority = CCP_Constant;
3980 // Treat "bool" as a type.
3981 else if (MacroName.equals("bool"))
3982 Priority = CCP_Type + (LangOpts.ObjC ? CCD_bool_in_ObjC : 0);
3987 CXCursorKind clang::getCursorKindForDecl(const Decl *D) {
3989 return CXCursor_UnexposedDecl;
3991 switch (D->getKind()) {
3993 return CXCursor_EnumDecl;
3994 case Decl::EnumConstant:
3995 return CXCursor_EnumConstantDecl;
3997 return CXCursor_FieldDecl;
3998 case Decl::Function:
3999 return CXCursor_FunctionDecl;
4000 case Decl::ObjCCategory:
4001 return CXCursor_ObjCCategoryDecl;
4002 case Decl::ObjCCategoryImpl:
4003 return CXCursor_ObjCCategoryImplDecl;
4004 case Decl::ObjCImplementation:
4005 return CXCursor_ObjCImplementationDecl;
4007 case Decl::ObjCInterface:
4008 return CXCursor_ObjCInterfaceDecl;
4009 case Decl::ObjCIvar:
4010 return CXCursor_ObjCIvarDecl;
4011 case Decl::ObjCMethod:
4012 return cast<ObjCMethodDecl>(D)->isInstanceMethod()
4013 ? CXCursor_ObjCInstanceMethodDecl
4014 : CXCursor_ObjCClassMethodDecl;
4015 case Decl::CXXMethod:
4016 return CXCursor_CXXMethod;
4017 case Decl::CXXConstructor:
4018 return CXCursor_Constructor;
4019 case Decl::CXXDestructor:
4020 return CXCursor_Destructor;
4021 case Decl::CXXConversion:
4022 return CXCursor_ConversionFunction;
4023 case Decl::ObjCProperty:
4024 return CXCursor_ObjCPropertyDecl;
4025 case Decl::ObjCProtocol:
4026 return CXCursor_ObjCProtocolDecl;
4028 return CXCursor_ParmDecl;
4030 return CXCursor_TypedefDecl;
4031 case Decl::TypeAlias:
4032 return CXCursor_TypeAliasDecl;
4033 case Decl::TypeAliasTemplate:
4034 return CXCursor_TypeAliasTemplateDecl;
4036 return CXCursor_VarDecl;
4037 case Decl::Namespace:
4038 return CXCursor_Namespace;
4039 case Decl::NamespaceAlias:
4040 return CXCursor_NamespaceAlias;
4041 case Decl::TemplateTypeParm:
4042 return CXCursor_TemplateTypeParameter;
4043 case Decl::NonTypeTemplateParm:
4044 return CXCursor_NonTypeTemplateParameter;
4045 case Decl::TemplateTemplateParm:
4046 return CXCursor_TemplateTemplateParameter;
4047 case Decl::FunctionTemplate:
4048 return CXCursor_FunctionTemplate;
4049 case Decl::ClassTemplate:
4050 return CXCursor_ClassTemplate;
4051 case Decl::AccessSpec:
4052 return CXCursor_CXXAccessSpecifier;
4053 case Decl::ClassTemplatePartialSpecialization:
4054 return CXCursor_ClassTemplatePartialSpecialization;
4055 case Decl::UsingDirective:
4056 return CXCursor_UsingDirective;
4057 case Decl::StaticAssert:
4058 return CXCursor_StaticAssert;
4060 return CXCursor_FriendDecl;
4061 case Decl::TranslationUnit:
4062 return CXCursor_TranslationUnit;
4065 case Decl::UnresolvedUsingValue:
4066 case Decl::UnresolvedUsingTypename:
4067 return CXCursor_UsingDeclaration;
4069 case Decl::UsingEnum:
4070 return CXCursor_EnumDecl;
4072 case Decl::ObjCPropertyImpl:
4073 switch (cast<ObjCPropertyImplDecl>(D)->getPropertyImplementation()) {
4074 case ObjCPropertyImplDecl::Dynamic:
4075 return CXCursor_ObjCDynamicDecl;
4077 case ObjCPropertyImplDecl::Synthesize:
4078 return CXCursor_ObjCSynthesizeDecl;
4080 llvm_unreachable("Unexpected Kind!");
4083 return CXCursor_ModuleImportDecl;
4085 case Decl::ObjCTypeParam:
4086 return CXCursor_TemplateTypeParameter;
4089 return CXCursor_ConceptDecl;
4092 if (const auto *TD = dyn_cast<TagDecl>(D)) {
4093 switch (TD->getTagKind()) {
4094 case TTK_Interface: // fall through
4096 return CXCursor_StructDecl;
4098 return CXCursor_ClassDecl;
4100 return CXCursor_UnionDecl;
4102 return CXCursor_EnumDecl;
4107 return CXCursor_UnexposedDecl;
4110 static void AddMacroResults(Preprocessor &PP, ResultBuilder &Results,
4111 bool LoadExternal, bool IncludeUndefined,
4112 bool TargetTypeIsPointer = false) {
4113 typedef CodeCompletionResult Result;
4115 Results.EnterNewScope();
4117 for (Preprocessor::macro_iterator M = PP.macro_begin(LoadExternal),
4118 MEnd = PP.macro_end(LoadExternal);
4120 auto MD = PP.getMacroDefinition(M->first);
4121 if (IncludeUndefined || MD) {
4122 MacroInfo *MI = MD.getMacroInfo();
4123 if (MI && MI->isUsedForHeaderGuard())
4127 Result(M->first, MI,
4128 getMacroUsagePriority(M->first->getName(), PP.getLangOpts(),
4129 TargetTypeIsPointer)));
4133 Results.ExitScope();
4136 static void AddPrettyFunctionResults(const LangOptions &LangOpts,
4137 ResultBuilder &Results) {
4138 typedef CodeCompletionResult Result;
4140 Results.EnterNewScope();
4142 Results.AddResult(Result("__PRETTY_FUNCTION__", CCP_Constant));
4143 Results.AddResult(Result("__FUNCTION__", CCP_Constant));
4144 if (LangOpts.C99 || LangOpts.CPlusPlus11)
4145 Results.AddResult(Result("__func__", CCP_Constant));
4146 Results.ExitScope();
4149 static void HandleCodeCompleteResults(Sema *S,
4150 CodeCompleteConsumer *CodeCompleter,
4151 const CodeCompletionContext &Context,
4152 CodeCompletionResult *Results,
4153 unsigned NumResults) {
4155 CodeCompleter->ProcessCodeCompleteResults(*S, Context, Results, NumResults);
4158 static CodeCompletionContext
4159 mapCodeCompletionContext(Sema &S, Sema::ParserCompletionContext PCC) {
4161 case Sema::PCC_Namespace:
4162 return CodeCompletionContext::CCC_TopLevel;
4164 case Sema::PCC_Class:
4165 return CodeCompletionContext::CCC_ClassStructUnion;
4167 case Sema::PCC_ObjCInterface:
4168 return CodeCompletionContext::CCC_ObjCInterface;
4170 case Sema::PCC_ObjCImplementation:
4171 return CodeCompletionContext::CCC_ObjCImplementation;
4173 case Sema::PCC_ObjCInstanceVariableList:
4174 return CodeCompletionContext::CCC_ObjCIvarList;
4176 case Sema::PCC_Template:
4177 case Sema::PCC_MemberTemplate:
4178 if (S.CurContext->isFileContext())
4179 return CodeCompletionContext::CCC_TopLevel;
4180 if (S.CurContext->isRecord())
4181 return CodeCompletionContext::CCC_ClassStructUnion;
4182 return CodeCompletionContext::CCC_Other;
4184 case Sema::PCC_RecoveryInFunction:
4185 return CodeCompletionContext::CCC_Recovery;
4187 case Sema::PCC_ForInit:
4188 if (S.getLangOpts().CPlusPlus || S.getLangOpts().C99 ||
4189 S.getLangOpts().ObjC)
4190 return CodeCompletionContext::CCC_ParenthesizedExpression;
4192 return CodeCompletionContext::CCC_Expression;
4194 case Sema::PCC_Expression:
4195 return CodeCompletionContext::CCC_Expression;
4196 case Sema::PCC_Condition:
4197 return CodeCompletionContext(CodeCompletionContext::CCC_Expression,
4198 S.getASTContext().BoolTy);
4200 case Sema::PCC_Statement:
4201 return CodeCompletionContext::CCC_Statement;
4203 case Sema::PCC_Type:
4204 return CodeCompletionContext::CCC_Type;
4206 case Sema::PCC_ParenthesizedExpression:
4207 return CodeCompletionContext::CCC_ParenthesizedExpression;
4209 case Sema::PCC_LocalDeclarationSpecifiers:
4210 return CodeCompletionContext::CCC_Type;
4213 llvm_unreachable("Invalid ParserCompletionContext!");
4216 /// If we're in a C++ virtual member function, add completion results
4217 /// that invoke the functions we override, since it's common to invoke the
4218 /// overridden function as well as adding new functionality.
4220 /// \param S The semantic analysis object for which we are generating results.
4222 /// \param InContext This context in which the nested-name-specifier preceding
4223 /// the code-completion point
4224 static void MaybeAddOverrideCalls(Sema &S, DeclContext *InContext,
4225 ResultBuilder &Results) {
4226 // Look through blocks.
4227 DeclContext *CurContext = S.CurContext;
4228 while (isa<BlockDecl>(CurContext))
4229 CurContext = CurContext->getParent();
4231 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(CurContext);
4232 if (!Method || !Method->isVirtual())
4235 // We need to have names for all of the parameters, if we're going to
4236 // generate a forwarding call.
4237 for (auto *P : Method->parameters())
4238 if (!P->getDeclName())
4241 PrintingPolicy Policy = getCompletionPrintingPolicy(S);
4242 for (const CXXMethodDecl *Overridden : Method->overridden_methods()) {
4243 CodeCompletionBuilder Builder(Results.getAllocator(),
4244 Results.getCodeCompletionTUInfo());
4245 if (Overridden->getCanonicalDecl() == Method->getCanonicalDecl())
4248 // If we need a nested-name-specifier, add one now.
4250 NestedNameSpecifier *NNS = getRequiredQualification(
4251 S.Context, CurContext, Overridden->getDeclContext());
4254 llvm::raw_string_ostream OS(Str);
4255 NNS->print(OS, Policy);
4256 Builder.AddTextChunk(Results.getAllocator().CopyString(OS.str()));
4258 } else if (!InContext->Equals(Overridden->getDeclContext()))
4261 Builder.AddTypedTextChunk(
4262 Results.getAllocator().CopyString(Overridden->getNameAsString()));
4263 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4264 bool FirstParam = true;
4265 for (auto *P : Method->parameters()) {
4269 Builder.AddChunk(CodeCompletionString::CK_Comma);
4271 Builder.AddPlaceholderChunk(
4272 Results.getAllocator().CopyString(P->getIdentifier()->getName()));
4274 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4275 Results.AddResult(CodeCompletionResult(
4276 Builder.TakeString(), CCP_SuperCompletion, CXCursor_CXXMethod,
4277 CXAvailability_Available, Overridden));
4278 Results.Ignore(Overridden);
4282 void Sema::CodeCompleteModuleImport(SourceLocation ImportLoc,
4283 ModuleIdPath Path) {
4284 typedef CodeCompletionResult Result;
4285 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4286 CodeCompleter->getCodeCompletionTUInfo(),
4287 CodeCompletionContext::CCC_Other);
4288 Results.EnterNewScope();
4290 CodeCompletionAllocator &Allocator = Results.getAllocator();
4291 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
4292 typedef CodeCompletionResult Result;
4294 // Enumerate all top-level modules.
4295 SmallVector<Module *, 8> Modules;
4296 PP.getHeaderSearchInfo().collectAllModules(Modules);
4297 for (unsigned I = 0, N = Modules.size(); I != N; ++I) {
4298 Builder.AddTypedTextChunk(
4299 Builder.getAllocator().CopyString(Modules[I]->Name));
4300 Results.AddResult(Result(
4301 Builder.TakeString(), CCP_Declaration, CXCursor_ModuleImportDecl,
4302 Modules[I]->isAvailable() ? CXAvailability_Available
4303 : CXAvailability_NotAvailable));
4305 } else if (getLangOpts().Modules) {
4306 // Load the named module.
4308 PP.getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
4309 /*IsInclusionDirective=*/false);
4310 // Enumerate submodules.
4312 for (auto *Submodule : Mod->submodules()) {
4313 Builder.AddTypedTextChunk(
4314 Builder.getAllocator().CopyString(Submodule->Name));
4315 Results.AddResult(Result(
4316 Builder.TakeString(), CCP_Declaration, CXCursor_ModuleImportDecl,
4317 Submodule->isAvailable() ? CXAvailability_Available
4318 : CXAvailability_NotAvailable));
4322 Results.ExitScope();
4323 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4324 Results.data(), Results.size());
4327 void Sema::CodeCompleteOrdinaryName(Scope *S,
4328 ParserCompletionContext CompletionContext) {
4329 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4330 CodeCompleter->getCodeCompletionTUInfo(),
4331 mapCodeCompletionContext(*this, CompletionContext));
4332 Results.EnterNewScope();
4334 // Determine how to filter results, e.g., so that the names of
4335 // values (functions, enumerators, function templates, etc.) are
4336 // only allowed where we can have an expression.
4337 switch (CompletionContext) {
4340 case PCC_ObjCInterface:
4341 case PCC_ObjCImplementation:
4342 case PCC_ObjCInstanceVariableList:
4344 case PCC_MemberTemplate:
4346 case PCC_LocalDeclarationSpecifiers:
4347 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
4351 case PCC_ParenthesizedExpression:
4352 case PCC_Expression:
4355 if (WantTypesInContext(CompletionContext, getLangOpts()))
4356 Results.setFilter(&ResultBuilder::IsOrdinaryName);
4358 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
4360 if (getLangOpts().CPlusPlus)
4361 MaybeAddOverrideCalls(*this, /*InContext=*/nullptr, Results);
4364 case PCC_RecoveryInFunction:
4369 // If we are in a C++ non-static member function, check the qualifiers on
4370 // the member function to filter/prioritize the results list.
4371 auto ThisType = getCurrentThisType();
4372 if (!ThisType.isNull())
4373 Results.setObjectTypeQualifiers(ThisType->getPointeeType().getQualifiers(),
4376 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4377 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4378 CodeCompleter->includeGlobals(),
4379 CodeCompleter->loadExternal());
4381 AddOrdinaryNameResults(CompletionContext, S, *this, Results);
4382 Results.ExitScope();
4384 switch (CompletionContext) {
4385 case PCC_ParenthesizedExpression:
4386 case PCC_Expression:
4388 case PCC_RecoveryInFunction:
4389 if (S->getFnParent())
4390 AddPrettyFunctionResults(getLangOpts(), Results);
4395 case PCC_ObjCInterface:
4396 case PCC_ObjCImplementation:
4397 case PCC_ObjCInstanceVariableList:
4399 case PCC_MemberTemplate:
4403 case PCC_LocalDeclarationSpecifiers:
4407 if (CodeCompleter->includeMacros())
4408 AddMacroResults(PP, Results, CodeCompleter->loadExternal(), false);
4410 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4411 Results.data(), Results.size());
4414 static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
4415 ParsedType Receiver,
4416 ArrayRef<IdentifierInfo *> SelIdents,
4417 bool AtArgumentExpression, bool IsSuper,
4418 ResultBuilder &Results);
4420 void Sema::CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
4421 bool AllowNonIdentifiers,
4422 bool AllowNestedNameSpecifiers) {
4423 typedef CodeCompletionResult Result;
4424 ResultBuilder Results(
4425 *this, CodeCompleter->getAllocator(),
4426 CodeCompleter->getCodeCompletionTUInfo(),
4427 AllowNestedNameSpecifiers
4428 // FIXME: Try to separate codepath leading here to deduce whether we
4429 // need an existing symbol or a new one.
4430 ? CodeCompletionContext::CCC_SymbolOrNewName
4431 : CodeCompletionContext::CCC_NewName);
4432 Results.EnterNewScope();
4434 // Type qualifiers can come after names.
4435 Results.AddResult(Result("const"));
4436 Results.AddResult(Result("volatile"));
4437 if (getLangOpts().C99)
4438 Results.AddResult(Result("restrict"));
4440 if (getLangOpts().CPlusPlus) {
4441 if (getLangOpts().CPlusPlus11 &&
4442 (DS.getTypeSpecType() == DeclSpec::TST_class ||
4443 DS.getTypeSpecType() == DeclSpec::TST_struct))
4444 Results.AddResult("final");
4446 if (AllowNonIdentifiers) {
4447 Results.AddResult(Result("operator"));
4450 // Add nested-name-specifiers.
4451 if (AllowNestedNameSpecifiers) {
4452 Results.allowNestedNameSpecifiers();
4453 Results.setFilter(&ResultBuilder::IsImpossibleToSatisfy);
4454 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4455 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer,
4456 CodeCompleter->includeGlobals(),
4457 CodeCompleter->loadExternal());
4458 Results.setFilter(nullptr);
4461 Results.ExitScope();
4463 // If we're in a context where we might have an expression (rather than a
4464 // declaration), and what we've seen so far is an Objective-C type that could
4465 // be a receiver of a class message, this may be a class message send with
4466 // the initial opening bracket '[' missing. Add appropriate completions.
4467 if (AllowNonIdentifiers && !AllowNestedNameSpecifiers &&
4468 DS.getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier &&
4469 DS.getTypeSpecType() == DeclSpec::TST_typename &&
4470 DS.getTypeSpecComplex() == DeclSpec::TSC_unspecified &&
4471 DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&
4472 !DS.isTypeAltiVecVector() && S &&
4473 (S->getFlags() & Scope::DeclScope) != 0 &&
4474 (S->getFlags() & (Scope::ClassScope | Scope::TemplateParamScope |
4475 Scope::FunctionPrototypeScope | Scope::AtCatchScope)) ==
4477 ParsedType T = DS.getRepAsType();
4478 if (!T.get().isNull() && T.get()->isObjCObjectOrInterfaceType())
4479 AddClassMessageCompletions(*this, S, T, std::nullopt, false, false,
4483 // Note that we intentionally suppress macro results here, since we do not
4484 // encourage using macros to produce the names of entities.
4486 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4487 Results.data(), Results.size());
4490 static const char *underscoreAttrScope(llvm::StringRef Scope) {
4491 if (Scope == "clang")
4498 static const char *noUnderscoreAttrScope(llvm::StringRef Scope) {
4499 if (Scope == "_Clang")
4501 if (Scope == "__gnu__")
4506 void Sema::CodeCompleteAttribute(AttributeCommonInfo::Syntax Syntax,
4507 AttributeCompletion Completion,
4508 const IdentifierInfo *InScope) {
4509 if (Completion == AttributeCompletion::None)
4511 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4512 CodeCompleter->getCodeCompletionTUInfo(),
4513 CodeCompletionContext::CCC_Attribute);
4515 // We're going to iterate over the normalized spellings of the attribute.
4516 // These don't include "underscore guarding": the normalized spelling is
4517 // clang::foo but you can also write _Clang::__foo__.
4519 // (Clang supports a mix like clang::__foo__ but we won't suggest it: either
4520 // you care about clashing with macros or you don't).
4522 // So if we're already in a scope, we determine its canonical spellings
4523 // (for comparison with normalized attr spelling) and remember whether it was
4524 // underscore-guarded (so we know how to spell contained attributes).
4525 llvm::StringRef InScopeName;
4526 bool InScopeUnderscore = false;
4528 InScopeName = InScope->getName();
4529 if (const char *NoUnderscore = noUnderscoreAttrScope(InScopeName)) {
4530 InScopeName = NoUnderscore;
4531 InScopeUnderscore = true;
4534 bool SyntaxSupportsGuards = Syntax == AttributeCommonInfo::AS_GNU ||
4535 Syntax == AttributeCommonInfo::AS_CXX11 ||
4536 Syntax == AttributeCommonInfo::AS_C2x;
4538 llvm::DenseSet<llvm::StringRef> FoundScopes;
4539 auto AddCompletions = [&](const ParsedAttrInfo &A) {
4540 if (A.IsTargetSpecific && !A.existsInTarget(Context.getTargetInfo()))
4542 if (!A.acceptsLangOpts(getLangOpts()))
4544 for (const auto &S : A.Spellings) {
4545 if (S.Syntax != Syntax)
4547 llvm::StringRef Name = S.NormalizedFullName;
4548 llvm::StringRef Scope;
4549 if ((Syntax == AttributeCommonInfo::AS_CXX11 ||
4550 Syntax == AttributeCommonInfo::AS_C2x)) {
4551 std::tie(Scope, Name) = Name.split("::");
4552 if (Name.empty()) // oops, unscoped
4553 std::swap(Name, Scope);
4556 // Do we just want a list of scopes rather than attributes?
4557 if (Completion == AttributeCompletion::Scope) {
4558 // Make sure to emit each scope only once.
4559 if (!Scope.empty() && FoundScopes.insert(Scope).second) {
4561 CodeCompletionResult(Results.getAllocator().CopyString(Scope)));
4562 // Include alternate form (__gnu__ instead of gnu).
4563 if (const char *Scope2 = underscoreAttrScope(Scope))
4564 Results.AddResult(CodeCompletionResult(Scope2));
4569 // If a scope was specified, it must match but we don't need to print it.
4570 if (!InScopeName.empty()) {
4571 if (Scope != InScopeName)
4576 auto Add = [&](llvm::StringRef Scope, llvm::StringRef Name,
4578 CodeCompletionBuilder Builder(Results.getAllocator(),
4579 Results.getCodeCompletionTUInfo());
4580 llvm::SmallString<32> Text;
4581 if (!Scope.empty()) {
4590 Builder.AddTypedTextChunk(Results.getAllocator().CopyString(Text));
4592 if (!A.ArgNames.empty()) {
4593 Builder.AddChunk(CodeCompletionString::CK_LeftParen, "(");
4595 for (const char *Arg : A.ArgNames) {
4597 Builder.AddChunk(CodeCompletionString::CK_Comma, ", ");
4599 Builder.AddPlaceholderChunk(Arg);
4601 Builder.AddChunk(CodeCompletionString::CK_RightParen, ")");
4604 Results.AddResult(Builder.TakeString());
4607 // Generate the non-underscore-guarded result.
4608 // Note this is (a suffix of) the NormalizedFullName, no need to copy.
4609 // If an underscore-guarded scope was specified, only the
4610 // underscore-guarded attribute name is relevant.
4611 if (!InScopeUnderscore)
4612 Add(Scope, Name, /*Underscores=*/false);
4614 // Generate the underscore-guarded version, for syntaxes that support it.
4615 // We skip this if the scope was already spelled and not guarded, or
4616 // we must spell it and can't guard it.
4617 if (!(InScope && !InScopeUnderscore) && SyntaxSupportsGuards) {
4618 llvm::SmallString<32> Guarded;
4619 if (Scope.empty()) {
4620 Add(Scope, Name, /*Underscores=*/true);
4622 const char *GuardedScope = underscoreAttrScope(Scope);
4625 Add(GuardedScope, Name, /*Underscores=*/true);
4629 // It may be nice to include the Kind so we can look up the docs later.
4633 for (const auto *A : ParsedAttrInfo::getAllBuiltin())
4635 for (const auto &Entry : ParsedAttrInfoRegistry::entries())
4636 AddCompletions(*Entry.instantiate());
4638 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4639 Results.data(), Results.size());
4642 struct Sema::CodeCompleteExpressionData {
4643 CodeCompleteExpressionData(QualType PreferredType = QualType(),
4644 bool IsParenthesized = false)
4645 : PreferredType(PreferredType), IntegralConstantExpression(false),
4646 ObjCCollection(false), IsParenthesized(IsParenthesized) {}
4648 QualType PreferredType;
4649 bool IntegralConstantExpression;
4650 bool ObjCCollection;
4651 bool IsParenthesized;
4652 SmallVector<Decl *, 4> IgnoreDecls;
4656 /// Information that allows to avoid completing redundant enumerators.
4657 struct CoveredEnumerators {
4658 llvm::SmallPtrSet<EnumConstantDecl *, 8> Seen;
4659 NestedNameSpecifier *SuggestedQualifier = nullptr;
4663 static void AddEnumerators(ResultBuilder &Results, ASTContext &Context,
4664 EnumDecl *Enum, DeclContext *CurContext,
4665 const CoveredEnumerators &Enumerators) {
4666 NestedNameSpecifier *Qualifier = Enumerators.SuggestedQualifier;
4667 if (Context.getLangOpts().CPlusPlus && !Qualifier && Enumerators.Seen.empty()) {
4668 // If there are no prior enumerators in C++, check whether we have to
4669 // qualify the names of the enumerators that we suggest, because they
4670 // may not be visible in this scope.
4671 Qualifier = getRequiredQualification(Context, CurContext, Enum);
4674 Results.EnterNewScope();
4675 for (auto *E : Enum->enumerators()) {
4676 if (Enumerators.Seen.count(E))
4679 CodeCompletionResult R(E, CCP_EnumInCase, Qualifier);
4680 Results.AddResult(R, CurContext, nullptr, false);
4682 Results.ExitScope();
4685 /// Try to find a corresponding FunctionProtoType for function-like types (e.g.
4686 /// function pointers, std::function, etc).
4687 static const FunctionProtoType *TryDeconstructFunctionLike(QualType T) {
4688 assert(!T.isNull());
4689 // Try to extract first template argument from std::function<> and similar.
4690 // Note we only handle the sugared types, they closely match what users wrote.
4691 // We explicitly choose to not handle ClassTemplateSpecializationDecl.
4692 if (auto *Specialization = T->getAs<TemplateSpecializationType>()) {
4693 if (Specialization->template_arguments().size() != 1)
4695 const TemplateArgument &Argument = Specialization->template_arguments()[0];
4696 if (Argument.getKind() != TemplateArgument::Type)
4698 return Argument.getAsType()->getAs<FunctionProtoType>();
4700 // Handle other cases.
4701 if (T->isPointerType())
4702 T = T->getPointeeType();
4703 return T->getAs<FunctionProtoType>();
4706 /// Adds a pattern completion for a lambda expression with the specified
4707 /// parameter types and placeholders for parameter names.
4708 static void AddLambdaCompletion(ResultBuilder &Results,
4709 llvm::ArrayRef<QualType> Parameters,
4710 const LangOptions &LangOpts) {
4711 if (!Results.includeCodePatterns())
4713 CodeCompletionBuilder Completion(Results.getAllocator(),
4714 Results.getCodeCompletionTUInfo());
4715 // [](<parameters>) {}
4716 Completion.AddChunk(CodeCompletionString::CK_LeftBracket);
4717 Completion.AddPlaceholderChunk("=");
4718 Completion.AddChunk(CodeCompletionString::CK_RightBracket);
4719 if (!Parameters.empty()) {
4720 Completion.AddChunk(CodeCompletionString::CK_LeftParen);
4722 for (auto Parameter : Parameters) {
4724 Completion.AddChunk(CodeCompletionString::ChunkKind::CK_Comma);
4728 constexpr llvm::StringLiteral NamePlaceholder = "!#!NAME_GOES_HERE!#!";
4729 std::string Type = std::string(NamePlaceholder);
4730 Parameter.getAsStringInternal(Type, PrintingPolicy(LangOpts));
4731 llvm::StringRef Prefix, Suffix;
4732 std::tie(Prefix, Suffix) = llvm::StringRef(Type).split(NamePlaceholder);
4733 Prefix = Prefix.rtrim();
4734 Suffix = Suffix.ltrim();
4736 Completion.AddTextChunk(Completion.getAllocator().CopyString(Prefix));
4737 Completion.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4738 Completion.AddPlaceholderChunk("parameter");
4739 Completion.AddTextChunk(Completion.getAllocator().CopyString(Suffix));
4741 Completion.AddChunk(CodeCompletionString::CK_RightParen);
4743 Completion.AddChunk(clang::CodeCompletionString::CK_HorizontalSpace);
4744 Completion.AddChunk(CodeCompletionString::CK_LeftBrace);
4745 Completion.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4746 Completion.AddPlaceholderChunk("body");
4747 Completion.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4748 Completion.AddChunk(CodeCompletionString::CK_RightBrace);
4750 Results.AddResult(Completion.TakeString());
4753 /// Perform code-completion in an expression context when we know what
4754 /// type we're looking for.
4755 void Sema::CodeCompleteExpression(Scope *S,
4756 const CodeCompleteExpressionData &Data) {
4757 ResultBuilder Results(
4758 *this, CodeCompleter->getAllocator(),
4759 CodeCompleter->getCodeCompletionTUInfo(),
4760 CodeCompletionContext(
4761 Data.IsParenthesized
4762 ? CodeCompletionContext::CCC_ParenthesizedExpression
4763 : CodeCompletionContext::CCC_Expression,
4764 Data.PreferredType));
4766 Data.IsParenthesized ? PCC_ParenthesizedExpression : PCC_Expression;
4767 if (Data.ObjCCollection)
4768 Results.setFilter(&ResultBuilder::IsObjCCollection);
4769 else if (Data.IntegralConstantExpression)
4770 Results.setFilter(&ResultBuilder::IsIntegralConstantValue);
4771 else if (WantTypesInContext(PCC, getLangOpts()))
4772 Results.setFilter(&ResultBuilder::IsOrdinaryName);
4774 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
4776 if (!Data.PreferredType.isNull())
4777 Results.setPreferredType(Data.PreferredType.getNonReferenceType());
4779 // Ignore any declarations that we were told that we don't care about.
4780 for (unsigned I = 0, N = Data.IgnoreDecls.size(); I != N; ++I)
4781 Results.Ignore(Data.IgnoreDecls[I]);
4783 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4784 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4785 CodeCompleter->includeGlobals(),
4786 CodeCompleter->loadExternal());
4788 Results.EnterNewScope();
4789 AddOrdinaryNameResults(PCC, S, *this, Results);
4790 Results.ExitScope();
4792 bool PreferredTypeIsPointer = false;
4793 if (!Data.PreferredType.isNull()) {
4794 PreferredTypeIsPointer = Data.PreferredType->isAnyPointerType() ||
4795 Data.PreferredType->isMemberPointerType() ||
4796 Data.PreferredType->isBlockPointerType();
4797 if (Data.PreferredType->isEnumeralType()) {
4798 EnumDecl *Enum = Data.PreferredType->castAs<EnumType>()->getDecl();
4799 if (auto *Def = Enum->getDefinition())
4801 // FIXME: collect covered enumerators in cases like:
4802 // if (x == my_enum::one) { ... } else if (x == ^) {}
4803 AddEnumerators(Results, Context, Enum, CurContext, CoveredEnumerators());
4807 if (S->getFnParent() && !Data.ObjCCollection &&
4808 !Data.IntegralConstantExpression)
4809 AddPrettyFunctionResults(getLangOpts(), Results);
4811 if (CodeCompleter->includeMacros())
4812 AddMacroResults(PP, Results, CodeCompleter->loadExternal(), false,
4813 PreferredTypeIsPointer);
4815 // Complete a lambda expression when preferred type is a function.
4816 if (!Data.PreferredType.isNull() && getLangOpts().CPlusPlus11) {
4817 if (const FunctionProtoType *F =
4818 TryDeconstructFunctionLike(Data.PreferredType))
4819 AddLambdaCompletion(Results, F->getParamTypes(), getLangOpts());
4822 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4823 Results.data(), Results.size());
4826 void Sema::CodeCompleteExpression(Scope *S, QualType PreferredType,
4827 bool IsParenthesized) {
4828 return CodeCompleteExpression(
4829 S, CodeCompleteExpressionData(PreferredType, IsParenthesized));
4832 void Sema::CodeCompletePostfixExpression(Scope *S, ExprResult E,
4833 QualType PreferredType) {
4835 CodeCompleteExpression(S, PreferredType);
4836 else if (getLangOpts().ObjC)
4837 CodeCompleteObjCInstanceMessage(S, E.get(), std::nullopt, false);
4840 /// The set of properties that have already been added, referenced by
4842 typedef llvm::SmallPtrSet<IdentifierInfo *, 16> AddedPropertiesSet;
4844 /// Retrieve the container definition, if any?
4845 static ObjCContainerDecl *getContainerDef(ObjCContainerDecl *Container) {
4846 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
4847 if (Interface->hasDefinition())
4848 return Interface->getDefinition();
4853 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4854 if (Protocol->hasDefinition())
4855 return Protocol->getDefinition();
4862 /// Adds a block invocation code completion result for the given block
4863 /// declaration \p BD.
4864 static void AddObjCBlockCall(ASTContext &Context, const PrintingPolicy &Policy,
4865 CodeCompletionBuilder &Builder,
4866 const NamedDecl *BD,
4867 const FunctionTypeLoc &BlockLoc,
4868 const FunctionProtoTypeLoc &BlockProtoLoc) {
4869 Builder.AddResultTypeChunk(
4870 GetCompletionTypeString(BlockLoc.getReturnLoc().getType(), Context,
4871 Policy, Builder.getAllocator()));
4873 AddTypedNameChunk(Context, Policy, BD, Builder);
4874 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4876 if (BlockProtoLoc && BlockProtoLoc.getTypePtr()->isVariadic()) {
4877 Builder.AddPlaceholderChunk("...");
4879 for (unsigned I = 0, N = BlockLoc.getNumParams(); I != N; ++I) {
4881 Builder.AddChunk(CodeCompletionString::CK_Comma);
4883 // Format the placeholder string.
4884 std::string PlaceholderStr =
4885 FormatFunctionParameter(Policy, BlockLoc.getParam(I));
4887 if (I == N - 1 && BlockProtoLoc &&
4888 BlockProtoLoc.getTypePtr()->isVariadic())
4889 PlaceholderStr += ", ...";
4891 // Add the placeholder string.
4892 Builder.AddPlaceholderChunk(
4893 Builder.getAllocator().CopyString(PlaceholderStr));
4897 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4901 AddObjCProperties(const CodeCompletionContext &CCContext,
4902 ObjCContainerDecl *Container, bool AllowCategories,
4903 bool AllowNullaryMethods, DeclContext *CurContext,
4904 AddedPropertiesSet &AddedProperties, ResultBuilder &Results,
4905 bool IsBaseExprStatement = false,
4906 bool IsClassProperty = false, bool InOriginalClass = true) {
4907 typedef CodeCompletionResult Result;
4909 // Retrieve the definition.
4910 Container = getContainerDef(Container);
4912 // Add properties in this container.
4913 const auto AddProperty = [&](const ObjCPropertyDecl *P) {
4914 if (!AddedProperties.insert(P->getIdentifier()).second)
4917 // FIXME: Provide block invocation completion for non-statement
4919 if (!P->getType().getTypePtr()->isBlockPointerType() ||
4920 !IsBaseExprStatement) {
4921 Result R = Result(P, Results.getBasePriority(P), nullptr);
4922 if (!InOriginalClass)
4924 Results.MaybeAddResult(R, CurContext);
4928 // Block setter and invocation completion is provided only when we are able
4929 // to find the FunctionProtoTypeLoc with parameter names for the block.
4930 FunctionTypeLoc BlockLoc;
4931 FunctionProtoTypeLoc BlockProtoLoc;
4932 findTypeLocationForBlockDecl(P->getTypeSourceInfo(), BlockLoc,
4935 Result R = Result(P, Results.getBasePriority(P), nullptr);
4936 if (!InOriginalClass)
4938 Results.MaybeAddResult(R, CurContext);
4942 // The default completion result for block properties should be the block
4943 // invocation completion when the base expression is a statement.
4944 CodeCompletionBuilder Builder(Results.getAllocator(),
4945 Results.getCodeCompletionTUInfo());
4946 AddObjCBlockCall(Container->getASTContext(),
4947 getCompletionPrintingPolicy(Results.getSema()), Builder, P,
4948 BlockLoc, BlockProtoLoc);
4949 Result R = Result(Builder.TakeString(), P, Results.getBasePriority(P));
4950 if (!InOriginalClass)
4952 Results.MaybeAddResult(R, CurContext);
4954 // Provide additional block setter completion iff the base expression is a
4955 // statement and the block property is mutable.
4956 if (!P->isReadOnly()) {
4957 CodeCompletionBuilder Builder(Results.getAllocator(),
4958 Results.getCodeCompletionTUInfo());
4959 AddResultTypeChunk(Container->getASTContext(),
4960 getCompletionPrintingPolicy(Results.getSema()), P,
4961 CCContext.getBaseType(), Builder);
4962 Builder.AddTypedTextChunk(
4963 Results.getAllocator().CopyString(P->getName()));
4964 Builder.AddChunk(CodeCompletionString::CK_Equal);
4966 std::string PlaceholderStr = formatBlockPlaceholder(
4967 getCompletionPrintingPolicy(Results.getSema()), P, BlockLoc,
4968 BlockProtoLoc, /*SuppressBlockName=*/true);
4969 // Add the placeholder string.
4970 Builder.AddPlaceholderChunk(
4971 Builder.getAllocator().CopyString(PlaceholderStr));
4973 // When completing blocks properties that return void the default
4974 // property completion result should show up before the setter,
4975 // otherwise the setter completion should show up before the default
4976 // property completion, as we normally want to use the result of the
4979 Result(Builder.TakeString(), P,
4980 Results.getBasePriority(P) +
4981 (BlockLoc.getTypePtr()->getReturnType()->isVoidType()
4982 ? CCD_BlockPropertySetter
4983 : -CCD_BlockPropertySetter));
4984 if (!InOriginalClass)
4986 Results.MaybeAddResult(R, CurContext);
4990 if (IsClassProperty) {
4991 for (const auto *P : Container->class_properties())
4994 for (const auto *P : Container->instance_properties())
4998 // Add nullary methods or implicit class properties
4999 if (AllowNullaryMethods) {
5000 ASTContext &Context = Container->getASTContext();
5001 PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema());
5002 // Adds a method result
5003 const auto AddMethod = [&](const ObjCMethodDecl *M) {
5004 IdentifierInfo *Name = M->getSelector().getIdentifierInfoForSlot(0);
5007 if (!AddedProperties.insert(Name).second)
5009 CodeCompletionBuilder Builder(Results.getAllocator(),
5010 Results.getCodeCompletionTUInfo());
5011 AddResultTypeChunk(Context, Policy, M, CCContext.getBaseType(), Builder);
5012 Builder.AddTypedTextChunk(
5013 Results.getAllocator().CopyString(Name->getName()));
5014 Result R = Result(Builder.TakeString(), M,
5015 CCP_MemberDeclaration + CCD_MethodAsProperty);
5016 if (!InOriginalClass)
5018 Results.MaybeAddResult(R, CurContext);
5021 if (IsClassProperty) {
5022 for (const auto *M : Container->methods()) {
5023 // Gather the class method that can be used as implicit property
5024 // getters. Methods with arguments or methods that return void aren't
5025 // added to the results as they can't be used as a getter.
5026 if (!M->getSelector().isUnarySelector() ||
5027 M->getReturnType()->isVoidType() || M->isInstanceMethod())
5032 for (auto *M : Container->methods()) {
5033 if (M->getSelector().isUnarySelector())
5039 // Add properties in referenced protocols.
5040 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
5041 for (auto *P : Protocol->protocols())
5042 AddObjCProperties(CCContext, P, AllowCategories, AllowNullaryMethods,
5043 CurContext, AddedProperties, Results,
5044 IsBaseExprStatement, IsClassProperty,
5045 /*InOriginalClass*/ false);
5046 } else if (ObjCInterfaceDecl *IFace =
5047 dyn_cast<ObjCInterfaceDecl>(Container)) {
5048 if (AllowCategories) {
5049 // Look through categories.
5050 for (auto *Cat : IFace->known_categories())
5051 AddObjCProperties(CCContext, Cat, AllowCategories, AllowNullaryMethods,
5052 CurContext, AddedProperties, Results,
5053 IsBaseExprStatement, IsClassProperty,
5057 // Look through protocols.
5058 for (auto *I : IFace->all_referenced_protocols())
5059 AddObjCProperties(CCContext, I, AllowCategories, AllowNullaryMethods,
5060 CurContext, AddedProperties, Results,
5061 IsBaseExprStatement, IsClassProperty,
5062 /*InOriginalClass*/ false);
5064 // Look in the superclass.
5065 if (IFace->getSuperClass())
5066 AddObjCProperties(CCContext, IFace->getSuperClass(), AllowCategories,
5067 AllowNullaryMethods, CurContext, AddedProperties,
5068 Results, IsBaseExprStatement, IsClassProperty,
5069 /*InOriginalClass*/ false);
5070 } else if (const auto *Category =
5071 dyn_cast<ObjCCategoryDecl>(Container)) {
5072 // Look through protocols.
5073 for (auto *P : Category->protocols())
5074 AddObjCProperties(CCContext, P, AllowCategories, AllowNullaryMethods,
5075 CurContext, AddedProperties, Results,
5076 IsBaseExprStatement, IsClassProperty,
5077 /*InOriginalClass*/ false);
5082 AddRecordMembersCompletionResults(Sema &SemaRef, ResultBuilder &Results,
5083 Scope *S, QualType BaseType,
5084 ExprValueKind BaseKind, RecordDecl *RD,
5085 std::optional<FixItHint> AccessOpFixIt) {
5086 // Indicate that we are performing a member access, and the cv-qualifiers
5087 // for the base object type.
5088 Results.setObjectTypeQualifiers(BaseType.getQualifiers(), BaseKind);
5090 // Access to a C/C++ class, struct, or union.
5091 Results.allowNestedNameSpecifiers();
5092 std::vector<FixItHint> FixIts;
5094 FixIts.emplace_back(*AccessOpFixIt);
5095 CodeCompletionDeclConsumer Consumer(Results, RD, BaseType, std::move(FixIts));
5096 SemaRef.LookupVisibleDecls(RD, Sema::LookupMemberName, Consumer,
5097 SemaRef.CodeCompleter->includeGlobals(),
5098 /*IncludeDependentBases=*/true,
5099 SemaRef.CodeCompleter->loadExternal());
5101 if (SemaRef.getLangOpts().CPlusPlus) {
5102 if (!Results.empty()) {
5103 // The "template" keyword can follow "->" or "." in the grammar.
5104 // However, we only want to suggest the template keyword if something
5106 bool IsDependent = BaseType->isDependentType();
5108 for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent())
5109 if (DeclContext *Ctx = DepScope->getEntity()) {
5110 IsDependent = Ctx->isDependentContext();
5116 Results.AddResult(CodeCompletionResult("template"));
5121 // Returns the RecordDecl inside the BaseType, falling back to primary template
5122 // in case of specializations. Since we might not have a decl for the
5123 // instantiation/specialization yet, e.g. dependent code.
5124 static RecordDecl *getAsRecordDecl(QualType BaseType) {
5125 BaseType = BaseType.getNonReferenceType();
5126 if (auto *RD = BaseType->getAsRecordDecl()) {
5127 if (const auto *CTSD =
5128 llvm::dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
5129 // Template might not be instantiated yet, fall back to primary template
5131 if (CTSD->getTemplateSpecializationKind() == TSK_Undeclared)
5132 RD = CTSD->getSpecializedTemplate()->getTemplatedDecl();
5137 if (const auto *TST = BaseType->getAs<TemplateSpecializationType>()) {
5138 if (const auto *TD = dyn_cast_or_null<ClassTemplateDecl>(
5139 TST->getTemplateName().getAsTemplateDecl())) {
5140 return TD->getTemplatedDecl();
5148 // Collects completion-relevant information about a concept-constrainted type T.
5149 // In particular, examines the constraint expressions to find members of T.
5151 // The design is very simple: we walk down each constraint looking for
5152 // expressions of the form T.foo().
5153 // If we're extra lucky, the return type is specified.
5154 // We don't do any clever handling of && or || in constraint expressions, we
5155 // take members from both branches.
5157 // For example, given:
5158 // template <class T> concept X = requires (T t, string& s) { t.print(s); };
5159 // template <X U> void foo(U u) { u.^ }
5160 // We want to suggest the inferred member function 'print(string)'.
5161 // We see that u has type U, so X<U> holds.
5162 // X<U> requires t.print(s) to be valid, where t has type U (substituted for T).
5163 // By looking at the CallExpr we find the signature of print().
5165 // While we tend to know in advance which kind of members (access via . -> ::)
5166 // we want, it's simpler just to gather them all and post-filter.
5168 // FIXME: some of this machinery could be used for non-concept type-parms too,
5169 // enabling completion for type parameters based on other uses of that param.
5171 // FIXME: there are other cases where a type can be constrained by a concept,
5172 // e.g. inside `if constexpr(ConceptSpecializationExpr) { ... }`
5175 // Describes a likely member of a type, inferred by concept constraints.
5176 // Offered as a code completion for T. T-> and T:: contexts.
5178 // Always non-null: we only handle members with ordinary identifier names.
5179 const IdentifierInfo *Name = nullptr;
5180 // Set for functions we've seen called.
5181 // We don't have the declared parameter types, only the actual types of
5182 // arguments we've seen. These are still valuable, as it's hard to render
5183 // a useful function completion with neither parameter types nor names!
5184 std::optional<SmallVector<QualType, 1>> ArgTypes;
5185 // Whether this is accessed as T.member, T->member, or T::member.
5186 enum AccessOperator {
5191 // What's known about the type of a variable or return type of a function.
5192 const TypeConstraint *ResultType = nullptr;
5193 // FIXME: also track:
5194 // - kind of entity (function/variable/type), to expose structured results
5195 // - template args kinds/types, as a proxy for template params
5197 // For now we simply return these results as "pattern" strings.
5198 CodeCompletionString *render(Sema &S, CodeCompletionAllocator &Alloc,
5199 CodeCompletionTUInfo &Info) const {
5200 CodeCompletionBuilder B(Alloc, Info);
5203 std::string AsString;
5205 llvm::raw_string_ostream OS(AsString);
5206 QualType ExactType = deduceType(*ResultType);
5207 if (!ExactType.isNull())
5208 ExactType.print(OS, getCompletionPrintingPolicy(S));
5210 ResultType->print(OS, getCompletionPrintingPolicy(S));
5212 B.AddResultTypeChunk(Alloc.CopyString(AsString));
5215 B.AddTypedTextChunk(Alloc.CopyString(Name->getName()));
5216 // Function argument list
5218 B.AddChunk(clang::CodeCompletionString::CK_LeftParen);
5220 for (QualType Arg : *ArgTypes) {
5224 B.AddChunk(clang::CodeCompletionString::CK_Comma);
5225 B.AddChunk(clang::CodeCompletionString::CK_HorizontalSpace);
5227 B.AddPlaceholderChunk(Alloc.CopyString(
5228 Arg.getAsString(getCompletionPrintingPolicy(S))));
5230 B.AddChunk(clang::CodeCompletionString::CK_RightParen);
5232 return B.TakeString();
5236 // BaseType is the type parameter T to infer members from.
5237 // T must be accessible within S, as we use it to find the template entity
5238 // that T is attached to in order to gather the relevant constraints.
5239 ConceptInfo(const TemplateTypeParmType &BaseType, Scope *S) {
5240 auto *TemplatedEntity = getTemplatedEntity(BaseType.getDecl(), S);
5241 for (const Expr *E : constraintsForTemplatedEntity(TemplatedEntity))
5242 believe(E, &BaseType);
5245 std::vector<Member> members() {
5246 std::vector<Member> Results;
5247 for (const auto &E : this->Results)
5248 Results.push_back(E.second);
5249 llvm::sort(Results, [](const Member &L, const Member &R) {
5250 return L.Name->getName() < R.Name->getName();
5256 // Infer members of T, given that the expression E (dependent on T) is true.
5257 void believe(const Expr *E, const TemplateTypeParmType *T) {
5260 if (auto *CSE = dyn_cast<ConceptSpecializationExpr>(E)) {
5261 // If the concept is
5262 // template <class A, class B> concept CD = f<A, B>();
5263 // And the concept specialization is
5265 // Then we're substituting T for B, so we want to make f<A, B>() true
5266 // by adding members to B - i.e. believe(f<A, B>(), B);
5269 // - we don't attempt to substitute int for A
5270 // - when T is used in other ways (like CD<T*>) we ignore it
5271 ConceptDecl *CD = CSE->getNamedConcept();
5272 TemplateParameterList *Params = CD->getTemplateParameters();
5274 for (const auto &Arg : CSE->getTemplateArguments()) {
5275 if (Index >= Params->size())
5276 break; // Won't happen in valid code.
5277 if (isApprox(Arg, T)) {
5278 auto *TTPD = dyn_cast<TemplateTypeParmDecl>(Params->getParam(Index));
5281 // T was used as an argument, and bound to the parameter TT.
5282 auto *TT = cast<TemplateTypeParmType>(TTPD->getTypeForDecl());
5283 // So now we know the constraint as a function of TT is true.
5284 believe(CD->getConstraintExpr(), TT);
5285 // (concepts themselves have no associated constraints to require)
5290 } else if (auto *BO = dyn_cast<BinaryOperator>(E)) {
5291 // For A && B, we can infer members from both branches.
5292 // For A || B, the union is still more useful than the intersection.
5293 if (BO->getOpcode() == BO_LAnd || BO->getOpcode() == BO_LOr) {
5294 believe(BO->getLHS(), T);
5295 believe(BO->getRHS(), T);
5297 } else if (auto *RE = dyn_cast<RequiresExpr>(E)) {
5298 // A requires(){...} lets us infer members from each requirement.
5299 for (const concepts::Requirement *Req : RE->getRequirements()) {
5300 if (!Req->isDependent())
5301 continue; // Can't tell us anything about T.
5302 // Now Req cannot a substitution-error: those aren't dependent.
5304 if (auto *TR = dyn_cast<concepts::TypeRequirement>(Req)) {
5305 // Do a full traversal so we get `foo` from `typename T::foo::bar`.
5306 QualType AssertedType = TR->getType()->getType();
5307 ValidVisitor(this, T).TraverseType(AssertedType);
5308 } else if (auto *ER = dyn_cast<concepts::ExprRequirement>(Req)) {
5309 ValidVisitor Visitor(this, T);
5310 // If we have a type constraint on the value of the expression,
5311 // AND the whole outer expression describes a member, then we'll
5312 // be able to use the constraint to provide the return type.
5313 if (ER->getReturnTypeRequirement().isTypeConstraint()) {
5315 ER->getReturnTypeRequirement().getTypeConstraint();
5316 Visitor.OuterExpr = ER->getExpr();
5318 Visitor.TraverseStmt(ER->getExpr());
5319 } else if (auto *NR = dyn_cast<concepts::NestedRequirement>(Req)) {
5320 believe(NR->getConstraintExpr(), T);
5326 // This visitor infers members of T based on traversing expressions/types
5327 // that involve T. It is invoked with code known to be valid for T.
5328 class ValidVisitor : public RecursiveASTVisitor<ValidVisitor> {
5330 const TemplateTypeParmType *T;
5332 CallExpr *Caller = nullptr;
5333 Expr *Callee = nullptr;
5336 // If set, OuterExpr is constrained by OuterType.
5337 Expr *OuterExpr = nullptr;
5338 const TypeConstraint *OuterType = nullptr;
5340 ValidVisitor(ConceptInfo *Outer, const TemplateTypeParmType *T)
5341 : Outer(Outer), T(T) {
5345 // In T.foo or T->foo, `foo` is a member function/variable.
5346 bool VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E) {
5347 const Type *Base = E->getBaseType().getTypePtr();
5348 bool IsArrow = E->isArrow();
5349 if (Base->isPointerType() && IsArrow) {
5351 Base = Base->getPointeeType().getTypePtr();
5353 if (isApprox(Base, T))
5354 addValue(E, E->getMember(), IsArrow ? Member::Arrow : Member::Dot);
5358 // In T::foo, `foo` is a static member function/variable.
5359 bool VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) {
5360 if (E->getQualifier() && isApprox(E->getQualifier()->getAsType(), T))
5361 addValue(E, E->getDeclName(), Member::Colons);
5365 // In T::typename foo, `foo` is a type.
5366 bool VisitDependentNameType(DependentNameType *DNT) {
5367 const auto *Q = DNT->getQualifier();
5368 if (Q && isApprox(Q->getAsType(), T))
5369 addType(DNT->getIdentifier());
5373 // In T::foo::bar, `foo` must be a type.
5374 // VisitNNS() doesn't exist, and TraverseNNS isn't always called :-(
5375 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNSL) {
5377 NestedNameSpecifier *NNS = NNSL.getNestedNameSpecifier();
5378 const auto *Q = NNS->getPrefix();
5379 if (Q && isApprox(Q->getAsType(), T))
5380 addType(NNS->getAsIdentifier());
5382 // FIXME: also handle T::foo<X>::bar
5383 return RecursiveASTVisitor::TraverseNestedNameSpecifierLoc(NNSL);
5386 // FIXME also handle T::foo<X>
5388 // Track the innermost caller/callee relationship so we can tell if a
5389 // nested expr is being called as a function.
5390 bool VisitCallExpr(CallExpr *CE) {
5392 Callee = CE->getCallee();
5397 void addResult(Member &&M) {
5398 auto R = Outer->Results.try_emplace(M.Name);
5399 Member &O = R.first->second;
5400 // Overwrite existing if the new member has more info.
5401 // The preference of . vs :: vs -> is fairly arbitrary.
5402 if (/*Inserted*/ R.second ||
5403 std::make_tuple(M.ArgTypes.has_value(), M.ResultType != nullptr,
5404 M.Operator) > std::make_tuple(O.ArgTypes.has_value(),
5405 O.ResultType != nullptr,
5410 void addType(const IdentifierInfo *Name) {
5415 M.Operator = Member::Colons;
5416 addResult(std::move(M));
5419 void addValue(Expr *E, DeclarationName Name,
5420 Member::AccessOperator Operator) {
5421 if (!Name.isIdentifier())
5424 Result.Name = Name.getAsIdentifierInfo();
5425 Result.Operator = Operator;
5426 // If this is the callee of an immediately-enclosing CallExpr, then
5427 // treat it as a method, otherwise it's a variable.
5428 if (Caller != nullptr && Callee == E) {
5429 Result.ArgTypes.emplace();
5430 for (const auto *Arg : Caller->arguments())
5431 Result.ArgTypes->push_back(Arg->getType());
5432 if (Caller == OuterExpr) {
5433 Result.ResultType = OuterType;
5437 Result.ResultType = OuterType;
5439 addResult(std::move(Result));
5443 static bool isApprox(const TemplateArgument &Arg, const Type *T) {
5444 return Arg.getKind() == TemplateArgument::Type &&
5445 isApprox(Arg.getAsType().getTypePtr(), T);
5448 static bool isApprox(const Type *T1, const Type *T2) {
5450 T1->getCanonicalTypeUnqualified() ==
5451 T2->getCanonicalTypeUnqualified();
5454 // Returns the DeclContext immediately enclosed by the template parameter
5455 // scope. For primary templates, this is the templated (e.g.) CXXRecordDecl.
5456 // For specializations, this is e.g. ClassTemplatePartialSpecializationDecl.
5457 static DeclContext *getTemplatedEntity(const TemplateTypeParmDecl *D,
5461 Scope *Inner = nullptr;
5463 if (S->isTemplateParamScope() && S->isDeclScope(D))
5464 return Inner ? Inner->getEntity() : nullptr;
5471 // Gets all the type constraint expressions that might apply to the type
5472 // variables associated with DC (as returned by getTemplatedEntity()).
5473 static SmallVector<const Expr *, 1>
5474 constraintsForTemplatedEntity(DeclContext *DC) {
5475 SmallVector<const Expr *, 1> Result;
5478 // Primary templates can have constraints.
5479 if (const auto *TD = cast<Decl>(DC)->getDescribedTemplate())
5480 TD->getAssociatedConstraints(Result);
5481 // Partial specializations may have constraints.
5482 if (const auto *CTPSD =
5483 dyn_cast<ClassTemplatePartialSpecializationDecl>(DC))
5484 CTPSD->getAssociatedConstraints(Result);
5485 if (const auto *VTPSD = dyn_cast<VarTemplatePartialSpecializationDecl>(DC))
5486 VTPSD->getAssociatedConstraints(Result);
5490 // Attempt to find the unique type satisfying a constraint.
5491 // This lets us show e.g. `int` instead of `std::same_as<int>`.
5492 static QualType deduceType(const TypeConstraint &T) {
5493 // Assume a same_as<T> return type constraint is std::same_as or equivalent.
5494 // In this case the return type is T.
5495 DeclarationName DN = T.getNamedConcept()->getDeclName();
5496 if (DN.isIdentifier() && DN.getAsIdentifierInfo()->isStr("same_as"))
5497 if (const auto *Args = T.getTemplateArgsAsWritten())
5498 if (Args->getNumTemplateArgs() == 1) {
5499 const auto &Arg = Args->arguments().front().getArgument();
5500 if (Arg.getKind() == TemplateArgument::Type)
5501 return Arg.getAsType();
5506 llvm::DenseMap<const IdentifierInfo *, Member> Results;
5509 // Returns a type for E that yields acceptable member completions.
5510 // In particular, when E->getType() is DependentTy, try to guess a likely type.
5511 // We accept some lossiness (like dropping parameters).
5512 // We only try to handle common expressions on the LHS of MemberExpr.
5513 QualType getApproximateType(const Expr *E) {
5514 if (E->getType().isNull())
5516 E = E->IgnoreParenImpCasts();
5517 QualType Unresolved = E->getType();
5518 // We only resolve DependentTy, or undeduced autos (including auto* etc).
5519 if (!Unresolved->isSpecificBuiltinType(BuiltinType::Dependent)) {
5520 AutoType *Auto = Unresolved->getContainedAutoType();
5521 if (!Auto || !Auto->isUndeducedAutoType())
5524 // A call: approximate-resolve callee to a function type, get its return type
5525 if (const CallExpr *CE = llvm::dyn_cast<CallExpr>(E)) {
5526 QualType Callee = getApproximateType(CE->getCallee());
5527 if (Callee.isNull() ||
5528 Callee->isSpecificPlaceholderType(BuiltinType::BoundMember))
5529 Callee = Expr::findBoundMemberType(CE->getCallee());
5530 if (Callee.isNull())
5533 if (const auto *FnTypePtr = Callee->getAs<PointerType>()) {
5534 Callee = FnTypePtr->getPointeeType();
5535 } else if (const auto *BPT = Callee->getAs<BlockPointerType>()) {
5536 Callee = BPT->getPointeeType();
5538 if (const FunctionType *FnType = Callee->getAs<FunctionType>())
5539 return FnType->getReturnType().getNonReferenceType();
5541 // Unresolved call: try to guess the return type.
5542 if (const auto *OE = llvm::dyn_cast<OverloadExpr>(CE->getCallee())) {
5543 // If all candidates have the same approximate return type, use it.
5544 // Discard references and const to allow more to be "the same".
5545 // (In particular, if there's one candidate + ADL, resolve it).
5546 const Type *Common = nullptr;
5547 for (const auto *D : OE->decls()) {
5548 QualType ReturnType;
5549 if (const auto *FD = llvm::dyn_cast<FunctionDecl>(D))
5550 ReturnType = FD->getReturnType();
5551 else if (const auto *FTD = llvm::dyn_cast<FunctionTemplateDecl>(D))
5552 ReturnType = FTD->getTemplatedDecl()->getReturnType();
5553 if (ReturnType.isNull())
5555 const Type *Candidate =
5556 ReturnType.getNonReferenceType().getCanonicalType().getTypePtr();
5557 if (Common && Common != Candidate)
5558 return Unresolved; // Multiple candidates.
5561 if (Common != nullptr)
5562 return QualType(Common, 0);
5565 // A dependent member: approximate-resolve the base, then lookup.
5566 if (const auto *CDSME = llvm::dyn_cast<CXXDependentScopeMemberExpr>(E)) {
5567 QualType Base = CDSME->isImplicitAccess()
5568 ? CDSME->getBaseType()
5569 : getApproximateType(CDSME->getBase());
5570 if (CDSME->isArrow() && !Base.isNull())
5571 Base = Base->getPointeeType(); // could handle unique_ptr etc here?
5575 : llvm::dyn_cast_or_null<CXXRecordDecl>(getAsRecordDecl(Base));
5576 if (RD && RD->isCompleteDefinition()) {
5577 // Look up member heuristically, including in bases.
5578 for (const auto *Member : RD->lookupDependentName(
5579 CDSME->getMember(), [](const NamedDecl *Member) {
5580 return llvm::isa<ValueDecl>(Member);
5582 return llvm::cast<ValueDecl>(Member)->getType().getNonReferenceType();
5586 // A reference to an `auto` variable: approximate-resolve its initializer.
5587 if (const auto *DRE = llvm::dyn_cast<DeclRefExpr>(E)) {
5588 if (const auto *VD = llvm::dyn_cast<VarDecl>(DRE->getDecl())) {
5590 return getApproximateType(VD->getInit());
5596 // If \p Base is ParenListExpr, assume a chain of comma operators and pick the
5597 // last expr. We expect other ParenListExprs to be resolved to e.g. constructor
5598 // calls before here. (So the ParenListExpr should be nonempty, but check just
5600 Expr *unwrapParenList(Expr *Base) {
5601 if (auto *PLE = llvm::dyn_cast_or_null<ParenListExpr>(Base)) {
5602 if (PLE->getNumExprs() == 0)
5604 Base = PLE->getExpr(PLE->getNumExprs() - 1);
5611 void Sema::CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base,
5613 SourceLocation OpLoc, bool IsArrow,
5614 bool IsBaseExprStatement,
5615 QualType PreferredType) {
5616 Base = unwrapParenList(Base);
5617 OtherOpBase = unwrapParenList(OtherOpBase);
5618 if (!Base || !CodeCompleter)
5621 ExprResult ConvertedBase = PerformMemberExprBaseConversion(Base, IsArrow);
5622 if (ConvertedBase.isInvalid())
5624 QualType ConvertedBaseType = getApproximateType(ConvertedBase.get());
5626 enum CodeCompletionContext::Kind contextKind;
5629 if (const auto *Ptr = ConvertedBaseType->getAs<PointerType>())
5630 ConvertedBaseType = Ptr->getPointeeType();
5634 contextKind = CodeCompletionContext::CCC_ArrowMemberAccess;
5636 if (ConvertedBaseType->isObjCObjectPointerType() ||
5637 ConvertedBaseType->isObjCObjectOrInterfaceType()) {
5638 contextKind = CodeCompletionContext::CCC_ObjCPropertyAccess;
5640 contextKind = CodeCompletionContext::CCC_DotMemberAccess;
5644 CodeCompletionContext CCContext(contextKind, ConvertedBaseType);
5645 CCContext.setPreferredType(PreferredType);
5646 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5647 CodeCompleter->getCodeCompletionTUInfo(), CCContext,
5648 &ResultBuilder::IsMember);
5650 auto DoCompletion = [&](Expr *Base, bool IsArrow,
5651 std::optional<FixItHint> AccessOpFixIt) -> bool {
5655 ExprResult ConvertedBase = PerformMemberExprBaseConversion(Base, IsArrow);
5656 if (ConvertedBase.isInvalid())
5658 Base = ConvertedBase.get();
5660 QualType BaseType = getApproximateType(Base);
5661 if (BaseType.isNull())
5663 ExprValueKind BaseKind = Base->getValueKind();
5666 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
5667 BaseType = Ptr->getPointeeType();
5668 BaseKind = VK_LValue;
5669 } else if (BaseType->isObjCObjectPointerType() ||
5670 BaseType->isTemplateTypeParmType()) {
5671 // Both cases (dot/arrow) handled below.
5677 if (RecordDecl *RD = getAsRecordDecl(BaseType)) {
5678 AddRecordMembersCompletionResults(*this, Results, S, BaseType, BaseKind,
5679 RD, std::move(AccessOpFixIt));
5680 } else if (const auto *TTPT =
5681 dyn_cast<TemplateTypeParmType>(BaseType.getTypePtr())) {
5683 IsArrow ? ConceptInfo::Member::Arrow : ConceptInfo::Member::Dot;
5684 for (const auto &R : ConceptInfo(*TTPT, S).members()) {
5685 if (R.Operator != Operator)
5687 CodeCompletionResult Result(
5688 R.render(*this, CodeCompleter->getAllocator(),
5689 CodeCompleter->getCodeCompletionTUInfo()));
5691 Result.FixIts.push_back(*AccessOpFixIt);
5692 Results.AddResult(std::move(Result));
5694 } else if (!IsArrow && BaseType->isObjCObjectPointerType()) {
5695 // Objective-C property reference. Bail if we're performing fix-it code
5696 // completion since Objective-C properties are normally backed by ivars,
5697 // most Objective-C fix-its here would have little value.
5698 if (AccessOpFixIt) {
5701 AddedPropertiesSet AddedProperties;
5703 if (const ObjCObjectPointerType *ObjCPtr =
5704 BaseType->getAsObjCInterfacePointerType()) {
5705 // Add property results based on our interface.
5706 assert(ObjCPtr && "Non-NULL pointer guaranteed above!");
5707 AddObjCProperties(CCContext, ObjCPtr->getInterfaceDecl(), true,
5708 /*AllowNullaryMethods=*/true, CurContext,
5709 AddedProperties, Results, IsBaseExprStatement);
5712 // Add properties from the protocols in a qualified interface.
5713 for (auto *I : BaseType->castAs<ObjCObjectPointerType>()->quals())
5714 AddObjCProperties(CCContext, I, true, /*AllowNullaryMethods=*/true,
5715 CurContext, AddedProperties, Results,
5716 IsBaseExprStatement, /*IsClassProperty*/ false,
5717 /*InOriginalClass*/ false);
5718 } else if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
5719 (!IsArrow && BaseType->isObjCObjectType())) {
5720 // Objective-C instance variable access. Bail if we're performing fix-it
5721 // code completion since Objective-C properties are normally backed by
5722 // ivars, most Objective-C fix-its here would have little value.
5723 if (AccessOpFixIt) {
5726 ObjCInterfaceDecl *Class = nullptr;
5727 if (const ObjCObjectPointerType *ObjCPtr =
5728 BaseType->getAs<ObjCObjectPointerType>())
5729 Class = ObjCPtr->getInterfaceDecl();
5731 Class = BaseType->castAs<ObjCObjectType>()->getInterface();
5733 // Add all ivars from this class and its superclasses.
5735 CodeCompletionDeclConsumer Consumer(Results, Class, BaseType);
5736 Results.setFilter(&ResultBuilder::IsObjCIvar);
5738 Class, LookupMemberName, Consumer, CodeCompleter->includeGlobals(),
5739 /*IncludeDependentBases=*/false, CodeCompleter->loadExternal());
5743 // FIXME: How do we cope with isa?
5747 Results.EnterNewScope();
5749 bool CompletionSucceded = DoCompletion(Base, IsArrow, std::nullopt);
5750 if (CodeCompleter->includeFixIts()) {
5751 const CharSourceRange OpRange =
5752 CharSourceRange::getTokenRange(OpLoc, OpLoc);
5753 CompletionSucceded |= DoCompletion(
5754 OtherOpBase, !IsArrow,
5755 FixItHint::CreateReplacement(OpRange, IsArrow ? "." : "->"));
5758 Results.ExitScope();
5760 if (!CompletionSucceded)
5763 // Hand off the results found for code completion.
5764 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
5765 Results.data(), Results.size());
5768 void Sema::CodeCompleteObjCClassPropertyRefExpr(Scope *S,
5769 IdentifierInfo &ClassName,
5770 SourceLocation ClassNameLoc,
5771 bool IsBaseExprStatement) {
5772 IdentifierInfo *ClassNamePtr = &ClassName;
5773 ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(ClassNamePtr, ClassNameLoc);
5776 CodeCompletionContext CCContext(
5777 CodeCompletionContext::CCC_ObjCPropertyAccess);
5778 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5779 CodeCompleter->getCodeCompletionTUInfo(), CCContext,
5780 &ResultBuilder::IsMember);
5781 Results.EnterNewScope();
5782 AddedPropertiesSet AddedProperties;
5783 AddObjCProperties(CCContext, IFace, true,
5784 /*AllowNullaryMethods=*/true, CurContext, AddedProperties,
5785 Results, IsBaseExprStatement,
5786 /*IsClassProperty=*/true);
5787 Results.ExitScope();
5788 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
5789 Results.data(), Results.size());
5792 void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) {
5796 ResultBuilder::LookupFilter Filter = nullptr;
5797 enum CodeCompletionContext::Kind ContextKind =
5798 CodeCompletionContext::CCC_Other;
5799 switch ((DeclSpec::TST)TagSpec) {
5800 case DeclSpec::TST_enum:
5801 Filter = &ResultBuilder::IsEnum;
5802 ContextKind = CodeCompletionContext::CCC_EnumTag;
5805 case DeclSpec::TST_union:
5806 Filter = &ResultBuilder::IsUnion;
5807 ContextKind = CodeCompletionContext::CCC_UnionTag;
5810 case DeclSpec::TST_struct:
5811 case DeclSpec::TST_class:
5812 case DeclSpec::TST_interface:
5813 Filter = &ResultBuilder::IsClassOrStruct;
5814 ContextKind = CodeCompletionContext::CCC_ClassOrStructTag;
5818 llvm_unreachable("Unknown type specifier kind in CodeCompleteTag");
5821 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5822 CodeCompleter->getCodeCompletionTUInfo(), ContextKind);
5823 CodeCompletionDeclConsumer Consumer(Results, CurContext);
5825 // First pass: look for tags.
5826 Results.setFilter(Filter);
5827 LookupVisibleDecls(S, LookupTagName, Consumer,
5828 CodeCompleter->includeGlobals(),
5829 CodeCompleter->loadExternal());
5831 if (CodeCompleter->includeGlobals()) {
5832 // Second pass: look for nested name specifiers.
5833 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
5834 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer,
5835 CodeCompleter->includeGlobals(),
5836 CodeCompleter->loadExternal());
5839 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
5840 Results.data(), Results.size());
5843 static void AddTypeQualifierResults(DeclSpec &DS, ResultBuilder &Results,
5844 const LangOptions &LangOpts) {
5845 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_const))
5846 Results.AddResult("const");
5847 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_volatile))
5848 Results.AddResult("volatile");
5849 if (LangOpts.C99 && !(DS.getTypeQualifiers() & DeclSpec::TQ_restrict))
5850 Results.AddResult("restrict");
5851 if (LangOpts.C11 && !(DS.getTypeQualifiers() & DeclSpec::TQ_atomic))
5852 Results.AddResult("_Atomic");
5853 if (LangOpts.MSVCCompat && !(DS.getTypeQualifiers() & DeclSpec::TQ_unaligned))
5854 Results.AddResult("__unaligned");
5857 void Sema::CodeCompleteTypeQualifiers(DeclSpec &DS) {
5858 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5859 CodeCompleter->getCodeCompletionTUInfo(),
5860 CodeCompletionContext::CCC_TypeQualifiers);
5861 Results.EnterNewScope();
5862 AddTypeQualifierResults(DS, Results, LangOpts);
5863 Results.ExitScope();
5864 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
5865 Results.data(), Results.size());
5868 void Sema::CodeCompleteFunctionQualifiers(DeclSpec &DS, Declarator &D,
5869 const VirtSpecifiers *VS) {
5870 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5871 CodeCompleter->getCodeCompletionTUInfo(),
5872 CodeCompletionContext::CCC_TypeQualifiers);
5873 Results.EnterNewScope();
5874 AddTypeQualifierResults(DS, Results, LangOpts);
5875 if (LangOpts.CPlusPlus11) {
5876 Results.AddResult("noexcept");
5877 if (D.getContext() == DeclaratorContext::Member && !D.isCtorOrDtor() &&
5878 !D.isStaticMember()) {
5879 if (!VS || !VS->isFinalSpecified())
5880 Results.AddResult("final");
5881 if (!VS || !VS->isOverrideSpecified())
5882 Results.AddResult("override");
5885 Results.ExitScope();
5886 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
5887 Results.data(), Results.size());
5890 void Sema::CodeCompleteBracketDeclarator(Scope *S) {
5891 CodeCompleteExpression(S, QualType(getASTContext().getSizeType()));
5894 void Sema::CodeCompleteCase(Scope *S) {
5895 if (getCurFunction()->SwitchStack.empty() || !CodeCompleter)
5898 SwitchStmt *Switch = getCurFunction()->SwitchStack.back().getPointer();
5899 // Condition expression might be invalid, do not continue in this case.
5900 if (!Switch->getCond())
5902 QualType type = Switch->getCond()->IgnoreImplicit()->getType();
5903 if (!type->isEnumeralType()) {
5904 CodeCompleteExpressionData Data(type);
5905 Data.IntegralConstantExpression = true;
5906 CodeCompleteExpression(S, Data);
5910 // Code-complete the cases of a switch statement over an enumeration type
5911 // by providing the list of
5912 EnumDecl *Enum = type->castAs<EnumType>()->getDecl();
5913 if (EnumDecl *Def = Enum->getDefinition())
5916 // Determine which enumerators we have already seen in the switch statement.
5917 // FIXME: Ideally, we would also be able to look *past* the code-completion
5918 // token, in case we are code-completing in the middle of the switch and not
5919 // at the end. However, we aren't able to do so at the moment.
5920 CoveredEnumerators Enumerators;
5921 for (SwitchCase *SC = Switch->getSwitchCaseList(); SC;
5922 SC = SC->getNextSwitchCase()) {
5923 CaseStmt *Case = dyn_cast<CaseStmt>(SC);
5927 Expr *CaseVal = Case->getLHS()->IgnoreParenCasts();
5928 if (auto *DRE = dyn_cast<DeclRefExpr>(CaseVal))
5929 if (auto *Enumerator =
5930 dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
5931 // We look into the AST of the case statement to determine which
5932 // enumerator was named. Alternatively, we could compute the value of
5933 // the integral constant expression, then compare it against the
5934 // values of each enumerator. However, value-based approach would not
5935 // work as well with C++ templates where enumerators declared within a
5936 // template are type- and value-dependent.
5937 Enumerators.Seen.insert(Enumerator);
5939 // If this is a qualified-id, keep track of the nested-name-specifier
5940 // so that we can reproduce it as part of code completion, e.g.,
5942 // switch (TagD.getKind()) {
5943 // case TagDecl::TK_enum:
5947 // At the XXX, our completions are TagDecl::TK_union,
5948 // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
5949 // TK_struct, and TK_class.
5950 Enumerators.SuggestedQualifier = DRE->getQualifier();
5954 // Add any enumerators that have not yet been mentioned.
5955 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5956 CodeCompleter->getCodeCompletionTUInfo(),
5957 CodeCompletionContext::CCC_Expression);
5958 AddEnumerators(Results, Context, Enum, CurContext, Enumerators);
5960 if (CodeCompleter->includeMacros()) {
5961 AddMacroResults(PP, Results, CodeCompleter->loadExternal(), false);
5963 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
5964 Results.data(), Results.size());
5967 static bool anyNullArguments(ArrayRef<Expr *> Args) {
5968 if (Args.size() && !Args.data())
5971 for (unsigned I = 0; I != Args.size(); ++I)
5978 typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate;
5980 static void mergeCandidatesWithResults(
5981 Sema &SemaRef, SmallVectorImpl<ResultCandidate> &Results,
5982 OverloadCandidateSet &CandidateSet, SourceLocation Loc, size_t ArgSize) {
5983 // Sort the overload candidate set by placing the best overloads first.
5984 llvm::stable_sort(CandidateSet, [&](const OverloadCandidate &X,
5985 const OverloadCandidate &Y) {
5986 return isBetterOverloadCandidate(SemaRef, X, Y, Loc,
5987 CandidateSet.getKind());
5990 // Add the remaining viable overload candidates as code-completion results.
5991 for (OverloadCandidate &Candidate : CandidateSet) {
5992 if (Candidate.Function) {
5993 if (Candidate.Function->isDeleted())
5995 if (shouldEnforceArgLimit(/*PartialOverloading=*/true,
5996 Candidate.Function) &&
5997 Candidate.Function->getNumParams() <= ArgSize &&
5998 // Having zero args is annoying, normally we don't surface a function
5999 // with 2 params, if you already have 2 params, because you are
6000 // inserting the 3rd now. But with zero, it helps the user to figure
6001 // out there are no overloads that take any arguments. Hence we are
6002 // keeping the overload.
6006 if (Candidate.Viable)
6007 Results.push_back(ResultCandidate(Candidate.Function));
6011 /// Get the type of the Nth parameter from a given set of overload
6013 static QualType getParamType(Sema &SemaRef,
6014 ArrayRef<ResultCandidate> Candidates, unsigned N) {
6016 // Given the overloads 'Candidates' for a function call matching all arguments
6017 // up to N, return the type of the Nth parameter if it is the same for all
6018 // overload candidates.
6020 for (auto &Candidate : Candidates) {
6021 QualType CandidateParamType = Candidate.getParamType(N);
6022 if (CandidateParamType.isNull())
6024 if (ParamType.isNull()) {
6025 ParamType = CandidateParamType;
6028 if (!SemaRef.Context.hasSameUnqualifiedType(
6029 ParamType.getNonReferenceType(),
6030 CandidateParamType.getNonReferenceType()))
6031 // Two conflicting types, give up.
6039 ProduceSignatureHelp(Sema &SemaRef, MutableArrayRef<ResultCandidate> Candidates,
6040 unsigned CurrentArg, SourceLocation OpenParLoc,
6042 if (Candidates.empty())
6044 if (SemaRef.getPreprocessor().isCodeCompletionReached())
6045 SemaRef.CodeCompleter->ProcessOverloadCandidates(
6046 SemaRef, CurrentArg, Candidates.data(), Candidates.size(), OpenParLoc,
6048 return getParamType(SemaRef, Candidates, CurrentArg);
6051 // Given a callee expression `Fn`, if the call is through a function pointer,
6052 // try to find the declaration of the corresponding function pointer type,
6053 // so that we can recover argument names from it.
6054 static FunctionProtoTypeLoc GetPrototypeLoc(Expr *Fn) {
6056 if (const auto *T = Fn->getType().getTypePtr()->getAs<TypedefType>()) {
6057 Target = T->getDecl()->getTypeSourceInfo()->getTypeLoc();
6059 } else if (const auto *DR = dyn_cast<DeclRefExpr>(Fn)) {
6060 const auto *D = DR->getDecl();
6061 if (const auto *const VD = dyn_cast<VarDecl>(D)) {
6062 Target = VD->getTypeSourceInfo()->getTypeLoc();
6069 if (auto P = Target.getAs<PointerTypeLoc>()) {
6070 Target = P.getPointeeLoc();
6073 if (auto P = Target.getAs<ParenTypeLoc>()) {
6074 Target = P.getInnerLoc();
6077 if (auto F = Target.getAs<FunctionProtoTypeLoc>()) {
6084 QualType Sema::ProduceCallSignatureHelp(Expr *Fn, ArrayRef<Expr *> Args,
6085 SourceLocation OpenParLoc) {
6086 Fn = unwrapParenList(Fn);
6087 if (!CodeCompleter || !Fn)
6090 // FIXME: Provide support for variadic template functions.
6091 // Ignore type-dependent call expressions entirely.
6092 if (Fn->isTypeDependent() || anyNullArguments(Args))
6094 // In presence of dependent args we surface all possible signatures using the
6095 // non-dependent args in the prefix. Afterwards we do a post filtering to make
6096 // sure provided candidates satisfy parameter count restrictions.
6097 auto ArgsWithoutDependentTypes =
6098 Args.take_while([](Expr *Arg) { return !Arg->isTypeDependent(); });
6100 SmallVector<ResultCandidate, 8> Results;
6102 Expr *NakedFn = Fn->IgnoreParenCasts();
6103 // Build an overload candidate set based on the functions we find.
6104 SourceLocation Loc = Fn->getExprLoc();
6105 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
6107 if (auto ULE = dyn_cast<UnresolvedLookupExpr>(NakedFn)) {
6108 AddOverloadedCallCandidates(ULE, ArgsWithoutDependentTypes, CandidateSet,
6109 /*PartialOverloading=*/true);
6110 } else if (auto UME = dyn_cast<UnresolvedMemberExpr>(NakedFn)) {
6111 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
6112 if (UME->hasExplicitTemplateArgs()) {
6113 UME->copyTemplateArgumentsInto(TemplateArgsBuffer);
6114 TemplateArgs = &TemplateArgsBuffer;
6117 // Add the base as first argument (use a nullptr if the base is implicit).
6118 SmallVector<Expr *, 12> ArgExprs(
6119 1, UME->isImplicitAccess() ? nullptr : UME->getBase());
6120 ArgExprs.append(ArgsWithoutDependentTypes.begin(),
6121 ArgsWithoutDependentTypes.end());
6122 UnresolvedSet<8> Decls;
6123 Decls.append(UME->decls_begin(), UME->decls_end());
6124 const bool FirstArgumentIsBase = !UME->isImplicitAccess() && UME->getBase();
6125 AddFunctionCandidates(Decls, ArgExprs, CandidateSet, TemplateArgs,
6126 /*SuppressUserConversions=*/false,
6127 /*PartialOverloading=*/true, FirstArgumentIsBase);
6129 FunctionDecl *FD = nullptr;
6130 if (auto *MCE = dyn_cast<MemberExpr>(NakedFn))
6131 FD = dyn_cast<FunctionDecl>(MCE->getMemberDecl());
6132 else if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn))
6133 FD = dyn_cast<FunctionDecl>(DRE->getDecl());
6134 if (FD) { // We check whether it's a resolved function declaration.
6135 if (!getLangOpts().CPlusPlus ||
6136 !FD->getType()->getAs<FunctionProtoType>())
6137 Results.push_back(ResultCandidate(FD));
6139 AddOverloadCandidate(FD, DeclAccessPair::make(FD, FD->getAccess()),
6140 ArgsWithoutDependentTypes, CandidateSet,
6141 /*SuppressUserConversions=*/false,
6142 /*PartialOverloading=*/true);
6144 } else if (auto DC = NakedFn->getType()->getAsCXXRecordDecl()) {
6145 // If expression's type is CXXRecordDecl, it may overload the function
6146 // call operator, so we check if it does and add them as candidates.
6147 // A complete type is needed to lookup for member function call operators.
6148 if (isCompleteType(Loc, NakedFn->getType())) {
6149 DeclarationName OpName =
6150 Context.DeclarationNames.getCXXOperatorName(OO_Call);
6151 LookupResult R(*this, OpName, Loc, LookupOrdinaryName);
6152 LookupQualifiedName(R, DC);
6153 R.suppressDiagnostics();
6154 SmallVector<Expr *, 12> ArgExprs(1, NakedFn);
6155 ArgExprs.append(ArgsWithoutDependentTypes.begin(),
6156 ArgsWithoutDependentTypes.end());
6157 AddFunctionCandidates(R.asUnresolvedSet(), ArgExprs, CandidateSet,
6158 /*ExplicitArgs=*/nullptr,
6159 /*SuppressUserConversions=*/false,
6160 /*PartialOverloading=*/true);
6163 // Lastly we check whether expression's type is function pointer or
6166 FunctionProtoTypeLoc P = GetPrototypeLoc(NakedFn);
6167 QualType T = NakedFn->getType();
6168 if (!T->getPointeeType().isNull())
6169 T = T->getPointeeType();
6171 if (auto FP = T->getAs<FunctionProtoType>()) {
6172 if (!TooManyArguments(FP->getNumParams(),
6173 ArgsWithoutDependentTypes.size(),
6174 /*PartialOverloading=*/true) ||
6177 Results.push_back(ResultCandidate(P));
6179 Results.push_back(ResultCandidate(FP));
6182 } else if (auto FT = T->getAs<FunctionType>())
6183 // No prototype and declaration, it may be a K & R style function.
6184 Results.push_back(ResultCandidate(FT));
6187 mergeCandidatesWithResults(*this, Results, CandidateSet, Loc, Args.size());
6188 QualType ParamType = ProduceSignatureHelp(*this, Results, Args.size(),
6189 OpenParLoc, /*Braced=*/false);
6190 return !CandidateSet.empty() ? ParamType : QualType();
6193 // Determine which param to continue aggregate initialization from after
6194 // a designated initializer.
6196 // Given struct S { int a,b,c,d,e; }:
6197 // after `S{.b=1,` we want to suggest c to continue
6198 // after `S{.b=1, 2,` we continue with d (this is legal C and ext in C++)
6199 // after `S{.b=1, .a=2,` we continue with b (this is legal C and ext in C++)
6201 // Possible outcomes:
6202 // - we saw a designator for a field, and continue from the returned index.
6203 // Only aggregate initialization is allowed.
6204 // - we saw a designator, but it was complex or we couldn't find the field.
6205 // Only aggregate initialization is possible, but we can't assist with it.
6206 // Returns an out-of-range index.
6207 // - we saw no designators, just positional arguments.
6208 // Returns std::nullopt.
6209 static std::optional<unsigned>
6210 getNextAggregateIndexAfterDesignatedInit(const ResultCandidate &Aggregate,
6211 ArrayRef<Expr *> Args) {
6212 static constexpr unsigned Invalid = std::numeric_limits<unsigned>::max();
6213 assert(Aggregate.getKind() == ResultCandidate::CK_Aggregate);
6215 // Look for designated initializers.
6216 // They're in their syntactic form, not yet resolved to fields.
6217 const IdentifierInfo *DesignatedFieldName = nullptr;
6218 unsigned ArgsAfterDesignator = 0;
6219 for (const Expr *Arg : Args) {
6220 if (const auto *DIE = dyn_cast<DesignatedInitExpr>(Arg)) {
6221 if (DIE->size() == 1 && DIE->getDesignator(0)->isFieldDesignator()) {
6222 DesignatedFieldName = DIE->getDesignator(0)->getFieldName();
6223 ArgsAfterDesignator = 0;
6225 return Invalid; // Complicated designator.
6227 } else if (isa<DesignatedInitUpdateExpr>(Arg)) {
6228 return Invalid; // Unsupported.
6230 ++ArgsAfterDesignator;
6233 if (!DesignatedFieldName)
6234 return std::nullopt;
6236 // Find the index within the class's fields.
6237 // (Probing getParamDecl() directly would be quadratic in number of fields).
6238 unsigned DesignatedIndex = 0;
6239 const FieldDecl *DesignatedField = nullptr;
6240 for (const auto *Field : Aggregate.getAggregate()->fields()) {
6241 if (Field->getIdentifier() == DesignatedFieldName) {
6242 DesignatedField = Field;
6247 if (!DesignatedField)
6248 return Invalid; // Designator referred to a missing field, give up.
6250 // Find the index within the aggregate (which may have leading bases).
6251 unsigned AggregateSize = Aggregate.getNumParams();
6252 while (DesignatedIndex < AggregateSize &&
6253 Aggregate.getParamDecl(DesignatedIndex) != DesignatedField)
6256 // Continue from the index after the last named field.
6257 return DesignatedIndex + ArgsAfterDesignator + 1;
6260 QualType Sema::ProduceConstructorSignatureHelp(QualType Type,
6262 ArrayRef<Expr *> Args,
6263 SourceLocation OpenParLoc,
6267 SmallVector<ResultCandidate, 8> Results;
6269 // A complete type is needed to lookup for constructors.
6271 isCompleteType(Loc, Type) ? Type->getAsRecordDecl() : nullptr;
6274 CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD);
6276 // Consider aggregate initialization.
6277 // We don't check that types so far are correct.
6278 // We also don't handle C99/C++17 brace-elision, we assume init-list elements
6279 // are 1:1 with fields.
6280 // FIXME: it would be nice to support "unwrapping" aggregates that contain
6281 // a single subaggregate, like std::array<T, N> -> T __elements[N].
6282 if (Braced && !RD->isUnion() &&
6283 (!LangOpts.CPlusPlus || (CRD && CRD->isAggregate()))) {
6284 ResultCandidate AggregateSig(RD);
6285 unsigned AggregateSize = AggregateSig.getNumParams();
6287 if (auto NextIndex =
6288 getNextAggregateIndexAfterDesignatedInit(AggregateSig, Args)) {
6289 // A designator was used, only aggregate init is possible.
6290 if (*NextIndex >= AggregateSize)
6292 Results.push_back(AggregateSig);
6293 return ProduceSignatureHelp(*this, Results, *NextIndex, OpenParLoc,
6297 // Describe aggregate initialization, but also constructors below.
6298 if (Args.size() < AggregateSize)
6299 Results.push_back(AggregateSig);
6302 // FIXME: Provide support for member initializers.
6303 // FIXME: Provide support for variadic template constructors.
6306 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
6307 for (NamedDecl *C : LookupConstructors(CRD)) {
6308 if (auto *FD = dyn_cast<FunctionDecl>(C)) {
6309 // FIXME: we can't yet provide correct signature help for initializer
6310 // list constructors, so skip them entirely.
6311 if (Braced && LangOpts.CPlusPlus && isInitListConstructor(FD))
6313 AddOverloadCandidate(FD, DeclAccessPair::make(FD, C->getAccess()), Args,
6315 /*SuppressUserConversions=*/false,
6316 /*PartialOverloading=*/true,
6317 /*AllowExplicit*/ true);
6318 } else if (auto *FTD = dyn_cast<FunctionTemplateDecl>(C)) {
6319 if (Braced && LangOpts.CPlusPlus &&
6320 isInitListConstructor(FTD->getTemplatedDecl()))
6323 AddTemplateOverloadCandidate(
6324 FTD, DeclAccessPair::make(FTD, C->getAccess()),
6325 /*ExplicitTemplateArgs=*/nullptr, Args, CandidateSet,
6326 /*SuppressUserConversions=*/false,
6327 /*PartialOverloading=*/true);
6330 mergeCandidatesWithResults(*this, Results, CandidateSet, Loc, Args.size());
6333 return ProduceSignatureHelp(*this, Results, Args.size(), OpenParLoc, Braced);
6336 QualType Sema::ProduceCtorInitMemberSignatureHelp(
6337 Decl *ConstructorDecl, CXXScopeSpec SS, ParsedType TemplateTypeTy,
6338 ArrayRef<Expr *> ArgExprs, IdentifierInfo *II, SourceLocation OpenParLoc,
6343 CXXConstructorDecl *Constructor =
6344 dyn_cast<CXXConstructorDecl>(ConstructorDecl);
6347 // FIXME: Add support for Base class constructors as well.
6348 if (ValueDecl *MemberDecl = tryLookupCtorInitMemberDecl(
6349 Constructor->getParent(), SS, TemplateTypeTy, II))
6350 return ProduceConstructorSignatureHelp(MemberDecl->getType(),
6351 MemberDecl->getLocation(), ArgExprs,
6352 OpenParLoc, Braced);
6356 static bool argMatchesTemplateParams(const ParsedTemplateArgument &Arg,
6358 const TemplateParameterList &Params) {
6359 const NamedDecl *Param;
6360 if (Index < Params.size())
6361 Param = Params.getParam(Index);
6362 else if (Params.hasParameterPack())
6363 Param = Params.asArray().back();
6365 return false; // too many args
6367 switch (Arg.getKind()) {
6368 case ParsedTemplateArgument::Type:
6369 return llvm::isa<TemplateTypeParmDecl>(Param); // constraints not checked
6370 case ParsedTemplateArgument::NonType:
6371 return llvm::isa<NonTypeTemplateParmDecl>(Param); // type not checked
6372 case ParsedTemplateArgument::Template:
6373 return llvm::isa<TemplateTemplateParmDecl>(Param); // signature not checked
6375 llvm_unreachable("Unhandled switch case");
6378 QualType Sema::ProduceTemplateArgumentSignatureHelp(
6379 TemplateTy ParsedTemplate, ArrayRef<ParsedTemplateArgument> Args,
6380 SourceLocation LAngleLoc) {
6381 if (!CodeCompleter || !ParsedTemplate)
6384 SmallVector<ResultCandidate, 8> Results;
6385 auto Consider = [&](const TemplateDecl *TD) {
6386 // Only add if the existing args are compatible with the template.
6387 bool Matches = true;
6388 for (unsigned I = 0; I < Args.size(); ++I) {
6389 if (!argMatchesTemplateParams(Args[I], I, *TD->getTemplateParameters())) {
6395 Results.emplace_back(TD);
6398 TemplateName Template = ParsedTemplate.get();
6399 if (const auto *TD = Template.getAsTemplateDecl()) {
6401 } else if (const auto *OTS = Template.getAsOverloadedTemplate()) {
6402 for (const NamedDecl *ND : *OTS)
6403 if (const auto *TD = llvm::dyn_cast<TemplateDecl>(ND))
6406 return ProduceSignatureHelp(*this, Results, Args.size(), LAngleLoc,
6410 static QualType getDesignatedType(QualType BaseType, const Designation &Desig) {
6411 for (unsigned I = 0; I < Desig.getNumDesignators(); ++I) {
6412 if (BaseType.isNull())
6415 const auto &D = Desig.getDesignator(I);
6416 if (D.isArrayDesignator() || D.isArrayRangeDesignator()) {
6417 if (BaseType->isArrayType())
6418 NextType = BaseType->getAsArrayTypeUnsafe()->getElementType();
6420 assert(D.isFieldDesignator());
6421 auto *RD = getAsRecordDecl(BaseType);
6422 if (RD && RD->isCompleteDefinition()) {
6423 for (const auto *Member : RD->lookup(D.getFieldDecl()))
6424 if (const FieldDecl *FD = llvm::dyn_cast<FieldDecl>(Member)) {
6425 NextType = FD->getType();
6430 BaseType = NextType;
6435 void Sema::CodeCompleteDesignator(QualType BaseType,
6436 llvm::ArrayRef<Expr *> InitExprs,
6437 const Designation &D) {
6438 BaseType = getDesignatedType(BaseType, D);
6439 if (BaseType.isNull())
6441 const auto *RD = getAsRecordDecl(BaseType);
6442 if (!RD || RD->fields().empty())
6445 CodeCompletionContext CCC(CodeCompletionContext::CCC_DotMemberAccess,
6447 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6448 CodeCompleter->getCodeCompletionTUInfo(), CCC);
6450 Results.EnterNewScope();
6451 for (const Decl *D : RD->decls()) {
6452 const FieldDecl *FD;
6453 if (auto *IFD = dyn_cast<IndirectFieldDecl>(D))
6454 FD = IFD->getAnonField();
6455 else if (auto *DFD = dyn_cast<FieldDecl>(D))
6460 // FIXME: Make use of previous designators to mark any fields before those
6461 // inaccessible, and also compute the next initializer priority.
6462 ResultBuilder::Result Result(FD, Results.getBasePriority(FD));
6463 Results.AddResult(Result, CurContext, /*Hiding=*/nullptr);
6465 Results.ExitScope();
6466 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
6467 Results.data(), Results.size());
6470 void Sema::CodeCompleteInitializer(Scope *S, Decl *D) {
6471 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
6473 CodeCompleteOrdinaryName(S, PCC_Expression);
6477 CodeCompleteExpressionData Data;
6478 Data.PreferredType = VD->getType();
6479 // Ignore VD to avoid completing the variable itself, e.g. in 'int foo = ^'.
6480 Data.IgnoreDecls.push_back(VD);
6482 CodeCompleteExpression(S, Data);
6485 void Sema::CodeCompleteAfterIf(Scope *S, bool IsBracedThen) {
6486 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6487 CodeCompleter->getCodeCompletionTUInfo(),
6488 mapCodeCompletionContext(*this, PCC_Statement));
6489 Results.setFilter(&ResultBuilder::IsOrdinaryName);
6490 Results.EnterNewScope();
6492 CodeCompletionDeclConsumer Consumer(Results, CurContext);
6493 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
6494 CodeCompleter->includeGlobals(),
6495 CodeCompleter->loadExternal());
6497 AddOrdinaryNameResults(PCC_Statement, S, *this, Results);
6500 CodeCompletionBuilder Builder(Results.getAllocator(),
6501 Results.getCodeCompletionTUInfo());
6503 auto AddElseBodyPattern = [&] {
6505 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6506 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
6507 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
6508 Builder.AddPlaceholderChunk("statements");
6509 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
6510 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
6512 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
6513 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6514 Builder.AddPlaceholderChunk("statement");
6515 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
6518 Builder.AddTypedTextChunk("else");
6519 if (Results.includeCodePatterns())
6520 AddElseBodyPattern();
6521 Results.AddResult(Builder.TakeString());
6524 Builder.AddTypedTextChunk("else if");
6525 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6526 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6527 if (getLangOpts().CPlusPlus)
6528 Builder.AddPlaceholderChunk("condition");
6530 Builder.AddPlaceholderChunk("expression");
6531 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6532 if (Results.includeCodePatterns()) {
6533 AddElseBodyPattern();
6535 Results.AddResult(Builder.TakeString());
6537 Results.ExitScope();
6539 if (S->getFnParent())
6540 AddPrettyFunctionResults(getLangOpts(), Results);
6542 if (CodeCompleter->includeMacros())
6543 AddMacroResults(PP, Results, CodeCompleter->loadExternal(), false);
6545 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
6546 Results.data(), Results.size());
6549 void Sema::CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
6550 bool EnteringContext,
6551 bool IsUsingDeclaration, QualType BaseType,
6552 QualType PreferredType) {
6553 if (SS.isEmpty() || !CodeCompleter)
6556 CodeCompletionContext CC(CodeCompletionContext::CCC_Symbol, PreferredType);
6557 CC.setIsUsingDeclaration(IsUsingDeclaration);
6558 CC.setCXXScopeSpecifier(SS);
6560 // We want to keep the scope specifier even if it's invalid (e.g. the scope
6561 // "a::b::" is not corresponding to any context/namespace in the AST), since
6562 // it can be useful for global code completion which have information about
6563 // contexts/symbols that are not in the AST.
6564 if (SS.isInvalid()) {
6565 // As SS is invalid, we try to collect accessible contexts from the current
6566 // scope with a dummy lookup so that the completion consumer can try to
6567 // guess what the specified scope is.
6568 ResultBuilder DummyResults(*this, CodeCompleter->getAllocator(),
6569 CodeCompleter->getCodeCompletionTUInfo(), CC);
6570 if (!PreferredType.isNull())
6571 DummyResults.setPreferredType(PreferredType);
6572 if (S->getEntity()) {
6573 CodeCompletionDeclConsumer Consumer(DummyResults, S->getEntity(),
6575 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
6576 /*IncludeGlobalScope=*/false,
6577 /*LoadExternal=*/false);
6579 HandleCodeCompleteResults(this, CodeCompleter,
6580 DummyResults.getCompletionContext(), nullptr, 0);
6583 // Always pretend to enter a context to ensure that a dependent type
6584 // resolves to a dependent record.
6585 DeclContext *Ctx = computeDeclContext(SS, /*EnteringContext=*/true);
6587 // Try to instantiate any non-dependent declaration contexts before
6588 // we look in them. Bail out if we fail.
6589 NestedNameSpecifier *NNS = SS.getScopeRep();
6590 if (NNS != nullptr && SS.isValid() && !NNS->isDependent()) {
6591 if (Ctx == nullptr || RequireCompleteDeclContext(SS, Ctx))
6595 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6596 CodeCompleter->getCodeCompletionTUInfo(), CC);
6597 if (!PreferredType.isNull())
6598 Results.setPreferredType(PreferredType);
6599 Results.EnterNewScope();
6601 // The "template" keyword can follow "::" in the grammar, but only
6602 // put it into the grammar if the nested-name-specifier is dependent.
6603 // FIXME: results is always empty, this appears to be dead.
6604 if (!Results.empty() && NNS->isDependent())
6605 Results.AddResult("template");
6607 // If the scope is a concept-constrained type parameter, infer nested
6608 // members based on the constraints.
6609 if (const auto *TTPT =
6610 dyn_cast_or_null<TemplateTypeParmType>(NNS->getAsType())) {
6611 for (const auto &R : ConceptInfo(*TTPT, S).members()) {
6612 if (R.Operator != ConceptInfo::Member::Colons)
6614 Results.AddResult(CodeCompletionResult(
6615 R.render(*this, CodeCompleter->getAllocator(),
6616 CodeCompleter->getCodeCompletionTUInfo())));
6620 // Add calls to overridden virtual functions, if there are any.
6622 // FIXME: This isn't wonderful, because we don't know whether we're actually
6623 // in a context that permits expressions. This is a general issue with
6624 // qualified-id completions.
6625 if (Ctx && !EnteringContext)
6626 MaybeAddOverrideCalls(*this, Ctx, Results);
6627 Results.ExitScope();
6630 (CodeCompleter->includeNamespaceLevelDecls() || !Ctx->isFileContext())) {
6631 CodeCompletionDeclConsumer Consumer(Results, Ctx, BaseType);
6632 LookupVisibleDecls(Ctx, LookupOrdinaryName, Consumer,
6633 /*IncludeGlobalScope=*/true,
6634 /*IncludeDependentBases=*/true,
6635 CodeCompleter->loadExternal());
6638 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
6639 Results.data(), Results.size());
6642 void Sema::CodeCompleteUsing(Scope *S) {
6646 // This can be both a using alias or using declaration, in the former we
6647 // expect a new name and a symbol in the latter case.
6648 CodeCompletionContext Context(CodeCompletionContext::CCC_SymbolOrNewName);
6649 Context.setIsUsingDeclaration(true);
6651 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6652 CodeCompleter->getCodeCompletionTUInfo(), Context,
6653 &ResultBuilder::IsNestedNameSpecifier);
6654 Results.EnterNewScope();
6656 // If we aren't in class scope, we could see the "namespace" keyword.
6657 if (!S->isClassScope())
6658 Results.AddResult(CodeCompletionResult("namespace"));
6660 // After "using", we can see anything that would start a
6661 // nested-name-specifier.
6662 CodeCompletionDeclConsumer Consumer(Results, CurContext);
6663 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
6664 CodeCompleter->includeGlobals(),
6665 CodeCompleter->loadExternal());
6666 Results.ExitScope();
6668 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
6669 Results.data(), Results.size());
6672 void Sema::CodeCompleteUsingDirective(Scope *S) {
6676 // After "using namespace", we expect to see a namespace name or namespace
6678 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6679 CodeCompleter->getCodeCompletionTUInfo(),
6680 CodeCompletionContext::CCC_Namespace,
6681 &ResultBuilder::IsNamespaceOrAlias);
6682 Results.EnterNewScope();
6683 CodeCompletionDeclConsumer Consumer(Results, CurContext);
6684 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
6685 CodeCompleter->includeGlobals(),
6686 CodeCompleter->loadExternal());
6687 Results.ExitScope();
6688 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
6689 Results.data(), Results.size());
6692 void Sema::CodeCompleteNamespaceDecl(Scope *S) {
6696 DeclContext *Ctx = S->getEntity();
6697 if (!S->getParent())
6698 Ctx = Context.getTranslationUnitDecl();
6700 bool SuppressedGlobalResults =
6701 Ctx && !CodeCompleter->includeGlobals() && isa<TranslationUnitDecl>(Ctx);
6703 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6704 CodeCompleter->getCodeCompletionTUInfo(),
6705 SuppressedGlobalResults
6706 ? CodeCompletionContext::CCC_Namespace
6707 : CodeCompletionContext::CCC_Other,
6708 &ResultBuilder::IsNamespace);
6710 if (Ctx && Ctx->isFileContext() && !SuppressedGlobalResults) {
6711 // We only want to see those namespaces that have already been defined
6712 // within this scope, because its likely that the user is creating an
6713 // extended namespace declaration. Keep track of the most recent
6714 // definition of each namespace.
6715 std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest;
6716 for (DeclContext::specific_decl_iterator<NamespaceDecl>
6717 NS(Ctx->decls_begin()),
6718 NSEnd(Ctx->decls_end());
6720 OrigToLatest[NS->getOriginalNamespace()] = *NS;
6722 // Add the most recent definition (or extended definition) of each
6723 // namespace to the list of results.
6724 Results.EnterNewScope();
6725 for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator
6726 NS = OrigToLatest.begin(),
6727 NSEnd = OrigToLatest.end();
6730 CodeCompletionResult(NS->second, Results.getBasePriority(NS->second),
6732 CurContext, nullptr, false);
6733 Results.ExitScope();
6736 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
6737 Results.data(), Results.size());
6740 void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) {
6744 // After "namespace", we expect to see a namespace or alias.
6745 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6746 CodeCompleter->getCodeCompletionTUInfo(),
6747 CodeCompletionContext::CCC_Namespace,
6748 &ResultBuilder::IsNamespaceOrAlias);
6749 CodeCompletionDeclConsumer Consumer(Results, CurContext);
6750 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
6751 CodeCompleter->includeGlobals(),
6752 CodeCompleter->loadExternal());
6753 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
6754 Results.data(), Results.size());
6757 void Sema::CodeCompleteOperatorName(Scope *S) {
6761 typedef CodeCompletionResult Result;
6762 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6763 CodeCompleter->getCodeCompletionTUInfo(),
6764 CodeCompletionContext::CCC_Type,
6765 &ResultBuilder::IsType);
6766 Results.EnterNewScope();
6768 // Add the names of overloadable operators. Note that OO_Conditional is not
6769 // actually overloadable.
6770 #define OVERLOADED_OPERATOR(Name, Spelling, Token, Unary, Binary, MemberOnly) \
6771 if (OO_##Name != OO_Conditional) \
6772 Results.AddResult(Result(Spelling));
6773 #include "clang/Basic/OperatorKinds.def"
6775 // Add any type names visible from the current scope
6776 Results.allowNestedNameSpecifiers();
6777 CodeCompletionDeclConsumer Consumer(Results, CurContext);
6778 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
6779 CodeCompleter->includeGlobals(),
6780 CodeCompleter->loadExternal());
6782 // Add any type specifiers
6783 AddTypeSpecifierResults(getLangOpts(), Results);
6784 Results.ExitScope();
6786 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
6787 Results.data(), Results.size());
6790 void Sema::CodeCompleteConstructorInitializer(
6791 Decl *ConstructorD, ArrayRef<CXXCtorInitializer *> Initializers) {
6795 AdjustDeclIfTemplate(ConstructorD);
6797 auto *Constructor = dyn_cast<CXXConstructorDecl>(ConstructorD);
6801 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6802 CodeCompleter->getCodeCompletionTUInfo(),
6803 CodeCompletionContext::CCC_Symbol);
6804 Results.EnterNewScope();
6806 // Fill in any already-initialized fields or base classes.
6807 llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields;
6808 llvm::SmallPtrSet<CanQualType, 4> InitializedBases;
6809 for (unsigned I = 0, E = Initializers.size(); I != E; ++I) {
6810 if (Initializers[I]->isBaseInitializer())
6811 InitializedBases.insert(Context.getCanonicalType(
6812 QualType(Initializers[I]->getBaseClass(), 0)));
6814 InitializedFields.insert(
6815 cast<FieldDecl>(Initializers[I]->getAnyMember()));
6818 // Add completions for base classes.
6819 PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
6820 bool SawLastInitializer = Initializers.empty();
6821 CXXRecordDecl *ClassDecl = Constructor->getParent();
6823 auto GenerateCCS = [&](const NamedDecl *ND, const char *Name) {
6824 CodeCompletionBuilder Builder(Results.getAllocator(),
6825 Results.getCodeCompletionTUInfo());
6826 Builder.AddTypedTextChunk(Name);
6827 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6828 if (const auto *Function = dyn_cast<FunctionDecl>(ND))
6829 AddFunctionParameterChunks(PP, Policy, Function, Builder);
6830 else if (const auto *FunTemplDecl = dyn_cast<FunctionTemplateDecl>(ND))
6831 AddFunctionParameterChunks(PP, Policy, FunTemplDecl->getTemplatedDecl(),
6833 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6834 return Builder.TakeString();
6836 auto AddDefaultCtorInit = [&](const char *Name, const char *Type,
6837 const NamedDecl *ND) {
6838 CodeCompletionBuilder Builder(Results.getAllocator(),
6839 Results.getCodeCompletionTUInfo());
6840 Builder.AddTypedTextChunk(Name);
6841 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6842 Builder.AddPlaceholderChunk(Type);
6843 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6845 auto CCR = CodeCompletionResult(
6846 Builder.TakeString(), ND,
6847 SawLastInitializer ? CCP_NextInitializer : CCP_MemberDeclaration);
6848 if (isa<FieldDecl>(ND))
6849 CCR.CursorKind = CXCursor_MemberRef;
6850 return Results.AddResult(CCR);
6852 return Results.AddResult(CodeCompletionResult(
6853 Builder.TakeString(),
6854 SawLastInitializer ? CCP_NextInitializer : CCP_MemberDeclaration));
6856 auto AddCtorsWithName = [&](const CXXRecordDecl *RD, unsigned int Priority,
6857 const char *Name, const FieldDecl *FD) {
6859 return AddDefaultCtorInit(Name,
6860 FD ? Results.getAllocator().CopyString(
6861 FD->getType().getAsString(Policy))
6864 auto Ctors = getConstructors(Context, RD);
6865 if (Ctors.begin() == Ctors.end())
6866 return AddDefaultCtorInit(Name, Name, RD);
6867 for (const NamedDecl *Ctor : Ctors) {
6868 auto CCR = CodeCompletionResult(GenerateCCS(Ctor, Name), RD, Priority);
6869 CCR.CursorKind = getCursorKindForDecl(Ctor);
6870 Results.AddResult(CCR);
6873 auto AddBase = [&](const CXXBaseSpecifier &Base) {
6874 const char *BaseName =
6875 Results.getAllocator().CopyString(Base.getType().getAsString(Policy));
6876 const auto *RD = Base.getType()->getAsCXXRecordDecl();
6878 RD, SawLastInitializer ? CCP_NextInitializer : CCP_MemberDeclaration,
6881 auto AddField = [&](const FieldDecl *FD) {
6882 const char *FieldName =
6883 Results.getAllocator().CopyString(FD->getIdentifier()->getName());
6884 const CXXRecordDecl *RD = FD->getType()->getAsCXXRecordDecl();
6886 RD, SawLastInitializer ? CCP_NextInitializer : CCP_MemberDeclaration,
6890 for (const auto &Base : ClassDecl->bases()) {
6891 if (!InitializedBases.insert(Context.getCanonicalType(Base.getType()))
6893 SawLastInitializer =
6894 !Initializers.empty() && Initializers.back()->isBaseInitializer() &&
6895 Context.hasSameUnqualifiedType(
6896 Base.getType(), QualType(Initializers.back()->getBaseClass(), 0));
6901 SawLastInitializer = false;
6904 // Add completions for virtual base classes.
6905 for (const auto &Base : ClassDecl->vbases()) {
6906 if (!InitializedBases.insert(Context.getCanonicalType(Base.getType()))
6908 SawLastInitializer =
6909 !Initializers.empty() && Initializers.back()->isBaseInitializer() &&
6910 Context.hasSameUnqualifiedType(
6911 Base.getType(), QualType(Initializers.back()->getBaseClass(), 0));
6916 SawLastInitializer = false;
6919 // Add completions for members.
6920 for (auto *Field : ClassDecl->fields()) {
6921 if (!InitializedFields.insert(cast<FieldDecl>(Field->getCanonicalDecl()))
6923 SawLastInitializer = !Initializers.empty() &&
6924 Initializers.back()->isAnyMemberInitializer() &&
6925 Initializers.back()->getAnyMember() == Field;
6929 if (!Field->getDeclName())
6933 SawLastInitializer = false;
6935 Results.ExitScope();
6937 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
6938 Results.data(), Results.size());
6941 /// Determine whether this scope denotes a namespace.
6942 static bool isNamespaceScope(Scope *S) {
6943 DeclContext *DC = S->getEntity();
6947 return DC->isFileContext();
6950 void Sema::CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro,
6951 bool AfterAmpersand) {
6952 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6953 CodeCompleter->getCodeCompletionTUInfo(),
6954 CodeCompletionContext::CCC_Other);
6955 Results.EnterNewScope();
6957 // Note what has already been captured.
6958 llvm::SmallPtrSet<IdentifierInfo *, 4> Known;
6959 bool IncludedThis = false;
6960 for (const auto &C : Intro.Captures) {
6961 if (C.Kind == LCK_This) {
6962 IncludedThis = true;
6969 // Look for other capturable variables.
6970 for (; S && !isNamespaceScope(S); S = S->getParent()) {
6971 for (const auto *D : S->decls()) {
6972 const auto *Var = dyn_cast<VarDecl>(D);
6973 if (!Var || !Var->hasLocalStorage() || Var->hasAttr<BlocksAttr>())
6976 if (Known.insert(Var->getIdentifier()).second)
6977 Results.AddResult(CodeCompletionResult(Var, CCP_LocalDeclaration),
6978 CurContext, nullptr, false);
6982 // Add 'this', if it would be valid.
6983 if (!IncludedThis && !AfterAmpersand && Intro.Default != LCD_ByCopy)
6984 addThisCompletion(*this, Results);
6986 Results.ExitScope();
6988 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
6989 Results.data(), Results.size());
6992 void Sema::CodeCompleteAfterFunctionEquals(Declarator &D) {
6993 if (!LangOpts.CPlusPlus11)
6995 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6996 CodeCompleter->getCodeCompletionTUInfo(),
6997 CodeCompletionContext::CCC_Other);
6998 auto ShouldAddDefault = [&D, this]() {
6999 if (!D.isFunctionDeclarator())
7001 auto &Id = D.getName();
7002 if (Id.getKind() == UnqualifiedIdKind::IK_DestructorName)
7004 // FIXME(liuhui): Ideally, we should check the constructor parameter list to
7005 // verify that it is the default, copy or move constructor?
7006 if (Id.getKind() == UnqualifiedIdKind::IK_ConstructorName &&
7007 D.getFunctionTypeInfo().NumParams <= 1)
7009 if (Id.getKind() == UnqualifiedIdKind::IK_OperatorFunctionId) {
7010 auto Op = Id.OperatorFunctionId.Operator;
7011 // FIXME(liuhui): Ideally, we should check the function parameter list to
7012 // verify that it is the copy or move assignment?
7013 if (Op == OverloadedOperatorKind::OO_Equal)
7015 if (LangOpts.CPlusPlus20 &&
7016 (Op == OverloadedOperatorKind::OO_EqualEqual ||
7017 Op == OverloadedOperatorKind::OO_ExclaimEqual ||
7018 Op == OverloadedOperatorKind::OO_Less ||
7019 Op == OverloadedOperatorKind::OO_LessEqual ||
7020 Op == OverloadedOperatorKind::OO_Greater ||
7021 Op == OverloadedOperatorKind::OO_GreaterEqual ||
7022 Op == OverloadedOperatorKind::OO_Spaceship))
7028 Results.EnterNewScope();
7029 if (ShouldAddDefault())
7030 Results.AddResult("default");
7031 // FIXME(liuhui): Ideally, we should only provide `delete` completion for the
7032 // first function declaration.
7033 Results.AddResult("delete");
7034 Results.ExitScope();
7035 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
7036 Results.data(), Results.size());
7039 /// Macro that optionally prepends an "@" to the string literal passed in via
7040 /// Keyword, depending on whether NeedAt is true or false.
7041 #define OBJC_AT_KEYWORD_NAME(NeedAt, Keyword) ((NeedAt) ? "@" Keyword : Keyword)
7043 static void AddObjCImplementationResults(const LangOptions &LangOpts,
7044 ResultBuilder &Results, bool NeedAt) {
7045 typedef CodeCompletionResult Result;
7046 // Since we have an implementation, we can end it.
7047 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "end")));
7049 CodeCompletionBuilder Builder(Results.getAllocator(),
7050 Results.getCodeCompletionTUInfo());
7051 if (LangOpts.ObjC) {
7053 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "dynamic"));
7054 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7055 Builder.AddPlaceholderChunk("property");
7056 Results.AddResult(Result(Builder.TakeString()));
7059 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "synthesize"));
7060 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7061 Builder.AddPlaceholderChunk("property");
7062 Results.AddResult(Result(Builder.TakeString()));
7066 static void AddObjCInterfaceResults(const LangOptions &LangOpts,
7067 ResultBuilder &Results, bool NeedAt) {
7068 typedef CodeCompletionResult Result;
7070 // Since we have an interface or protocol, we can end it.
7071 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "end")));
7073 if (LangOpts.ObjC) {
7075 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "property")));
7078 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "required")));
7081 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "optional")));
7085 static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt) {
7086 typedef CodeCompletionResult Result;
7087 CodeCompletionBuilder Builder(Results.getAllocator(),
7088 Results.getCodeCompletionTUInfo());
7091 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "class"));
7092 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7093 Builder.AddPlaceholderChunk("name");
7094 Results.AddResult(Result(Builder.TakeString()));
7096 if (Results.includeCodePatterns()) {
7098 // FIXME: Could introduce the whole pattern, including superclasses and
7100 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "interface"));
7101 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7102 Builder.AddPlaceholderChunk("class");
7103 Results.AddResult(Result(Builder.TakeString()));
7106 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "protocol"));
7107 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7108 Builder.AddPlaceholderChunk("protocol");
7109 Results.AddResult(Result(Builder.TakeString()));
7111 // @implementation name
7112 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "implementation"));
7113 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7114 Builder.AddPlaceholderChunk("class");
7115 Results.AddResult(Result(Builder.TakeString()));
7118 // @compatibility_alias name
7119 Builder.AddTypedTextChunk(
7120 OBJC_AT_KEYWORD_NAME(NeedAt, "compatibility_alias"));
7121 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7122 Builder.AddPlaceholderChunk("alias");
7123 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7124 Builder.AddPlaceholderChunk("class");
7125 Results.AddResult(Result(Builder.TakeString()));
7127 if (Results.getSema().getLangOpts().Modules) {
7129 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "import"));
7130 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7131 Builder.AddPlaceholderChunk("module");
7132 Results.AddResult(Result(Builder.TakeString()));
7136 void Sema::CodeCompleteObjCAtDirective(Scope *S) {
7137 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
7138 CodeCompleter->getCodeCompletionTUInfo(),
7139 CodeCompletionContext::CCC_Other);
7140 Results.EnterNewScope();
7141 if (isa<ObjCImplDecl>(CurContext))
7142 AddObjCImplementationResults(getLangOpts(), Results, false);
7143 else if (CurContext->isObjCContainer())
7144 AddObjCInterfaceResults(getLangOpts(), Results, false);
7146 AddObjCTopLevelResults(Results, false);
7147 Results.ExitScope();
7148 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
7149 Results.data(), Results.size());
7152 static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt) {
7153 typedef CodeCompletionResult Result;
7154 CodeCompletionBuilder Builder(Results.getAllocator(),
7155 Results.getCodeCompletionTUInfo());
7157 // @encode ( type-name )
7158 const char *EncodeType = "char[]";
7159 if (Results.getSema().getLangOpts().CPlusPlus ||
7160 Results.getSema().getLangOpts().ConstStrings)
7161 EncodeType = "const char[]";
7162 Builder.AddResultTypeChunk(EncodeType);
7163 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "encode"));
7164 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7165 Builder.AddPlaceholderChunk("type-name");
7166 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7167 Results.AddResult(Result(Builder.TakeString()));
7169 // @protocol ( protocol-name )
7170 Builder.AddResultTypeChunk("Protocol *");
7171 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "protocol"));
7172 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7173 Builder.AddPlaceholderChunk("protocol-name");
7174 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7175 Results.AddResult(Result(Builder.TakeString()));
7177 // @selector ( selector )
7178 Builder.AddResultTypeChunk("SEL");
7179 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "selector"));
7180 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7181 Builder.AddPlaceholderChunk("selector");
7182 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7183 Results.AddResult(Result(Builder.TakeString()));
7186 Builder.AddResultTypeChunk("NSString *");
7187 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "\""));
7188 Builder.AddPlaceholderChunk("string");
7189 Builder.AddTextChunk("\"");
7190 Results.AddResult(Result(Builder.TakeString()));
7193 Builder.AddResultTypeChunk("NSArray *");
7194 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "["));
7195 Builder.AddPlaceholderChunk("objects, ...");
7196 Builder.AddChunk(CodeCompletionString::CK_RightBracket);
7197 Results.AddResult(Result(Builder.TakeString()));
7199 // @{key : object, ...}
7200 Builder.AddResultTypeChunk("NSDictionary *");
7201 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "{"));
7202 Builder.AddPlaceholderChunk("key");
7203 Builder.AddChunk(CodeCompletionString::CK_Colon);
7204 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7205 Builder.AddPlaceholderChunk("object, ...");
7206 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
7207 Results.AddResult(Result(Builder.TakeString()));
7210 Builder.AddResultTypeChunk("id");
7211 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "("));
7212 Builder.AddPlaceholderChunk("expression");
7213 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7214 Results.AddResult(Result(Builder.TakeString()));
7217 static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt) {
7218 typedef CodeCompletionResult Result;
7219 CodeCompletionBuilder Builder(Results.getAllocator(),
7220 Results.getCodeCompletionTUInfo());
7222 if (Results.includeCodePatterns()) {
7223 // @try { statements } @catch ( declaration ) { statements } @finally
7225 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "try"));
7226 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
7227 Builder.AddPlaceholderChunk("statements");
7228 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
7229 Builder.AddTextChunk("@catch");
7230 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7231 Builder.AddPlaceholderChunk("parameter");
7232 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7233 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
7234 Builder.AddPlaceholderChunk("statements");
7235 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
7236 Builder.AddTextChunk("@finally");
7237 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
7238 Builder.AddPlaceholderChunk("statements");
7239 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
7240 Results.AddResult(Result(Builder.TakeString()));
7244 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "throw"));
7245 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7246 Builder.AddPlaceholderChunk("expression");
7247 Results.AddResult(Result(Builder.TakeString()));
7249 if (Results.includeCodePatterns()) {
7250 // @synchronized ( expression ) { statements }
7251 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "synchronized"));
7252 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7253 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7254 Builder.AddPlaceholderChunk("expression");
7255 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7256 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
7257 Builder.AddPlaceholderChunk("statements");
7258 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
7259 Results.AddResult(Result(Builder.TakeString()));
7263 static void AddObjCVisibilityResults(const LangOptions &LangOpts,
7264 ResultBuilder &Results, bool NeedAt) {
7265 typedef CodeCompletionResult Result;
7266 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "private")));
7267 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "protected")));
7268 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "public")));
7270 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "package")));
7273 void Sema::CodeCompleteObjCAtVisibility(Scope *S) {
7274 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
7275 CodeCompleter->getCodeCompletionTUInfo(),
7276 CodeCompletionContext::CCC_Other);
7277 Results.EnterNewScope();
7278 AddObjCVisibilityResults(getLangOpts(), Results, false);
7279 Results.ExitScope();
7280 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
7281 Results.data(), Results.size());
7284 void Sema::CodeCompleteObjCAtStatement(Scope *S) {
7285 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
7286 CodeCompleter->getCodeCompletionTUInfo(),
7287 CodeCompletionContext::CCC_Other);
7288 Results.EnterNewScope();
7289 AddObjCStatementResults(Results, false);
7290 AddObjCExpressionResults(Results, false);
7291 Results.ExitScope();
7292 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
7293 Results.data(), Results.size());
7296 void Sema::CodeCompleteObjCAtExpression(Scope *S) {
7297 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
7298 CodeCompleter->getCodeCompletionTUInfo(),
7299 CodeCompletionContext::CCC_Other);
7300 Results.EnterNewScope();
7301 AddObjCExpressionResults(Results, false);
7302 Results.ExitScope();
7303 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
7304 Results.data(), Results.size());
7307 /// Determine whether the addition of the given flag to an Objective-C
7308 /// property's attributes will cause a conflict.
7309 static bool ObjCPropertyFlagConflicts(unsigned Attributes, unsigned NewFlag) {
7310 // Check if we've already added this flag.
7311 if (Attributes & NewFlag)
7314 Attributes |= NewFlag;
7316 // Check for collisions with "readonly".
7317 if ((Attributes & ObjCPropertyAttribute::kind_readonly) &&
7318 (Attributes & ObjCPropertyAttribute::kind_readwrite))
7321 // Check for more than one of { assign, copy, retain, strong, weak }.
7322 unsigned AssignCopyRetMask =
7324 (ObjCPropertyAttribute::kind_assign |
7325 ObjCPropertyAttribute::kind_unsafe_unretained |
7326 ObjCPropertyAttribute::kind_copy | ObjCPropertyAttribute::kind_retain |
7327 ObjCPropertyAttribute::kind_strong | ObjCPropertyAttribute::kind_weak);
7328 if (AssignCopyRetMask &&
7329 AssignCopyRetMask != ObjCPropertyAttribute::kind_assign &&
7330 AssignCopyRetMask != ObjCPropertyAttribute::kind_unsafe_unretained &&
7331 AssignCopyRetMask != ObjCPropertyAttribute::kind_copy &&
7332 AssignCopyRetMask != ObjCPropertyAttribute::kind_retain &&
7333 AssignCopyRetMask != ObjCPropertyAttribute::kind_strong &&
7334 AssignCopyRetMask != ObjCPropertyAttribute::kind_weak)
7340 void Sema::CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS) {
7344 unsigned Attributes = ODS.getPropertyAttributes();
7346 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
7347 CodeCompleter->getCodeCompletionTUInfo(),
7348 CodeCompletionContext::CCC_Other);
7349 Results.EnterNewScope();
7350 if (!ObjCPropertyFlagConflicts(Attributes,
7351 ObjCPropertyAttribute::kind_readonly))
7352 Results.AddResult(CodeCompletionResult("readonly"));
7353 if (!ObjCPropertyFlagConflicts(Attributes,
7354 ObjCPropertyAttribute::kind_assign))
7355 Results.AddResult(CodeCompletionResult("assign"));
7356 if (!ObjCPropertyFlagConflicts(Attributes,
7357 ObjCPropertyAttribute::kind_unsafe_unretained))
7358 Results.AddResult(CodeCompletionResult("unsafe_unretained"));
7359 if (!ObjCPropertyFlagConflicts(Attributes,
7360 ObjCPropertyAttribute::kind_readwrite))
7361 Results.AddResult(CodeCompletionResult("readwrite"));
7362 if (!ObjCPropertyFlagConflicts(Attributes,
7363 ObjCPropertyAttribute::kind_retain))
7364 Results.AddResult(CodeCompletionResult("retain"));
7365 if (!ObjCPropertyFlagConflicts(Attributes,
7366 ObjCPropertyAttribute::kind_strong))
7367 Results.AddResult(CodeCompletionResult("strong"));
7368 if (!ObjCPropertyFlagConflicts(Attributes, ObjCPropertyAttribute::kind_copy))
7369 Results.AddResult(CodeCompletionResult("copy"));
7370 if (!ObjCPropertyFlagConflicts(Attributes,
7371 ObjCPropertyAttribute::kind_nonatomic))
7372 Results.AddResult(CodeCompletionResult("nonatomic"));
7373 if (!ObjCPropertyFlagConflicts(Attributes,
7374 ObjCPropertyAttribute::kind_atomic))
7375 Results.AddResult(CodeCompletionResult("atomic"));
7377 // Only suggest "weak" if we're compiling for ARC-with-weak-references or GC.
7378 if (getLangOpts().ObjCWeak || getLangOpts().getGC() != LangOptions::NonGC)
7379 if (!ObjCPropertyFlagConflicts(Attributes,
7380 ObjCPropertyAttribute::kind_weak))
7381 Results.AddResult(CodeCompletionResult("weak"));
7383 if (!ObjCPropertyFlagConflicts(Attributes,
7384 ObjCPropertyAttribute::kind_setter)) {
7385 CodeCompletionBuilder Setter(Results.getAllocator(),
7386 Results.getCodeCompletionTUInfo());
7387 Setter.AddTypedTextChunk("setter");
7388 Setter.AddTextChunk("=");
7389 Setter.AddPlaceholderChunk("method");
7390 Results.AddResult(CodeCompletionResult(Setter.TakeString()));
7392 if (!ObjCPropertyFlagConflicts(Attributes,
7393 ObjCPropertyAttribute::kind_getter)) {
7394 CodeCompletionBuilder Getter(Results.getAllocator(),
7395 Results.getCodeCompletionTUInfo());
7396 Getter.AddTypedTextChunk("getter");
7397 Getter.AddTextChunk("=");
7398 Getter.AddPlaceholderChunk("method");
7399 Results.AddResult(CodeCompletionResult(Getter.TakeString()));
7401 if (!ObjCPropertyFlagConflicts(Attributes,
7402 ObjCPropertyAttribute::kind_nullability)) {
7403 Results.AddResult(CodeCompletionResult("nonnull"));
7404 Results.AddResult(CodeCompletionResult("nullable"));
7405 Results.AddResult(CodeCompletionResult("null_unspecified"));
7406 Results.AddResult(CodeCompletionResult("null_resettable"));
7408 Results.ExitScope();
7409 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
7410 Results.data(), Results.size());
7413 /// Describes the kind of Objective-C method that we want to find
7414 /// via code completion.
7415 enum ObjCMethodKind {
7416 MK_Any, ///< Any kind of method, provided it means other specified criteria.
7417 MK_ZeroArgSelector, ///< Zero-argument (unary) selector.
7418 MK_OneArgSelector ///< One-argument selector.
7421 static bool isAcceptableObjCSelector(Selector Sel, ObjCMethodKind WantKind,
7422 ArrayRef<IdentifierInfo *> SelIdents,
7423 bool AllowSameLength = true) {
7424 unsigned NumSelIdents = SelIdents.size();
7425 if (NumSelIdents > Sel.getNumArgs())
7431 case MK_ZeroArgSelector:
7432 return Sel.isUnarySelector();
7433 case MK_OneArgSelector:
7434 return Sel.getNumArgs() == 1;
7437 if (!AllowSameLength && NumSelIdents && NumSelIdents == Sel.getNumArgs())
7440 for (unsigned I = 0; I != NumSelIdents; ++I)
7441 if (SelIdents[I] != Sel.getIdentifierInfoForSlot(I))
7447 static bool isAcceptableObjCMethod(ObjCMethodDecl *Method,
7448 ObjCMethodKind WantKind,
7449 ArrayRef<IdentifierInfo *> SelIdents,
7450 bool AllowSameLength = true) {
7451 return isAcceptableObjCSelector(Method->getSelector(), WantKind, SelIdents,
7455 /// A set of selectors, which is used to avoid introducing multiple
7456 /// completions with the same selector into the result set.
7457 typedef llvm::SmallPtrSet<Selector, 16> VisitedSelectorSet;
7459 /// Add all of the Objective-C methods in the given Objective-C
7460 /// container to the set of results.
7462 /// The container will be a class, protocol, category, or implementation of
7463 /// any of the above. This mether will recurse to include methods from
7464 /// the superclasses of classes along with their categories, protocols, and
7465 /// implementations.
7467 /// \param Container the container in which we'll look to find methods.
7469 /// \param WantInstanceMethods Whether to add instance methods (only); if
7470 /// false, this routine will add factory methods (only).
7472 /// \param CurContext the context in which we're performing the lookup that
7475 /// \param AllowSameLength Whether we allow a method to be added to the list
7476 /// when it has the same number of parameters as we have selector identifiers.
7478 /// \param Results the structure into which we'll add results.
7479 static void AddObjCMethods(ObjCContainerDecl *Container,
7480 bool WantInstanceMethods, ObjCMethodKind WantKind,
7481 ArrayRef<IdentifierInfo *> SelIdents,
7482 DeclContext *CurContext,
7483 VisitedSelectorSet &Selectors, bool AllowSameLength,
7484 ResultBuilder &Results, bool InOriginalClass = true,
7485 bool IsRootClass = false) {
7486 typedef CodeCompletionResult Result;
7487 Container = getContainerDef(Container);
7488 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container);
7489 IsRootClass = IsRootClass || (IFace && !IFace->getSuperClass());
7490 for (ObjCMethodDecl *M : Container->methods()) {
7491 // The instance methods on the root class can be messaged via the
7493 if (M->isInstanceMethod() == WantInstanceMethods ||
7494 (IsRootClass && !WantInstanceMethods)) {
7495 // Check whether the selector identifiers we've been given are a
7496 // subset of the identifiers for this particular method.
7497 if (!isAcceptableObjCMethod(M, WantKind, SelIdents, AllowSameLength))
7500 if (!Selectors.insert(M->getSelector()).second)
7503 Result R = Result(M, Results.getBasePriority(M), nullptr);
7504 R.StartParameter = SelIdents.size();
7505 R.AllParametersAreInformative = (WantKind != MK_Any);
7506 if (!InOriginalClass)
7508 Results.MaybeAddResult(R, CurContext);
7512 // Visit the protocols of protocols.
7513 if (const auto *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
7514 if (Protocol->hasDefinition()) {
7515 const ObjCList<ObjCProtocolDecl> &Protocols =
7516 Protocol->getReferencedProtocols();
7517 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
7518 E = Protocols.end();
7520 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, CurContext,
7521 Selectors, AllowSameLength, Results, false, IsRootClass);
7525 if (!IFace || !IFace->hasDefinition())
7528 // Add methods in protocols.
7529 for (ObjCProtocolDecl *I : IFace->protocols())
7530 AddObjCMethods(I, WantInstanceMethods, WantKind, SelIdents, CurContext,
7531 Selectors, AllowSameLength, Results, false, IsRootClass);
7533 // Add methods in categories.
7534 for (ObjCCategoryDecl *CatDecl : IFace->known_categories()) {
7535 AddObjCMethods(CatDecl, WantInstanceMethods, WantKind, SelIdents,
7536 CurContext, Selectors, AllowSameLength, Results,
7537 InOriginalClass, IsRootClass);
7539 // Add a categories protocol methods.
7540 const ObjCList<ObjCProtocolDecl> &Protocols =
7541 CatDecl->getReferencedProtocols();
7542 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
7543 E = Protocols.end();
7545 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, CurContext,
7546 Selectors, AllowSameLength, Results, false, IsRootClass);
7548 // Add methods in category implementations.
7549 if (ObjCCategoryImplDecl *Impl = CatDecl->getImplementation())
7550 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents, CurContext,
7551 Selectors, AllowSameLength, Results, InOriginalClass,
7555 // Add methods in superclass.
7556 // Avoid passing in IsRootClass since root classes won't have super classes.
7557 if (IFace->getSuperClass())
7558 AddObjCMethods(IFace->getSuperClass(), WantInstanceMethods, WantKind,
7559 SelIdents, CurContext, Selectors, AllowSameLength, Results,
7560 /*IsRootClass=*/false);
7562 // Add methods in our implementation, if any.
7563 if (ObjCImplementationDecl *Impl = IFace->getImplementation())
7564 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents, CurContext,
7565 Selectors, AllowSameLength, Results, InOriginalClass,
7569 void Sema::CodeCompleteObjCPropertyGetter(Scope *S) {
7570 // Try to find the interface where getters might live.
7571 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext);
7573 if (ObjCCategoryDecl *Category =
7574 dyn_cast_or_null<ObjCCategoryDecl>(CurContext))
7575 Class = Category->getClassInterface();
7581 // Find all of the potential getters.
7582 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
7583 CodeCompleter->getCodeCompletionTUInfo(),
7584 CodeCompletionContext::CCC_Other);
7585 Results.EnterNewScope();
7587 VisitedSelectorSet Selectors;
7588 AddObjCMethods(Class, true, MK_ZeroArgSelector, std::nullopt, CurContext,
7590 /*AllowSameLength=*/true, Results);
7591 Results.ExitScope();
7592 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
7593 Results.data(), Results.size());
7596 void Sema::CodeCompleteObjCPropertySetter(Scope *S) {
7597 // Try to find the interface where setters might live.
7598 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext);
7600 if (ObjCCategoryDecl *Category =
7601 dyn_cast_or_null<ObjCCategoryDecl>(CurContext))
7602 Class = Category->getClassInterface();
7608 // Find all of the potential getters.
7609 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
7610 CodeCompleter->getCodeCompletionTUInfo(),
7611 CodeCompletionContext::CCC_Other);
7612 Results.EnterNewScope();
7614 VisitedSelectorSet Selectors;
7615 AddObjCMethods(Class, true, MK_OneArgSelector, std::nullopt, CurContext,
7617 /*AllowSameLength=*/true, Results);
7619 Results.ExitScope();
7620 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
7621 Results.data(), Results.size());
7624 void Sema::CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
7626 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
7627 CodeCompleter->getCodeCompletionTUInfo(),
7628 CodeCompletionContext::CCC_Type);
7629 Results.EnterNewScope();
7631 // Add context-sensitive, Objective-C parameter-passing keywords.
7632 bool AddedInOut = false;
7633 if ((DS.getObjCDeclQualifier() &
7634 (ObjCDeclSpec::DQ_In | ObjCDeclSpec::DQ_Inout)) == 0) {
7635 Results.AddResult("in");
7636 Results.AddResult("inout");
7639 if ((DS.getObjCDeclQualifier() &
7640 (ObjCDeclSpec::DQ_Out | ObjCDeclSpec::DQ_Inout)) == 0) {
7641 Results.AddResult("out");
7643 Results.AddResult("inout");
7645 if ((DS.getObjCDeclQualifier() &
7646 (ObjCDeclSpec::DQ_Bycopy | ObjCDeclSpec::DQ_Byref |
7647 ObjCDeclSpec::DQ_Oneway)) == 0) {
7648 Results.AddResult("bycopy");
7649 Results.AddResult("byref");
7650 Results.AddResult("oneway");
7652 if ((DS.getObjCDeclQualifier() & ObjCDeclSpec::DQ_CSNullability) == 0) {
7653 Results.AddResult("nonnull");
7654 Results.AddResult("nullable");
7655 Results.AddResult("null_unspecified");
7658 // If we're completing the return type of an Objective-C method and the
7659 // identifier IBAction refers to a macro, provide a completion item for
7661 // IBAction)<#selector#>:(id)sender
7662 if (DS.getObjCDeclQualifier() == 0 && !IsParameter &&
7663 PP.isMacroDefined("IBAction")) {
7664 CodeCompletionBuilder Builder(Results.getAllocator(),
7665 Results.getCodeCompletionTUInfo(),
7666 CCP_CodePattern, CXAvailability_Available);
7667 Builder.AddTypedTextChunk("IBAction");
7668 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7669 Builder.AddPlaceholderChunk("selector");
7670 Builder.AddChunk(CodeCompletionString::CK_Colon);
7671 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7672 Builder.AddTextChunk("id");
7673 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7674 Builder.AddTextChunk("sender");
7675 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
7678 // If we're completing the return type, provide 'instancetype'.
7680 Results.AddResult(CodeCompletionResult("instancetype"));
7683 // Add various builtin type names and specifiers.
7684 AddOrdinaryNameResults(PCC_Type, S, *this, Results);
7685 Results.ExitScope();
7687 // Add the various type names
7688 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
7689 CodeCompletionDeclConsumer Consumer(Results, CurContext);
7690 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
7691 CodeCompleter->includeGlobals(),
7692 CodeCompleter->loadExternal());
7694 if (CodeCompleter->includeMacros())
7695 AddMacroResults(PP, Results, CodeCompleter->loadExternal(), false);
7697 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
7698 Results.data(), Results.size());
7701 /// When we have an expression with type "id", we may assume
7702 /// that it has some more-specific class type based on knowledge of
7703 /// common uses of Objective-C. This routine returns that class type,
7704 /// or NULL if no better result could be determined.
7705 static ObjCInterfaceDecl *GetAssumedMessageSendExprType(Expr *E) {
7706 auto *Msg = dyn_cast_or_null<ObjCMessageExpr>(E);
7710 Selector Sel = Msg->getSelector();
7714 IdentifierInfo *Id = Sel.getIdentifierInfoForSlot(0);
7718 ObjCMethodDecl *Method = Msg->getMethodDecl();
7722 // Determine the class that we're sending the message to.
7723 ObjCInterfaceDecl *IFace = nullptr;
7724 switch (Msg->getReceiverKind()) {
7725 case ObjCMessageExpr::Class:
7726 if (const ObjCObjectType *ObjType =
7727 Msg->getClassReceiver()->getAs<ObjCObjectType>())
7728 IFace = ObjType->getInterface();
7731 case ObjCMessageExpr::Instance: {
7732 QualType T = Msg->getInstanceReceiver()->getType();
7733 if (const ObjCObjectPointerType *Ptr = T->getAs<ObjCObjectPointerType>())
7734 IFace = Ptr->getInterfaceDecl();
7738 case ObjCMessageExpr::SuperInstance:
7739 case ObjCMessageExpr::SuperClass:
7746 ObjCInterfaceDecl *Super = IFace->getSuperClass();
7747 if (Method->isInstanceMethod())
7748 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
7749 .Case("retain", IFace)
7750 .Case("strong", IFace)
7751 .Case("autorelease", IFace)
7752 .Case("copy", IFace)
7753 .Case("copyWithZone", IFace)
7754 .Case("mutableCopy", IFace)
7755 .Case("mutableCopyWithZone", IFace)
7756 .Case("awakeFromCoder", IFace)
7757 .Case("replacementObjectFromCoder", IFace)
7758 .Case("class", IFace)
7759 .Case("classForCoder", IFace)
7760 .Case("superclass", Super)
7763 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
7765 .Case("alloc", IFace)
7766 .Case("allocWithZone", IFace)
7767 .Case("class", IFace)
7768 .Case("superclass", Super)
7772 // Add a special completion for a message send to "super", which fills in the
7773 // most likely case of forwarding all of our arguments to the superclass
7776 /// \param S The semantic analysis object.
7778 /// \param NeedSuperKeyword Whether we need to prefix this completion with
7779 /// the "super" keyword. Otherwise, we just need to provide the arguments.
7781 /// \param SelIdents The identifiers in the selector that have already been
7782 /// provided as arguments for a send to "super".
7784 /// \param Results The set of results to augment.
7786 /// \returns the Objective-C method declaration that would be invoked by
7787 /// this "super" completion. If NULL, no completion was added.
7788 static ObjCMethodDecl *
7789 AddSuperSendCompletion(Sema &S, bool NeedSuperKeyword,
7790 ArrayRef<IdentifierInfo *> SelIdents,
7791 ResultBuilder &Results) {
7792 ObjCMethodDecl *CurMethod = S.getCurMethodDecl();
7796 ObjCInterfaceDecl *Class = CurMethod->getClassInterface();
7800 // Try to find a superclass method with the same selector.
7801 ObjCMethodDecl *SuperMethod = nullptr;
7802 while ((Class = Class->getSuperClass()) && !SuperMethod) {
7803 // Check in the class
7804 SuperMethod = Class->getMethod(CurMethod->getSelector(),
7805 CurMethod->isInstanceMethod());
7807 // Check in categories or class extensions.
7809 for (const auto *Cat : Class->known_categories()) {
7810 if ((SuperMethod = Cat->getMethod(CurMethod->getSelector(),
7811 CurMethod->isInstanceMethod())))
7820 // Check whether the superclass method has the same signature.
7821 if (CurMethod->param_size() != SuperMethod->param_size() ||
7822 CurMethod->isVariadic() != SuperMethod->isVariadic())
7825 for (ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin(),
7826 CurPEnd = CurMethod->param_end(),
7827 SuperP = SuperMethod->param_begin();
7828 CurP != CurPEnd; ++CurP, ++SuperP) {
7829 // Make sure the parameter types are compatible.
7830 if (!S.Context.hasSameUnqualifiedType((*CurP)->getType(),
7831 (*SuperP)->getType()))
7834 // Make sure we have a parameter name to forward!
7835 if (!(*CurP)->getIdentifier())
7839 // We have a superclass method. Now, form the send-to-super completion.
7840 CodeCompletionBuilder Builder(Results.getAllocator(),
7841 Results.getCodeCompletionTUInfo());
7843 // Give this completion a return type.
7844 AddResultTypeChunk(S.Context, getCompletionPrintingPolicy(S), SuperMethod,
7845 Results.getCompletionContext().getBaseType(), Builder);
7847 // If we need the "super" keyword, add it (plus some spacing).
7848 if (NeedSuperKeyword) {
7849 Builder.AddTypedTextChunk("super");
7850 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7853 Selector Sel = CurMethod->getSelector();
7854 if (Sel.isUnarySelector()) {
7855 if (NeedSuperKeyword)
7856 Builder.AddTextChunk(
7857 Builder.getAllocator().CopyString(Sel.getNameForSlot(0)));
7859 Builder.AddTypedTextChunk(
7860 Builder.getAllocator().CopyString(Sel.getNameForSlot(0)));
7862 ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin();
7863 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I, ++CurP) {
7864 if (I > SelIdents.size())
7865 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7867 if (I < SelIdents.size())
7868 Builder.AddInformativeChunk(
7869 Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":"));
7870 else if (NeedSuperKeyword || I > SelIdents.size()) {
7871 Builder.AddTextChunk(
7872 Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":"));
7873 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
7874 (*CurP)->getIdentifier()->getName()));
7876 Builder.AddTypedTextChunk(
7877 Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":"));
7878 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
7879 (*CurP)->getIdentifier()->getName()));
7884 Results.AddResult(CodeCompletionResult(Builder.TakeString(), SuperMethod,
7885 CCP_SuperCompletion));
7889 void Sema::CodeCompleteObjCMessageReceiver(Scope *S) {
7890 typedef CodeCompletionResult Result;
7891 ResultBuilder Results(
7892 *this, CodeCompleter->getAllocator(),
7893 CodeCompleter->getCodeCompletionTUInfo(),
7894 CodeCompletionContext::CCC_ObjCMessageReceiver,
7895 getLangOpts().CPlusPlus11
7896 ? &ResultBuilder::IsObjCMessageReceiverOrLambdaCapture
7897 : &ResultBuilder::IsObjCMessageReceiver);
7899 CodeCompletionDeclConsumer Consumer(Results, CurContext);
7900 Results.EnterNewScope();
7901 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
7902 CodeCompleter->includeGlobals(),
7903 CodeCompleter->loadExternal());
7905 // If we are in an Objective-C method inside a class that has a superclass,
7906 // add "super" as an option.
7907 if (ObjCMethodDecl *Method = getCurMethodDecl())
7908 if (ObjCInterfaceDecl *Iface = Method->getClassInterface())
7909 if (Iface->getSuperClass()) {
7910 Results.AddResult(Result("super"));
7912 AddSuperSendCompletion(*this, /*NeedSuperKeyword=*/true, std::nullopt,
7916 if (getLangOpts().CPlusPlus11)
7917 addThisCompletion(*this, Results);
7919 Results.ExitScope();
7921 if (CodeCompleter->includeMacros())
7922 AddMacroResults(PP, Results, CodeCompleter->loadExternal(), false);
7923 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
7924 Results.data(), Results.size());
7927 void Sema::CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
7928 ArrayRef<IdentifierInfo *> SelIdents,
7929 bool AtArgumentExpression) {
7930 ObjCInterfaceDecl *CDecl = nullptr;
7931 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
7932 // Figure out which interface we're in.
7933 CDecl = CurMethod->getClassInterface();
7937 // Find the superclass of this class.
7938 CDecl = CDecl->getSuperClass();
7942 if (CurMethod->isInstanceMethod()) {
7943 // We are inside an instance method, which means that the message
7944 // send [super ...] is actually calling an instance method on the
7946 return CodeCompleteObjCInstanceMessage(S, nullptr, SelIdents,
7947 AtArgumentExpression, CDecl);
7950 // Fall through to send to the superclass in CDecl.
7952 // "super" may be the name of a type or variable. Figure out which
7954 IdentifierInfo *Super = getSuperIdentifier();
7955 NamedDecl *ND = LookupSingleName(S, Super, SuperLoc, LookupOrdinaryName);
7956 if ((CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(ND))) {
7957 // "super" names an interface. Use it.
7958 } else if (TypeDecl *TD = dyn_cast_or_null<TypeDecl>(ND)) {
7959 if (const ObjCObjectType *Iface =
7960 Context.getTypeDeclType(TD)->getAs<ObjCObjectType>())
7961 CDecl = Iface->getInterface();
7962 } else if (ND && isa<UnresolvedUsingTypenameDecl>(ND)) {
7963 // "super" names an unresolved type; we can't be more specific.
7965 // Assume that "super" names some kind of value and parse that way.
7967 SourceLocation TemplateKWLoc;
7969 id.setIdentifier(Super, SuperLoc);
7970 ExprResult SuperExpr = ActOnIdExpression(S, SS, TemplateKWLoc, id,
7971 /*HasTrailingLParen=*/false,
7972 /*IsAddressOfOperand=*/false);
7973 return CodeCompleteObjCInstanceMessage(S, (Expr *)SuperExpr.get(),
7974 SelIdents, AtArgumentExpression);
7980 ParsedType Receiver;
7982 Receiver = ParsedType::make(Context.getObjCInterfaceType(CDecl));
7983 return CodeCompleteObjCClassMessage(S, Receiver, SelIdents,
7984 AtArgumentExpression,
7988 /// Given a set of code-completion results for the argument of a message
7989 /// send, determine the preferred type (if any) for that argument expression.
7990 static QualType getPreferredArgumentTypeForMessageSend(ResultBuilder &Results,
7991 unsigned NumSelIdents) {
7992 typedef CodeCompletionResult Result;
7993 ASTContext &Context = Results.getSema().Context;
7995 QualType PreferredType;
7996 unsigned BestPriority = CCP_Unlikely * 2;
7997 Result *ResultsData = Results.data();
7998 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
7999 Result &R = ResultsData[I];
8000 if (R.Kind == Result::RK_Declaration &&
8001 isa<ObjCMethodDecl>(R.Declaration)) {
8002 if (R.Priority <= BestPriority) {
8003 const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(R.Declaration);
8004 if (NumSelIdents <= Method->param_size()) {
8005 QualType MyPreferredType =
8006 Method->parameters()[NumSelIdents - 1]->getType();
8007 if (R.Priority < BestPriority || PreferredType.isNull()) {
8008 BestPriority = R.Priority;
8009 PreferredType = MyPreferredType;
8010 } else if (!Context.hasSameUnqualifiedType(PreferredType,
8012 PreferredType = QualType();
8019 return PreferredType;
8022 static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
8023 ParsedType Receiver,
8024 ArrayRef<IdentifierInfo *> SelIdents,
8025 bool AtArgumentExpression, bool IsSuper,
8026 ResultBuilder &Results) {
8027 typedef CodeCompletionResult Result;
8028 ObjCInterfaceDecl *CDecl = nullptr;
8030 // If the given name refers to an interface type, retrieve the
8031 // corresponding declaration.
8033 QualType T = SemaRef.GetTypeFromParser(Receiver, nullptr);
8035 if (const ObjCObjectType *Interface = T->getAs<ObjCObjectType>())
8036 CDecl = Interface->getInterface();
8039 // Add all of the factory methods in this Objective-C class, its protocols,
8040 // superclasses, categories, implementation, etc.
8041 Results.EnterNewScope();
8043 // If this is a send-to-super, try to add the special "super" send
8046 if (ObjCMethodDecl *SuperMethod =
8047 AddSuperSendCompletion(SemaRef, false, SelIdents, Results))
8048 Results.Ignore(SuperMethod);
8051 // If we're inside an Objective-C method definition, prefer its selector to
8053 if (ObjCMethodDecl *CurMethod = SemaRef.getCurMethodDecl())
8054 Results.setPreferredSelector(CurMethod->getSelector());
8056 VisitedSelectorSet Selectors;
8058 AddObjCMethods(CDecl, false, MK_Any, SelIdents, SemaRef.CurContext,
8059 Selectors, AtArgumentExpression, Results);
8061 // We're messaging "id" as a type; provide all class/factory methods.
8063 // If we have an external source, load the entire class method
8064 // pool from the AST file.
8065 if (SemaRef.getExternalSource()) {
8066 for (uint32_t I = 0,
8067 N = SemaRef.getExternalSource()->GetNumExternalSelectors();
8069 Selector Sel = SemaRef.getExternalSource()->GetExternalSelector(I);
8070 if (Sel.isNull() || SemaRef.MethodPool.count(Sel))
8073 SemaRef.ReadMethodPool(Sel);
8077 for (Sema::GlobalMethodPool::iterator M = SemaRef.MethodPool.begin(),
8078 MEnd = SemaRef.MethodPool.end();
8080 for (ObjCMethodList *MethList = &M->second.second;
8081 MethList && MethList->getMethod(); MethList = MethList->getNext()) {
8082 if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents))
8085 Result R(MethList->getMethod(),
8086 Results.getBasePriority(MethList->getMethod()), nullptr);
8087 R.StartParameter = SelIdents.size();
8088 R.AllParametersAreInformative = false;
8089 Results.MaybeAddResult(R, SemaRef.CurContext);
8094 Results.ExitScope();
8097 void Sema::CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
8098 ArrayRef<IdentifierInfo *> SelIdents,
8099 bool AtArgumentExpression,
8102 QualType T = this->GetTypeFromParser(Receiver);
8104 ResultBuilder Results(
8105 *this, CodeCompleter->getAllocator(),
8106 CodeCompleter->getCodeCompletionTUInfo(),
8107 CodeCompletionContext(CodeCompletionContext::CCC_ObjCClassMessage, T,
8110 AddClassMessageCompletions(*this, S, Receiver, SelIdents,
8111 AtArgumentExpression, IsSuper, Results);
8113 // If we're actually at the argument expression (rather than prior to the
8114 // selector), we're actually performing code completion for an expression.
8115 // Determine whether we have a single, best method. If so, we can
8116 // code-complete the expression using the corresponding parameter type as
8117 // our preferred type, improving completion results.
8118 if (AtArgumentExpression) {
8119 QualType PreferredType =
8120 getPreferredArgumentTypeForMessageSend(Results, SelIdents.size());
8121 if (PreferredType.isNull())
8122 CodeCompleteOrdinaryName(S, PCC_Expression);
8124 CodeCompleteExpression(S, PreferredType);
8128 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
8129 Results.data(), Results.size());
8132 void Sema::CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
8133 ArrayRef<IdentifierInfo *> SelIdents,
8134 bool AtArgumentExpression,
8135 ObjCInterfaceDecl *Super) {
8136 typedef CodeCompletionResult Result;
8138 Expr *RecExpr = static_cast<Expr *>(Receiver);
8140 // If necessary, apply function/array conversion to the receiver.
8141 // C99 6.7.5.3p[7,8].
8143 ExprResult Conv = DefaultFunctionArrayLvalueConversion(RecExpr);
8144 if (Conv.isInvalid()) // conversion failed. bail.
8146 RecExpr = Conv.get();
8148 QualType ReceiverType = RecExpr
8149 ? RecExpr->getType()
8150 : Super ? Context.getObjCObjectPointerType(
8151 Context.getObjCInterfaceType(Super))
8152 : Context.getObjCIdType();
8154 // If we're messaging an expression with type "id" or "Class", check
8155 // whether we know something special about the receiver that allows
8156 // us to assume a more-specific receiver type.
8157 if (ReceiverType->isObjCIdType() || ReceiverType->isObjCClassType()) {
8158 if (ObjCInterfaceDecl *IFace = GetAssumedMessageSendExprType(RecExpr)) {
8159 if (ReceiverType->isObjCClassType())
8160 return CodeCompleteObjCClassMessage(
8161 S, ParsedType::make(Context.getObjCInterfaceType(IFace)), SelIdents,
8162 AtArgumentExpression, Super);
8165 Context.getObjCObjectPointerType(Context.getObjCInterfaceType(IFace));
8167 } else if (RecExpr && getLangOpts().CPlusPlus) {
8168 ExprResult Conv = PerformContextuallyConvertToObjCPointer(RecExpr);
8169 if (Conv.isUsable()) {
8170 RecExpr = Conv.get();
8171 ReceiverType = RecExpr->getType();
8175 // Build the set of methods we can see.
8176 ResultBuilder Results(
8177 *this, CodeCompleter->getAllocator(),
8178 CodeCompleter->getCodeCompletionTUInfo(),
8179 CodeCompletionContext(CodeCompletionContext::CCC_ObjCInstanceMessage,
8180 ReceiverType, SelIdents));
8182 Results.EnterNewScope();
8184 // If this is a send-to-super, try to add the special "super" send
8187 if (ObjCMethodDecl *SuperMethod =
8188 AddSuperSendCompletion(*this, false, SelIdents, Results))
8189 Results.Ignore(SuperMethod);
8192 // If we're inside an Objective-C method definition, prefer its selector to
8194 if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
8195 Results.setPreferredSelector(CurMethod->getSelector());
8197 // Keep track of the selectors we've already added.
8198 VisitedSelectorSet Selectors;
8200 // Handle messages to Class. This really isn't a message to an instance
8201 // method, so we treat it the same way we would treat a message send to a
8203 if (ReceiverType->isObjCClassType() ||
8204 ReceiverType->isObjCQualifiedClassType()) {
8205 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
8206 if (ObjCInterfaceDecl *ClassDecl = CurMethod->getClassInterface())
8207 AddObjCMethods(ClassDecl, false, MK_Any, SelIdents, CurContext,
8208 Selectors, AtArgumentExpression, Results);
8211 // Handle messages to a qualified ID ("id<foo>").
8212 else if (const ObjCObjectPointerType *QualID =
8213 ReceiverType->getAsObjCQualifiedIdType()) {
8214 // Search protocols for instance methods.
8215 for (auto *I : QualID->quals())
8216 AddObjCMethods(I, true, MK_Any, SelIdents, CurContext, Selectors,
8217 AtArgumentExpression, Results);
8219 // Handle messages to a pointer to interface type.
8220 else if (const ObjCObjectPointerType *IFacePtr =
8221 ReceiverType->getAsObjCInterfacePointerType()) {
8222 // Search the class, its superclasses, etc., for instance methods.
8223 AddObjCMethods(IFacePtr->getInterfaceDecl(), true, MK_Any, SelIdents,
8224 CurContext, Selectors, AtArgumentExpression, Results);
8226 // Search protocols for instance methods.
8227 for (auto *I : IFacePtr->quals())
8228 AddObjCMethods(I, true, MK_Any, SelIdents, CurContext, Selectors,
8229 AtArgumentExpression, Results);
8231 // Handle messages to "id".
8232 else if (ReceiverType->isObjCIdType()) {
8233 // We're messaging "id", so provide all instance methods we know
8234 // about as code-completion results.
8236 // If we have an external source, load the entire class method
8237 // pool from the AST file.
8238 if (ExternalSource) {
8239 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
8241 Selector Sel = ExternalSource->GetExternalSelector(I);
8242 if (Sel.isNull() || MethodPool.count(Sel))
8245 ReadMethodPool(Sel);
8249 for (GlobalMethodPool::iterator M = MethodPool.begin(),
8250 MEnd = MethodPool.end();
8252 for (ObjCMethodList *MethList = &M->second.first;
8253 MethList && MethList->getMethod(); MethList = MethList->getNext()) {
8254 if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents))
8257 if (!Selectors.insert(MethList->getMethod()->getSelector()).second)
8260 Result R(MethList->getMethod(),
8261 Results.getBasePriority(MethList->getMethod()), nullptr);
8262 R.StartParameter = SelIdents.size();
8263 R.AllParametersAreInformative = false;
8264 Results.MaybeAddResult(R, CurContext);
8268 Results.ExitScope();
8270 // If we're actually at the argument expression (rather than prior to the
8271 // selector), we're actually performing code completion for an expression.
8272 // Determine whether we have a single, best method. If so, we can
8273 // code-complete the expression using the corresponding parameter type as
8274 // our preferred type, improving completion results.
8275 if (AtArgumentExpression) {
8276 QualType PreferredType =
8277 getPreferredArgumentTypeForMessageSend(Results, SelIdents.size());
8278 if (PreferredType.isNull())
8279 CodeCompleteOrdinaryName(S, PCC_Expression);
8281 CodeCompleteExpression(S, PreferredType);
8285 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
8286 Results.data(), Results.size());
8289 void Sema::CodeCompleteObjCForCollection(Scope *S,
8290 DeclGroupPtrTy IterationVar) {
8291 CodeCompleteExpressionData Data;
8292 Data.ObjCCollection = true;
8294 if (IterationVar.getAsOpaquePtr()) {
8295 DeclGroupRef DG = IterationVar.get();
8296 for (DeclGroupRef::iterator I = DG.begin(), End = DG.end(); I != End; ++I) {
8298 Data.IgnoreDecls.push_back(*I);
8302 CodeCompleteExpression(S, Data);
8305 void Sema::CodeCompleteObjCSelector(Scope *S,
8306 ArrayRef<IdentifierInfo *> SelIdents) {
8307 // If we have an external source, load the entire class method
8308 // pool from the AST file.
8309 if (ExternalSource) {
8310 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors(); I != N;
8312 Selector Sel = ExternalSource->GetExternalSelector(I);
8313 if (Sel.isNull() || MethodPool.count(Sel))
8316 ReadMethodPool(Sel);
8320 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
8321 CodeCompleter->getCodeCompletionTUInfo(),
8322 CodeCompletionContext::CCC_SelectorName);
8323 Results.EnterNewScope();
8324 for (GlobalMethodPool::iterator M = MethodPool.begin(),
8325 MEnd = MethodPool.end();
8328 Selector Sel = M->first;
8329 if (!isAcceptableObjCSelector(Sel, MK_Any, SelIdents))
8332 CodeCompletionBuilder Builder(Results.getAllocator(),
8333 Results.getCodeCompletionTUInfo());
8334 if (Sel.isUnarySelector()) {
8335 Builder.AddTypedTextChunk(
8336 Builder.getAllocator().CopyString(Sel.getNameForSlot(0)));
8337 Results.AddResult(Builder.TakeString());
8341 std::string Accumulator;
8342 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I) {
8343 if (I == SelIdents.size()) {
8344 if (!Accumulator.empty()) {
8345 Builder.AddInformativeChunk(
8346 Builder.getAllocator().CopyString(Accumulator));
8347 Accumulator.clear();
8351 Accumulator += Sel.getNameForSlot(I);
8354 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(Accumulator));
8355 Results.AddResult(Builder.TakeString());
8357 Results.ExitScope();
8359 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
8360 Results.data(), Results.size());
8363 /// Add all of the protocol declarations that we find in the given
8364 /// (translation unit) context.
8365 static void AddProtocolResults(DeclContext *Ctx, DeclContext *CurContext,
8366 bool OnlyForwardDeclarations,
8367 ResultBuilder &Results) {
8368 typedef CodeCompletionResult Result;
8370 for (const auto *D : Ctx->decls()) {
8371 // Record any protocols we find.
8372 if (const auto *Proto = dyn_cast<ObjCProtocolDecl>(D))
8373 if (!OnlyForwardDeclarations || !Proto->hasDefinition())
8375 Result(Proto, Results.getBasePriority(Proto), nullptr), CurContext,
8380 void Sema::CodeCompleteObjCProtocolReferences(
8381 ArrayRef<IdentifierLocPair> Protocols) {
8382 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
8383 CodeCompleter->getCodeCompletionTUInfo(),
8384 CodeCompletionContext::CCC_ObjCProtocolName);
8386 if (CodeCompleter->includeGlobals()) {
8387 Results.EnterNewScope();
8389 // Tell the result set to ignore all of the protocols we have
8391 // FIXME: This doesn't work when caching code-completion results.
8392 for (const IdentifierLocPair &Pair : Protocols)
8393 if (ObjCProtocolDecl *Protocol = LookupProtocol(Pair.first, Pair.second))
8394 Results.Ignore(Protocol);
8396 // Add all protocols.
8397 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, false,
8400 Results.ExitScope();
8403 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
8404 Results.data(), Results.size());
8407 void Sema::CodeCompleteObjCProtocolDecl(Scope *) {
8408 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
8409 CodeCompleter->getCodeCompletionTUInfo(),
8410 CodeCompletionContext::CCC_ObjCProtocolName);
8412 if (CodeCompleter->includeGlobals()) {
8413 Results.EnterNewScope();
8415 // Add all protocols.
8416 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, true,
8419 Results.ExitScope();
8422 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
8423 Results.data(), Results.size());
8426 /// Add all of the Objective-C interface declarations that we find in
8427 /// the given (translation unit) context.
8428 static void AddInterfaceResults(DeclContext *Ctx, DeclContext *CurContext,
8429 bool OnlyForwardDeclarations,
8430 bool OnlyUnimplemented,
8431 ResultBuilder &Results) {
8432 typedef CodeCompletionResult Result;
8434 for (const auto *D : Ctx->decls()) {
8435 // Record any interfaces we find.
8436 if (const auto *Class = dyn_cast<ObjCInterfaceDecl>(D))
8437 if ((!OnlyForwardDeclarations || !Class->hasDefinition()) &&
8438 (!OnlyUnimplemented || !Class->getImplementation()))
8440 Result(Class, Results.getBasePriority(Class), nullptr), CurContext,
8445 void Sema::CodeCompleteObjCInterfaceDecl(Scope *S) {
8446 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
8447 CodeCompleter->getCodeCompletionTUInfo(),
8448 CodeCompletionContext::CCC_ObjCInterfaceName);
8449 Results.EnterNewScope();
8451 if (CodeCompleter->includeGlobals()) {
8453 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
8457 Results.ExitScope();
8459 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
8460 Results.data(), Results.size());
8463 void Sema::CodeCompleteObjCClassForwardDecl(Scope *S) {
8464 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
8465 CodeCompleter->getCodeCompletionTUInfo(),
8466 CodeCompletionContext::CCC_ObjCClassForwardDecl);
8467 Results.EnterNewScope();
8469 if (CodeCompleter->includeGlobals()) {
8471 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
8475 Results.ExitScope();
8477 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
8478 Results.data(), Results.size());
8481 void Sema::CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName,
8482 SourceLocation ClassNameLoc) {
8483 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
8484 CodeCompleter->getCodeCompletionTUInfo(),
8485 CodeCompletionContext::CCC_ObjCInterfaceName);
8486 Results.EnterNewScope();
8488 // Make sure that we ignore the class we're currently defining.
8489 NamedDecl *CurClass =
8490 LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
8491 if (CurClass && isa<ObjCInterfaceDecl>(CurClass))
8492 Results.Ignore(CurClass);
8494 if (CodeCompleter->includeGlobals()) {
8496 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
8500 Results.ExitScope();
8502 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
8503 Results.data(), Results.size());
8506 void Sema::CodeCompleteObjCImplementationDecl(Scope *S) {
8507 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
8508 CodeCompleter->getCodeCompletionTUInfo(),
8509 CodeCompletionContext::CCC_ObjCImplementation);
8510 Results.EnterNewScope();
8512 if (CodeCompleter->includeGlobals()) {
8513 // Add all unimplemented classes.
8514 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
8518 Results.ExitScope();
8520 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
8521 Results.data(), Results.size());
8524 void Sema::CodeCompleteObjCInterfaceCategory(Scope *S,
8525 IdentifierInfo *ClassName,
8526 SourceLocation ClassNameLoc) {
8527 typedef CodeCompletionResult Result;
8529 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
8530 CodeCompleter->getCodeCompletionTUInfo(),
8531 CodeCompletionContext::CCC_ObjCCategoryName);
8533 // Ignore any categories we find that have already been implemented by this
8535 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
8536 NamedDecl *CurClass =
8537 LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
8538 if (ObjCInterfaceDecl *Class =
8539 dyn_cast_or_null<ObjCInterfaceDecl>(CurClass)) {
8540 for (const auto *Cat : Class->visible_categories())
8541 CategoryNames.insert(Cat->getIdentifier());
8544 // Add all of the categories we know about.
8545 Results.EnterNewScope();
8546 TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
8547 for (const auto *D : TU->decls())
8548 if (const auto *Category = dyn_cast<ObjCCategoryDecl>(D))
8549 if (CategoryNames.insert(Category->getIdentifier()).second)
8551 Result(Category, Results.getBasePriority(Category), nullptr),
8552 CurContext, nullptr, false);
8553 Results.ExitScope();
8555 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
8556 Results.data(), Results.size());
8559 void Sema::CodeCompleteObjCImplementationCategory(Scope *S,
8560 IdentifierInfo *ClassName,
8561 SourceLocation ClassNameLoc) {
8562 typedef CodeCompletionResult Result;
8564 // Find the corresponding interface. If we couldn't find the interface, the
8565 // program itself is ill-formed. However, we'll try to be helpful still by
8566 // providing the list of all of the categories we know about.
8567 NamedDecl *CurClass =
8568 LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
8569 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass);
8571 return CodeCompleteObjCInterfaceCategory(S, ClassName, ClassNameLoc);
8573 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
8574 CodeCompleter->getCodeCompletionTUInfo(),
8575 CodeCompletionContext::CCC_ObjCCategoryName);
8577 // Add all of the categories that have corresponding interface
8578 // declarations in this class and any of its superclasses, except for
8579 // already-implemented categories in the class itself.
8580 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
8581 Results.EnterNewScope();
8582 bool IgnoreImplemented = true;
8584 for (const auto *Cat : Class->visible_categories()) {
8585 if ((!IgnoreImplemented || !Cat->getImplementation()) &&
8586 CategoryNames.insert(Cat->getIdentifier()).second)
8587 Results.AddResult(Result(Cat, Results.getBasePriority(Cat), nullptr),
8588 CurContext, nullptr, false);
8591 Class = Class->getSuperClass();
8592 IgnoreImplemented = false;
8594 Results.ExitScope();
8596 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
8597 Results.data(), Results.size());
8600 void Sema::CodeCompleteObjCPropertyDefinition(Scope *S) {
8601 CodeCompletionContext CCContext(CodeCompletionContext::CCC_Other);
8602 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
8603 CodeCompleter->getCodeCompletionTUInfo(), CCContext);
8605 // Figure out where this @synthesize lives.
8606 ObjCContainerDecl *Container =
8607 dyn_cast_or_null<ObjCContainerDecl>(CurContext);
8608 if (!Container || (!isa<ObjCImplementationDecl>(Container) &&
8609 !isa<ObjCCategoryImplDecl>(Container)))
8612 // Ignore any properties that have already been implemented.
8613 Container = getContainerDef(Container);
8614 for (const auto *D : Container->decls())
8615 if (const auto *PropertyImpl = dyn_cast<ObjCPropertyImplDecl>(D))
8616 Results.Ignore(PropertyImpl->getPropertyDecl());
8618 // Add any properties that we find.
8619 AddedPropertiesSet AddedProperties;
8620 Results.EnterNewScope();
8621 if (ObjCImplementationDecl *ClassImpl =
8622 dyn_cast<ObjCImplementationDecl>(Container))
8623 AddObjCProperties(CCContext, ClassImpl->getClassInterface(), false,
8624 /*AllowNullaryMethods=*/false, CurContext,
8625 AddedProperties, Results);
8627 AddObjCProperties(CCContext,
8628 cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl(),
8629 false, /*AllowNullaryMethods=*/false, CurContext,
8630 AddedProperties, Results);
8631 Results.ExitScope();
8633 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
8634 Results.data(), Results.size());
8637 void Sema::CodeCompleteObjCPropertySynthesizeIvar(
8638 Scope *S, IdentifierInfo *PropertyName) {
8639 typedef CodeCompletionResult Result;
8640 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
8641 CodeCompleter->getCodeCompletionTUInfo(),
8642 CodeCompletionContext::CCC_Other);
8644 // Figure out where this @synthesize lives.
8645 ObjCContainerDecl *Container =
8646 dyn_cast_or_null<ObjCContainerDecl>(CurContext);
8647 if (!Container || (!isa<ObjCImplementationDecl>(Container) &&
8648 !isa<ObjCCategoryImplDecl>(Container)))
8651 // Figure out which interface we're looking into.
8652 ObjCInterfaceDecl *Class = nullptr;
8653 if (ObjCImplementationDecl *ClassImpl =
8654 dyn_cast<ObjCImplementationDecl>(Container))
8655 Class = ClassImpl->getClassInterface();
8657 Class = cast<ObjCCategoryImplDecl>(Container)
8659 ->getClassInterface();
8661 // Determine the type of the property we're synthesizing.
8662 QualType PropertyType = Context.getObjCIdType();
8664 if (ObjCPropertyDecl *Property = Class->FindPropertyDeclaration(
8665 PropertyName, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
8667 Property->getType().getNonReferenceType().getUnqualifiedType();
8669 // Give preference to ivars
8670 Results.setPreferredType(PropertyType);
8674 // Add all of the instance variables in this class and its superclasses.
8675 Results.EnterNewScope();
8676 bool SawSimilarlyNamedIvar = false;
8677 std::string NameWithPrefix;
8678 NameWithPrefix += '_';
8679 NameWithPrefix += PropertyName->getName();
8680 std::string NameWithSuffix = PropertyName->getName().str();
8681 NameWithSuffix += '_';
8682 for (; Class; Class = Class->getSuperClass()) {
8683 for (ObjCIvarDecl *Ivar = Class->all_declared_ivar_begin(); Ivar;
8684 Ivar = Ivar->getNextIvar()) {
8685 Results.AddResult(Result(Ivar, Results.getBasePriority(Ivar), nullptr),
8686 CurContext, nullptr, false);
8688 // Determine whether we've seen an ivar with a name similar to the
8690 if ((PropertyName == Ivar->getIdentifier() ||
8691 NameWithPrefix == Ivar->getName() ||
8692 NameWithSuffix == Ivar->getName())) {
8693 SawSimilarlyNamedIvar = true;
8695 // Reduce the priority of this result by one, to give it a slight
8696 // advantage over other results whose names don't match so closely.
8697 if (Results.size() &&
8698 Results.data()[Results.size() - 1].Kind ==
8699 CodeCompletionResult::RK_Declaration &&
8700 Results.data()[Results.size() - 1].Declaration == Ivar)
8701 Results.data()[Results.size() - 1].Priority--;
8706 if (!SawSimilarlyNamedIvar) {
8707 // Create ivar result _propName, that the user can use to synthesize
8708 // an ivar of the appropriate type.
8709 unsigned Priority = CCP_MemberDeclaration + 1;
8710 typedef CodeCompletionResult Result;
8711 CodeCompletionAllocator &Allocator = Results.getAllocator();
8712 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo(),
8713 Priority, CXAvailability_Available);
8715 PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
8716 Builder.AddResultTypeChunk(
8717 GetCompletionTypeString(PropertyType, Context, Policy, Allocator));
8718 Builder.AddTypedTextChunk(Allocator.CopyString(NameWithPrefix));
8720 Result(Builder.TakeString(), Priority, CXCursor_ObjCIvarDecl));
8723 Results.ExitScope();
8725 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
8726 Results.data(), Results.size());
8729 // Mapping from selectors to the methods that implement that selector, along
8730 // with the "in original class" flag.
8731 typedef llvm::DenseMap<Selector,
8732 llvm::PointerIntPair<ObjCMethodDecl *, 1, bool>>
8735 /// Find all of the methods that reside in the given container
8736 /// (and its superclasses, protocols, etc.) that meet the given
8737 /// criteria. Insert those methods into the map of known methods,
8738 /// indexed by selector so they can be easily found.
8739 static void FindImplementableMethods(ASTContext &Context,
8740 ObjCContainerDecl *Container,
8741 std::optional<bool> WantInstanceMethods,
8742 QualType ReturnType,
8743 KnownMethodsMap &KnownMethods,
8744 bool InOriginalClass = true) {
8745 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)) {
8746 // Make sure we have a definition; that's what we'll walk.
8747 if (!IFace->hasDefinition())
8750 IFace = IFace->getDefinition();
8753 const ObjCList<ObjCProtocolDecl> &Protocols =
8754 IFace->getReferencedProtocols();
8755 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
8756 E = Protocols.end();
8758 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
8759 KnownMethods, InOriginalClass);
8761 // Add methods from any class extensions and categories.
8762 for (auto *Cat : IFace->visible_categories()) {
8763 FindImplementableMethods(Context, Cat, WantInstanceMethods, ReturnType,
8764 KnownMethods, false);
8767 // Visit the superclass.
8768 if (IFace->getSuperClass())
8769 FindImplementableMethods(Context, IFace->getSuperClass(),
8770 WantInstanceMethods, ReturnType, KnownMethods,
8774 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
8775 // Recurse into protocols.
8776 const ObjCList<ObjCProtocolDecl> &Protocols =
8777 Category->getReferencedProtocols();
8778 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
8779 E = Protocols.end();
8781 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
8782 KnownMethods, InOriginalClass);
8784 // If this category is the original class, jump to the interface.
8785 if (InOriginalClass && Category->getClassInterface())
8786 FindImplementableMethods(Context, Category->getClassInterface(),
8787 WantInstanceMethods, ReturnType, KnownMethods,
8791 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
8792 // Make sure we have a definition; that's what we'll walk.
8793 if (!Protocol->hasDefinition())
8795 Protocol = Protocol->getDefinition();
8796 Container = Protocol;
8798 // Recurse into protocols.
8799 const ObjCList<ObjCProtocolDecl> &Protocols =
8800 Protocol->getReferencedProtocols();
8801 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
8802 E = Protocols.end();
8804 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
8805 KnownMethods, false);
8808 // Add methods in this container. This operation occurs last because
8809 // we want the methods from this container to override any methods
8810 // we've previously seen with the same selector.
8811 for (auto *M : Container->methods()) {
8812 if (!WantInstanceMethods || M->isInstanceMethod() == *WantInstanceMethods) {
8813 if (!ReturnType.isNull() &&
8814 !Context.hasSameUnqualifiedType(ReturnType, M->getReturnType()))
8817 KnownMethods[M->getSelector()] =
8818 KnownMethodsMap::mapped_type(M, InOriginalClass);
8823 /// Add the parenthesized return or parameter type chunk to a code
8824 /// completion string.
8825 static void AddObjCPassingTypeChunk(QualType Type, unsigned ObjCDeclQuals,
8826 ASTContext &Context,
8827 const PrintingPolicy &Policy,
8828 CodeCompletionBuilder &Builder) {
8829 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
8830 std::string Quals = formatObjCParamQualifiers(ObjCDeclQuals, Type);
8832 Builder.AddTextChunk(Builder.getAllocator().CopyString(Quals));
8833 Builder.AddTextChunk(
8834 GetCompletionTypeString(Type, Context, Policy, Builder.getAllocator()));
8835 Builder.AddChunk(CodeCompletionString::CK_RightParen);
8838 /// Determine whether the given class is or inherits from a class by
8840 static bool InheritsFromClassNamed(ObjCInterfaceDecl *Class, StringRef Name) {
8844 if (Class->getIdentifier() && Class->getIdentifier()->getName() == Name)
8847 return InheritsFromClassNamed(Class->getSuperClass(), Name);
8850 /// Add code completions for Objective-C Key-Value Coding (KVC) and
8851 /// Key-Value Observing (KVO).
8852 static void AddObjCKeyValueCompletions(ObjCPropertyDecl *Property,
8853 bool IsInstanceMethod,
8854 QualType ReturnType, ASTContext &Context,
8855 VisitedSelectorSet &KnownSelectors,
8856 ResultBuilder &Results) {
8857 IdentifierInfo *PropName = Property->getIdentifier();
8858 if (!PropName || PropName->getLength() == 0)
8861 PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema());
8863 // Builder that will create each code completion.
8864 typedef CodeCompletionResult Result;
8865 CodeCompletionAllocator &Allocator = Results.getAllocator();
8866 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
8868 // The selector table.
8869 SelectorTable &Selectors = Context.Selectors;
8871 // The property name, copied into the code completion allocation region
8874 CodeCompletionAllocator &Allocator;
8876 const char *CopiedKey;
8878 KeyHolder(CodeCompletionAllocator &Allocator, StringRef Key)
8879 : Allocator(Allocator), Key(Key), CopiedKey(nullptr) {}
8881 operator const char *() {
8885 return CopiedKey = Allocator.CopyString(Key);
8887 } Key(Allocator, PropName->getName());
8889 // The uppercased name of the property name.
8890 std::string UpperKey = std::string(PropName->getName());
8891 if (!UpperKey.empty())
8892 UpperKey[0] = toUppercase(UpperKey[0]);
8894 bool ReturnTypeMatchesProperty =
8895 ReturnType.isNull() ||
8896 Context.hasSameUnqualifiedType(ReturnType.getNonReferenceType(),
8897 Property->getType());
8898 bool ReturnTypeMatchesVoid = ReturnType.isNull() || ReturnType->isVoidType();
8900 // Add the normal accessor -(type)key.
8901 if (IsInstanceMethod &&
8902 KnownSelectors.insert(Selectors.getNullarySelector(PropName)).second &&
8903 ReturnTypeMatchesProperty && !Property->getGetterMethodDecl()) {
8904 if (ReturnType.isNull())
8905 AddObjCPassingTypeChunk(Property->getType(), /*Quals=*/0, Context, Policy,
8908 Builder.AddTypedTextChunk(Key);
8909 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
8910 CXCursor_ObjCInstanceMethodDecl));
8913 // If we have an integral or boolean property (or the user has provided
8914 // an integral or boolean return type), add the accessor -(type)isKey.
8915 if (IsInstanceMethod &&
8916 ((!ReturnType.isNull() &&
8917 (ReturnType->isIntegerType() || ReturnType->isBooleanType())) ||
8918 (ReturnType.isNull() && (Property->getType()->isIntegerType() ||
8919 Property->getType()->isBooleanType())))) {
8920 std::string SelectorName = (Twine("is") + UpperKey).str();
8921 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
8922 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
8924 if (ReturnType.isNull()) {
8925 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
8926 Builder.AddTextChunk("BOOL");
8927 Builder.AddChunk(CodeCompletionString::CK_RightParen);
8930 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorId->getName()));
8931 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
8932 CXCursor_ObjCInstanceMethodDecl));
8936 // Add the normal mutator.
8937 if (IsInstanceMethod && ReturnTypeMatchesVoid &&
8938 !Property->getSetterMethodDecl()) {
8939 std::string SelectorName = (Twine("set") + UpperKey).str();
8940 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
8941 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
8942 if (ReturnType.isNull()) {
8943 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
8944 Builder.AddTextChunk("void");
8945 Builder.AddChunk(CodeCompletionString::CK_RightParen);
8948 Builder.AddTypedTextChunk(
8949 Allocator.CopyString(SelectorId->getName() + ":"));
8950 AddObjCPassingTypeChunk(Property->getType(), /*Quals=*/0, Context, Policy,
8952 Builder.AddTextChunk(Key);
8953 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
8954 CXCursor_ObjCInstanceMethodDecl));
8958 // Indexed and unordered accessors
8959 unsigned IndexedGetterPriority = CCP_CodePattern;
8960 unsigned IndexedSetterPriority = CCP_CodePattern;
8961 unsigned UnorderedGetterPriority = CCP_CodePattern;
8962 unsigned UnorderedSetterPriority = CCP_CodePattern;
8963 if (const auto *ObjCPointer =
8964 Property->getType()->getAs<ObjCObjectPointerType>()) {
8965 if (ObjCInterfaceDecl *IFace = ObjCPointer->getInterfaceDecl()) {
8966 // If this interface type is not provably derived from a known
8967 // collection, penalize the corresponding completions.
8968 if (!InheritsFromClassNamed(IFace, "NSMutableArray")) {
8969 IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
8970 if (!InheritsFromClassNamed(IFace, "NSArray"))
8971 IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
8974 if (!InheritsFromClassNamed(IFace, "NSMutableSet")) {
8975 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
8976 if (!InheritsFromClassNamed(IFace, "NSSet"))
8977 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
8981 IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
8982 IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
8983 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
8984 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
8987 // Add -(NSUInteger)countOf<key>
8988 if (IsInstanceMethod &&
8989 (ReturnType.isNull() || ReturnType->isIntegerType())) {
8990 std::string SelectorName = (Twine("countOf") + UpperKey).str();
8991 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
8992 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
8994 if (ReturnType.isNull()) {
8995 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
8996 Builder.AddTextChunk("NSUInteger");
8997 Builder.AddChunk(CodeCompletionString::CK_RightParen);
9000 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorId->getName()));
9002 Result(Builder.TakeString(),
9003 std::min(IndexedGetterPriority, UnorderedGetterPriority),
9004 CXCursor_ObjCInstanceMethodDecl));
9009 // Add -(id)objectInKeyAtIndex:(NSUInteger)index
9010 if (IsInstanceMethod &&
9011 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
9012 std::string SelectorName = (Twine("objectIn") + UpperKey + "AtIndex").str();
9013 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
9014 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
9015 if (ReturnType.isNull()) {
9016 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9017 Builder.AddTextChunk("id");
9018 Builder.AddChunk(CodeCompletionString::CK_RightParen);
9021 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
9022 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9023 Builder.AddTextChunk("NSUInteger");
9024 Builder.AddChunk(CodeCompletionString::CK_RightParen);
9025 Builder.AddTextChunk("index");
9026 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
9027 CXCursor_ObjCInstanceMethodDecl));
9031 // Add -(NSArray *)keyAtIndexes:(NSIndexSet *)indexes
9032 if (IsInstanceMethod &&
9033 (ReturnType.isNull() ||
9034 (ReturnType->isObjCObjectPointerType() &&
9035 ReturnType->castAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
9036 ReturnType->castAs<ObjCObjectPointerType>()
9037 ->getInterfaceDecl()
9038 ->getName() == "NSArray"))) {
9039 std::string SelectorName = (Twine(Property->getName()) + "AtIndexes").str();
9040 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
9041 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
9042 if (ReturnType.isNull()) {
9043 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9044 Builder.AddTextChunk("NSArray *");
9045 Builder.AddChunk(CodeCompletionString::CK_RightParen);
9048 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
9049 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9050 Builder.AddTextChunk("NSIndexSet *");
9051 Builder.AddChunk(CodeCompletionString::CK_RightParen);
9052 Builder.AddTextChunk("indexes");
9053 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
9054 CXCursor_ObjCInstanceMethodDecl));
9058 // Add -(void)getKey:(type **)buffer range:(NSRange)inRange
9059 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
9060 std::string SelectorName = (Twine("get") + UpperKey).str();
9061 IdentifierInfo *SelectorIds[2] = {&Context.Idents.get(SelectorName),
9062 &Context.Idents.get("range")};
9064 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
9065 if (ReturnType.isNull()) {
9066 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9067 Builder.AddTextChunk("void");
9068 Builder.AddChunk(CodeCompletionString::CK_RightParen);
9071 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
9072 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9073 Builder.AddPlaceholderChunk("object-type");
9074 Builder.AddTextChunk(" **");
9075 Builder.AddChunk(CodeCompletionString::CK_RightParen);
9076 Builder.AddTextChunk("buffer");
9077 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9078 Builder.AddTypedTextChunk("range:");
9079 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9080 Builder.AddTextChunk("NSRange");
9081 Builder.AddChunk(CodeCompletionString::CK_RightParen);
9082 Builder.AddTextChunk("inRange");
9083 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
9084 CXCursor_ObjCInstanceMethodDecl));
9088 // Mutable indexed accessors
9090 // - (void)insertObject:(type *)object inKeyAtIndex:(NSUInteger)index
9091 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
9092 std::string SelectorName = (Twine("in") + UpperKey + "AtIndex").str();
9093 IdentifierInfo *SelectorIds[2] = {&Context.Idents.get("insertObject"),
9094 &Context.Idents.get(SelectorName)};
9096 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
9097 if (ReturnType.isNull()) {
9098 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9099 Builder.AddTextChunk("void");
9100 Builder.AddChunk(CodeCompletionString::CK_RightParen);
9103 Builder.AddTypedTextChunk("insertObject:");
9104 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9105 Builder.AddPlaceholderChunk("object-type");
9106 Builder.AddTextChunk(" *");
9107 Builder.AddChunk(CodeCompletionString::CK_RightParen);
9108 Builder.AddTextChunk("object");
9109 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9110 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
9111 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9112 Builder.AddPlaceholderChunk("NSUInteger");
9113 Builder.AddChunk(CodeCompletionString::CK_RightParen);
9114 Builder.AddTextChunk("index");
9115 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
9116 CXCursor_ObjCInstanceMethodDecl));
9120 // - (void)insertKey:(NSArray *)array atIndexes:(NSIndexSet *)indexes
9121 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
9122 std::string SelectorName = (Twine("insert") + UpperKey).str();
9123 IdentifierInfo *SelectorIds[2] = {&Context.Idents.get(SelectorName),
9124 &Context.Idents.get("atIndexes")};
9126 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
9127 if (ReturnType.isNull()) {
9128 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9129 Builder.AddTextChunk("void");
9130 Builder.AddChunk(CodeCompletionString::CK_RightParen);
9133 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
9134 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9135 Builder.AddTextChunk("NSArray *");
9136 Builder.AddChunk(CodeCompletionString::CK_RightParen);
9137 Builder.AddTextChunk("array");
9138 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9139 Builder.AddTypedTextChunk("atIndexes:");
9140 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9141 Builder.AddPlaceholderChunk("NSIndexSet *");
9142 Builder.AddChunk(CodeCompletionString::CK_RightParen);
9143 Builder.AddTextChunk("indexes");
9144 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
9145 CXCursor_ObjCInstanceMethodDecl));
9149 // -(void)removeObjectFromKeyAtIndex:(NSUInteger)index
9150 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
9151 std::string SelectorName =
9152 (Twine("removeObjectFrom") + UpperKey + "AtIndex").str();
9153 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
9154 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).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.AddTextChunk("NSUInteger");
9164 Builder.AddChunk(CodeCompletionString::CK_RightParen);
9165 Builder.AddTextChunk("index");
9166 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
9167 CXCursor_ObjCInstanceMethodDecl));
9171 // -(void)removeKeyAtIndexes:(NSIndexSet *)indexes
9172 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
9173 std::string SelectorName = (Twine("remove") + UpperKey + "AtIndexes").str();
9174 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
9175 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
9176 if (ReturnType.isNull()) {
9177 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9178 Builder.AddTextChunk("void");
9179 Builder.AddChunk(CodeCompletionString::CK_RightParen);
9182 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
9183 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9184 Builder.AddTextChunk("NSIndexSet *");
9185 Builder.AddChunk(CodeCompletionString::CK_RightParen);
9186 Builder.AddTextChunk("indexes");
9187 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
9188 CXCursor_ObjCInstanceMethodDecl));
9192 // - (void)replaceObjectInKeyAtIndex:(NSUInteger)index withObject:(id)object
9193 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
9194 std::string SelectorName =
9195 (Twine("replaceObjectIn") + UpperKey + "AtIndex").str();
9196 IdentifierInfo *SelectorIds[2] = {&Context.Idents.get(SelectorName),
9197 &Context.Idents.get("withObject")};
9199 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
9200 if (ReturnType.isNull()) {
9201 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9202 Builder.AddTextChunk("void");
9203 Builder.AddChunk(CodeCompletionString::CK_RightParen);
9206 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
9207 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9208 Builder.AddPlaceholderChunk("NSUInteger");
9209 Builder.AddChunk(CodeCompletionString::CK_RightParen);
9210 Builder.AddTextChunk("index");
9211 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9212 Builder.AddTypedTextChunk("withObject:");
9213 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9214 Builder.AddTextChunk("id");
9215 Builder.AddChunk(CodeCompletionString::CK_RightParen);
9216 Builder.AddTextChunk("object");
9217 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
9218 CXCursor_ObjCInstanceMethodDecl));
9222 // - (void)replaceKeyAtIndexes:(NSIndexSet *)indexes withKey:(NSArray *)array
9223 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
9224 std::string SelectorName1 =
9225 (Twine("replace") + UpperKey + "AtIndexes").str();
9226 std::string SelectorName2 = (Twine("with") + UpperKey).str();
9227 IdentifierInfo *SelectorIds[2] = {&Context.Idents.get(SelectorName1),
9228 &Context.Idents.get(SelectorName2)};
9230 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
9231 if (ReturnType.isNull()) {
9232 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9233 Builder.AddTextChunk("void");
9234 Builder.AddChunk(CodeCompletionString::CK_RightParen);
9237 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName1 + ":"));
9238 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9239 Builder.AddPlaceholderChunk("NSIndexSet *");
9240 Builder.AddChunk(CodeCompletionString::CK_RightParen);
9241 Builder.AddTextChunk("indexes");
9242 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9243 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName2 + ":"));
9244 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9245 Builder.AddTextChunk("NSArray *");
9246 Builder.AddChunk(CodeCompletionString::CK_RightParen);
9247 Builder.AddTextChunk("array");
9248 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
9249 CXCursor_ObjCInstanceMethodDecl));
9253 // Unordered getters
9254 // - (NSEnumerator *)enumeratorOfKey
9255 if (IsInstanceMethod &&
9256 (ReturnType.isNull() ||
9257 (ReturnType->isObjCObjectPointerType() &&
9258 ReturnType->castAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
9259 ReturnType->castAs<ObjCObjectPointerType>()
9260 ->getInterfaceDecl()
9261 ->getName() == "NSEnumerator"))) {
9262 std::string SelectorName = (Twine("enumeratorOf") + UpperKey).str();
9263 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
9264 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
9266 if (ReturnType.isNull()) {
9267 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9268 Builder.AddTextChunk("NSEnumerator *");
9269 Builder.AddChunk(CodeCompletionString::CK_RightParen);
9272 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
9273 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
9274 CXCursor_ObjCInstanceMethodDecl));
9278 // - (type *)memberOfKey:(type *)object
9279 if (IsInstanceMethod &&
9280 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
9281 std::string SelectorName = (Twine("memberOf") + UpperKey).str();
9282 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
9283 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
9284 if (ReturnType.isNull()) {
9285 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9286 Builder.AddPlaceholderChunk("object-type");
9287 Builder.AddTextChunk(" *");
9288 Builder.AddChunk(CodeCompletionString::CK_RightParen);
9291 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
9292 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9293 if (ReturnType.isNull()) {
9294 Builder.AddPlaceholderChunk("object-type");
9295 Builder.AddTextChunk(" *");
9297 Builder.AddTextChunk(GetCompletionTypeString(
9298 ReturnType, Context, Policy, Builder.getAllocator()));
9300 Builder.AddChunk(CodeCompletionString::CK_RightParen);
9301 Builder.AddTextChunk("object");
9302 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
9303 CXCursor_ObjCInstanceMethodDecl));
9307 // Mutable unordered accessors
9308 // - (void)addKeyObject:(type *)object
9309 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
9310 std::string SelectorName =
9311 (Twine("add") + UpperKey + Twine("Object")).str();
9312 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
9313 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
9314 if (ReturnType.isNull()) {
9315 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9316 Builder.AddTextChunk("void");
9317 Builder.AddChunk(CodeCompletionString::CK_RightParen);
9320 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
9321 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9322 Builder.AddPlaceholderChunk("object-type");
9323 Builder.AddTextChunk(" *");
9324 Builder.AddChunk(CodeCompletionString::CK_RightParen);
9325 Builder.AddTextChunk("object");
9326 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
9327 CXCursor_ObjCInstanceMethodDecl));
9331 // - (void)addKey:(NSSet *)objects
9332 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
9333 std::string SelectorName = (Twine("add") + UpperKey).str();
9334 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
9335 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
9336 if (ReturnType.isNull()) {
9337 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9338 Builder.AddTextChunk("void");
9339 Builder.AddChunk(CodeCompletionString::CK_RightParen);
9342 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
9343 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9344 Builder.AddTextChunk("NSSet *");
9345 Builder.AddChunk(CodeCompletionString::CK_RightParen);
9346 Builder.AddTextChunk("objects");
9347 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
9348 CXCursor_ObjCInstanceMethodDecl));
9352 // - (void)removeKeyObject:(type *)object
9353 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
9354 std::string SelectorName =
9355 (Twine("remove") + UpperKey + Twine("Object")).str();
9356 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
9357 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
9358 if (ReturnType.isNull()) {
9359 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9360 Builder.AddTextChunk("void");
9361 Builder.AddChunk(CodeCompletionString::CK_RightParen);
9364 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
9365 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9366 Builder.AddPlaceholderChunk("object-type");
9367 Builder.AddTextChunk(" *");
9368 Builder.AddChunk(CodeCompletionString::CK_RightParen);
9369 Builder.AddTextChunk("object");
9370 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
9371 CXCursor_ObjCInstanceMethodDecl));
9375 // - (void)removeKey:(NSSet *)objects
9376 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
9377 std::string SelectorName = (Twine("remove") + UpperKey).str();
9378 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
9379 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
9380 if (ReturnType.isNull()) {
9381 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9382 Builder.AddTextChunk("void");
9383 Builder.AddChunk(CodeCompletionString::CK_RightParen);
9386 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
9387 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9388 Builder.AddTextChunk("NSSet *");
9389 Builder.AddChunk(CodeCompletionString::CK_RightParen);
9390 Builder.AddTextChunk("objects");
9391 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
9392 CXCursor_ObjCInstanceMethodDecl));
9396 // - (void)intersectKey:(NSSet *)objects
9397 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
9398 std::string SelectorName = (Twine("intersect") + UpperKey).str();
9399 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
9400 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
9401 if (ReturnType.isNull()) {
9402 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9403 Builder.AddTextChunk("void");
9404 Builder.AddChunk(CodeCompletionString::CK_RightParen);
9407 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
9408 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9409 Builder.AddTextChunk("NSSet *");
9410 Builder.AddChunk(CodeCompletionString::CK_RightParen);
9411 Builder.AddTextChunk("objects");
9412 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
9413 CXCursor_ObjCInstanceMethodDecl));
9417 // Key-Value Observing
9418 // + (NSSet *)keyPathsForValuesAffectingKey
9419 if (!IsInstanceMethod &&
9420 (ReturnType.isNull() ||
9421 (ReturnType->isObjCObjectPointerType() &&
9422 ReturnType->castAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
9423 ReturnType->castAs<ObjCObjectPointerType>()
9424 ->getInterfaceDecl()
9425 ->getName() == "NSSet"))) {
9426 std::string SelectorName =
9427 (Twine("keyPathsForValuesAffecting") + UpperKey).str();
9428 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
9429 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
9431 if (ReturnType.isNull()) {
9432 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9433 Builder.AddTextChunk("NSSet<NSString *> *");
9434 Builder.AddChunk(CodeCompletionString::CK_RightParen);
9437 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
9438 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
9439 CXCursor_ObjCClassMethodDecl));
9443 // + (BOOL)automaticallyNotifiesObserversForKey
9444 if (!IsInstanceMethod &&
9445 (ReturnType.isNull() || ReturnType->isIntegerType() ||
9446 ReturnType->isBooleanType())) {
9447 std::string SelectorName =
9448 (Twine("automaticallyNotifiesObserversOf") + UpperKey).str();
9449 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
9450 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
9452 if (ReturnType.isNull()) {
9453 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9454 Builder.AddTextChunk("BOOL");
9455 Builder.AddChunk(CodeCompletionString::CK_RightParen);
9458 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
9459 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
9460 CXCursor_ObjCClassMethodDecl));
9465 void Sema::CodeCompleteObjCMethodDecl(Scope *S,
9466 std::optional<bool> IsInstanceMethod,
9467 ParsedType ReturnTy) {
9468 // Determine the return type of the method we're declaring, if
9470 QualType ReturnType = GetTypeFromParser(ReturnTy);
9471 Decl *IDecl = nullptr;
9472 if (CurContext->isObjCContainer()) {
9473 ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext);
9476 // Determine where we should start searching for methods.
9477 ObjCContainerDecl *SearchDecl = nullptr;
9478 bool IsInImplementation = false;
9479 if (Decl *D = IDecl) {
9480 if (ObjCImplementationDecl *Impl = dyn_cast<ObjCImplementationDecl>(D)) {
9481 SearchDecl = Impl->getClassInterface();
9482 IsInImplementation = true;
9483 } else if (ObjCCategoryImplDecl *CatImpl =
9484 dyn_cast<ObjCCategoryImplDecl>(D)) {
9485 SearchDecl = CatImpl->getCategoryDecl();
9486 IsInImplementation = true;
9488 SearchDecl = dyn_cast<ObjCContainerDecl>(D);
9491 if (!SearchDecl && S) {
9492 if (DeclContext *DC = S->getEntity())
9493 SearchDecl = dyn_cast<ObjCContainerDecl>(DC);
9497 HandleCodeCompleteResults(this, CodeCompleter,
9498 CodeCompletionContext::CCC_Other, nullptr, 0);
9502 // Find all of the methods that we could declare/implement here.
9503 KnownMethodsMap KnownMethods;
9504 FindImplementableMethods(Context, SearchDecl, IsInstanceMethod, ReturnType,
9507 // Add declarations or definitions for each of the known methods.
9508 typedef CodeCompletionResult Result;
9509 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
9510 CodeCompleter->getCodeCompletionTUInfo(),
9511 CodeCompletionContext::CCC_Other);
9512 Results.EnterNewScope();
9513 PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
9514 for (KnownMethodsMap::iterator M = KnownMethods.begin(),
9515 MEnd = KnownMethods.end();
9517 ObjCMethodDecl *Method = M->second.getPointer();
9518 CodeCompletionBuilder Builder(Results.getAllocator(),
9519 Results.getCodeCompletionTUInfo());
9521 // Add the '-'/'+' prefix if it wasn't provided yet.
9522 if (!IsInstanceMethod) {
9523 Builder.AddTextChunk(Method->isInstanceMethod() ? "-" : "+");
9524 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9527 // If the result type was not already provided, add it to the
9528 // pattern as (type).
9529 if (ReturnType.isNull()) {
9530 QualType ResTy = Method->getSendResultType().stripObjCKindOfType(Context);
9531 AttributedType::stripOuterNullability(ResTy);
9532 AddObjCPassingTypeChunk(ResTy, Method->getObjCDeclQualifier(), Context,
9536 Selector Sel = Method->getSelector();
9538 if (Sel.isUnarySelector()) {
9539 // Unary selectors have no arguments.
9540 Builder.AddTypedTextChunk(
9541 Builder.getAllocator().CopyString(Sel.getNameForSlot(0)));
9543 // Add all parameters to the pattern.
9545 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
9546 PEnd = Method->param_end();
9547 P != PEnd; (void)++P, ++I) {
9548 // Add the part of the selector name.
9550 Builder.AddTypedTextChunk(
9551 Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":"));
9552 else if (I < Sel.getNumArgs()) {
9553 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9554 Builder.AddTypedTextChunk(
9555 Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":"));
9559 // Add the parameter type.
9561 if ((*P)->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
9562 ParamType = (*P)->getType();
9564 ParamType = (*P)->getOriginalType();
9565 ParamType = ParamType.substObjCTypeArgs(
9566 Context, {}, ObjCSubstitutionContext::Parameter);
9567 AttributedType::stripOuterNullability(ParamType);
9568 AddObjCPassingTypeChunk(ParamType, (*P)->getObjCDeclQualifier(),
9569 Context, Policy, Builder);
9571 if (IdentifierInfo *Id = (*P)->getIdentifier())
9572 Builder.AddTextChunk(
9573 Builder.getAllocator().CopyString(Id->getName()));
9577 if (Method->isVariadic()) {
9578 if (Method->param_size() > 0)
9579 Builder.AddChunk(CodeCompletionString::CK_Comma);
9580 Builder.AddTextChunk("...");
9583 if (IsInImplementation && Results.includeCodePatterns()) {
9584 // We will be defining the method here, so add a compound statement.
9585 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9586 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
9587 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
9588 if (!Method->getReturnType()->isVoidType()) {
9589 // If the result type is not void, add a return clause.
9590 Builder.AddTextChunk("return");
9591 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9592 Builder.AddPlaceholderChunk("expression");
9593 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
9595 Builder.AddPlaceholderChunk("statements");
9597 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
9598 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
9601 unsigned Priority = CCP_CodePattern;
9602 auto R = Result(Builder.TakeString(), Method, Priority);
9603 if (!M->second.getInt())
9605 Results.AddResult(std::move(R));
9608 // Add Key-Value-Coding and Key-Value-Observing accessor methods for all of
9609 // the properties in this class and its categories.
9610 if (Context.getLangOpts().ObjC) {
9611 SmallVector<ObjCContainerDecl *, 4> Containers;
9612 Containers.push_back(SearchDecl);
9614 VisitedSelectorSet KnownSelectors;
9615 for (KnownMethodsMap::iterator M = KnownMethods.begin(),
9616 MEnd = KnownMethods.end();
9618 KnownSelectors.insert(M->first);
9620 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(SearchDecl);
9622 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(SearchDecl))
9623 IFace = Category->getClassInterface();
9626 llvm::append_range(Containers, IFace->visible_categories());
9628 if (IsInstanceMethod) {
9629 for (unsigned I = 0, N = Containers.size(); I != N; ++I)
9630 for (auto *P : Containers[I]->instance_properties())
9631 AddObjCKeyValueCompletions(P, *IsInstanceMethod, ReturnType, Context,
9632 KnownSelectors, Results);
9636 Results.ExitScope();
9638 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
9639 Results.data(), Results.size());
9642 void Sema::CodeCompleteObjCMethodDeclSelector(
9643 Scope *S, bool IsInstanceMethod, bool AtParameterName, ParsedType ReturnTy,
9644 ArrayRef<IdentifierInfo *> SelIdents) {
9645 // If we have an external source, load the entire class method
9646 // pool from the AST file.
9647 if (ExternalSource) {
9648 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors(); I != N;
9650 Selector Sel = ExternalSource->GetExternalSelector(I);
9651 if (Sel.isNull() || MethodPool.count(Sel))
9654 ReadMethodPool(Sel);
9658 // Build the set of methods we can see.
9659 typedef CodeCompletionResult Result;
9660 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
9661 CodeCompleter->getCodeCompletionTUInfo(),
9662 CodeCompletionContext::CCC_Other);
9665 Results.setPreferredType(GetTypeFromParser(ReturnTy).getNonReferenceType());
9667 Results.EnterNewScope();
9668 for (GlobalMethodPool::iterator M = MethodPool.begin(),
9669 MEnd = MethodPool.end();
9671 for (ObjCMethodList *MethList = IsInstanceMethod ? &M->second.first
9672 : &M->second.second;
9673 MethList && MethList->getMethod(); MethList = MethList->getNext()) {
9674 if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents))
9677 if (AtParameterName) {
9678 // Suggest parameter names we've seen before.
9679 unsigned NumSelIdents = SelIdents.size();
9681 NumSelIdents <= MethList->getMethod()->param_size()) {
9682 ParmVarDecl *Param =
9683 MethList->getMethod()->parameters()[NumSelIdents - 1];
9684 if (Param->getIdentifier()) {
9685 CodeCompletionBuilder Builder(Results.getAllocator(),
9686 Results.getCodeCompletionTUInfo());
9687 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
9688 Param->getIdentifier()->getName()));
9689 Results.AddResult(Builder.TakeString());
9696 Result R(MethList->getMethod(),
9697 Results.getBasePriority(MethList->getMethod()), nullptr);
9698 R.StartParameter = SelIdents.size();
9699 R.AllParametersAreInformative = false;
9700 R.DeclaringEntity = true;
9701 Results.MaybeAddResult(R, CurContext);
9705 Results.ExitScope();
9707 if (!AtParameterName && !SelIdents.empty() &&
9708 SelIdents.front()->getName().startswith("init")) {
9709 for (const auto &M : PP.macros()) {
9710 if (M.first->getName() != "NS_DESIGNATED_INITIALIZER")
9712 Results.EnterNewScope();
9713 CodeCompletionBuilder Builder(Results.getAllocator(),
9714 Results.getCodeCompletionTUInfo());
9715 Builder.AddTypedTextChunk(
9716 Builder.getAllocator().CopyString(M.first->getName()));
9717 Results.AddResult(CodeCompletionResult(Builder.TakeString(), CCP_Macro,
9718 CXCursor_MacroDefinition));
9719 Results.ExitScope();
9723 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
9724 Results.data(), Results.size());
9727 void Sema::CodeCompletePreprocessorDirective(bool InConditional) {
9728 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
9729 CodeCompleter->getCodeCompletionTUInfo(),
9730 CodeCompletionContext::CCC_PreprocessorDirective);
9731 Results.EnterNewScope();
9734 CodeCompletionBuilder Builder(Results.getAllocator(),
9735 Results.getCodeCompletionTUInfo());
9736 Builder.AddTypedTextChunk("if");
9737 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9738 Builder.AddPlaceholderChunk("condition");
9739 Results.AddResult(Builder.TakeString());
9742 Builder.AddTypedTextChunk("ifdef");
9743 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9744 Builder.AddPlaceholderChunk("macro");
9745 Results.AddResult(Builder.TakeString());
9748 Builder.AddTypedTextChunk("ifndef");
9749 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9750 Builder.AddPlaceholderChunk("macro");
9751 Results.AddResult(Builder.TakeString());
9753 if (InConditional) {
9754 // #elif <condition>
9755 Builder.AddTypedTextChunk("elif");
9756 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9757 Builder.AddPlaceholderChunk("condition");
9758 Results.AddResult(Builder.TakeString());
9761 Builder.AddTypedTextChunk("elifdef");
9762 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9763 Builder.AddPlaceholderChunk("macro");
9764 Results.AddResult(Builder.TakeString());
9766 // #elifndef <macro>
9767 Builder.AddTypedTextChunk("elifndef");
9768 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9769 Builder.AddPlaceholderChunk("macro");
9770 Results.AddResult(Builder.TakeString());
9773 Builder.AddTypedTextChunk("else");
9774 Results.AddResult(Builder.TakeString());
9777 Builder.AddTypedTextChunk("endif");
9778 Results.AddResult(Builder.TakeString());
9781 // #include "header"
9782 Builder.AddTypedTextChunk("include");
9783 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9784 Builder.AddTextChunk("\"");
9785 Builder.AddPlaceholderChunk("header");
9786 Builder.AddTextChunk("\"");
9787 Results.AddResult(Builder.TakeString());
9789 // #include <header>
9790 Builder.AddTypedTextChunk("include");
9791 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9792 Builder.AddTextChunk("<");
9793 Builder.AddPlaceholderChunk("header");
9794 Builder.AddTextChunk(">");
9795 Results.AddResult(Builder.TakeString());
9798 Builder.AddTypedTextChunk("define");
9799 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9800 Builder.AddPlaceholderChunk("macro");
9801 Results.AddResult(Builder.TakeString());
9803 // #define <macro>(<args>)
9804 Builder.AddTypedTextChunk("define");
9805 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9806 Builder.AddPlaceholderChunk("macro");
9807 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9808 Builder.AddPlaceholderChunk("args");
9809 Builder.AddChunk(CodeCompletionString::CK_RightParen);
9810 Results.AddResult(Builder.TakeString());
9813 Builder.AddTypedTextChunk("undef");
9814 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9815 Builder.AddPlaceholderChunk("macro");
9816 Results.AddResult(Builder.TakeString());
9819 Builder.AddTypedTextChunk("line");
9820 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9821 Builder.AddPlaceholderChunk("number");
9822 Results.AddResult(Builder.TakeString());
9824 // #line <number> "filename"
9825 Builder.AddTypedTextChunk("line");
9826 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9827 Builder.AddPlaceholderChunk("number");
9828 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9829 Builder.AddTextChunk("\"");
9830 Builder.AddPlaceholderChunk("filename");
9831 Builder.AddTextChunk("\"");
9832 Results.AddResult(Builder.TakeString());
9835 Builder.AddTypedTextChunk("error");
9836 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9837 Builder.AddPlaceholderChunk("message");
9838 Results.AddResult(Builder.TakeString());
9840 // #pragma <arguments>
9841 Builder.AddTypedTextChunk("pragma");
9842 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9843 Builder.AddPlaceholderChunk("arguments");
9844 Results.AddResult(Builder.TakeString());
9846 if (getLangOpts().ObjC) {
9848 Builder.AddTypedTextChunk("import");
9849 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9850 Builder.AddTextChunk("\"");
9851 Builder.AddPlaceholderChunk("header");
9852 Builder.AddTextChunk("\"");
9853 Results.AddResult(Builder.TakeString());
9856 Builder.AddTypedTextChunk("import");
9857 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9858 Builder.AddTextChunk("<");
9859 Builder.AddPlaceholderChunk("header");
9860 Builder.AddTextChunk(">");
9861 Results.AddResult(Builder.TakeString());
9864 // #include_next "header"
9865 Builder.AddTypedTextChunk("include_next");
9866 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9867 Builder.AddTextChunk("\"");
9868 Builder.AddPlaceholderChunk("header");
9869 Builder.AddTextChunk("\"");
9870 Results.AddResult(Builder.TakeString());
9872 // #include_next <header>
9873 Builder.AddTypedTextChunk("include_next");
9874 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9875 Builder.AddTextChunk("<");
9876 Builder.AddPlaceholderChunk("header");
9877 Builder.AddTextChunk(">");
9878 Results.AddResult(Builder.TakeString());
9880 // #warning <message>
9881 Builder.AddTypedTextChunk("warning");
9882 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9883 Builder.AddPlaceholderChunk("message");
9884 Results.AddResult(Builder.TakeString());
9886 // Note: #ident and #sccs are such crazy anachronisms that we don't provide
9887 // completions for them. And __include_macros is a Clang-internal extension
9888 // that we don't want to encourage anyone to use.
9890 // FIXME: we don't support #assert or #unassert, so don't suggest them.
9891 Results.ExitScope();
9893 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
9894 Results.data(), Results.size());
9897 void Sema::CodeCompleteInPreprocessorConditionalExclusion(Scope *S) {
9898 CodeCompleteOrdinaryName(S, S->getFnParent() ? Sema::PCC_RecoveryInFunction
9899 : Sema::PCC_Namespace);
9902 void Sema::CodeCompletePreprocessorMacroName(bool IsDefinition) {
9903 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
9904 CodeCompleter->getCodeCompletionTUInfo(),
9905 IsDefinition ? CodeCompletionContext::CCC_MacroName
9906 : CodeCompletionContext::CCC_MacroNameUse);
9907 if (!IsDefinition && CodeCompleter->includeMacros()) {
9908 // Add just the names of macros, not their arguments.
9909 CodeCompletionBuilder Builder(Results.getAllocator(),
9910 Results.getCodeCompletionTUInfo());
9911 Results.EnterNewScope();
9912 for (Preprocessor::macro_iterator M = PP.macro_begin(),
9913 MEnd = PP.macro_end();
9915 Builder.AddTypedTextChunk(
9916 Builder.getAllocator().CopyString(M->first->getName()));
9917 Results.AddResult(CodeCompletionResult(
9918 Builder.TakeString(), CCP_CodePattern, CXCursor_MacroDefinition));
9920 Results.ExitScope();
9921 } else if (IsDefinition) {
9922 // FIXME: Can we detect when the user just wrote an include guard above?
9925 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
9926 Results.data(), Results.size());
9929 void Sema::CodeCompletePreprocessorExpression() {
9930 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
9931 CodeCompleter->getCodeCompletionTUInfo(),
9932 CodeCompletionContext::CCC_PreprocessorExpression);
9934 if (CodeCompleter->includeMacros())
9935 AddMacroResults(PP, Results, CodeCompleter->loadExternal(), true);
9937 // defined (<macro>)
9938 Results.EnterNewScope();
9939 CodeCompletionBuilder Builder(Results.getAllocator(),
9940 Results.getCodeCompletionTUInfo());
9941 Builder.AddTypedTextChunk("defined");
9942 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
9943 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9944 Builder.AddPlaceholderChunk("macro");
9945 Builder.AddChunk(CodeCompletionString::CK_RightParen);
9946 Results.AddResult(Builder.TakeString());
9947 Results.ExitScope();
9949 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
9950 Results.data(), Results.size());
9953 void Sema::CodeCompletePreprocessorMacroArgument(Scope *S,
9954 IdentifierInfo *Macro,
9955 MacroInfo *MacroInfo,
9956 unsigned Argument) {
9957 // FIXME: In the future, we could provide "overload" results, much like we
9958 // do for function calls.
9960 // Now just ignore this. There will be another code-completion callback
9961 // for the expanded tokens.
9964 // This handles completion inside an #include filename, e.g. #include <foo/ba
9965 // We look for the directory "foo" under each directory on the include path,
9966 // list its files, and reassemble the appropriate #include.
9967 void Sema::CodeCompleteIncludedFile(llvm::StringRef Dir, bool Angled) {
9968 // RelDir should use /, but unescaped \ is possible on windows!
9969 // Our completions will normalize to / for simplicity, this case is rare.
9970 std::string RelDir = llvm::sys::path::convert_to_slash(Dir);
9971 // We need the native slashes for the actual file system interactions.
9972 SmallString<128> NativeRelDir = StringRef(RelDir);
9973 llvm::sys::path::native(NativeRelDir);
9974 llvm::vfs::FileSystem &FS =
9975 getSourceManager().getFileManager().getVirtualFileSystem();
9977 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
9978 CodeCompleter->getCodeCompletionTUInfo(),
9979 CodeCompletionContext::CCC_IncludedFile);
9980 llvm::DenseSet<StringRef> SeenResults; // To deduplicate results.
9982 // Helper: adds one file or directory completion result.
9983 auto AddCompletion = [&](StringRef Filename, bool IsDirectory) {
9984 SmallString<64> TypedChunk = Filename;
9985 // Directory completion is up to the slash, e.g. <sys/
9986 TypedChunk.push_back(IsDirectory ? '/' : Angled ? '>' : '"');
9987 auto R = SeenResults.insert(TypedChunk);
9988 if (R.second) { // New completion
9989 const char *InternedTyped = Results.getAllocator().CopyString(TypedChunk);
9990 *R.first = InternedTyped; // Avoid dangling StringRef.
9991 CodeCompletionBuilder Builder(CodeCompleter->getAllocator(),
9992 CodeCompleter->getCodeCompletionTUInfo());
9993 Builder.AddTypedTextChunk(InternedTyped);
9994 // The result is a "Pattern", which is pretty opaque.
9995 // We may want to include the real filename to allow smart ranking.
9996 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
10000 // Helper: scans IncludeDir for nice files, and adds results for each.
10001 auto AddFilesFromIncludeDir = [&](StringRef IncludeDir,
10003 DirectoryLookup::LookupType_t LookupType) {
10004 llvm::SmallString<128> Dir = IncludeDir;
10005 if (!NativeRelDir.empty()) {
10006 if (LookupType == DirectoryLookup::LT_Framework) {
10007 // For a framework dir, #include <Foo/Bar/> actually maps to
10008 // a path of Foo.framework/Headers/Bar/.
10009 auto Begin = llvm::sys::path::begin(NativeRelDir);
10010 auto End = llvm::sys::path::end(NativeRelDir);
10012 llvm::sys::path::append(Dir, *Begin + ".framework", "Headers");
10013 llvm::sys::path::append(Dir, ++Begin, End);
10015 llvm::sys::path::append(Dir, NativeRelDir);
10019 const StringRef &Dirname = llvm::sys::path::filename(Dir);
10020 const bool isQt = Dirname.startswith("Qt") || Dirname == "ActiveQt";
10021 const bool ExtensionlessHeaders =
10022 IsSystem || isQt || Dir.endswith(".framework/Headers");
10023 std::error_code EC;
10024 unsigned Count = 0;
10025 for (auto It = FS.dir_begin(Dir, EC);
10026 !EC && It != llvm::vfs::directory_iterator(); It.increment(EC)) {
10027 if (++Count == 2500) // If we happen to hit a huge directory,
10028 break; // bail out early so we're not too slow.
10029 StringRef Filename = llvm::sys::path::filename(It->path());
10031 // To know whether a symlink should be treated as file or a directory, we
10032 // have to stat it. This should be cheap enough as there shouldn't be many
10034 llvm::sys::fs::file_type Type = It->type();
10035 if (Type == llvm::sys::fs::file_type::symlink_file) {
10036 if (auto FileStatus = FS.status(It->path()))
10037 Type = FileStatus->getType();
10040 case llvm::sys::fs::file_type::directory_file:
10041 // All entries in a framework directory must have a ".framework" suffix,
10042 // but the suffix does not appear in the source code's include/import.
10043 if (LookupType == DirectoryLookup::LT_Framework &&
10044 NativeRelDir.empty() && !Filename.consume_back(".framework"))
10047 AddCompletion(Filename, /*IsDirectory=*/true);
10049 case llvm::sys::fs::file_type::regular_file: {
10050 // Only files that really look like headers. (Except in special dirs).
10051 const bool IsHeader = Filename.ends_with_insensitive(".h") ||
10052 Filename.ends_with_insensitive(".hh") ||
10053 Filename.ends_with_insensitive(".hpp") ||
10054 Filename.ends_with_insensitive(".hxx") ||
10055 Filename.ends_with_insensitive(".inc") ||
10056 (ExtensionlessHeaders && !Filename.contains('.'));
10059 AddCompletion(Filename, /*IsDirectory=*/false);
10068 // Helper: adds results relative to IncludeDir, if possible.
10069 auto AddFilesFromDirLookup = [&](const DirectoryLookup &IncludeDir,
10071 switch (IncludeDir.getLookupType()) {
10072 case DirectoryLookup::LT_HeaderMap:
10073 // header maps are not (currently) enumerable.
10075 case DirectoryLookup::LT_NormalDir:
10076 AddFilesFromIncludeDir(IncludeDir.getDirRef()->getName(), IsSystem,
10077 DirectoryLookup::LT_NormalDir);
10079 case DirectoryLookup::LT_Framework:
10080 AddFilesFromIncludeDir(IncludeDir.getFrameworkDirRef()->getName(),
10081 IsSystem, DirectoryLookup::LT_Framework);
10086 // Finally with all our helpers, we can scan the include path.
10087 // Do this in standard order so deduplication keeps the right file.
10088 // (In case we decide to add more details to the results later).
10089 const auto &S = PP.getHeaderSearchInfo();
10090 using llvm::make_range;
10092 // The current directory is on the include path for "quoted" includes.
10093 if (auto CurFile = PP.getCurrentFileLexer()->getFileEntry())
10094 AddFilesFromIncludeDir(CurFile->getDir().getName(), false,
10095 DirectoryLookup::LT_NormalDir);
10096 for (const auto &D : make_range(S.quoted_dir_begin(), S.quoted_dir_end()))
10097 AddFilesFromDirLookup(D, false);
10099 for (const auto &D : make_range(S.angled_dir_begin(), S.angled_dir_end()))
10100 AddFilesFromDirLookup(D, false);
10101 for (const auto &D : make_range(S.system_dir_begin(), S.system_dir_end()))
10102 AddFilesFromDirLookup(D, true);
10104 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
10105 Results.data(), Results.size());
10108 void Sema::CodeCompleteNaturalLanguage() {
10109 HandleCodeCompleteResults(this, CodeCompleter,
10110 CodeCompletionContext::CCC_NaturalLanguage, nullptr,
10114 void Sema::CodeCompleteAvailabilityPlatformName() {
10115 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
10116 CodeCompleter->getCodeCompletionTUInfo(),
10117 CodeCompletionContext::CCC_Other);
10118 Results.EnterNewScope();
10119 static const char *Platforms[] = {"macOS", "iOS", "watchOS", "tvOS"};
10120 for (const char *Platform : llvm::ArrayRef(Platforms)) {
10121 Results.AddResult(CodeCompletionResult(Platform));
10122 Results.AddResult(CodeCompletionResult(Results.getAllocator().CopyString(
10123 Twine(Platform) + "ApplicationExtension")));
10125 Results.ExitScope();
10126 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
10127 Results.data(), Results.size());
10130 void Sema::GatherGlobalCodeCompletions(
10131 CodeCompletionAllocator &Allocator, CodeCompletionTUInfo &CCTUInfo,
10132 SmallVectorImpl<CodeCompletionResult> &Results) {
10133 ResultBuilder Builder(*this, Allocator, CCTUInfo,
10134 CodeCompletionContext::CCC_Recovery);
10135 if (!CodeCompleter || CodeCompleter->includeGlobals()) {
10136 CodeCompletionDeclConsumer Consumer(Builder,
10137 Context.getTranslationUnitDecl());
10138 LookupVisibleDecls(Context.getTranslationUnitDecl(), LookupAnyName,
10140 !CodeCompleter || CodeCompleter->loadExternal());
10143 if (!CodeCompleter || CodeCompleter->includeMacros())
10144 AddMacroResults(PP, Builder,
10145 !CodeCompleter || CodeCompleter->loadExternal(), true);
10148 Results.insert(Results.end(), Builder.data(),
10149 Builder.data() + Builder.size());