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
= 0;
104 ShadowMapEntry() = default;
105 ShadowMapEntry(const ShadowMapEntry
&) = delete;
106 ShadowMapEntry(ShadowMapEntry
&&Move
) { *this = std::move(Move
); }
107 ShadowMapEntry
&operator=(const ShadowMapEntry
&) = delete;
108 ShadowMapEntry
&operator=(ShadowMapEntry
&&Move
) {
109 SingleDeclIndex
= Move
.SingleDeclIndex
;
110 DeclOrVector
= Move
.DeclOrVector
;
111 Move
.DeclOrVector
= nullptr;
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_TopLevelOrExpression
:
229 case CodeCompletionContext::CCC_Recovery
:
230 if (ObjCMethodDecl
*Method
= SemaRef
.getCurMethodDecl())
231 if (Method
->isInstanceMethod())
232 if (ObjCInterfaceDecl
*Interface
= Method
->getClassInterface())
233 ObjCImplementation
= Interface
->getImplementation();
241 /// Determine the priority for a reference to the given declaration.
242 unsigned getBasePriority(const NamedDecl
*D
);
244 /// Whether we should include code patterns in the completion
246 bool includeCodePatterns() const {
247 return SemaRef
.CodeCompleter
&&
248 SemaRef
.CodeCompleter
->includeCodePatterns();
251 /// Set the filter used for code-completion results.
252 void setFilter(LookupFilter Filter
) { this->Filter
= Filter
; }
254 Result
*data() { return Results
.empty() ? nullptr : &Results
.front(); }
255 unsigned size() const { return Results
.size(); }
256 bool empty() const { return Results
.empty(); }
258 /// Specify the preferred type.
259 void setPreferredType(QualType T
) {
260 PreferredType
= SemaRef
.Context
.getCanonicalType(T
);
263 /// Set the cv-qualifiers on the object type, for us in filtering
264 /// calls to member functions.
266 /// When there are qualifiers in this set, they will be used to filter
267 /// out member functions that aren't available (because there will be a
268 /// cv-qualifier mismatch) or prefer functions with an exact qualifier
270 void setObjectTypeQualifiers(Qualifiers Quals
, ExprValueKind Kind
) {
271 ObjectTypeQualifiers
= Quals
;
273 HasObjectTypeQualifiers
= true;
276 /// Set the preferred selector.
278 /// When an Objective-C method declaration result is added, and that
279 /// method's selector matches this preferred selector, we give that method
280 /// a slight priority boost.
281 void setPreferredSelector(Selector Sel
) { PreferredSelector
= Sel
; }
283 /// Retrieve the code-completion context for which results are
285 const CodeCompletionContext
&getCompletionContext() const {
286 return CompletionContext
;
289 /// Specify whether nested-name-specifiers are allowed.
290 void allowNestedNameSpecifiers(bool Allow
= true) {
291 AllowNestedNameSpecifiers
= Allow
;
294 /// Return the semantic analysis object for which we are collecting
295 /// code completion results.
296 Sema
&getSema() const { return SemaRef
; }
298 /// Retrieve the allocator used to allocate code completion strings.
299 CodeCompletionAllocator
&getAllocator() const { return Allocator
; }
301 CodeCompletionTUInfo
&getCodeCompletionTUInfo() const { return CCTUInfo
; }
303 /// Determine whether the given declaration is at all interesting
304 /// as a code-completion result.
306 /// \param ND the declaration that we are inspecting.
308 /// \param AsNestedNameSpecifier will be set true if this declaration is
309 /// only interesting when it is a nested-name-specifier.
310 bool isInterestingDecl(const NamedDecl
*ND
,
311 bool &AsNestedNameSpecifier
) const;
313 /// Decide whether or not a use of function Decl can be a call.
315 /// \param ND the function declaration.
317 /// \param BaseExprType the object type in a member access expression,
319 bool canFunctionBeCalled(const NamedDecl
*ND
, QualType BaseExprType
) const;
321 /// Decide whether or not a use of member function Decl can be a call.
323 /// \param Method the function declaration.
325 /// \param BaseExprType the object type in a member access expression,
327 bool canCxxMethodBeCalled(const CXXMethodDecl
*Method
,
328 QualType BaseExprType
) const;
330 /// Check whether the result is hidden by the Hiding declaration.
332 /// \returns true if the result is hidden and cannot be found, false if
333 /// the hidden result could still be found. When false, \p R may be
334 /// modified to describe how the result can be found (e.g., via extra
336 bool CheckHiddenResult(Result
&R
, DeclContext
*CurContext
,
337 const NamedDecl
*Hiding
);
339 /// Add a new result to this result set (if it isn't already in one
340 /// of the shadow maps), or replace an existing result (for, e.g., a
343 /// \param R the result to add (if it is unique).
345 /// \param CurContext the context in which this result will be named.
346 void MaybeAddResult(Result R
, DeclContext
*CurContext
= nullptr);
348 /// Add a new result to this result set, where we already know
349 /// the hiding declaration (if any).
351 /// \param R the result to add (if it is unique).
353 /// \param CurContext the context in which this result will be named.
355 /// \param Hiding the declaration that hides the result.
357 /// \param InBaseClass whether the result was found in a base
358 /// class of the searched context.
360 /// \param BaseExprType the type of expression that precedes the "." or "->"
361 /// in a member access expression.
362 void AddResult(Result R
, DeclContext
*CurContext
, NamedDecl
*Hiding
,
363 bool InBaseClass
, QualType BaseExprType
);
365 /// Add a new non-declaration result to this result set.
366 void AddResult(Result R
);
368 /// Enter into a new scope.
369 void EnterNewScope();
371 /// Exit from the current scope.
374 /// Ignore this declaration, if it is seen again.
375 void Ignore(const Decl
*D
) { AllDeclsFound
.insert(D
->getCanonicalDecl()); }
377 /// Add a visited context.
378 void addVisitedContext(DeclContext
*Ctx
) {
379 CompletionContext
.addVisitedContext(Ctx
);
382 /// \name Name lookup predicates
384 /// These predicates can be passed to the name lookup functions to filter the
385 /// results of name lookup. All of the predicates have the same type, so that
388 bool IsOrdinaryName(const NamedDecl
*ND
) const;
389 bool IsOrdinaryNonTypeName(const NamedDecl
*ND
) const;
390 bool IsIntegralConstantValue(const NamedDecl
*ND
) const;
391 bool IsOrdinaryNonValueName(const NamedDecl
*ND
) const;
392 bool IsNestedNameSpecifier(const NamedDecl
*ND
) const;
393 bool IsEnum(const NamedDecl
*ND
) const;
394 bool IsClassOrStruct(const NamedDecl
*ND
) const;
395 bool IsUnion(const NamedDecl
*ND
) const;
396 bool IsNamespace(const NamedDecl
*ND
) const;
397 bool IsNamespaceOrAlias(const NamedDecl
*ND
) const;
398 bool IsType(const NamedDecl
*ND
) const;
399 bool IsMember(const NamedDecl
*ND
) const;
400 bool IsObjCIvar(const NamedDecl
*ND
) const;
401 bool IsObjCMessageReceiver(const NamedDecl
*ND
) const;
402 bool IsObjCMessageReceiverOrLambdaCapture(const NamedDecl
*ND
) const;
403 bool IsObjCCollection(const NamedDecl
*ND
) const;
404 bool IsImpossibleToSatisfy(const NamedDecl
*ND
) const;
409 void PreferredTypeBuilder::enterReturn(Sema
&S
, SourceLocation Tok
) {
412 if (isa
<BlockDecl
>(S
.CurContext
)) {
413 if (sema::BlockScopeInfo
*BSI
= S
.getCurBlock()) {
414 ComputeType
= nullptr;
415 Type
= BSI
->ReturnType
;
418 } else if (const auto *Function
= dyn_cast
<FunctionDecl
>(S
.CurContext
)) {
419 ComputeType
= nullptr;
420 Type
= Function
->getReturnType();
422 } else if (const auto *Method
= dyn_cast
<ObjCMethodDecl
>(S
.CurContext
)) {
423 ComputeType
= nullptr;
424 Type
= Method
->getReturnType();
429 void PreferredTypeBuilder::enterVariableInit(SourceLocation Tok
, Decl
*D
) {
432 auto *VD
= llvm::dyn_cast_or_null
<ValueDecl
>(D
);
433 ComputeType
= nullptr;
434 Type
= VD
? VD
->getType() : QualType();
438 static QualType
getDesignatedType(QualType BaseType
, const Designation
&Desig
);
440 void PreferredTypeBuilder::enterDesignatedInitializer(SourceLocation Tok
,
442 const Designation
&D
) {
445 ComputeType
= nullptr;
446 Type
= getDesignatedType(BaseType
, D
);
450 void PreferredTypeBuilder::enterFunctionArgument(
451 SourceLocation Tok
, llvm::function_ref
<QualType()> ComputeType
) {
454 this->ComputeType
= ComputeType
;
459 void PreferredTypeBuilder::enterParenExpr(SourceLocation Tok
,
460 SourceLocation LParLoc
) {
463 // expected type for parenthesized expression does not change.
464 if (ExpectedLoc
== LParLoc
)
468 static QualType
getPreferredTypeOfBinaryRHS(Sema
&S
, Expr
*LHS
,
473 QualType LHSType
= LHS
->getType();
474 if (LHSType
->isPointerType()) {
475 if (Op
== tok::plus
|| Op
== tok::plusequal
|| Op
== tok::minusequal
)
476 return S
.getASTContext().getPointerDiffType();
477 // Pointer difference is more common than subtracting an int from a pointer.
478 if (Op
== tok::minus
)
483 // No way to infer the type of RHS from LHS.
486 // Prefer the type of the left operand for all of these.
487 // Arithmetic operations.
491 case tok::minusequal
:
493 case tok::percentequal
:
495 case tok::slashequal
:
500 // Comparison operators.
501 case tok::equalequal
:
502 case tok::exclaimequal
:
506 case tok::greaterequal
:
508 return LHS
->getType();
509 // Binary shifts are often overloaded, so don't try to guess those.
510 case tok::greatergreater
:
511 case tok::greatergreaterequal
:
513 case tok::lesslessequal
:
514 if (LHSType
->isIntegralOrEnumerationType())
515 return S
.getASTContext().IntTy
;
517 // Logical operators, assume we want bool.
520 case tok::caretcaret
:
521 return S
.getASTContext().BoolTy
;
522 // Operators often used for bit manipulation are typically used with the type
523 // of the left argument.
527 case tok::caretequal
:
530 if (LHSType
->isIntegralOrEnumerationType())
533 // RHS should be a pointer to a member of the 'LHS' type, but we can't give
534 // any particular type here.
535 case tok::periodstar
:
539 // FIXME(ibiryukov): handle the missing op, re-add the assertion.
540 // assert(false && "unhandled binary op");
545 /// Get preferred type for an argument of an unary expression. \p ContextType is
546 /// preferred type of the whole unary expression.
547 static QualType
getPreferredTypeOfUnaryArg(Sema
&S
, QualType ContextType
,
551 return S
.getASTContext().BoolTy
;
553 if (!ContextType
.isNull() && ContextType
->isPointerType())
554 return ContextType
->getPointeeType();
557 if (ContextType
.isNull())
559 return S
.getASTContext().getPointerType(ContextType
.getNonReferenceType());
563 case tok::minusminus
:
565 if (ContextType
.isNull())
566 return S
.getASTContext().IntTy
;
567 // leave as is, these operators typically return the same type.
573 assert(false && "unhandled unary op");
578 void PreferredTypeBuilder::enterBinary(Sema
&S
, SourceLocation Tok
, Expr
*LHS
,
582 ComputeType
= nullptr;
583 Type
= getPreferredTypeOfBinaryRHS(S
, LHS
, Op
);
587 void PreferredTypeBuilder::enterMemAccess(Sema
&S
, SourceLocation Tok
,
589 if (!Enabled
|| !Base
)
591 // Do we have expected type for Base?
592 if (ExpectedLoc
!= Base
->getBeginLoc())
594 // Keep the expected type, only update the location.
598 void PreferredTypeBuilder::enterUnary(Sema
&S
, SourceLocation Tok
,
599 tok::TokenKind OpKind
,
600 SourceLocation OpLoc
) {
603 ComputeType
= nullptr;
604 Type
= getPreferredTypeOfUnaryArg(S
, this->get(OpLoc
), OpKind
);
608 void PreferredTypeBuilder::enterSubscript(Sema
&S
, SourceLocation Tok
,
612 ComputeType
= nullptr;
613 Type
= S
.getASTContext().IntTy
;
617 void PreferredTypeBuilder::enterTypeCast(SourceLocation Tok
,
621 ComputeType
= nullptr;
622 Type
= !CastType
.isNull() ? CastType
.getCanonicalType() : QualType();
626 void PreferredTypeBuilder::enterCondition(Sema
&S
, SourceLocation Tok
) {
629 ComputeType
= nullptr;
630 Type
= S
.getASTContext().BoolTy
;
634 class ResultBuilder::ShadowMapEntry::iterator
{
635 llvm::PointerUnion
<const NamedDecl
*, const DeclIndexPair
*> DeclOrIterator
;
636 unsigned SingleDeclIndex
;
639 typedef DeclIndexPair value_type
;
640 typedef value_type reference
;
641 typedef std::ptrdiff_t difference_type
;
642 typedef std::input_iterator_tag iterator_category
;
648 pointer(const DeclIndexPair
&Value
) : Value(Value
) {}
650 const DeclIndexPair
*operator->() const { return &Value
; }
653 iterator() : DeclOrIterator((NamedDecl
*)nullptr), SingleDeclIndex(0) {}
655 iterator(const NamedDecl
*SingleDecl
, unsigned Index
)
656 : DeclOrIterator(SingleDecl
), SingleDeclIndex(Index
) {}
658 iterator(const DeclIndexPair
*Iterator
)
659 : DeclOrIterator(Iterator
), SingleDeclIndex(0) {}
661 iterator
&operator++() {
662 if (DeclOrIterator
.is
<const NamedDecl
*>()) {
663 DeclOrIterator
= (NamedDecl
*)nullptr;
668 const DeclIndexPair
*I
= DeclOrIterator
.get
<const DeclIndexPair
*>();
674 /*iterator operator++(int) {
680 reference
operator*() const {
681 if (const NamedDecl
*ND
= DeclOrIterator
.dyn_cast
<const NamedDecl
*>())
682 return reference(ND
, SingleDeclIndex
);
684 return *DeclOrIterator
.get
<const DeclIndexPair
*>();
687 pointer
operator->() const { return pointer(**this); }
689 friend bool operator==(const iterator
&X
, const iterator
&Y
) {
690 return X
.DeclOrIterator
.getOpaqueValue() ==
691 Y
.DeclOrIterator
.getOpaqueValue() &&
692 X
.SingleDeclIndex
== Y
.SingleDeclIndex
;
695 friend bool operator!=(const iterator
&X
, const iterator
&Y
) {
700 ResultBuilder::ShadowMapEntry::iterator
701 ResultBuilder::ShadowMapEntry::begin() const {
702 if (DeclOrVector
.isNull())
705 if (const NamedDecl
*ND
= DeclOrVector
.dyn_cast
<const NamedDecl
*>())
706 return iterator(ND
, SingleDeclIndex
);
708 return iterator(DeclOrVector
.get
<DeclIndexPairVector
*>()->begin());
711 ResultBuilder::ShadowMapEntry::iterator
712 ResultBuilder::ShadowMapEntry::end() const {
713 if (DeclOrVector
.is
<const NamedDecl
*>() || DeclOrVector
.isNull())
716 return iterator(DeclOrVector
.get
<DeclIndexPairVector
*>()->end());
719 /// Compute the qualification required to get from the current context
720 /// (\p CurContext) to the target context (\p TargetContext).
722 /// \param Context the AST context in which the qualification will be used.
724 /// \param CurContext the context where an entity is being named, which is
725 /// typically based on the current scope.
727 /// \param TargetContext the context in which the named entity actually
730 /// \returns a nested name specifier that refers into the target context, or
731 /// NULL if no qualification is needed.
732 static NestedNameSpecifier
*
733 getRequiredQualification(ASTContext
&Context
, const DeclContext
*CurContext
,
734 const DeclContext
*TargetContext
) {
735 SmallVector
<const DeclContext
*, 4> TargetParents
;
737 for (const DeclContext
*CommonAncestor
= TargetContext
;
738 CommonAncestor
&& !CommonAncestor
->Encloses(CurContext
);
739 CommonAncestor
= CommonAncestor
->getLookupParent()) {
740 if (CommonAncestor
->isTransparentContext() ||
741 CommonAncestor
->isFunctionOrMethod())
744 TargetParents
.push_back(CommonAncestor
);
747 NestedNameSpecifier
*Result
= nullptr;
748 while (!TargetParents
.empty()) {
749 const DeclContext
*Parent
= TargetParents
.pop_back_val();
751 if (const auto *Namespace
= dyn_cast
<NamespaceDecl
>(Parent
)) {
752 if (!Namespace
->getIdentifier())
755 Result
= NestedNameSpecifier::Create(Context
, Result
, Namespace
);
756 } else if (const auto *TD
= dyn_cast
<TagDecl
>(Parent
))
757 Result
= NestedNameSpecifier::Create(
758 Context
, Result
, false, Context
.getTypeDeclType(TD
).getTypePtr());
763 // Some declarations have reserved names that we don't want to ever show.
764 // Filter out names reserved for the implementation if they come from a
766 static bool shouldIgnoreDueToReservedName(const NamedDecl
*ND
, Sema
&SemaRef
) {
767 ReservedIdentifierStatus Status
= ND
->isReserved(SemaRef
.getLangOpts());
768 // Ignore reserved names for compiler provided decls.
769 if (isReservedInAllContexts(Status
) && ND
->getLocation().isInvalid())
772 // For system headers ignore only double-underscore names.
773 // This allows for system headers providing private symbols with a single
775 if (Status
== ReservedIdentifierStatus::StartsWithDoubleUnderscore
&&
776 SemaRef
.SourceMgr
.isInSystemHeader(
777 SemaRef
.SourceMgr
.getSpellingLoc(ND
->getLocation())))
783 bool ResultBuilder::isInterestingDecl(const NamedDecl
*ND
,
784 bool &AsNestedNameSpecifier
) const {
785 AsNestedNameSpecifier
= false;
788 ND
= ND
->getUnderlyingDecl();
790 // Skip unnamed entities.
791 if (!ND
->getDeclName())
794 // Friend declarations and declarations introduced due to friends are never
796 if (ND
->getFriendObjectKind() == Decl::FOK_Undeclared
)
799 // Class template (partial) specializations are never added as results.
800 if (isa
<ClassTemplateSpecializationDecl
>(ND
) ||
801 isa
<ClassTemplatePartialSpecializationDecl
>(ND
))
804 // Using declarations themselves are never added as results.
805 if (isa
<UsingDecl
>(ND
))
808 if (shouldIgnoreDueToReservedName(ND
, SemaRef
))
811 if (Filter
== &ResultBuilder::IsNestedNameSpecifier
||
812 (isa
<NamespaceDecl
>(ND
) && Filter
!= &ResultBuilder::IsNamespace
&&
813 Filter
!= &ResultBuilder::IsNamespaceOrAlias
&& Filter
!= nullptr))
814 AsNestedNameSpecifier
= true;
816 // Filter out any unwanted results.
817 if (Filter
&& !(this->*Filter
)(Named
)) {
818 // Check whether it is interesting as a nested-name-specifier.
819 if (AllowNestedNameSpecifiers
&& SemaRef
.getLangOpts().CPlusPlus
&&
820 IsNestedNameSpecifier(ND
) &&
821 (Filter
!= &ResultBuilder::IsMember
||
822 (isa
<CXXRecordDecl
>(ND
) &&
823 cast
<CXXRecordDecl
>(ND
)->isInjectedClassName()))) {
824 AsNestedNameSpecifier
= true;
830 // ... then it must be interesting!
834 bool ResultBuilder::CheckHiddenResult(Result
&R
, DeclContext
*CurContext
,
835 const NamedDecl
*Hiding
) {
836 // In C, there is no way to refer to a hidden name.
837 // FIXME: This isn't true; we can find a tag name hidden by an ordinary
838 // name if we introduce the tag type.
839 if (!SemaRef
.getLangOpts().CPlusPlus
)
842 const DeclContext
*HiddenCtx
=
843 R
.Declaration
->getDeclContext()->getRedeclContext();
845 // There is no way to qualify a name declared in a function or method.
846 if (HiddenCtx
->isFunctionOrMethod())
849 if (HiddenCtx
== Hiding
->getDeclContext()->getRedeclContext())
852 // We can refer to the result with the appropriate qualification. Do it.
854 R
.QualifierIsInformative
= false;
857 R
.Qualifier
= getRequiredQualification(SemaRef
.Context
, CurContext
,
858 R
.Declaration
->getDeclContext());
862 /// A simplified classification of types used to determine whether two
863 /// types are "similar enough" when adjusting priorities.
864 SimplifiedTypeClass
clang::getSimplifiedTypeClass(CanQualType T
) {
865 switch (T
->getTypeClass()) {
867 switch (cast
<BuiltinType
>(T
)->getKind()) {
868 case BuiltinType::Void
:
871 case BuiltinType::NullPtr
:
874 case BuiltinType::Overload
:
875 case BuiltinType::Dependent
:
878 case BuiltinType::ObjCId
:
879 case BuiltinType::ObjCClass
:
880 case BuiltinType::ObjCSel
:
881 return STC_ObjectiveC
;
884 return STC_Arithmetic
;
888 return STC_Arithmetic
;
893 case Type::BlockPointer
:
896 case Type::LValueReference
:
897 case Type::RValueReference
:
898 return getSimplifiedTypeClass(T
->getAs
<ReferenceType
>()->getPointeeType());
900 case Type::ConstantArray
:
901 case Type::IncompleteArray
:
902 case Type::VariableArray
:
903 case Type::DependentSizedArray
:
906 case Type::DependentSizedExtVector
:
908 case Type::ExtVector
:
909 return STC_Arithmetic
;
911 case Type::FunctionProto
:
912 case Type::FunctionNoProto
:
919 return STC_Arithmetic
;
921 case Type::ObjCObject
:
922 case Type::ObjCInterface
:
923 case Type::ObjCObjectPointer
:
924 return STC_ObjectiveC
;
931 /// Get the type that a given expression will have if this declaration
932 /// is used as an expression in its "typical" code-completion form.
933 QualType
clang::getDeclUsageType(ASTContext
&C
, const NamedDecl
*ND
) {
934 ND
= ND
->getUnderlyingDecl();
936 if (const auto *Type
= dyn_cast
<TypeDecl
>(ND
))
937 return C
.getTypeDeclType(Type
);
938 if (const auto *Iface
= dyn_cast
<ObjCInterfaceDecl
>(ND
))
939 return C
.getObjCInterfaceType(Iface
);
942 if (const FunctionDecl
*Function
= ND
->getAsFunction())
943 T
= Function
->getCallResultType();
944 else if (const auto *Method
= dyn_cast
<ObjCMethodDecl
>(ND
))
945 T
= Method
->getSendResultType();
946 else if (const auto *Enumerator
= dyn_cast
<EnumConstantDecl
>(ND
))
947 T
= C
.getTypeDeclType(cast
<EnumDecl
>(Enumerator
->getDeclContext()));
948 else if (const auto *Property
= dyn_cast
<ObjCPropertyDecl
>(ND
))
949 T
= Property
->getType();
950 else if (const auto *Value
= dyn_cast
<ValueDecl
>(ND
))
951 T
= Value
->getType();
956 // Dig through references, function pointers, and block pointers to
957 // get down to the likely type of an expression when the entity is
960 if (const auto *Ref
= T
->getAs
<ReferenceType
>()) {
961 T
= Ref
->getPointeeType();
965 if (const auto *Pointer
= T
->getAs
<PointerType
>()) {
966 if (Pointer
->getPointeeType()->isFunctionType()) {
967 T
= Pointer
->getPointeeType();
974 if (const auto *Block
= T
->getAs
<BlockPointerType
>()) {
975 T
= Block
->getPointeeType();
979 if (const auto *Function
= T
->getAs
<FunctionType
>()) {
980 T
= Function
->getReturnType();
990 unsigned ResultBuilder::getBasePriority(const NamedDecl
*ND
) {
994 // Context-based decisions.
995 const DeclContext
*LexicalDC
= ND
->getLexicalDeclContext();
996 if (LexicalDC
->isFunctionOrMethod()) {
997 // _cmd is relatively rare
998 if (const auto *ImplicitParam
= dyn_cast
<ImplicitParamDecl
>(ND
))
999 if (ImplicitParam
->getIdentifier() &&
1000 ImplicitParam
->getIdentifier()->isStr("_cmd"))
1001 return CCP_ObjC_cmd
;
1003 return CCP_LocalDeclaration
;
1006 const DeclContext
*DC
= ND
->getDeclContext()->getRedeclContext();
1007 if (DC
->isRecord() || isa
<ObjCContainerDecl
>(DC
)) {
1008 // Explicit destructor calls are very rare.
1009 if (isa
<CXXDestructorDecl
>(ND
))
1010 return CCP_Unlikely
;
1011 // Explicit operator and conversion function calls are also very rare.
1012 auto DeclNameKind
= ND
->getDeclName().getNameKind();
1013 if (DeclNameKind
== DeclarationName::CXXOperatorName
||
1014 DeclNameKind
== DeclarationName::CXXLiteralOperatorName
||
1015 DeclNameKind
== DeclarationName::CXXConversionFunctionName
)
1016 return CCP_Unlikely
;
1017 return CCP_MemberDeclaration
;
1020 // Content-based decisions.
1021 if (isa
<EnumConstantDecl
>(ND
))
1022 return CCP_Constant
;
1024 // Use CCP_Type for type declarations unless we're in a statement, Objective-C
1025 // message receiver, or parenthesized expression context. There, it's as
1026 // likely that the user will want to write a type as other declarations.
1027 if ((isa
<TypeDecl
>(ND
) || isa
<ObjCInterfaceDecl
>(ND
)) &&
1028 !(CompletionContext
.getKind() == CodeCompletionContext::CCC_Statement
||
1029 CompletionContext
.getKind() ==
1030 CodeCompletionContext::CCC_ObjCMessageReceiver
||
1031 CompletionContext
.getKind() ==
1032 CodeCompletionContext::CCC_ParenthesizedExpression
))
1035 return CCP_Declaration
;
1038 void ResultBuilder::AdjustResultPriorityForDecl(Result
&R
) {
1039 // If this is an Objective-C method declaration whose selector matches our
1040 // preferred selector, give it a priority boost.
1041 if (!PreferredSelector
.isNull())
1042 if (const auto *Method
= dyn_cast
<ObjCMethodDecl
>(R
.Declaration
))
1043 if (PreferredSelector
== Method
->getSelector())
1044 R
.Priority
+= CCD_SelectorMatch
;
1046 // If we have a preferred type, adjust the priority for results with exactly-
1047 // matching or nearly-matching types.
1048 if (!PreferredType
.isNull()) {
1049 QualType T
= getDeclUsageType(SemaRef
.Context
, R
.Declaration
);
1051 CanQualType TC
= SemaRef
.Context
.getCanonicalType(T
);
1052 // Check for exactly-matching types (modulo qualifiers).
1053 if (SemaRef
.Context
.hasSameUnqualifiedType(PreferredType
, TC
))
1054 R
.Priority
/= CCF_ExactTypeMatch
;
1055 // Check for nearly-matching types, based on classification of each.
1056 else if ((getSimplifiedTypeClass(PreferredType
) ==
1057 getSimplifiedTypeClass(TC
)) &&
1058 !(PreferredType
->isEnumeralType() && TC
->isEnumeralType()))
1059 R
.Priority
/= CCF_SimilarTypeMatch
;
1064 static DeclContext::lookup_result
getConstructors(ASTContext
&Context
,
1065 const CXXRecordDecl
*Record
) {
1066 QualType RecordTy
= Context
.getTypeDeclType(Record
);
1067 DeclarationName ConstructorName
=
1068 Context
.DeclarationNames
.getCXXConstructorName(
1069 Context
.getCanonicalType(RecordTy
));
1070 return Record
->lookup(ConstructorName
);
1073 void ResultBuilder::MaybeAddConstructorResults(Result R
) {
1074 if (!SemaRef
.getLangOpts().CPlusPlus
|| !R
.Declaration
||
1075 !CompletionContext
.wantConstructorResults())
1078 const NamedDecl
*D
= R
.Declaration
;
1079 const CXXRecordDecl
*Record
= nullptr;
1080 if (const ClassTemplateDecl
*ClassTemplate
= dyn_cast
<ClassTemplateDecl
>(D
))
1081 Record
= ClassTemplate
->getTemplatedDecl();
1082 else if ((Record
= dyn_cast
<CXXRecordDecl
>(D
))) {
1083 // Skip specializations and partial specializations.
1084 if (isa
<ClassTemplateSpecializationDecl
>(Record
))
1087 // There are no constructors here.
1091 Record
= Record
->getDefinition();
1095 for (NamedDecl
*Ctor
: getConstructors(SemaRef
.Context
, Record
)) {
1096 R
.Declaration
= Ctor
;
1097 R
.CursorKind
= getCursorKindForDecl(R
.Declaration
);
1098 Results
.push_back(R
);
1102 static bool isConstructor(const Decl
*ND
) {
1103 if (const auto *Tmpl
= dyn_cast
<FunctionTemplateDecl
>(ND
))
1104 ND
= Tmpl
->getTemplatedDecl();
1105 return isa
<CXXConstructorDecl
>(ND
);
1108 void ResultBuilder::MaybeAddResult(Result R
, DeclContext
*CurContext
) {
1109 assert(!ShadowMaps
.empty() && "Must enter into a results scope");
1111 if (R
.Kind
!= Result::RK_Declaration
) {
1112 // For non-declaration results, just add the result.
1113 Results
.push_back(R
);
1117 // Look through using declarations.
1118 if (const UsingShadowDecl
*Using
= dyn_cast
<UsingShadowDecl
>(R
.Declaration
)) {
1119 CodeCompletionResult
Result(Using
->getTargetDecl(),
1120 getBasePriority(Using
->getTargetDecl()),
1122 (R
.Availability
== CXAvailability_Available
||
1123 R
.Availability
== CXAvailability_Deprecated
),
1124 std::move(R
.FixIts
));
1125 Result
.ShadowDecl
= Using
;
1126 MaybeAddResult(Result
, CurContext
);
1130 const Decl
*CanonDecl
= R
.Declaration
->getCanonicalDecl();
1131 unsigned IDNS
= CanonDecl
->getIdentifierNamespace();
1133 bool AsNestedNameSpecifier
= false;
1134 if (!isInterestingDecl(R
.Declaration
, AsNestedNameSpecifier
))
1137 // C++ constructors are never found by name lookup.
1138 if (isConstructor(R
.Declaration
))
1141 ShadowMap
&SMap
= ShadowMaps
.back();
1142 ShadowMapEntry::iterator I
, IEnd
;
1143 ShadowMap::iterator NamePos
= SMap
.find(R
.Declaration
->getDeclName());
1144 if (NamePos
!= SMap
.end()) {
1145 I
= NamePos
->second
.begin();
1146 IEnd
= NamePos
->second
.end();
1149 for (; I
!= IEnd
; ++I
) {
1150 const NamedDecl
*ND
= I
->first
;
1151 unsigned Index
= I
->second
;
1152 if (ND
->getCanonicalDecl() == CanonDecl
) {
1153 // This is a redeclaration. Always pick the newer declaration.
1154 Results
[Index
].Declaration
= R
.Declaration
;
1161 // This is a new declaration in this scope. However, check whether this
1162 // declaration name is hidden by a similarly-named declaration in an outer
1164 std::list
<ShadowMap
>::iterator SM
, SMEnd
= ShadowMaps
.end();
1166 for (SM
= ShadowMaps
.begin(); SM
!= SMEnd
; ++SM
) {
1167 ShadowMapEntry::iterator I
, IEnd
;
1168 ShadowMap::iterator NamePos
= SM
->find(R
.Declaration
->getDeclName());
1169 if (NamePos
!= SM
->end()) {
1170 I
= NamePos
->second
.begin();
1171 IEnd
= NamePos
->second
.end();
1173 for (; I
!= IEnd
; ++I
) {
1174 // A tag declaration does not hide a non-tag declaration.
1175 if (I
->first
->hasTagIdentifierNamespace() &&
1176 (IDNS
& (Decl::IDNS_Member
| Decl::IDNS_Ordinary
|
1177 Decl::IDNS_LocalExtern
| Decl::IDNS_ObjCProtocol
)))
1180 // Protocols are in distinct namespaces from everything else.
1181 if (((I
->first
->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol
) ||
1182 (IDNS
& Decl::IDNS_ObjCProtocol
)) &&
1183 I
->first
->getIdentifierNamespace() != IDNS
)
1186 // The newly-added result is hidden by an entry in the shadow map.
1187 if (CheckHiddenResult(R
, CurContext
, I
->first
))
1194 // Make sure that any given declaration only shows up in the result set once.
1195 if (!AllDeclsFound
.insert(CanonDecl
).second
)
1198 // If the filter is for nested-name-specifiers, then this result starts a
1199 // nested-name-specifier.
1200 if (AsNestedNameSpecifier
) {
1201 R
.StartsNestedNameSpecifier
= true;
1202 R
.Priority
= CCP_NestedNameSpecifier
;
1204 AdjustResultPriorityForDecl(R
);
1206 // If this result is supposed to have an informative qualifier, add one.
1207 if (R
.QualifierIsInformative
&& !R
.Qualifier
&&
1208 !R
.StartsNestedNameSpecifier
) {
1209 const DeclContext
*Ctx
= R
.Declaration
->getDeclContext();
1210 if (const NamespaceDecl
*Namespace
= dyn_cast
<NamespaceDecl
>(Ctx
))
1212 NestedNameSpecifier::Create(SemaRef
.Context
, nullptr, Namespace
);
1213 else if (const TagDecl
*Tag
= dyn_cast
<TagDecl
>(Ctx
))
1214 R
.Qualifier
= NestedNameSpecifier::Create(
1215 SemaRef
.Context
, nullptr, false,
1216 SemaRef
.Context
.getTypeDeclType(Tag
).getTypePtr());
1218 R
.QualifierIsInformative
= false;
1221 // Insert this result into the set of results and into the current shadow
1223 SMap
[R
.Declaration
->getDeclName()].Add(R
.Declaration
, Results
.size());
1224 Results
.push_back(R
);
1226 if (!AsNestedNameSpecifier
)
1227 MaybeAddConstructorResults(R
);
1230 static void setInBaseClass(ResultBuilder::Result
&R
) {
1231 R
.Priority
+= CCD_InBaseClass
;
1232 R
.InBaseClass
= true;
1235 enum class OverloadCompare
{ BothViable
, Dominates
, Dominated
};
1236 // Will Candidate ever be called on the object, when overloaded with Incumbent?
1237 // Returns Dominates if Candidate is always called, Dominated if Incumbent is
1238 // always called, BothViable if either may be called depending on arguments.
1239 // Precondition: must actually be overloads!
1240 static OverloadCompare
compareOverloads(const CXXMethodDecl
&Candidate
,
1241 const CXXMethodDecl
&Incumbent
,
1242 const Qualifiers
&ObjectQuals
,
1243 ExprValueKind ObjectKind
) {
1244 // Base/derived shadowing is handled elsewhere.
1245 if (Candidate
.getDeclContext() != Incumbent
.getDeclContext())
1246 return OverloadCompare::BothViable
;
1247 if (Candidate
.isVariadic() != Incumbent
.isVariadic() ||
1248 Candidate
.getNumParams() != Incumbent
.getNumParams() ||
1249 Candidate
.getMinRequiredArguments() !=
1250 Incumbent
.getMinRequiredArguments())
1251 return OverloadCompare::BothViable
;
1252 for (unsigned I
= 0, E
= Candidate
.getNumParams(); I
!= E
; ++I
)
1253 if (Candidate
.parameters()[I
]->getType().getCanonicalType() !=
1254 Incumbent
.parameters()[I
]->getType().getCanonicalType())
1255 return OverloadCompare::BothViable
;
1256 if (!Candidate
.specific_attrs
<EnableIfAttr
>().empty() ||
1257 !Incumbent
.specific_attrs
<EnableIfAttr
>().empty())
1258 return OverloadCompare::BothViable
;
1259 // At this point, we know calls can't pick one or the other based on
1260 // arguments, so one of the two must win. (Or both fail, handled elsewhere).
1261 RefQualifierKind CandidateRef
= Candidate
.getRefQualifier();
1262 RefQualifierKind IncumbentRef
= Incumbent
.getRefQualifier();
1263 if (CandidateRef
!= IncumbentRef
) {
1264 // If the object kind is LValue/RValue, there's one acceptable ref-qualifier
1265 // and it can't be mixed with ref-unqualified overloads (in valid code).
1267 // For xvalue objects, we prefer the rvalue overload even if we have to
1268 // add qualifiers (which is rare, because const&& is rare).
1269 if (ObjectKind
== clang::VK_XValue
)
1270 return CandidateRef
== RQ_RValue
? OverloadCompare::Dominates
1271 : OverloadCompare::Dominated
;
1273 // Now the ref qualifiers are the same (or we're in some invalid state).
1274 // So make some decision based on the qualifiers.
1275 Qualifiers CandidateQual
= Candidate
.getMethodQualifiers();
1276 Qualifiers IncumbentQual
= Incumbent
.getMethodQualifiers();
1277 bool CandidateSuperset
= CandidateQual
.compatiblyIncludes(IncumbentQual
);
1278 bool IncumbentSuperset
= IncumbentQual
.compatiblyIncludes(CandidateQual
);
1279 if (CandidateSuperset
== IncumbentSuperset
)
1280 return OverloadCompare::BothViable
;
1281 return IncumbentSuperset
? OverloadCompare::Dominates
1282 : OverloadCompare::Dominated
;
1285 bool ResultBuilder::canCxxMethodBeCalled(const CXXMethodDecl
*Method
,
1286 QualType BaseExprType
) const {
1287 // Find the class scope that we're currently in.
1288 // We could e.g. be inside a lambda, so walk up the DeclContext until we
1289 // find a CXXMethodDecl.
1290 DeclContext
*CurContext
= SemaRef
.CurContext
;
1291 const auto *CurrentClassScope
= [&]() -> const CXXRecordDecl
* {
1292 for (DeclContext
*Ctx
= CurContext
; Ctx
; Ctx
= Ctx
->getParent()) {
1293 const auto *CtxMethod
= llvm::dyn_cast
<CXXMethodDecl
>(Ctx
);
1294 if (CtxMethod
&& !CtxMethod
->getParent()->isLambda()) {
1295 return CtxMethod
->getParent();
1301 // If we're not inside the scope of the method's class, it can't be a call.
1302 bool FunctionCanBeCall
=
1303 CurrentClassScope
&&
1304 (CurrentClassScope
== Method
->getParent() ||
1305 CurrentClassScope
->isDerivedFrom(Method
->getParent()));
1307 // We skip the following calculation for exceptions if it's already true.
1308 if (FunctionCanBeCall
)
1311 // Exception: foo->FooBase::bar() or foo->Foo::bar() *is* a call.
1312 if (const CXXRecordDecl
*MaybeDerived
=
1313 BaseExprType
.isNull() ? nullptr
1314 : BaseExprType
->getAsCXXRecordDecl()) {
1315 auto *MaybeBase
= Method
->getParent();
1317 MaybeDerived
== MaybeBase
|| MaybeDerived
->isDerivedFrom(MaybeBase
);
1320 return FunctionCanBeCall
;
1323 bool ResultBuilder::canFunctionBeCalled(const NamedDecl
*ND
,
1324 QualType BaseExprType
) const {
1325 // We apply heuristics only to CCC_Symbol:
1326 // * CCC_{Arrow,Dot}MemberAccess reflect member access expressions:
1327 // f.method() and f->method(). These are always calls.
1328 // * A qualified name to a member function may *not* be a call. We have to
1329 // subdivide the cases: For example, f.Base::method(), which is regarded as
1330 // CCC_Symbol, should be a call.
1331 // * Non-member functions and static member functions are always considered
1333 if (CompletionContext
.getKind() == clang::CodeCompletionContext::CCC_Symbol
) {
1334 if (const auto *FuncTmpl
= dyn_cast
<FunctionTemplateDecl
>(ND
)) {
1335 ND
= FuncTmpl
->getTemplatedDecl();
1337 const auto *Method
= dyn_cast
<CXXMethodDecl
>(ND
);
1338 if (Method
&& !Method
->isStatic()) {
1339 return canCxxMethodBeCalled(Method
, BaseExprType
);
1345 void ResultBuilder::AddResult(Result R
, DeclContext
*CurContext
,
1346 NamedDecl
*Hiding
, bool InBaseClass
= false,
1347 QualType BaseExprType
= QualType()) {
1348 if (R
.Kind
!= Result::RK_Declaration
) {
1349 // For non-declaration results, just add the result.
1350 Results
.push_back(R
);
1354 // Look through using declarations.
1355 if (const auto *Using
= dyn_cast
<UsingShadowDecl
>(R
.Declaration
)) {
1356 CodeCompletionResult
Result(Using
->getTargetDecl(),
1357 getBasePriority(Using
->getTargetDecl()),
1359 (R
.Availability
== CXAvailability_Available
||
1360 R
.Availability
== CXAvailability_Deprecated
),
1361 std::move(R
.FixIts
));
1362 Result
.ShadowDecl
= Using
;
1363 AddResult(Result
, CurContext
, Hiding
, /*InBaseClass=*/false,
1364 /*BaseExprType=*/BaseExprType
);
1368 bool AsNestedNameSpecifier
= false;
1369 if (!isInterestingDecl(R
.Declaration
, AsNestedNameSpecifier
))
1372 // C++ constructors are never found by name lookup.
1373 if (isConstructor(R
.Declaration
))
1376 if (Hiding
&& CheckHiddenResult(R
, CurContext
, Hiding
))
1379 // Make sure that any given declaration only shows up in the result set once.
1380 if (!AllDeclsFound
.insert(R
.Declaration
->getCanonicalDecl()).second
)
1383 // If the filter is for nested-name-specifiers, then this result starts a
1384 // nested-name-specifier.
1385 if (AsNestedNameSpecifier
) {
1386 R
.StartsNestedNameSpecifier
= true;
1387 R
.Priority
= CCP_NestedNameSpecifier
;
1388 } else if (Filter
== &ResultBuilder::IsMember
&& !R
.Qualifier
&&
1391 R
.Declaration
->getDeclContext()->getRedeclContext()))
1392 R
.QualifierIsInformative
= true;
1394 // If this result is supposed to have an informative qualifier, add one.
1395 if (R
.QualifierIsInformative
&& !R
.Qualifier
&&
1396 !R
.StartsNestedNameSpecifier
) {
1397 const DeclContext
*Ctx
= R
.Declaration
->getDeclContext();
1398 if (const auto *Namespace
= dyn_cast
<NamespaceDecl
>(Ctx
))
1400 NestedNameSpecifier::Create(SemaRef
.Context
, nullptr, Namespace
);
1401 else if (const auto *Tag
= dyn_cast
<TagDecl
>(Ctx
))
1402 R
.Qualifier
= NestedNameSpecifier::Create(
1403 SemaRef
.Context
, nullptr, false,
1404 SemaRef
.Context
.getTypeDeclType(Tag
).getTypePtr());
1406 R
.QualifierIsInformative
= false;
1409 // Adjust the priority if this result comes from a base class.
1413 AdjustResultPriorityForDecl(R
);
1415 if (HasObjectTypeQualifiers
)
1416 if (const auto *Method
= dyn_cast
<CXXMethodDecl
>(R
.Declaration
))
1417 if (Method
->isInstance()) {
1418 Qualifiers MethodQuals
= Method
->getMethodQualifiers();
1419 if (ObjectTypeQualifiers
== MethodQuals
)
1420 R
.Priority
+= CCD_ObjectQualifierMatch
;
1421 else if (ObjectTypeQualifiers
- MethodQuals
) {
1422 // The method cannot be invoked, because doing so would drop
1426 // Detect cases where a ref-qualified method cannot be invoked.
1427 switch (Method
->getRefQualifier()) {
1429 if (ObjectKind
!= VK_LValue
&& !MethodQuals
.hasConst())
1433 if (ObjectKind
== VK_LValue
)
1440 /// Check whether this dominates another overloaded method, which should
1441 /// be suppressed (or vice versa).
1442 /// Motivating case is const_iterator begin() const vs iterator begin().
1443 auto &OverloadSet
= OverloadMap
[std::make_pair(
1444 CurContext
, Method
->getDeclName().getAsOpaqueInteger())];
1445 for (const DeclIndexPair Entry
: OverloadSet
) {
1446 Result
&Incumbent
= Results
[Entry
.second
];
1447 switch (compareOverloads(*Method
,
1448 *cast
<CXXMethodDecl
>(Incumbent
.Declaration
),
1449 ObjectTypeQualifiers
, ObjectKind
)) {
1450 case OverloadCompare::Dominates
:
1451 // Replace the dominated overload with this one.
1452 // FIXME: if the overload dominates multiple incumbents then we
1453 // should remove all. But two overloads is by far the common case.
1454 Incumbent
= std::move(R
);
1456 case OverloadCompare::Dominated
:
1457 // This overload can't be called, drop it.
1459 case OverloadCompare::BothViable
:
1463 OverloadSet
.Add(Method
, Results
.size());
1466 R
.FunctionCanBeCall
= canFunctionBeCalled(R
.getDeclaration(), BaseExprType
);
1468 // Insert this result into the set of results.
1469 Results
.push_back(R
);
1471 if (!AsNestedNameSpecifier
)
1472 MaybeAddConstructorResults(R
);
1475 void ResultBuilder::AddResult(Result R
) {
1476 assert(R
.Kind
!= Result::RK_Declaration
&&
1477 "Declaration results need more context");
1478 Results
.push_back(R
);
1481 /// Enter into a new scope.
1482 void ResultBuilder::EnterNewScope() { ShadowMaps
.emplace_back(); }
1484 /// Exit from the current scope.
1485 void ResultBuilder::ExitScope() {
1486 ShadowMaps
.pop_back();
1489 /// Determines whether this given declaration will be found by
1490 /// ordinary name lookup.
1491 bool ResultBuilder::IsOrdinaryName(const NamedDecl
*ND
) const {
1492 ND
= ND
->getUnderlyingDecl();
1494 // If name lookup finds a local extern declaration, then we are in a
1495 // context where it behaves like an ordinary name.
1496 unsigned IDNS
= Decl::IDNS_Ordinary
| Decl::IDNS_LocalExtern
;
1497 if (SemaRef
.getLangOpts().CPlusPlus
)
1498 IDNS
|= Decl::IDNS_Tag
| Decl::IDNS_Namespace
| Decl::IDNS_Member
;
1499 else if (SemaRef
.getLangOpts().ObjC
) {
1500 if (isa
<ObjCIvarDecl
>(ND
))
1504 return ND
->getIdentifierNamespace() & IDNS
;
1507 /// Determines whether this given declaration will be found by
1508 /// ordinary name lookup but is not a type name.
1509 bool ResultBuilder::IsOrdinaryNonTypeName(const NamedDecl
*ND
) const {
1510 ND
= ND
->getUnderlyingDecl();
1511 if (isa
<TypeDecl
>(ND
))
1513 // Objective-C interfaces names are not filtered by this method because they
1514 // can be used in a class property expression. We can still filter out
1515 // @class declarations though.
1516 if (const auto *ID
= dyn_cast
<ObjCInterfaceDecl
>(ND
)) {
1517 if (!ID
->getDefinition())
1521 unsigned IDNS
= Decl::IDNS_Ordinary
| Decl::IDNS_LocalExtern
;
1522 if (SemaRef
.getLangOpts().CPlusPlus
)
1523 IDNS
|= Decl::IDNS_Tag
| Decl::IDNS_Namespace
| Decl::IDNS_Member
;
1524 else if (SemaRef
.getLangOpts().ObjC
) {
1525 if (isa
<ObjCIvarDecl
>(ND
))
1529 return ND
->getIdentifierNamespace() & IDNS
;
1532 bool ResultBuilder::IsIntegralConstantValue(const NamedDecl
*ND
) const {
1533 if (!IsOrdinaryNonTypeName(ND
))
1536 if (const auto *VD
= dyn_cast
<ValueDecl
>(ND
->getUnderlyingDecl()))
1537 if (VD
->getType()->isIntegralOrEnumerationType())
1543 /// Determines whether this given declaration will be found by
1544 /// ordinary name lookup.
1545 bool ResultBuilder::IsOrdinaryNonValueName(const NamedDecl
*ND
) const {
1546 ND
= ND
->getUnderlyingDecl();
1548 unsigned IDNS
= Decl::IDNS_Ordinary
| Decl::IDNS_LocalExtern
;
1549 if (SemaRef
.getLangOpts().CPlusPlus
)
1550 IDNS
|= Decl::IDNS_Tag
| Decl::IDNS_Namespace
;
1552 return (ND
->getIdentifierNamespace() & IDNS
) && !isa
<ValueDecl
>(ND
) &&
1553 !isa
<FunctionTemplateDecl
>(ND
) && !isa
<ObjCPropertyDecl
>(ND
);
1556 /// Determines whether the given declaration is suitable as the
1557 /// start of a C++ nested-name-specifier, e.g., a class or namespace.
1558 bool ResultBuilder::IsNestedNameSpecifier(const NamedDecl
*ND
) const {
1559 // Allow us to find class templates, too.
1560 if (const auto *ClassTemplate
= dyn_cast
<ClassTemplateDecl
>(ND
))
1561 ND
= ClassTemplate
->getTemplatedDecl();
1563 return SemaRef
.isAcceptableNestedNameSpecifier(ND
);
1566 /// Determines whether the given declaration is an enumeration.
1567 bool ResultBuilder::IsEnum(const NamedDecl
*ND
) const {
1568 return isa
<EnumDecl
>(ND
);
1571 /// Determines whether the given declaration is a class or struct.
1572 bool ResultBuilder::IsClassOrStruct(const NamedDecl
*ND
) const {
1573 // Allow us to find class templates, too.
1574 if (const auto *ClassTemplate
= dyn_cast
<ClassTemplateDecl
>(ND
))
1575 ND
= ClassTemplate
->getTemplatedDecl();
1577 // For purposes of this check, interfaces match too.
1578 if (const auto *RD
= dyn_cast
<RecordDecl
>(ND
))
1579 return RD
->getTagKind() == TTK_Class
|| RD
->getTagKind() == TTK_Struct
||
1580 RD
->getTagKind() == TTK_Interface
;
1585 /// Determines whether the given declaration is a union.
1586 bool ResultBuilder::IsUnion(const NamedDecl
*ND
) const {
1587 // Allow us to find class templates, too.
1588 if (const auto *ClassTemplate
= dyn_cast
<ClassTemplateDecl
>(ND
))
1589 ND
= ClassTemplate
->getTemplatedDecl();
1591 if (const auto *RD
= dyn_cast
<RecordDecl
>(ND
))
1592 return RD
->getTagKind() == TTK_Union
;
1597 /// Determines whether the given declaration is a namespace.
1598 bool ResultBuilder::IsNamespace(const NamedDecl
*ND
) const {
1599 return isa
<NamespaceDecl
>(ND
);
1602 /// Determines whether the given declaration is a namespace or
1603 /// namespace alias.
1604 bool ResultBuilder::IsNamespaceOrAlias(const NamedDecl
*ND
) const {
1605 return isa
<NamespaceDecl
>(ND
->getUnderlyingDecl());
1608 /// Determines whether the given declaration is a type.
1609 bool ResultBuilder::IsType(const NamedDecl
*ND
) const {
1610 ND
= ND
->getUnderlyingDecl();
1611 return isa
<TypeDecl
>(ND
) || isa
<ObjCInterfaceDecl
>(ND
);
1614 /// Determines which members of a class should be visible via
1615 /// "." or "->". Only value declarations, nested name specifiers, and
1616 /// using declarations thereof should show up.
1617 bool ResultBuilder::IsMember(const NamedDecl
*ND
) const {
1618 ND
= ND
->getUnderlyingDecl();
1619 return isa
<ValueDecl
>(ND
) || isa
<FunctionTemplateDecl
>(ND
) ||
1620 isa
<ObjCPropertyDecl
>(ND
);
1623 static bool isObjCReceiverType(ASTContext
&C
, QualType T
) {
1624 T
= C
.getCanonicalType(T
);
1625 switch (T
->getTypeClass()) {
1626 case Type::ObjCObject
:
1627 case Type::ObjCInterface
:
1628 case Type::ObjCObjectPointer
:
1632 switch (cast
<BuiltinType
>(T
)->getKind()) {
1633 case BuiltinType::ObjCId
:
1634 case BuiltinType::ObjCClass
:
1635 case BuiltinType::ObjCSel
:
1647 if (!C
.getLangOpts().CPlusPlus
)
1650 // FIXME: We could perform more analysis here to determine whether a
1651 // particular class type has any conversions to Objective-C types. For now,
1652 // just accept all class types.
1653 return T
->isDependentType() || T
->isRecordType();
1656 bool ResultBuilder::IsObjCMessageReceiver(const NamedDecl
*ND
) const {
1657 QualType T
= getDeclUsageType(SemaRef
.Context
, ND
);
1661 T
= SemaRef
.Context
.getBaseElementType(T
);
1662 return isObjCReceiverType(SemaRef
.Context
, T
);
1665 bool ResultBuilder::IsObjCMessageReceiverOrLambdaCapture(
1666 const NamedDecl
*ND
) const {
1667 if (IsObjCMessageReceiver(ND
))
1670 const auto *Var
= dyn_cast
<VarDecl
>(ND
);
1674 return Var
->hasLocalStorage() && !Var
->hasAttr
<BlocksAttr
>();
1677 bool ResultBuilder::IsObjCCollection(const NamedDecl
*ND
) const {
1678 if ((SemaRef
.getLangOpts().CPlusPlus
&& !IsOrdinaryName(ND
)) ||
1679 (!SemaRef
.getLangOpts().CPlusPlus
&& !IsOrdinaryNonTypeName(ND
)))
1682 QualType T
= getDeclUsageType(SemaRef
.Context
, ND
);
1686 T
= SemaRef
.Context
.getBaseElementType(T
);
1687 return T
->isObjCObjectType() || T
->isObjCObjectPointerType() ||
1688 T
->isObjCIdType() ||
1689 (SemaRef
.getLangOpts().CPlusPlus
&& T
->isRecordType());
1692 bool ResultBuilder::IsImpossibleToSatisfy(const NamedDecl
*ND
) const {
1696 /// Determines whether the given declaration is an Objective-C
1697 /// instance variable.
1698 bool ResultBuilder::IsObjCIvar(const NamedDecl
*ND
) const {
1699 return isa
<ObjCIvarDecl
>(ND
);
1704 /// Visible declaration consumer that adds a code-completion result
1705 /// for each visible declaration.
1706 class CodeCompletionDeclConsumer
: public VisibleDeclConsumer
{
1707 ResultBuilder
&Results
;
1708 DeclContext
*InitialLookupCtx
;
1709 // NamingClass and BaseType are used for access-checking. See
1710 // Sema::IsSimplyAccessible for details.
1711 CXXRecordDecl
*NamingClass
;
1713 std::vector
<FixItHint
> FixIts
;
1716 CodeCompletionDeclConsumer(
1717 ResultBuilder
&Results
, DeclContext
*InitialLookupCtx
,
1718 QualType BaseType
= QualType(),
1719 std::vector
<FixItHint
> FixIts
= std::vector
<FixItHint
>())
1720 : Results(Results
), InitialLookupCtx(InitialLookupCtx
),
1721 FixIts(std::move(FixIts
)) {
1722 NamingClass
= llvm::dyn_cast
<CXXRecordDecl
>(InitialLookupCtx
);
1723 // If BaseType was not provided explicitly, emulate implicit 'this->'.
1724 if (BaseType
.isNull()) {
1725 auto ThisType
= Results
.getSema().getCurrentThisType();
1726 if (!ThisType
.isNull()) {
1727 assert(ThisType
->isPointerType());
1728 BaseType
= ThisType
->getPointeeType();
1730 NamingClass
= BaseType
->getAsCXXRecordDecl();
1733 this->BaseType
= BaseType
;
1736 void FoundDecl(NamedDecl
*ND
, NamedDecl
*Hiding
, DeclContext
*Ctx
,
1737 bool InBaseClass
) override
{
1738 ResultBuilder::Result
Result(ND
, Results
.getBasePriority(ND
), nullptr,
1739 false, IsAccessible(ND
, Ctx
), FixIts
);
1740 Results
.AddResult(Result
, InitialLookupCtx
, Hiding
, InBaseClass
, BaseType
);
1743 void EnteredContext(DeclContext
*Ctx
) override
{
1744 Results
.addVisitedContext(Ctx
);
1748 bool IsAccessible(NamedDecl
*ND
, DeclContext
*Ctx
) {
1749 // Naming class to use for access check. In most cases it was provided
1750 // explicitly (e.g. member access (lhs.foo) or qualified lookup (X::)),
1751 // for unqualified lookup we fallback to the \p Ctx in which we found the
1753 auto *NamingClass
= this->NamingClass
;
1754 QualType BaseType
= this->BaseType
;
1755 if (auto *Cls
= llvm::dyn_cast_or_null
<CXXRecordDecl
>(Ctx
)) {
1758 // When we emulate implicit 'this->' in an unqualified lookup, we might
1759 // end up with an invalid naming class. In that case, we avoid emulating
1760 // 'this->' qualifier to satisfy preconditions of the access checking.
1761 if (NamingClass
->getCanonicalDecl() != Cls
->getCanonicalDecl() &&
1762 !NamingClass
->isDerivedFrom(Cls
)) {
1764 BaseType
= QualType();
1767 // The decl was found outside the C++ class, so only ObjC access checks
1768 // apply. Those do not rely on NamingClass and BaseType, so we clear them
1770 NamingClass
= nullptr;
1771 BaseType
= QualType();
1773 return Results
.getSema().IsSimplyAccessible(ND
, NamingClass
, BaseType
);
1778 /// Add type specifiers for the current language as keyword results.
1779 static void AddTypeSpecifierResults(const LangOptions
&LangOpts
,
1780 ResultBuilder
&Results
) {
1781 typedef CodeCompletionResult Result
;
1782 Results
.AddResult(Result("short", CCP_Type
));
1783 Results
.AddResult(Result("long", CCP_Type
));
1784 Results
.AddResult(Result("signed", CCP_Type
));
1785 Results
.AddResult(Result("unsigned", CCP_Type
));
1786 Results
.AddResult(Result("void", CCP_Type
));
1787 Results
.AddResult(Result("char", CCP_Type
));
1788 Results
.AddResult(Result("int", CCP_Type
));
1789 Results
.AddResult(Result("float", CCP_Type
));
1790 Results
.AddResult(Result("double", CCP_Type
));
1791 Results
.AddResult(Result("enum", CCP_Type
));
1792 Results
.AddResult(Result("struct", CCP_Type
));
1793 Results
.AddResult(Result("union", CCP_Type
));
1794 Results
.AddResult(Result("const", CCP_Type
));
1795 Results
.AddResult(Result("volatile", CCP_Type
));
1799 Results
.AddResult(Result("_Complex", CCP_Type
));
1800 Results
.AddResult(Result("_Imaginary", CCP_Type
));
1801 Results
.AddResult(Result("_Bool", CCP_Type
));
1802 Results
.AddResult(Result("restrict", CCP_Type
));
1805 CodeCompletionBuilder
Builder(Results
.getAllocator(),
1806 Results
.getCodeCompletionTUInfo());
1807 if (LangOpts
.CPlusPlus
) {
1810 Result("bool", CCP_Type
+ (LangOpts
.ObjC
? CCD_bool_in_ObjC
: 0)));
1811 Results
.AddResult(Result("class", CCP_Type
));
1812 Results
.AddResult(Result("wchar_t", CCP_Type
));
1815 Builder
.AddTypedTextChunk("typename");
1816 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
1817 Builder
.AddPlaceholderChunk("name");
1818 Results
.AddResult(Result(Builder
.TakeString()));
1820 if (LangOpts
.CPlusPlus11
) {
1821 Results
.AddResult(Result("auto", CCP_Type
));
1822 Results
.AddResult(Result("char16_t", CCP_Type
));
1823 Results
.AddResult(Result("char32_t", CCP_Type
));
1825 Builder
.AddTypedTextChunk("decltype");
1826 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
1827 Builder
.AddPlaceholderChunk("expression");
1828 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
1829 Results
.AddResult(Result(Builder
.TakeString()));
1832 Results
.AddResult(Result("__auto_type", CCP_Type
));
1835 if (LangOpts
.GNUKeywords
) {
1836 // FIXME: Enable when we actually support decimal floating point.
1837 // Results.AddResult(Result("_Decimal32"));
1838 // Results.AddResult(Result("_Decimal64"));
1839 // Results.AddResult(Result("_Decimal128"));
1841 Builder
.AddTypedTextChunk("typeof");
1842 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
1843 Builder
.AddPlaceholderChunk("expression");
1844 Results
.AddResult(Result(Builder
.TakeString()));
1846 Builder
.AddTypedTextChunk("typeof");
1847 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
1848 Builder
.AddPlaceholderChunk("type");
1849 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
1850 Results
.AddResult(Result(Builder
.TakeString()));
1854 Results
.AddResult(Result("_Nonnull", CCP_Type
));
1855 Results
.AddResult(Result("_Null_unspecified", CCP_Type
));
1856 Results
.AddResult(Result("_Nullable", CCP_Type
));
1859 static void AddStorageSpecifiers(Sema::ParserCompletionContext CCC
,
1860 const LangOptions
&LangOpts
,
1861 ResultBuilder
&Results
) {
1862 typedef CodeCompletionResult Result
;
1863 // Note: we don't suggest either "auto" or "register", because both
1864 // are pointless as storage specifiers. Elsewhere, we suggest "auto"
1865 // in C++0x as a type specifier.
1866 Results
.AddResult(Result("extern"));
1867 Results
.AddResult(Result("static"));
1869 if (LangOpts
.CPlusPlus11
) {
1870 CodeCompletionAllocator
&Allocator
= Results
.getAllocator();
1871 CodeCompletionBuilder
Builder(Allocator
, Results
.getCodeCompletionTUInfo());
1874 Builder
.AddTypedTextChunk("alignas");
1875 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
1876 Builder
.AddPlaceholderChunk("expression");
1877 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
1878 Results
.AddResult(Result(Builder
.TakeString()));
1880 Results
.AddResult(Result("constexpr"));
1881 Results
.AddResult(Result("thread_local"));
1885 static void AddFunctionSpecifiers(Sema::ParserCompletionContext CCC
,
1886 const LangOptions
&LangOpts
,
1887 ResultBuilder
&Results
) {
1888 typedef CodeCompletionResult Result
;
1890 case Sema::PCC_Class
:
1891 case Sema::PCC_MemberTemplate
:
1892 if (LangOpts
.CPlusPlus
) {
1893 Results
.AddResult(Result("explicit"));
1894 Results
.AddResult(Result("friend"));
1895 Results
.AddResult(Result("mutable"));
1896 Results
.AddResult(Result("virtual"));
1900 case Sema::PCC_ObjCInterface
:
1901 case Sema::PCC_ObjCImplementation
:
1902 case Sema::PCC_Namespace
:
1903 case Sema::PCC_Template
:
1904 if (LangOpts
.CPlusPlus
|| LangOpts
.C99
)
1905 Results
.AddResult(Result("inline"));
1908 case Sema::PCC_ObjCInstanceVariableList
:
1909 case Sema::PCC_Expression
:
1910 case Sema::PCC_Statement
:
1911 case Sema::PCC_TopLevelOrExpression
:
1912 case Sema::PCC_ForInit
:
1913 case Sema::PCC_Condition
:
1914 case Sema::PCC_RecoveryInFunction
:
1915 case Sema::PCC_Type
:
1916 case Sema::PCC_ParenthesizedExpression
:
1917 case Sema::PCC_LocalDeclarationSpecifiers
:
1922 static void AddObjCExpressionResults(ResultBuilder
&Results
, bool NeedAt
);
1923 static void AddObjCStatementResults(ResultBuilder
&Results
, bool NeedAt
);
1924 static void AddObjCVisibilityResults(const LangOptions
&LangOpts
,
1925 ResultBuilder
&Results
, bool NeedAt
);
1926 static void AddObjCImplementationResults(const LangOptions
&LangOpts
,
1927 ResultBuilder
&Results
, bool NeedAt
);
1928 static void AddObjCInterfaceResults(const LangOptions
&LangOpts
,
1929 ResultBuilder
&Results
, bool NeedAt
);
1930 static void AddObjCTopLevelResults(ResultBuilder
&Results
, bool NeedAt
);
1932 static void AddTypedefResult(ResultBuilder
&Results
) {
1933 CodeCompletionBuilder
Builder(Results
.getAllocator(),
1934 Results
.getCodeCompletionTUInfo());
1935 Builder
.AddTypedTextChunk("typedef");
1936 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
1937 Builder
.AddPlaceholderChunk("type");
1938 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
1939 Builder
.AddPlaceholderChunk("name");
1940 Builder
.AddChunk(CodeCompletionString::CK_SemiColon
);
1941 Results
.AddResult(CodeCompletionResult(Builder
.TakeString()));
1944 // using name = type
1945 static void AddUsingAliasResult(CodeCompletionBuilder
&Builder
,
1946 ResultBuilder
&Results
) {
1947 Builder
.AddTypedTextChunk("using");
1948 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
1949 Builder
.AddPlaceholderChunk("name");
1950 Builder
.AddChunk(CodeCompletionString::CK_Equal
);
1951 Builder
.AddPlaceholderChunk("type");
1952 Builder
.AddChunk(CodeCompletionString::CK_SemiColon
);
1953 Results
.AddResult(CodeCompletionResult(Builder
.TakeString()));
1956 static bool WantTypesInContext(Sema::ParserCompletionContext CCC
,
1957 const LangOptions
&LangOpts
) {
1959 case Sema::PCC_Namespace
:
1960 case Sema::PCC_Class
:
1961 case Sema::PCC_ObjCInstanceVariableList
:
1962 case Sema::PCC_Template
:
1963 case Sema::PCC_MemberTemplate
:
1964 case Sema::PCC_Statement
:
1965 case Sema::PCC_RecoveryInFunction
:
1966 case Sema::PCC_Type
:
1967 case Sema::PCC_ParenthesizedExpression
:
1968 case Sema::PCC_LocalDeclarationSpecifiers
:
1969 case Sema::PCC_TopLevelOrExpression
:
1972 case Sema::PCC_Expression
:
1973 case Sema::PCC_Condition
:
1974 return LangOpts
.CPlusPlus
;
1976 case Sema::PCC_ObjCInterface
:
1977 case Sema::PCC_ObjCImplementation
:
1980 case Sema::PCC_ForInit
:
1981 return LangOpts
.CPlusPlus
|| LangOpts
.ObjC
|| LangOpts
.C99
;
1984 llvm_unreachable("Invalid ParserCompletionContext!");
1987 static PrintingPolicy
getCompletionPrintingPolicy(const ASTContext
&Context
,
1988 const Preprocessor
&PP
) {
1989 PrintingPolicy Policy
= Sema::getPrintingPolicy(Context
, PP
);
1990 Policy
.AnonymousTagLocations
= false;
1991 Policy
.SuppressStrongLifetime
= true;
1992 Policy
.SuppressUnwrittenScope
= true;
1993 Policy
.SuppressScope
= true;
1994 Policy
.CleanUglifiedParameters
= true;
1998 /// Retrieve a printing policy suitable for code completion.
1999 static PrintingPolicy
getCompletionPrintingPolicy(Sema
&S
) {
2000 return getCompletionPrintingPolicy(S
.Context
, S
.PP
);
2003 /// Retrieve the string representation of the given type as a string
2004 /// that has the appropriate lifetime for code completion.
2006 /// This routine provides a fast path where we provide constant strings for
2007 /// common type names.
2008 static const char *GetCompletionTypeString(QualType T
, ASTContext
&Context
,
2009 const PrintingPolicy
&Policy
,
2010 CodeCompletionAllocator
&Allocator
) {
2011 if (!T
.getLocalQualifiers()) {
2012 // Built-in type names are constant strings.
2013 if (const BuiltinType
*BT
= dyn_cast
<BuiltinType
>(T
))
2014 return BT
->getNameAsCString(Policy
);
2016 // Anonymous tag types are constant strings.
2017 if (const TagType
*TagT
= dyn_cast
<TagType
>(T
))
2018 if (TagDecl
*Tag
= TagT
->getDecl())
2019 if (!Tag
->hasNameForLinkage()) {
2020 switch (Tag
->getTagKind()) {
2022 return "struct <anonymous>";
2024 return "__interface <anonymous>";
2026 return "class <anonymous>";
2028 return "union <anonymous>";
2030 return "enum <anonymous>";
2035 // Slow path: format the type as a string.
2037 T
.getAsStringInternal(Result
, Policy
);
2038 return Allocator
.CopyString(Result
);
2041 /// Add a completion for "this", if we're in a member function.
2042 static void addThisCompletion(Sema
&S
, ResultBuilder
&Results
) {
2043 QualType ThisTy
= S
.getCurrentThisType();
2044 if (ThisTy
.isNull())
2047 CodeCompletionAllocator
&Allocator
= Results
.getAllocator();
2048 CodeCompletionBuilder
Builder(Allocator
, Results
.getCodeCompletionTUInfo());
2049 PrintingPolicy Policy
= getCompletionPrintingPolicy(S
);
2050 Builder
.AddResultTypeChunk(
2051 GetCompletionTypeString(ThisTy
, S
.Context
, Policy
, Allocator
));
2052 Builder
.AddTypedTextChunk("this");
2053 Results
.AddResult(CodeCompletionResult(Builder
.TakeString()));
2056 static void AddStaticAssertResult(CodeCompletionBuilder
&Builder
,
2057 ResultBuilder
&Results
,
2058 const LangOptions
&LangOpts
) {
2059 if (!LangOpts
.CPlusPlus11
)
2062 Builder
.AddTypedTextChunk("static_assert");
2063 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
2064 Builder
.AddPlaceholderChunk("expression");
2065 Builder
.AddChunk(CodeCompletionString::CK_Comma
);
2066 Builder
.AddPlaceholderChunk("message");
2067 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
2068 Builder
.AddChunk(CodeCompletionString::CK_SemiColon
);
2069 Results
.AddResult(CodeCompletionResult(Builder
.TakeString()));
2072 static void AddOverrideResults(ResultBuilder
&Results
,
2073 const CodeCompletionContext
&CCContext
,
2074 CodeCompletionBuilder
&Builder
) {
2075 Sema
&S
= Results
.getSema();
2076 const auto *CR
= llvm::dyn_cast
<CXXRecordDecl
>(S
.CurContext
);
2077 // If not inside a class/struct/union return empty.
2080 // First store overrides within current class.
2081 // These are stored by name to make querying fast in the later step.
2082 llvm::StringMap
<std::vector
<FunctionDecl
*>> Overrides
;
2083 for (auto *Method
: CR
->methods()) {
2084 if (!Method
->isVirtual() || !Method
->getIdentifier())
2086 Overrides
[Method
->getName()].push_back(Method
);
2089 for (const auto &Base
: CR
->bases()) {
2090 const auto *BR
= Base
.getType().getTypePtr()->getAsCXXRecordDecl();
2093 for (auto *Method
: BR
->methods()) {
2094 if (!Method
->isVirtual() || !Method
->getIdentifier())
2096 const auto it
= Overrides
.find(Method
->getName());
2097 bool IsOverriden
= false;
2098 if (it
!= Overrides
.end()) {
2099 for (auto *MD
: it
->second
) {
2100 // If the method in current body is not an overload of this virtual
2101 // function, then it overrides this one.
2102 if (!S
.IsOverload(MD
, Method
, false)) {
2109 // Generates a new CodeCompletionResult by taking this function and
2110 // converting it into an override declaration with only one chunk in the
2111 // final CodeCompletionString as a TypedTextChunk.
2112 std::string OverrideSignature
;
2113 llvm::raw_string_ostream
OS(OverrideSignature
);
2114 CodeCompletionResult
CCR(Method
, 0);
2115 PrintingPolicy Policy
=
2116 getCompletionPrintingPolicy(S
.getASTContext(), S
.getPreprocessor());
2117 auto *CCS
= CCR
.createCodeCompletionStringForOverride(
2118 S
.getPreprocessor(), S
.getASTContext(), Builder
,
2119 /*IncludeBriefComments=*/false, CCContext
, Policy
);
2120 Results
.AddResult(CodeCompletionResult(CCS
, Method
, CCP_CodePattern
));
2126 /// Add language constructs that show up for "ordinary" names.
2127 static void AddOrdinaryNameResults(Sema::ParserCompletionContext CCC
, Scope
*S
,
2128 Sema
&SemaRef
, ResultBuilder
&Results
) {
2129 CodeCompletionAllocator
&Allocator
= Results
.getAllocator();
2130 CodeCompletionBuilder
Builder(Allocator
, Results
.getCodeCompletionTUInfo());
2132 typedef CodeCompletionResult Result
;
2134 case Sema::PCC_Namespace
:
2135 if (SemaRef
.getLangOpts().CPlusPlus
) {
2136 if (Results
.includeCodePatterns()) {
2137 // namespace <identifier> { declarations }
2138 Builder
.AddTypedTextChunk("namespace");
2139 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2140 Builder
.AddPlaceholderChunk("identifier");
2141 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2142 Builder
.AddChunk(CodeCompletionString::CK_LeftBrace
);
2143 Builder
.AddChunk(CodeCompletionString::CK_VerticalSpace
);
2144 Builder
.AddPlaceholderChunk("declarations");
2145 Builder
.AddChunk(CodeCompletionString::CK_VerticalSpace
);
2146 Builder
.AddChunk(CodeCompletionString::CK_RightBrace
);
2147 Results
.AddResult(Result(Builder
.TakeString()));
2150 // namespace identifier = identifier ;
2151 Builder
.AddTypedTextChunk("namespace");
2152 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2153 Builder
.AddPlaceholderChunk("name");
2154 Builder
.AddChunk(CodeCompletionString::CK_Equal
);
2155 Builder
.AddPlaceholderChunk("namespace");
2156 Builder
.AddChunk(CodeCompletionString::CK_SemiColon
);
2157 Results
.AddResult(Result(Builder
.TakeString()));
2160 Builder
.AddTypedTextChunk("using namespace");
2161 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2162 Builder
.AddPlaceholderChunk("identifier");
2163 Builder
.AddChunk(CodeCompletionString::CK_SemiColon
);
2164 Results
.AddResult(Result(Builder
.TakeString()));
2166 // asm(string-literal)
2167 Builder
.AddTypedTextChunk("asm");
2168 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
2169 Builder
.AddPlaceholderChunk("string-literal");
2170 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
2171 Results
.AddResult(Result(Builder
.TakeString()));
2173 if (Results
.includeCodePatterns()) {
2174 // Explicit template instantiation
2175 Builder
.AddTypedTextChunk("template");
2176 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2177 Builder
.AddPlaceholderChunk("declaration");
2178 Results
.AddResult(Result(Builder
.TakeString()));
2180 Results
.AddResult(Result("template", CodeCompletionResult::RK_Keyword
));
2184 if (SemaRef
.getLangOpts().ObjC
)
2185 AddObjCTopLevelResults(Results
, true);
2187 AddTypedefResult(Results
);
2190 case Sema::PCC_Class
:
2191 if (SemaRef
.getLangOpts().CPlusPlus
) {
2192 // Using declaration
2193 Builder
.AddTypedTextChunk("using");
2194 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2195 Builder
.AddPlaceholderChunk("qualifier");
2196 Builder
.AddTextChunk("::");
2197 Builder
.AddPlaceholderChunk("name");
2198 Builder
.AddChunk(CodeCompletionString::CK_SemiColon
);
2199 Results
.AddResult(Result(Builder
.TakeString()));
2201 if (SemaRef
.getLangOpts().CPlusPlus11
)
2202 AddUsingAliasResult(Builder
, Results
);
2204 // using typename qualifier::name (only in a dependent context)
2205 if (SemaRef
.CurContext
->isDependentContext()) {
2206 Builder
.AddTypedTextChunk("using typename");
2207 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2208 Builder
.AddPlaceholderChunk("qualifier");
2209 Builder
.AddTextChunk("::");
2210 Builder
.AddPlaceholderChunk("name");
2211 Builder
.AddChunk(CodeCompletionString::CK_SemiColon
);
2212 Results
.AddResult(Result(Builder
.TakeString()));
2215 AddStaticAssertResult(Builder
, Results
, SemaRef
.getLangOpts());
2217 if (CCC
== Sema::PCC_Class
) {
2218 AddTypedefResult(Results
);
2220 bool IsNotInheritanceScope
= !S
->isClassInheritanceScope();
2222 Builder
.AddTypedTextChunk("public");
2223 if (IsNotInheritanceScope
&& Results
.includeCodePatterns())
2224 Builder
.AddChunk(CodeCompletionString::CK_Colon
);
2225 Results
.AddResult(Result(Builder
.TakeString()));
2228 Builder
.AddTypedTextChunk("protected");
2229 if (IsNotInheritanceScope
&& Results
.includeCodePatterns())
2230 Builder
.AddChunk(CodeCompletionString::CK_Colon
);
2231 Results
.AddResult(Result(Builder
.TakeString()));
2234 Builder
.AddTypedTextChunk("private");
2235 if (IsNotInheritanceScope
&& Results
.includeCodePatterns())
2236 Builder
.AddChunk(CodeCompletionString::CK_Colon
);
2237 Results
.AddResult(Result(Builder
.TakeString()));
2239 // FIXME: This adds override results only if we are at the first word of
2240 // the declaration/definition. Also call this from other sides to have
2242 AddOverrideResults(Results
, CodeCompletionContext::CCC_ClassStructUnion
,
2248 case Sema::PCC_Template
:
2249 case Sema::PCC_MemberTemplate
:
2250 if (SemaRef
.getLangOpts().CPlusPlus
&& Results
.includeCodePatterns()) {
2251 // template < parameters >
2252 Builder
.AddTypedTextChunk("template");
2253 Builder
.AddChunk(CodeCompletionString::CK_LeftAngle
);
2254 Builder
.AddPlaceholderChunk("parameters");
2255 Builder
.AddChunk(CodeCompletionString::CK_RightAngle
);
2256 Results
.AddResult(Result(Builder
.TakeString()));
2258 Results
.AddResult(Result("template", CodeCompletionResult::RK_Keyword
));
2261 AddStorageSpecifiers(CCC
, SemaRef
.getLangOpts(), Results
);
2262 AddFunctionSpecifiers(CCC
, SemaRef
.getLangOpts(), Results
);
2265 case Sema::PCC_ObjCInterface
:
2266 AddObjCInterfaceResults(SemaRef
.getLangOpts(), Results
, true);
2267 AddStorageSpecifiers(CCC
, SemaRef
.getLangOpts(), Results
);
2268 AddFunctionSpecifiers(CCC
, SemaRef
.getLangOpts(), Results
);
2271 case Sema::PCC_ObjCImplementation
:
2272 AddObjCImplementationResults(SemaRef
.getLangOpts(), Results
, true);
2273 AddStorageSpecifiers(CCC
, SemaRef
.getLangOpts(), Results
);
2274 AddFunctionSpecifiers(CCC
, SemaRef
.getLangOpts(), Results
);
2277 case Sema::PCC_ObjCInstanceVariableList
:
2278 AddObjCVisibilityResults(SemaRef
.getLangOpts(), Results
, true);
2281 case Sema::PCC_RecoveryInFunction
:
2282 case Sema::PCC_TopLevelOrExpression
:
2283 case Sema::PCC_Statement
: {
2284 if (SemaRef
.getLangOpts().CPlusPlus11
)
2285 AddUsingAliasResult(Builder
, Results
);
2287 AddTypedefResult(Results
);
2289 if (SemaRef
.getLangOpts().CPlusPlus
&& Results
.includeCodePatterns() &&
2290 SemaRef
.getLangOpts().CXXExceptions
) {
2291 Builder
.AddTypedTextChunk("try");
2292 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2293 Builder
.AddChunk(CodeCompletionString::CK_LeftBrace
);
2294 Builder
.AddChunk(CodeCompletionString::CK_VerticalSpace
);
2295 Builder
.AddPlaceholderChunk("statements");
2296 Builder
.AddChunk(CodeCompletionString::CK_VerticalSpace
);
2297 Builder
.AddChunk(CodeCompletionString::CK_RightBrace
);
2298 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2299 Builder
.AddTextChunk("catch");
2300 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2301 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
2302 Builder
.AddPlaceholderChunk("declaration");
2303 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
2304 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2305 Builder
.AddChunk(CodeCompletionString::CK_LeftBrace
);
2306 Builder
.AddChunk(CodeCompletionString::CK_VerticalSpace
);
2307 Builder
.AddPlaceholderChunk("statements");
2308 Builder
.AddChunk(CodeCompletionString::CK_VerticalSpace
);
2309 Builder
.AddChunk(CodeCompletionString::CK_RightBrace
);
2310 Results
.AddResult(Result(Builder
.TakeString()));
2312 if (SemaRef
.getLangOpts().ObjC
)
2313 AddObjCStatementResults(Results
, true);
2315 if (Results
.includeCodePatterns()) {
2316 // if (condition) { statements }
2317 Builder
.AddTypedTextChunk("if");
2318 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2319 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
2320 if (SemaRef
.getLangOpts().CPlusPlus
)
2321 Builder
.AddPlaceholderChunk("condition");
2323 Builder
.AddPlaceholderChunk("expression");
2324 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
2325 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2326 Builder
.AddChunk(CodeCompletionString::CK_LeftBrace
);
2327 Builder
.AddChunk(CodeCompletionString::CK_VerticalSpace
);
2328 Builder
.AddPlaceholderChunk("statements");
2329 Builder
.AddChunk(CodeCompletionString::CK_VerticalSpace
);
2330 Builder
.AddChunk(CodeCompletionString::CK_RightBrace
);
2331 Results
.AddResult(Result(Builder
.TakeString()));
2333 // switch (condition) { }
2334 Builder
.AddTypedTextChunk("switch");
2335 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2336 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
2337 if (SemaRef
.getLangOpts().CPlusPlus
)
2338 Builder
.AddPlaceholderChunk("condition");
2340 Builder
.AddPlaceholderChunk("expression");
2341 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
2342 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2343 Builder
.AddChunk(CodeCompletionString::CK_LeftBrace
);
2344 Builder
.AddChunk(CodeCompletionString::CK_VerticalSpace
);
2345 Builder
.AddPlaceholderChunk("cases");
2346 Builder
.AddChunk(CodeCompletionString::CK_VerticalSpace
);
2347 Builder
.AddChunk(CodeCompletionString::CK_RightBrace
);
2348 Results
.AddResult(Result(Builder
.TakeString()));
2351 // Switch-specific statements.
2352 if (SemaRef
.getCurFunction() &&
2353 !SemaRef
.getCurFunction()->SwitchStack
.empty()) {
2355 Builder
.AddTypedTextChunk("case");
2356 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2357 Builder
.AddPlaceholderChunk("expression");
2358 Builder
.AddChunk(CodeCompletionString::CK_Colon
);
2359 Results
.AddResult(Result(Builder
.TakeString()));
2362 Builder
.AddTypedTextChunk("default");
2363 Builder
.AddChunk(CodeCompletionString::CK_Colon
);
2364 Results
.AddResult(Result(Builder
.TakeString()));
2367 if (Results
.includeCodePatterns()) {
2368 /// while (condition) { statements }
2369 Builder
.AddTypedTextChunk("while");
2370 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2371 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
2372 if (SemaRef
.getLangOpts().CPlusPlus
)
2373 Builder
.AddPlaceholderChunk("condition");
2375 Builder
.AddPlaceholderChunk("expression");
2376 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
2377 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2378 Builder
.AddChunk(CodeCompletionString::CK_LeftBrace
);
2379 Builder
.AddChunk(CodeCompletionString::CK_VerticalSpace
);
2380 Builder
.AddPlaceholderChunk("statements");
2381 Builder
.AddChunk(CodeCompletionString::CK_VerticalSpace
);
2382 Builder
.AddChunk(CodeCompletionString::CK_RightBrace
);
2383 Results
.AddResult(Result(Builder
.TakeString()));
2385 // do { statements } while ( expression );
2386 Builder
.AddTypedTextChunk("do");
2387 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2388 Builder
.AddChunk(CodeCompletionString::CK_LeftBrace
);
2389 Builder
.AddChunk(CodeCompletionString::CK_VerticalSpace
);
2390 Builder
.AddPlaceholderChunk("statements");
2391 Builder
.AddChunk(CodeCompletionString::CK_VerticalSpace
);
2392 Builder
.AddChunk(CodeCompletionString::CK_RightBrace
);
2393 Builder
.AddTextChunk("while");
2394 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2395 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
2396 Builder
.AddPlaceholderChunk("expression");
2397 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
2398 Results
.AddResult(Result(Builder
.TakeString()));
2400 // for ( for-init-statement ; condition ; expression ) { statements }
2401 Builder
.AddTypedTextChunk("for");
2402 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2403 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
2404 if (SemaRef
.getLangOpts().CPlusPlus
|| SemaRef
.getLangOpts().C99
)
2405 Builder
.AddPlaceholderChunk("init-statement");
2407 Builder
.AddPlaceholderChunk("init-expression");
2408 Builder
.AddChunk(CodeCompletionString::CK_SemiColon
);
2409 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2410 Builder
.AddPlaceholderChunk("condition");
2411 Builder
.AddChunk(CodeCompletionString::CK_SemiColon
);
2412 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2413 Builder
.AddPlaceholderChunk("inc-expression");
2414 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
2415 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2416 Builder
.AddChunk(CodeCompletionString::CK_LeftBrace
);
2417 Builder
.AddChunk(CodeCompletionString::CK_VerticalSpace
);
2418 Builder
.AddPlaceholderChunk("statements");
2419 Builder
.AddChunk(CodeCompletionString::CK_VerticalSpace
);
2420 Builder
.AddChunk(CodeCompletionString::CK_RightBrace
);
2421 Results
.AddResult(Result(Builder
.TakeString()));
2423 if (SemaRef
.getLangOpts().CPlusPlus11
|| SemaRef
.getLangOpts().ObjC
) {
2424 // for ( range_declaration (:|in) range_expression ) { statements }
2425 Builder
.AddTypedTextChunk("for");
2426 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2427 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
2428 Builder
.AddPlaceholderChunk("range-declaration");
2429 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2430 if (SemaRef
.getLangOpts().ObjC
)
2431 Builder
.AddTextChunk("in");
2433 Builder
.AddChunk(CodeCompletionString::CK_Colon
);
2434 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2435 Builder
.AddPlaceholderChunk("range-expression");
2436 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
2437 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2438 Builder
.AddChunk(CodeCompletionString::CK_LeftBrace
);
2439 Builder
.AddChunk(CodeCompletionString::CK_VerticalSpace
);
2440 Builder
.AddPlaceholderChunk("statements");
2441 Builder
.AddChunk(CodeCompletionString::CK_VerticalSpace
);
2442 Builder
.AddChunk(CodeCompletionString::CK_RightBrace
);
2443 Results
.AddResult(Result(Builder
.TakeString()));
2447 if (S
->getContinueParent()) {
2449 Builder
.AddTypedTextChunk("continue");
2450 Builder
.AddChunk(CodeCompletionString::CK_SemiColon
);
2451 Results
.AddResult(Result(Builder
.TakeString()));
2454 if (S
->getBreakParent()) {
2456 Builder
.AddTypedTextChunk("break");
2457 Builder
.AddChunk(CodeCompletionString::CK_SemiColon
);
2458 Results
.AddResult(Result(Builder
.TakeString()));
2461 // "return expression ;" or "return ;", depending on the return type.
2462 QualType ReturnType
;
2463 if (const auto *Function
= dyn_cast
<FunctionDecl
>(SemaRef
.CurContext
))
2464 ReturnType
= Function
->getReturnType();
2465 else if (const auto *Method
= dyn_cast
<ObjCMethodDecl
>(SemaRef
.CurContext
))
2466 ReturnType
= Method
->getReturnType();
2467 else if (SemaRef
.getCurBlock() &&
2468 !SemaRef
.getCurBlock()->ReturnType
.isNull())
2469 ReturnType
= SemaRef
.getCurBlock()->ReturnType
;;
2470 if (ReturnType
.isNull() || ReturnType
->isVoidType()) {
2471 Builder
.AddTypedTextChunk("return");
2472 Builder
.AddChunk(CodeCompletionString::CK_SemiColon
);
2473 Results
.AddResult(Result(Builder
.TakeString()));
2475 assert(!ReturnType
.isNull());
2476 // "return expression ;"
2477 Builder
.AddTypedTextChunk("return");
2478 Builder
.AddChunk(clang::CodeCompletionString::CK_HorizontalSpace
);
2479 Builder
.AddPlaceholderChunk("expression");
2480 Builder
.AddChunk(CodeCompletionString::CK_SemiColon
);
2481 Results
.AddResult(Result(Builder
.TakeString()));
2482 // When boolean, also add 'return true;' and 'return false;'.
2483 if (ReturnType
->isBooleanType()) {
2484 Builder
.AddTypedTextChunk("return true");
2485 Builder
.AddChunk(CodeCompletionString::CK_SemiColon
);
2486 Results
.AddResult(Result(Builder
.TakeString()));
2488 Builder
.AddTypedTextChunk("return false");
2489 Builder
.AddChunk(CodeCompletionString::CK_SemiColon
);
2490 Results
.AddResult(Result(Builder
.TakeString()));
2492 // For pointers, suggest 'return nullptr' in C++.
2493 if (SemaRef
.getLangOpts().CPlusPlus11
&&
2494 (ReturnType
->isPointerType() || ReturnType
->isMemberPointerType())) {
2495 Builder
.AddTypedTextChunk("return nullptr");
2496 Builder
.AddChunk(CodeCompletionString::CK_SemiColon
);
2497 Results
.AddResult(Result(Builder
.TakeString()));
2501 // goto identifier ;
2502 Builder
.AddTypedTextChunk("goto");
2503 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2504 Builder
.AddPlaceholderChunk("label");
2505 Builder
.AddChunk(CodeCompletionString::CK_SemiColon
);
2506 Results
.AddResult(Result(Builder
.TakeString()));
2509 Builder
.AddTypedTextChunk("using namespace");
2510 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2511 Builder
.AddPlaceholderChunk("identifier");
2512 Builder
.AddChunk(CodeCompletionString::CK_SemiColon
);
2513 Results
.AddResult(Result(Builder
.TakeString()));
2515 AddStaticAssertResult(Builder
, Results
, SemaRef
.getLangOpts());
2519 // Fall through (for statement expressions).
2520 case Sema::PCC_ForInit
:
2521 case Sema::PCC_Condition
:
2522 AddStorageSpecifiers(CCC
, SemaRef
.getLangOpts(), Results
);
2523 // Fall through: conditions and statements can have expressions.
2526 case Sema::PCC_ParenthesizedExpression
:
2527 if (SemaRef
.getLangOpts().ObjCAutoRefCount
&&
2528 CCC
== Sema::PCC_ParenthesizedExpression
) {
2529 // (__bridge <type>)<expression>
2530 Builder
.AddTypedTextChunk("__bridge");
2531 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2532 Builder
.AddPlaceholderChunk("type");
2533 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
2534 Builder
.AddPlaceholderChunk("expression");
2535 Results
.AddResult(Result(Builder
.TakeString()));
2537 // (__bridge_transfer <Objective-C type>)<expression>
2538 Builder
.AddTypedTextChunk("__bridge_transfer");
2539 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2540 Builder
.AddPlaceholderChunk("Objective-C type");
2541 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
2542 Builder
.AddPlaceholderChunk("expression");
2543 Results
.AddResult(Result(Builder
.TakeString()));
2545 // (__bridge_retained <CF type>)<expression>
2546 Builder
.AddTypedTextChunk("__bridge_retained");
2547 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2548 Builder
.AddPlaceholderChunk("CF type");
2549 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
2550 Builder
.AddPlaceholderChunk("expression");
2551 Results
.AddResult(Result(Builder
.TakeString()));
2556 case Sema::PCC_Expression
: {
2557 if (SemaRef
.getLangOpts().CPlusPlus
) {
2558 // 'this', if we're in a non-static member function.
2559 addThisCompletion(SemaRef
, Results
);
2562 Builder
.AddResultTypeChunk("bool");
2563 Builder
.AddTypedTextChunk("true");
2564 Results
.AddResult(Result(Builder
.TakeString()));
2567 Builder
.AddResultTypeChunk("bool");
2568 Builder
.AddTypedTextChunk("false");
2569 Results
.AddResult(Result(Builder
.TakeString()));
2571 if (SemaRef
.getLangOpts().RTTI
) {
2572 // dynamic_cast < type-id > ( expression )
2573 Builder
.AddTypedTextChunk("dynamic_cast");
2574 Builder
.AddChunk(CodeCompletionString::CK_LeftAngle
);
2575 Builder
.AddPlaceholderChunk("type");
2576 Builder
.AddChunk(CodeCompletionString::CK_RightAngle
);
2577 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
2578 Builder
.AddPlaceholderChunk("expression");
2579 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
2580 Results
.AddResult(Result(Builder
.TakeString()));
2583 // static_cast < type-id > ( expression )
2584 Builder
.AddTypedTextChunk("static_cast");
2585 Builder
.AddChunk(CodeCompletionString::CK_LeftAngle
);
2586 Builder
.AddPlaceholderChunk("type");
2587 Builder
.AddChunk(CodeCompletionString::CK_RightAngle
);
2588 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
2589 Builder
.AddPlaceholderChunk("expression");
2590 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
2591 Results
.AddResult(Result(Builder
.TakeString()));
2593 // reinterpret_cast < type-id > ( expression )
2594 Builder
.AddTypedTextChunk("reinterpret_cast");
2595 Builder
.AddChunk(CodeCompletionString::CK_LeftAngle
);
2596 Builder
.AddPlaceholderChunk("type");
2597 Builder
.AddChunk(CodeCompletionString::CK_RightAngle
);
2598 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
2599 Builder
.AddPlaceholderChunk("expression");
2600 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
2601 Results
.AddResult(Result(Builder
.TakeString()));
2603 // const_cast < type-id > ( expression )
2604 Builder
.AddTypedTextChunk("const_cast");
2605 Builder
.AddChunk(CodeCompletionString::CK_LeftAngle
);
2606 Builder
.AddPlaceholderChunk("type");
2607 Builder
.AddChunk(CodeCompletionString::CK_RightAngle
);
2608 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
2609 Builder
.AddPlaceholderChunk("expression");
2610 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
2611 Results
.AddResult(Result(Builder
.TakeString()));
2613 if (SemaRef
.getLangOpts().RTTI
) {
2614 // typeid ( expression-or-type )
2615 Builder
.AddResultTypeChunk("std::type_info");
2616 Builder
.AddTypedTextChunk("typeid");
2617 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
2618 Builder
.AddPlaceholderChunk("expression-or-type");
2619 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
2620 Results
.AddResult(Result(Builder
.TakeString()));
2624 Builder
.AddTypedTextChunk("new");
2625 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2626 Builder
.AddPlaceholderChunk("type");
2627 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
2628 Builder
.AddPlaceholderChunk("expressions");
2629 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
2630 Results
.AddResult(Result(Builder
.TakeString()));
2632 // new T [ ] ( ... )
2633 Builder
.AddTypedTextChunk("new");
2634 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2635 Builder
.AddPlaceholderChunk("type");
2636 Builder
.AddChunk(CodeCompletionString::CK_LeftBracket
);
2637 Builder
.AddPlaceholderChunk("size");
2638 Builder
.AddChunk(CodeCompletionString::CK_RightBracket
);
2639 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
2640 Builder
.AddPlaceholderChunk("expressions");
2641 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
2642 Results
.AddResult(Result(Builder
.TakeString()));
2644 // delete expression
2645 Builder
.AddResultTypeChunk("void");
2646 Builder
.AddTypedTextChunk("delete");
2647 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2648 Builder
.AddPlaceholderChunk("expression");
2649 Results
.AddResult(Result(Builder
.TakeString()));
2651 // delete [] expression
2652 Builder
.AddResultTypeChunk("void");
2653 Builder
.AddTypedTextChunk("delete");
2654 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2655 Builder
.AddChunk(CodeCompletionString::CK_LeftBracket
);
2656 Builder
.AddChunk(CodeCompletionString::CK_RightBracket
);
2657 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2658 Builder
.AddPlaceholderChunk("expression");
2659 Results
.AddResult(Result(Builder
.TakeString()));
2661 if (SemaRef
.getLangOpts().CXXExceptions
) {
2663 Builder
.AddResultTypeChunk("void");
2664 Builder
.AddTypedTextChunk("throw");
2665 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2666 Builder
.AddPlaceholderChunk("expression");
2667 Results
.AddResult(Result(Builder
.TakeString()));
2672 if (SemaRef
.getLangOpts().CPlusPlus11
) {
2674 Builder
.AddResultTypeChunk("std::nullptr_t");
2675 Builder
.AddTypedTextChunk("nullptr");
2676 Results
.AddResult(Result(Builder
.TakeString()));
2679 Builder
.AddResultTypeChunk("size_t");
2680 Builder
.AddTypedTextChunk("alignof");
2681 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
2682 Builder
.AddPlaceholderChunk("type");
2683 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
2684 Results
.AddResult(Result(Builder
.TakeString()));
2687 Builder
.AddResultTypeChunk("bool");
2688 Builder
.AddTypedTextChunk("noexcept");
2689 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
2690 Builder
.AddPlaceholderChunk("expression");
2691 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
2692 Results
.AddResult(Result(Builder
.TakeString()));
2694 // sizeof... expression
2695 Builder
.AddResultTypeChunk("size_t");
2696 Builder
.AddTypedTextChunk("sizeof...");
2697 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
2698 Builder
.AddPlaceholderChunk("parameter-pack");
2699 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
2700 Results
.AddResult(Result(Builder
.TakeString()));
2704 if (SemaRef
.getLangOpts().ObjC
) {
2705 // Add "super", if we're in an Objective-C class with a superclass.
2706 if (ObjCMethodDecl
*Method
= SemaRef
.getCurMethodDecl()) {
2707 // The interface can be NULL.
2708 if (ObjCInterfaceDecl
*ID
= Method
->getClassInterface())
2709 if (ID
->getSuperClass()) {
2710 std::string SuperType
;
2711 SuperType
= ID
->getSuperClass()->getNameAsString();
2712 if (Method
->isInstanceMethod())
2715 Builder
.AddResultTypeChunk(Allocator
.CopyString(SuperType
));
2716 Builder
.AddTypedTextChunk("super");
2717 Results
.AddResult(Result(Builder
.TakeString()));
2721 AddObjCExpressionResults(Results
, true);
2724 if (SemaRef
.getLangOpts().C11
) {
2726 Builder
.AddResultTypeChunk("size_t");
2727 if (SemaRef
.PP
.isMacroDefined("alignof"))
2728 Builder
.AddTypedTextChunk("alignof");
2730 Builder
.AddTypedTextChunk("_Alignof");
2731 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
2732 Builder
.AddPlaceholderChunk("type");
2733 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
2734 Results
.AddResult(Result(Builder
.TakeString()));
2737 if (SemaRef
.getLangOpts().C23
) {
2739 Builder
.AddResultTypeChunk("nullptr_t");
2740 Builder
.AddTypedTextChunk("nullptr");
2741 Results
.AddResult(Result(Builder
.TakeString()));
2744 // sizeof expression
2745 Builder
.AddResultTypeChunk("size_t");
2746 Builder
.AddTypedTextChunk("sizeof");
2747 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
2748 Builder
.AddPlaceholderChunk("expression-or-type");
2749 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
2750 Results
.AddResult(Result(Builder
.TakeString()));
2754 case Sema::PCC_Type
:
2755 case Sema::PCC_LocalDeclarationSpecifiers
:
2759 if (WantTypesInContext(CCC
, SemaRef
.getLangOpts()))
2760 AddTypeSpecifierResults(SemaRef
.getLangOpts(), Results
);
2762 if (SemaRef
.getLangOpts().CPlusPlus
&& CCC
!= Sema::PCC_Type
)
2763 Results
.AddResult(Result("operator"));
2766 /// If the given declaration has an associated type, add it as a result
2768 static void AddResultTypeChunk(ASTContext
&Context
,
2769 const PrintingPolicy
&Policy
,
2770 const NamedDecl
*ND
, QualType BaseType
,
2771 CodeCompletionBuilder
&Result
) {
2775 // Skip constructors and conversion functions, which have their return types
2776 // built into their names.
2777 if (isConstructor(ND
) || isa
<CXXConversionDecl
>(ND
))
2780 // Determine the type of the declaration (if it has a type).
2782 if (const FunctionDecl
*Function
= ND
->getAsFunction())
2783 T
= Function
->getReturnType();
2784 else if (const auto *Method
= dyn_cast
<ObjCMethodDecl
>(ND
)) {
2785 if (!BaseType
.isNull())
2786 T
= Method
->getSendResultType(BaseType
);
2788 T
= Method
->getReturnType();
2789 } else if (const auto *Enumerator
= dyn_cast
<EnumConstantDecl
>(ND
)) {
2790 T
= Context
.getTypeDeclType(cast
<TypeDecl
>(Enumerator
->getDeclContext()));
2791 T
= clang::TypeName::getFullyQualifiedType(T
, Context
);
2792 } else if (isa
<UnresolvedUsingValueDecl
>(ND
)) {
2793 /* Do nothing: ignore unresolved using declarations*/
2794 } else if (const auto *Ivar
= dyn_cast
<ObjCIvarDecl
>(ND
)) {
2795 if (!BaseType
.isNull())
2796 T
= Ivar
->getUsageType(BaseType
);
2798 T
= Ivar
->getType();
2799 } else if (const auto *Value
= dyn_cast
<ValueDecl
>(ND
)) {
2800 T
= Value
->getType();
2801 } else if (const auto *Property
= dyn_cast
<ObjCPropertyDecl
>(ND
)) {
2802 if (!BaseType
.isNull())
2803 T
= Property
->getUsageType(BaseType
);
2805 T
= Property
->getType();
2808 if (T
.isNull() || Context
.hasSameType(T
, Context
.DependentTy
))
2811 Result
.AddResultTypeChunk(
2812 GetCompletionTypeString(T
, Context
, Policy
, Result
.getAllocator()));
2815 static void MaybeAddSentinel(Preprocessor
&PP
,
2816 const NamedDecl
*FunctionOrMethod
,
2817 CodeCompletionBuilder
&Result
) {
2818 if (SentinelAttr
*Sentinel
= FunctionOrMethod
->getAttr
<SentinelAttr
>())
2819 if (Sentinel
->getSentinel() == 0) {
2820 if (PP
.getLangOpts().ObjC
&& PP
.isMacroDefined("nil"))
2821 Result
.AddTextChunk(", nil");
2822 else if (PP
.isMacroDefined("NULL"))
2823 Result
.AddTextChunk(", NULL");
2825 Result
.AddTextChunk(", (void*)0");
2829 static std::string
formatObjCParamQualifiers(unsigned ObjCQuals
,
2832 if (ObjCQuals
& Decl::OBJC_TQ_In
)
2834 else if (ObjCQuals
& Decl::OBJC_TQ_Inout
)
2836 else if (ObjCQuals
& Decl::OBJC_TQ_Out
)
2838 if (ObjCQuals
& Decl::OBJC_TQ_Bycopy
)
2839 Result
+= "bycopy ";
2840 else if (ObjCQuals
& Decl::OBJC_TQ_Byref
)
2842 if (ObjCQuals
& Decl::OBJC_TQ_Oneway
)
2843 Result
+= "oneway ";
2844 if (ObjCQuals
& Decl::OBJC_TQ_CSNullability
) {
2845 if (auto nullability
= AttributedType::stripOuterNullability(Type
)) {
2846 switch (*nullability
) {
2847 case NullabilityKind::NonNull
:
2848 Result
+= "nonnull ";
2851 case NullabilityKind::Nullable
:
2852 Result
+= "nullable ";
2855 case NullabilityKind::Unspecified
:
2856 Result
+= "null_unspecified ";
2859 case NullabilityKind::NullableResult
:
2860 llvm_unreachable("Not supported as a context-sensitive keyword!");
2868 /// Tries to find the most appropriate type location for an Objective-C
2869 /// block placeholder.
2871 /// This function ignores things like typedefs and qualifiers in order to
2872 /// present the most relevant and accurate block placeholders in code completion
2874 static void findTypeLocationForBlockDecl(const TypeSourceInfo
*TSInfo
,
2875 FunctionTypeLoc
&Block
,
2876 FunctionProtoTypeLoc
&BlockProto
,
2877 bool SuppressBlock
= false) {
2880 TypeLoc TL
= TSInfo
->getTypeLoc().getUnqualifiedLoc();
2882 // Look through typedefs.
2883 if (!SuppressBlock
) {
2884 if (TypedefTypeLoc TypedefTL
= TL
.getAsAdjusted
<TypedefTypeLoc
>()) {
2885 if (TypeSourceInfo
*InnerTSInfo
=
2886 TypedefTL
.getTypedefNameDecl()->getTypeSourceInfo()) {
2887 TL
= InnerTSInfo
->getTypeLoc().getUnqualifiedLoc();
2892 // Look through qualified types
2893 if (QualifiedTypeLoc QualifiedTL
= TL
.getAs
<QualifiedTypeLoc
>()) {
2894 TL
= QualifiedTL
.getUnqualifiedLoc();
2898 if (AttributedTypeLoc AttrTL
= TL
.getAs
<AttributedTypeLoc
>()) {
2899 TL
= AttrTL
.getModifiedLoc();
2904 // Try to get the function prototype behind the block pointer type,
2906 if (BlockPointerTypeLoc BlockPtr
= TL
.getAs
<BlockPointerTypeLoc
>()) {
2907 TL
= BlockPtr
.getPointeeLoc().IgnoreParens();
2908 Block
= TL
.getAs
<FunctionTypeLoc
>();
2909 BlockProto
= TL
.getAs
<FunctionProtoTypeLoc
>();
2915 static std::string
formatBlockPlaceholder(
2916 const PrintingPolicy
&Policy
, const NamedDecl
*BlockDecl
,
2917 FunctionTypeLoc
&Block
, FunctionProtoTypeLoc
&BlockProto
,
2918 bool SuppressBlockName
= false, bool SuppressBlock
= false,
2919 std::optional
<ArrayRef
<QualType
>> ObjCSubsts
= std::nullopt
);
2921 static std::string
FormatFunctionParameter(
2922 const PrintingPolicy
&Policy
, const DeclaratorDecl
*Param
,
2923 bool SuppressName
= false, bool SuppressBlock
= false,
2924 std::optional
<ArrayRef
<QualType
>> ObjCSubsts
= std::nullopt
) {
2925 // Params are unavailable in FunctionTypeLoc if the FunctionType is invalid.
2926 // It would be better to pass in the param Type, which is usually available.
2927 // But this case is rare, so just pretend we fell back to int as elsewhere.
2930 Decl::ObjCDeclQualifier ObjCQual
= Decl::OBJC_TQ_None
;
2931 if (const auto *PVD
= dyn_cast
<ParmVarDecl
>(Param
))
2932 ObjCQual
= PVD
->getObjCDeclQualifier();
2933 bool ObjCMethodParam
= isa
<ObjCMethodDecl
>(Param
->getDeclContext());
2934 if (Param
->getType()->isDependentType() ||
2935 !Param
->getType()->isBlockPointerType()) {
2936 // The argument for a dependent or non-block parameter is a placeholder
2937 // containing that parameter's type.
2940 if (Param
->getIdentifier() && !ObjCMethodParam
&& !SuppressName
)
2941 Result
= std::string(Param
->getIdentifier()->deuglifiedName());
2943 QualType Type
= Param
->getType();
2945 Type
= Type
.substObjCTypeArgs(Param
->getASTContext(), *ObjCSubsts
,
2946 ObjCSubstitutionContext::Parameter
);
2947 if (ObjCMethodParam
) {
2948 Result
= "(" + formatObjCParamQualifiers(ObjCQual
, Type
);
2949 Result
+= Type
.getAsString(Policy
) + ")";
2950 if (Param
->getIdentifier() && !SuppressName
)
2951 Result
+= Param
->getIdentifier()->deuglifiedName();
2953 Type
.getAsStringInternal(Result
, Policy
);
2958 // The argument for a block pointer parameter is a block literal with
2959 // the appropriate type.
2960 FunctionTypeLoc Block
;
2961 FunctionProtoTypeLoc BlockProto
;
2962 findTypeLocationForBlockDecl(Param
->getTypeSourceInfo(), Block
, BlockProto
,
2964 // Try to retrieve the block type information from the property if this is a
2965 // parameter in a setter.
2966 if (!Block
&& ObjCMethodParam
&&
2967 cast
<ObjCMethodDecl
>(Param
->getDeclContext())->isPropertyAccessor()) {
2968 if (const auto *PD
= cast
<ObjCMethodDecl
>(Param
->getDeclContext())
2969 ->findPropertyDecl(/*CheckOverrides=*/false))
2970 findTypeLocationForBlockDecl(PD
->getTypeSourceInfo(), Block
, BlockProto
,
2975 // We were unable to find a FunctionProtoTypeLoc with parameter names
2976 // for the block; just use the parameter type as a placeholder.
2978 if (!ObjCMethodParam
&& Param
->getIdentifier())
2979 Result
= std::string(Param
->getIdentifier()->deuglifiedName());
2981 QualType Type
= Param
->getType().getUnqualifiedType();
2983 if (ObjCMethodParam
) {
2984 Result
= Type
.getAsString(Policy
);
2985 std::string Quals
= formatObjCParamQualifiers(ObjCQual
, Type
);
2987 Result
= "(" + Quals
+ " " + Result
+ ")";
2988 if (Result
.back() != ')')
2990 if (Param
->getIdentifier())
2991 Result
+= Param
->getIdentifier()->deuglifiedName();
2993 Type
.getAsStringInternal(Result
, Policy
);
2999 // We have the function prototype behind the block pointer type, as it was
3000 // written in the source.
3001 return formatBlockPlaceholder(Policy
, Param
, Block
, BlockProto
,
3002 /*SuppressBlockName=*/false, SuppressBlock
,
3006 /// Returns a placeholder string that corresponds to an Objective-C block
3009 /// \param BlockDecl A declaration with an Objective-C block type.
3011 /// \param Block The most relevant type location for that block type.
3013 /// \param SuppressBlockName Determines whether or not the name of the block
3014 /// declaration is included in the resulting string.
3016 formatBlockPlaceholder(const PrintingPolicy
&Policy
, const NamedDecl
*BlockDecl
,
3017 FunctionTypeLoc
&Block
, FunctionProtoTypeLoc
&BlockProto
,
3018 bool SuppressBlockName
, bool SuppressBlock
,
3019 std::optional
<ArrayRef
<QualType
>> ObjCSubsts
) {
3021 QualType ResultType
= Block
.getTypePtr()->getReturnType();
3024 ResultType
.substObjCTypeArgs(BlockDecl
->getASTContext(), *ObjCSubsts
,
3025 ObjCSubstitutionContext::Result
);
3026 if (!ResultType
->isVoidType() || SuppressBlock
)
3027 ResultType
.getAsStringInternal(Result
, Policy
);
3029 // Format the parameter list.
3031 if (!BlockProto
|| Block
.getNumParams() == 0) {
3032 if (BlockProto
&& BlockProto
.getTypePtr()->isVariadic())
3038 for (unsigned I
= 0, N
= Block
.getNumParams(); I
!= N
; ++I
) {
3041 Params
+= FormatFunctionParameter(Policy
, Block
.getParam(I
),
3042 /*SuppressName=*/false,
3043 /*SuppressBlock=*/true, ObjCSubsts
);
3045 if (I
== N
- 1 && BlockProto
.getTypePtr()->isVariadic())
3051 if (SuppressBlock
) {
3052 // Format as a parameter.
3053 Result
= Result
+ " (^";
3054 if (!SuppressBlockName
&& BlockDecl
->getIdentifier())
3055 Result
+= BlockDecl
->getIdentifier()->getName();
3059 // Format as a block literal argument.
3060 Result
= '^' + Result
;
3063 if (!SuppressBlockName
&& BlockDecl
->getIdentifier())
3064 Result
+= BlockDecl
->getIdentifier()->getName();
3070 static std::string
GetDefaultValueString(const ParmVarDecl
*Param
,
3071 const SourceManager
&SM
,
3072 const LangOptions
&LangOpts
) {
3073 const SourceRange SrcRange
= Param
->getDefaultArgRange();
3074 CharSourceRange CharSrcRange
= CharSourceRange::getTokenRange(SrcRange
);
3075 bool Invalid
= CharSrcRange
.isInvalid();
3079 Lexer::getSourceText(CharSrcRange
, SM
, LangOpts
, &Invalid
);
3083 if (srcText
.empty() || srcText
== "=") {
3084 // Lexer can't determine the value.
3085 // This happens if the code is incorrect (for example class is forward
3089 std::string
DefValue(srcText
.str());
3090 // FIXME: remove this check if the Lexer::getSourceText value is fixed and
3091 // this value always has (or always does not have) '=' in front of it
3092 if (DefValue
.at(0) != '=') {
3093 // If we don't have '=' in front of value.
3094 // Lexer returns built-in types values without '=' and user-defined types
3096 return " = " + DefValue
;
3098 return " " + DefValue
;
3101 /// Add function parameter chunks to the given code completion string.
3102 static void AddFunctionParameterChunks(Preprocessor
&PP
,
3103 const PrintingPolicy
&Policy
,
3104 const FunctionDecl
*Function
,
3105 CodeCompletionBuilder
&Result
,
3107 bool InOptional
= false) {
3108 bool FirstParameter
= true;
3110 for (unsigned P
= Start
, N
= Function
->getNumParams(); P
!= N
; ++P
) {
3111 const ParmVarDecl
*Param
= Function
->getParamDecl(P
);
3113 if (Param
->hasDefaultArg() && !InOptional
) {
3114 // When we see an optional default argument, put that argument and
3115 // the remaining default arguments into a new, optional string.
3116 CodeCompletionBuilder
Opt(Result
.getAllocator(),
3117 Result
.getCodeCompletionTUInfo());
3118 if (!FirstParameter
)
3119 Opt
.AddChunk(CodeCompletionString::CK_Comma
);
3120 AddFunctionParameterChunks(PP
, Policy
, Function
, Opt
, P
, true);
3121 Result
.AddOptionalChunk(Opt
.TakeString());
3126 FirstParameter
= false;
3128 Result
.AddChunk(CodeCompletionString::CK_Comma
);
3132 // Format the placeholder string.
3133 std::string PlaceholderStr
= FormatFunctionParameter(Policy
, Param
);
3134 if (Param
->hasDefaultArg())
3136 GetDefaultValueString(Param
, PP
.getSourceManager(), PP
.getLangOpts());
3138 if (Function
->isVariadic() && P
== N
- 1)
3139 PlaceholderStr
+= ", ...";
3141 // Add the placeholder string.
3142 Result
.AddPlaceholderChunk(
3143 Result
.getAllocator().CopyString(PlaceholderStr
));
3146 if (const auto *Proto
= Function
->getType()->getAs
<FunctionProtoType
>())
3147 if (Proto
->isVariadic()) {
3148 if (Proto
->getNumParams() == 0)
3149 Result
.AddPlaceholderChunk("...");
3151 MaybeAddSentinel(PP
, Function
, Result
);
3155 /// Add template parameter chunks to the given code completion string.
3156 static void AddTemplateParameterChunks(
3157 ASTContext
&Context
, const PrintingPolicy
&Policy
,
3158 const TemplateDecl
*Template
, CodeCompletionBuilder
&Result
,
3159 unsigned MaxParameters
= 0, unsigned Start
= 0, bool InDefaultArg
= false) {
3160 bool FirstParameter
= true;
3162 // Prefer to take the template parameter names from the first declaration of
3164 Template
= cast
<TemplateDecl
>(Template
->getCanonicalDecl());
3166 TemplateParameterList
*Params
= Template
->getTemplateParameters();
3167 TemplateParameterList::iterator PEnd
= Params
->end();
3169 PEnd
= Params
->begin() + MaxParameters
;
3170 for (TemplateParameterList::iterator P
= Params
->begin() + Start
; P
!= PEnd
;
3172 bool HasDefaultArg
= false;
3173 std::string PlaceholderStr
;
3174 if (TemplateTypeParmDecl
*TTP
= dyn_cast
<TemplateTypeParmDecl
>(*P
)) {
3175 if (TTP
->wasDeclaredWithTypename())
3176 PlaceholderStr
= "typename";
3177 else if (const auto *TC
= TTP
->getTypeConstraint()) {
3178 llvm::raw_string_ostream
OS(PlaceholderStr
);
3179 TC
->print(OS
, Policy
);
3182 PlaceholderStr
= "class";
3184 if (TTP
->getIdentifier()) {
3185 PlaceholderStr
+= ' ';
3186 PlaceholderStr
+= TTP
->getIdentifier()->deuglifiedName();
3189 HasDefaultArg
= TTP
->hasDefaultArgument();
3190 } else if (NonTypeTemplateParmDecl
*NTTP
=
3191 dyn_cast
<NonTypeTemplateParmDecl
>(*P
)) {
3192 if (NTTP
->getIdentifier())
3193 PlaceholderStr
= std::string(NTTP
->getIdentifier()->deuglifiedName());
3194 NTTP
->getType().getAsStringInternal(PlaceholderStr
, Policy
);
3195 HasDefaultArg
= NTTP
->hasDefaultArgument();
3197 assert(isa
<TemplateTemplateParmDecl
>(*P
));
3198 TemplateTemplateParmDecl
*TTP
= cast
<TemplateTemplateParmDecl
>(*P
);
3200 // Since putting the template argument list into the placeholder would
3201 // be very, very long, we just use an abbreviation.
3202 PlaceholderStr
= "template<...> class";
3203 if (TTP
->getIdentifier()) {
3204 PlaceholderStr
+= ' ';
3205 PlaceholderStr
+= TTP
->getIdentifier()->deuglifiedName();
3208 HasDefaultArg
= TTP
->hasDefaultArgument();
3211 if (HasDefaultArg
&& !InDefaultArg
) {
3212 // When we see an optional default argument, put that argument and
3213 // the remaining default arguments into a new, optional string.
3214 CodeCompletionBuilder
Opt(Result
.getAllocator(),
3215 Result
.getCodeCompletionTUInfo());
3216 if (!FirstParameter
)
3217 Opt
.AddChunk(CodeCompletionString::CK_Comma
);
3218 AddTemplateParameterChunks(Context
, Policy
, Template
, Opt
, MaxParameters
,
3219 P
- Params
->begin(), true);
3220 Result
.AddOptionalChunk(Opt
.TakeString());
3224 InDefaultArg
= false;
3227 FirstParameter
= false;
3229 Result
.AddChunk(CodeCompletionString::CK_Comma
);
3231 // Add the placeholder string.
3232 Result
.AddPlaceholderChunk(
3233 Result
.getAllocator().CopyString(PlaceholderStr
));
3237 /// Add a qualifier to the given code-completion string, if the
3238 /// provided nested-name-specifier is non-NULL.
3239 static void AddQualifierToCompletionString(CodeCompletionBuilder
&Result
,
3240 NestedNameSpecifier
*Qualifier
,
3241 bool QualifierIsInformative
,
3242 ASTContext
&Context
,
3243 const PrintingPolicy
&Policy
) {
3247 std::string PrintedNNS
;
3249 llvm::raw_string_ostream
OS(PrintedNNS
);
3250 Qualifier
->print(OS
, Policy
);
3252 if (QualifierIsInformative
)
3253 Result
.AddInformativeChunk(Result
.getAllocator().CopyString(PrintedNNS
));
3255 Result
.AddTextChunk(Result
.getAllocator().CopyString(PrintedNNS
));
3259 AddFunctionTypeQualsToCompletionString(CodeCompletionBuilder
&Result
,
3260 const FunctionDecl
*Function
) {
3261 const auto *Proto
= Function
->getType()->getAs
<FunctionProtoType
>();
3262 if (!Proto
|| !Proto
->getMethodQuals())
3265 // FIXME: Add ref-qualifier!
3267 // Handle single qualifiers without copying
3268 if (Proto
->getMethodQuals().hasOnlyConst()) {
3269 Result
.AddInformativeChunk(" const");
3273 if (Proto
->getMethodQuals().hasOnlyVolatile()) {
3274 Result
.AddInformativeChunk(" volatile");
3278 if (Proto
->getMethodQuals().hasOnlyRestrict()) {
3279 Result
.AddInformativeChunk(" restrict");
3283 // Handle multiple qualifiers.
3284 std::string QualsStr
;
3285 if (Proto
->isConst())
3286 QualsStr
+= " const";
3287 if (Proto
->isVolatile())
3288 QualsStr
+= " volatile";
3289 if (Proto
->isRestrict())
3290 QualsStr
+= " restrict";
3291 Result
.AddInformativeChunk(Result
.getAllocator().CopyString(QualsStr
));
3294 /// Add the name of the given declaration
3295 static void AddTypedNameChunk(ASTContext
&Context
, const PrintingPolicy
&Policy
,
3296 const NamedDecl
*ND
,
3297 CodeCompletionBuilder
&Result
) {
3298 DeclarationName Name
= ND
->getDeclName();
3302 switch (Name
.getNameKind()) {
3303 case DeclarationName::CXXOperatorName
: {
3304 const char *OperatorName
= nullptr;
3305 switch (Name
.getCXXOverloadedOperator()) {
3307 case OO_Conditional
:
3308 case NUM_OVERLOADED_OPERATORS
:
3309 OperatorName
= "operator";
3312 #define OVERLOADED_OPERATOR(Name, Spelling, Token, Unary, Binary, MemberOnly) \
3314 OperatorName = "operator" Spelling; \
3316 #define OVERLOADED_OPERATOR_MULTI(Name, Spelling, Unary, Binary, MemberOnly)
3317 #include "clang/Basic/OperatorKinds.def"
3320 OperatorName
= "operator new";
3323 OperatorName
= "operator delete";
3326 OperatorName
= "operator new[]";
3328 case OO_Array_Delete
:
3329 OperatorName
= "operator delete[]";
3332 OperatorName
= "operator()";
3335 OperatorName
= "operator[]";
3338 Result
.AddTypedTextChunk(OperatorName
);
3342 case DeclarationName::Identifier
:
3343 case DeclarationName::CXXConversionFunctionName
:
3344 case DeclarationName::CXXDestructorName
:
3345 case DeclarationName::CXXLiteralOperatorName
:
3346 Result
.AddTypedTextChunk(
3347 Result
.getAllocator().CopyString(ND
->getNameAsString()));
3350 case DeclarationName::CXXDeductionGuideName
:
3351 case DeclarationName::CXXUsingDirective
:
3352 case DeclarationName::ObjCZeroArgSelector
:
3353 case DeclarationName::ObjCOneArgSelector
:
3354 case DeclarationName::ObjCMultiArgSelector
:
3357 case DeclarationName::CXXConstructorName
: {
3358 CXXRecordDecl
*Record
= nullptr;
3359 QualType Ty
= Name
.getCXXNameType();
3360 if (const auto *RecordTy
= Ty
->getAs
<RecordType
>())
3361 Record
= cast
<CXXRecordDecl
>(RecordTy
->getDecl());
3362 else if (const auto *InjectedTy
= Ty
->getAs
<InjectedClassNameType
>())
3363 Record
= InjectedTy
->getDecl();
3365 Result
.AddTypedTextChunk(
3366 Result
.getAllocator().CopyString(ND
->getNameAsString()));
3370 Result
.AddTypedTextChunk(
3371 Result
.getAllocator().CopyString(Record
->getNameAsString()));
3372 if (ClassTemplateDecl
*Template
= Record
->getDescribedClassTemplate()) {
3373 Result
.AddChunk(CodeCompletionString::CK_LeftAngle
);
3374 AddTemplateParameterChunks(Context
, Policy
, Template
, Result
);
3375 Result
.AddChunk(CodeCompletionString::CK_RightAngle
);
3382 CodeCompletionString
*CodeCompletionResult::CreateCodeCompletionString(
3383 Sema
&S
, const CodeCompletionContext
&CCContext
,
3384 CodeCompletionAllocator
&Allocator
, CodeCompletionTUInfo
&CCTUInfo
,
3385 bool IncludeBriefComments
) {
3386 return CreateCodeCompletionString(S
.Context
, S
.PP
, CCContext
, Allocator
,
3387 CCTUInfo
, IncludeBriefComments
);
3390 CodeCompletionString
*CodeCompletionResult::CreateCodeCompletionStringForMacro(
3391 Preprocessor
&PP
, CodeCompletionAllocator
&Allocator
,
3392 CodeCompletionTUInfo
&CCTUInfo
) {
3393 assert(Kind
== RK_Macro
);
3394 CodeCompletionBuilder
Result(Allocator
, CCTUInfo
, Priority
, Availability
);
3395 const MacroInfo
*MI
= PP
.getMacroInfo(Macro
);
3396 Result
.AddTypedTextChunk(Result
.getAllocator().CopyString(Macro
->getName()));
3398 if (!MI
|| !MI
->isFunctionLike())
3399 return Result
.TakeString();
3401 // Format a function-like macro with placeholders for the arguments.
3402 Result
.AddChunk(CodeCompletionString::CK_LeftParen
);
3403 MacroInfo::param_iterator A
= MI
->param_begin(), AEnd
= MI
->param_end();
3405 // C99 variadic macros add __VA_ARGS__ at the end. Skip it.
3406 if (MI
->isC99Varargs()) {
3410 Result
.AddPlaceholderChunk("...");
3414 for (MacroInfo::param_iterator A
= MI
->param_begin(); A
!= AEnd
; ++A
) {
3415 if (A
!= MI
->param_begin())
3416 Result
.AddChunk(CodeCompletionString::CK_Comma
);
3418 if (MI
->isVariadic() && (A
+ 1) == AEnd
) {
3419 SmallString
<32> Arg
= (*A
)->getName();
3420 if (MI
->isC99Varargs())
3424 Result
.AddPlaceholderChunk(Result
.getAllocator().CopyString(Arg
));
3428 // Non-variadic macros are simple.
3429 Result
.AddPlaceholderChunk(
3430 Result
.getAllocator().CopyString((*A
)->getName()));
3432 Result
.AddChunk(CodeCompletionString::CK_RightParen
);
3433 return Result
.TakeString();
3436 /// If possible, create a new code completion string for the given
3439 /// \returns Either a new, heap-allocated code completion string describing
3440 /// how to use this result, or NULL to indicate that the string or name of the
3441 /// result is all that is needed.
3442 CodeCompletionString
*CodeCompletionResult::CreateCodeCompletionString(
3443 ASTContext
&Ctx
, Preprocessor
&PP
, const CodeCompletionContext
&CCContext
,
3444 CodeCompletionAllocator
&Allocator
, CodeCompletionTUInfo
&CCTUInfo
,
3445 bool IncludeBriefComments
) {
3446 if (Kind
== RK_Macro
)
3447 return CreateCodeCompletionStringForMacro(PP
, Allocator
, CCTUInfo
);
3449 CodeCompletionBuilder
Result(Allocator
, CCTUInfo
, Priority
, Availability
);
3451 PrintingPolicy Policy
= getCompletionPrintingPolicy(Ctx
, PP
);
3452 if (Kind
== RK_Pattern
) {
3453 Pattern
->Priority
= Priority
;
3454 Pattern
->Availability
= Availability
;
3457 Result
.addParentContext(Declaration
->getDeclContext());
3458 Pattern
->ParentName
= Result
.getParentName();
3459 if (const RawComment
*RC
=
3460 getPatternCompletionComment(Ctx
, Declaration
)) {
3461 Result
.addBriefComment(RC
->getBriefText(Ctx
));
3462 Pattern
->BriefComment
= Result
.getBriefComment();
3469 if (Kind
== RK_Keyword
) {
3470 Result
.AddTypedTextChunk(Keyword
);
3471 return Result
.TakeString();
3473 assert(Kind
== RK_Declaration
&& "Missed a result kind?");
3474 return createCodeCompletionStringForDecl(
3475 PP
, Ctx
, Result
, IncludeBriefComments
, CCContext
, Policy
);
3478 static void printOverrideString(const CodeCompletionString
&CCS
,
3479 std::string
&BeforeName
,
3480 std::string
&NameAndSignature
) {
3481 bool SeenTypedChunk
= false;
3482 for (auto &Chunk
: CCS
) {
3483 if (Chunk
.Kind
== CodeCompletionString::CK_Optional
) {
3484 assert(SeenTypedChunk
&& "optional parameter before name");
3485 // Note that we put all chunks inside into NameAndSignature.
3486 printOverrideString(*Chunk
.Optional
, NameAndSignature
, NameAndSignature
);
3489 SeenTypedChunk
|= Chunk
.Kind
== CodeCompletionString::CK_TypedText
;
3491 NameAndSignature
+= Chunk
.Text
;
3493 BeforeName
+= Chunk
.Text
;
3497 CodeCompletionString
*
3498 CodeCompletionResult::createCodeCompletionStringForOverride(
3499 Preprocessor
&PP
, ASTContext
&Ctx
, CodeCompletionBuilder
&Result
,
3500 bool IncludeBriefComments
, const CodeCompletionContext
&CCContext
,
3501 PrintingPolicy
&Policy
) {
3502 auto *CCS
= createCodeCompletionStringForDecl(PP
, Ctx
, Result
,
3503 /*IncludeBriefComments=*/false,
3505 std::string BeforeName
;
3506 std::string NameAndSignature
;
3507 // For overrides all chunks go into the result, none are informative.
3508 printOverrideString(*CCS
, BeforeName
, NameAndSignature
);
3509 NameAndSignature
+= " override";
3511 Result
.AddTextChunk(Result
.getAllocator().CopyString(BeforeName
));
3512 Result
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
3513 Result
.AddTypedTextChunk(Result
.getAllocator().CopyString(NameAndSignature
));
3514 return Result
.TakeString();
3517 // FIXME: Right now this works well with lambdas. Add support for other functor
3518 // types like std::function.
3519 static const NamedDecl
*extractFunctorCallOperator(const NamedDecl
*ND
) {
3520 const auto *VD
= dyn_cast
<VarDecl
>(ND
);
3523 const auto *RecordDecl
= VD
->getType()->getAsCXXRecordDecl();
3524 if (!RecordDecl
|| !RecordDecl
->isLambda())
3526 return RecordDecl
->getLambdaCallOperator();
3529 CodeCompletionString
*CodeCompletionResult::createCodeCompletionStringForDecl(
3530 Preprocessor
&PP
, ASTContext
&Ctx
, CodeCompletionBuilder
&Result
,
3531 bool IncludeBriefComments
, const CodeCompletionContext
&CCContext
,
3532 PrintingPolicy
&Policy
) {
3533 const NamedDecl
*ND
= Declaration
;
3534 Result
.addParentContext(ND
->getDeclContext());
3536 if (IncludeBriefComments
) {
3537 // Add documentation comment, if it exists.
3538 if (const RawComment
*RC
= getCompletionComment(Ctx
, Declaration
)) {
3539 Result
.addBriefComment(RC
->getBriefText(Ctx
));
3543 if (StartsNestedNameSpecifier
) {
3544 Result
.AddTypedTextChunk(
3545 Result
.getAllocator().CopyString(ND
->getNameAsString()));
3546 Result
.AddTextChunk("::");
3547 return Result
.TakeString();
3550 for (const auto *I
: ND
->specific_attrs
<AnnotateAttr
>())
3551 Result
.AddAnnotation(Result
.getAllocator().CopyString(I
->getAnnotation()));
3553 auto AddFunctionTypeAndResult
= [&](const FunctionDecl
*Function
) {
3554 AddResultTypeChunk(Ctx
, Policy
, Function
, CCContext
.getBaseType(), Result
);
3555 AddQualifierToCompletionString(Result
, Qualifier
, QualifierIsInformative
,
3557 AddTypedNameChunk(Ctx
, Policy
, ND
, Result
);
3558 Result
.AddChunk(CodeCompletionString::CK_LeftParen
);
3559 AddFunctionParameterChunks(PP
, Policy
, Function
, Result
);
3560 Result
.AddChunk(CodeCompletionString::CK_RightParen
);
3561 AddFunctionTypeQualsToCompletionString(Result
, Function
);
3564 if (const auto *Function
= dyn_cast
<FunctionDecl
>(ND
)) {
3565 AddFunctionTypeAndResult(Function
);
3566 return Result
.TakeString();
3569 if (const auto *CallOperator
=
3570 dyn_cast_or_null
<FunctionDecl
>(extractFunctorCallOperator(ND
))) {
3571 AddFunctionTypeAndResult(CallOperator
);
3572 return Result
.TakeString();
3575 AddResultTypeChunk(Ctx
, Policy
, ND
, CCContext
.getBaseType(), Result
);
3577 if (const FunctionTemplateDecl
*FunTmpl
=
3578 dyn_cast
<FunctionTemplateDecl
>(ND
)) {
3579 AddQualifierToCompletionString(Result
, Qualifier
, QualifierIsInformative
,
3581 FunctionDecl
*Function
= FunTmpl
->getTemplatedDecl();
3582 AddTypedNameChunk(Ctx
, Policy
, Function
, Result
);
3584 // Figure out which template parameters are deduced (or have default
3586 // Note that we're creating a non-empty bit vector so that we can go
3587 // through the loop below to omit default template parameters for non-call
3589 llvm::SmallBitVector
Deduced(FunTmpl
->getTemplateParameters()->size());
3590 // Avoid running it if this is not a call: We should emit *all* template
3592 if (FunctionCanBeCall
)
3593 Sema::MarkDeducedTemplateParameters(Ctx
, FunTmpl
, Deduced
);
3594 unsigned LastDeducibleArgument
;
3595 for (LastDeducibleArgument
= Deduced
.size(); LastDeducibleArgument
> 0;
3596 --LastDeducibleArgument
) {
3597 if (!Deduced
[LastDeducibleArgument
- 1]) {
3598 // C++0x: Figure out if the template argument has a default. If so,
3599 // the user doesn't need to type this argument.
3600 // FIXME: We need to abstract template parameters better!
3601 bool HasDefaultArg
= false;
3602 NamedDecl
*Param
= FunTmpl
->getTemplateParameters()->getParam(
3603 LastDeducibleArgument
- 1);
3604 if (TemplateTypeParmDecl
*TTP
= dyn_cast
<TemplateTypeParmDecl
>(Param
))
3605 HasDefaultArg
= TTP
->hasDefaultArgument();
3606 else if (NonTypeTemplateParmDecl
*NTTP
=
3607 dyn_cast
<NonTypeTemplateParmDecl
>(Param
))
3608 HasDefaultArg
= NTTP
->hasDefaultArgument();
3610 assert(isa
<TemplateTemplateParmDecl
>(Param
));
3612 cast
<TemplateTemplateParmDecl
>(Param
)->hasDefaultArgument();
3620 if (LastDeducibleArgument
|| !FunctionCanBeCall
) {
3621 // Some of the function template arguments cannot be deduced from a
3622 // function call, so we introduce an explicit template argument list
3623 // containing all of the arguments up to the first deducible argument.
3625 // Or, if this isn't a call, emit all the template arguments
3626 // to disambiguate the (potential) overloads.
3628 // FIXME: Detect cases where the function parameters can be deduced from
3629 // the surrounding context, as per [temp.deduct.funcaddr].
3631 // template <class T> void foo(T);
3632 // void (*f)(int) = foo;
3633 Result
.AddChunk(CodeCompletionString::CK_LeftAngle
);
3634 AddTemplateParameterChunks(Ctx
, Policy
, FunTmpl
, Result
,
3635 LastDeducibleArgument
);
3636 Result
.AddChunk(CodeCompletionString::CK_RightAngle
);
3639 // Add the function parameters
3640 Result
.AddChunk(CodeCompletionString::CK_LeftParen
);
3641 AddFunctionParameterChunks(PP
, Policy
, Function
, Result
);
3642 Result
.AddChunk(CodeCompletionString::CK_RightParen
);
3643 AddFunctionTypeQualsToCompletionString(Result
, Function
);
3644 return Result
.TakeString();
3647 if (const auto *Template
= dyn_cast
<TemplateDecl
>(ND
)) {
3648 AddQualifierToCompletionString(Result
, Qualifier
, QualifierIsInformative
,
3650 Result
.AddTypedTextChunk(
3651 Result
.getAllocator().CopyString(Template
->getNameAsString()));
3652 Result
.AddChunk(CodeCompletionString::CK_LeftAngle
);
3653 AddTemplateParameterChunks(Ctx
, Policy
, Template
, Result
);
3654 Result
.AddChunk(CodeCompletionString::CK_RightAngle
);
3655 return Result
.TakeString();
3658 if (const auto *Method
= dyn_cast
<ObjCMethodDecl
>(ND
)) {
3659 Selector Sel
= Method
->getSelector();
3660 if (Sel
.isUnarySelector()) {
3661 Result
.AddTypedTextChunk(
3662 Result
.getAllocator().CopyString(Sel
.getNameForSlot(0)));
3663 return Result
.TakeString();
3666 std::string SelName
= Sel
.getNameForSlot(0).str();
3668 if (StartParameter
== 0)
3669 Result
.AddTypedTextChunk(Result
.getAllocator().CopyString(SelName
));
3671 Result
.AddInformativeChunk(Result
.getAllocator().CopyString(SelName
));
3673 // If there is only one parameter, and we're past it, add an empty
3674 // typed-text chunk since there is nothing to type.
3675 if (Method
->param_size() == 1)
3676 Result
.AddTypedTextChunk("");
3679 // The extra Idx < Sel.getNumArgs() check is needed due to legacy C-style
3680 // method parameters.
3681 for (ObjCMethodDecl::param_const_iterator P
= Method
->param_begin(),
3682 PEnd
= Method
->param_end();
3683 P
!= PEnd
&& Idx
< Sel
.getNumArgs(); (void)++P
, ++Idx
) {
3685 std::string Keyword
;
3686 if (Idx
> StartParameter
)
3687 Result
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
3688 if (IdentifierInfo
*II
= Sel
.getIdentifierInfoForSlot(Idx
))
3689 Keyword
+= II
->getName();
3691 if (Idx
< StartParameter
|| AllParametersAreInformative
)
3692 Result
.AddInformativeChunk(Result
.getAllocator().CopyString(Keyword
));
3694 Result
.AddTypedTextChunk(Result
.getAllocator().CopyString(Keyword
));
3697 // If we're before the starting parameter, skip the placeholder.
3698 if (Idx
< StartParameter
)
3702 QualType ParamType
= (*P
)->getType();
3703 std::optional
<ArrayRef
<QualType
>> ObjCSubsts
;
3704 if (!CCContext
.getBaseType().isNull())
3705 ObjCSubsts
= CCContext
.getBaseType()->getObjCSubstitutions(Method
);
3707 if (ParamType
->isBlockPointerType() && !DeclaringEntity
)
3708 Arg
= FormatFunctionParameter(Policy
, *P
, true,
3709 /*SuppressBlock=*/false, ObjCSubsts
);
3712 ParamType
= ParamType
.substObjCTypeArgs(
3713 Ctx
, *ObjCSubsts
, ObjCSubstitutionContext::Parameter
);
3714 Arg
= "(" + formatObjCParamQualifiers((*P
)->getObjCDeclQualifier(),
3716 Arg
+= ParamType
.getAsString(Policy
) + ")";
3717 if (IdentifierInfo
*II
= (*P
)->getIdentifier())
3718 if (DeclaringEntity
|| AllParametersAreInformative
)
3719 Arg
+= II
->getName();
3722 if (Method
->isVariadic() && (P
+ 1) == PEnd
)
3725 if (DeclaringEntity
)
3726 Result
.AddTextChunk(Result
.getAllocator().CopyString(Arg
));
3727 else if (AllParametersAreInformative
)
3728 Result
.AddInformativeChunk(Result
.getAllocator().CopyString(Arg
));
3730 Result
.AddPlaceholderChunk(Result
.getAllocator().CopyString(Arg
));
3733 if (Method
->isVariadic()) {
3734 if (Method
->param_size() == 0) {
3735 if (DeclaringEntity
)
3736 Result
.AddTextChunk(", ...");
3737 else if (AllParametersAreInformative
)
3738 Result
.AddInformativeChunk(", ...");
3740 Result
.AddPlaceholderChunk(", ...");
3743 MaybeAddSentinel(PP
, Method
, Result
);
3746 return Result
.TakeString();
3750 AddQualifierToCompletionString(Result
, Qualifier
, QualifierIsInformative
,
3753 Result
.AddTypedTextChunk(
3754 Result
.getAllocator().CopyString(ND
->getNameAsString()));
3755 return Result
.TakeString();
3758 const RawComment
*clang::getCompletionComment(const ASTContext
&Ctx
,
3759 const NamedDecl
*ND
) {
3762 if (auto *RC
= Ctx
.getRawCommentForAnyRedecl(ND
))
3765 // Try to find comment from a property for ObjC methods.
3766 const auto *M
= dyn_cast
<ObjCMethodDecl
>(ND
);
3769 const ObjCPropertyDecl
*PDecl
= M
->findPropertyDecl();
3773 return Ctx
.getRawCommentForAnyRedecl(PDecl
);
3776 const RawComment
*clang::getPatternCompletionComment(const ASTContext
&Ctx
,
3777 const NamedDecl
*ND
) {
3778 const auto *M
= dyn_cast_or_null
<ObjCMethodDecl
>(ND
);
3779 if (!M
|| !M
->isPropertyAccessor())
3782 // Provide code completion comment for self.GetterName where
3783 // GetterName is the getter method for a property with name
3784 // different from the property name (declared via a property
3785 // getter attribute.
3786 const ObjCPropertyDecl
*PDecl
= M
->findPropertyDecl();
3789 if (PDecl
->getGetterName() == M
->getSelector() &&
3790 PDecl
->getIdentifier() != M
->getIdentifier()) {
3791 if (auto *RC
= Ctx
.getRawCommentForAnyRedecl(M
))
3793 if (auto *RC
= Ctx
.getRawCommentForAnyRedecl(PDecl
))
3799 const RawComment
*clang::getParameterComment(
3800 const ASTContext
&Ctx
,
3801 const CodeCompleteConsumer::OverloadCandidate
&Result
, unsigned ArgIndex
) {
3802 auto FDecl
= Result
.getFunction();
3805 if (ArgIndex
< FDecl
->getNumParams())
3806 return Ctx
.getRawCommentForAnyRedecl(FDecl
->getParamDecl(ArgIndex
));
3810 static void AddOverloadAggregateChunks(const RecordDecl
*RD
,
3811 const PrintingPolicy
&Policy
,
3812 CodeCompletionBuilder
&Result
,
3813 unsigned CurrentArg
) {
3814 unsigned ChunkIndex
= 0;
3815 auto AddChunk
= [&](llvm::StringRef Placeholder
) {
3817 Result
.AddChunk(CodeCompletionString::CK_Comma
);
3818 const char *Copy
= Result
.getAllocator().CopyString(Placeholder
);
3819 if (ChunkIndex
== CurrentArg
)
3820 Result
.AddCurrentParameterChunk(Copy
);
3822 Result
.AddPlaceholderChunk(Copy
);
3825 // Aggregate initialization has all bases followed by all fields.
3826 // (Bases are not legal in C++11 but in that case we never get here).
3827 if (auto *CRD
= llvm::dyn_cast
<CXXRecordDecl
>(RD
)) {
3828 for (const auto &Base
: CRD
->bases())
3829 AddChunk(Base
.getType().getAsString(Policy
));
3831 for (const auto &Field
: RD
->fields())
3832 AddChunk(FormatFunctionParameter(Policy
, Field
));
3835 /// Add function overload parameter chunks to the given code completion
3837 static void AddOverloadParameterChunks(
3838 ASTContext
&Context
, const PrintingPolicy
&Policy
,
3839 const FunctionDecl
*Function
, const FunctionProtoType
*Prototype
,
3840 FunctionProtoTypeLoc PrototypeLoc
, CodeCompletionBuilder
&Result
,
3841 unsigned CurrentArg
, unsigned Start
= 0, bool InOptional
= false) {
3842 if (!Function
&& !Prototype
) {
3843 Result
.AddChunk(CodeCompletionString::CK_CurrentParameter
, "...");
3847 bool FirstParameter
= true;
3848 unsigned NumParams
=
3849 Function
? Function
->getNumParams() : Prototype
->getNumParams();
3851 for (unsigned P
= Start
; P
!= NumParams
; ++P
) {
3852 if (Function
&& Function
->getParamDecl(P
)->hasDefaultArg() && !InOptional
) {
3853 // When we see an optional default argument, put that argument and
3854 // the remaining default arguments into a new, optional string.
3855 CodeCompletionBuilder
Opt(Result
.getAllocator(),
3856 Result
.getCodeCompletionTUInfo());
3857 if (!FirstParameter
)
3858 Opt
.AddChunk(CodeCompletionString::CK_Comma
);
3859 // Optional sections are nested.
3860 AddOverloadParameterChunks(Context
, Policy
, Function
, Prototype
,
3861 PrototypeLoc
, Opt
, CurrentArg
, P
,
3862 /*InOptional=*/true);
3863 Result
.AddOptionalChunk(Opt
.TakeString());
3868 FirstParameter
= false;
3870 Result
.AddChunk(CodeCompletionString::CK_Comma
);
3874 // Format the placeholder string.
3875 std::string Placeholder
;
3876 assert(P
< Prototype
->getNumParams());
3877 if (Function
|| PrototypeLoc
) {
3878 const ParmVarDecl
*Param
=
3879 Function
? Function
->getParamDecl(P
) : PrototypeLoc
.getParam(P
);
3880 Placeholder
= FormatFunctionParameter(Policy
, Param
);
3881 if (Param
->hasDefaultArg())
3882 Placeholder
+= GetDefaultValueString(Param
, Context
.getSourceManager(),
3883 Context
.getLangOpts());
3885 Placeholder
= Prototype
->getParamType(P
).getAsString(Policy
);
3888 if (P
== CurrentArg
)
3889 Result
.AddCurrentParameterChunk(
3890 Result
.getAllocator().CopyString(Placeholder
));
3892 Result
.AddPlaceholderChunk(Result
.getAllocator().CopyString(Placeholder
));
3895 if (Prototype
&& Prototype
->isVariadic()) {
3896 CodeCompletionBuilder
Opt(Result
.getAllocator(),
3897 Result
.getCodeCompletionTUInfo());
3898 if (!FirstParameter
)
3899 Opt
.AddChunk(CodeCompletionString::CK_Comma
);
3901 if (CurrentArg
< NumParams
)
3902 Opt
.AddPlaceholderChunk("...");
3904 Opt
.AddCurrentParameterChunk("...");
3906 Result
.AddOptionalChunk(Opt
.TakeString());
3911 formatTemplateParameterPlaceholder(const NamedDecl
*Param
, bool &Optional
,
3912 const PrintingPolicy
&Policy
) {
3913 if (const auto *Type
= dyn_cast
<TemplateTypeParmDecl
>(Param
)) {
3914 Optional
= Type
->hasDefaultArgument();
3915 } else if (const auto *NonType
= dyn_cast
<NonTypeTemplateParmDecl
>(Param
)) {
3916 Optional
= NonType
->hasDefaultArgument();
3917 } else if (const auto *Template
= dyn_cast
<TemplateTemplateParmDecl
>(Param
)) {
3918 Optional
= Template
->hasDefaultArgument();
3921 llvm::raw_string_ostream
OS(Result
);
3922 Param
->print(OS
, Policy
);
3926 static std::string
templateResultType(const TemplateDecl
*TD
,
3927 const PrintingPolicy
&Policy
) {
3928 if (const auto *CTD
= dyn_cast
<ClassTemplateDecl
>(TD
))
3929 return CTD
->getTemplatedDecl()->getKindName().str();
3930 if (const auto *VTD
= dyn_cast
<VarTemplateDecl
>(TD
))
3931 return VTD
->getTemplatedDecl()->getType().getAsString(Policy
);
3932 if (const auto *FTD
= dyn_cast
<FunctionTemplateDecl
>(TD
))
3933 return FTD
->getTemplatedDecl()->getReturnType().getAsString(Policy
);
3934 if (isa
<TypeAliasTemplateDecl
>(TD
))
3936 if (isa
<TemplateTemplateParmDecl
>(TD
))
3938 if (isa
<ConceptDecl
>(TD
))
3943 static CodeCompletionString
*createTemplateSignatureString(
3944 const TemplateDecl
*TD
, CodeCompletionBuilder
&Builder
, unsigned CurrentArg
,
3945 const PrintingPolicy
&Policy
) {
3946 llvm::ArrayRef
<NamedDecl
*> Params
= TD
->getTemplateParameters()->asArray();
3947 CodeCompletionBuilder
OptionalBuilder(Builder
.getAllocator(),
3948 Builder
.getCodeCompletionTUInfo());
3949 std::string ResultType
= templateResultType(TD
, Policy
);
3950 if (!ResultType
.empty())
3951 Builder
.AddResultTypeChunk(Builder
.getAllocator().CopyString(ResultType
));
3952 Builder
.AddTextChunk(
3953 Builder
.getAllocator().CopyString(TD
->getNameAsString()));
3954 Builder
.AddChunk(CodeCompletionString::CK_LeftAngle
);
3955 // Initially we're writing into the main string. Once we see an optional arg
3956 // (with default), we're writing into the nested optional chunk.
3957 CodeCompletionBuilder
*Current
= &Builder
;
3958 for (unsigned I
= 0; I
< Params
.size(); ++I
) {
3959 bool Optional
= false;
3960 std::string Placeholder
=
3961 formatTemplateParameterPlaceholder(Params
[I
], Optional
, Policy
);
3963 Current
= &OptionalBuilder
;
3965 Current
->AddChunk(CodeCompletionString::CK_Comma
);
3966 Current
->AddChunk(I
== CurrentArg
3967 ? CodeCompletionString::CK_CurrentParameter
3968 : CodeCompletionString::CK_Placeholder
,
3969 Current
->getAllocator().CopyString(Placeholder
));
3971 // Add the optional chunk to the main string if we ever used it.
3972 if (Current
== &OptionalBuilder
)
3973 Builder
.AddOptionalChunk(OptionalBuilder
.TakeString());
3974 Builder
.AddChunk(CodeCompletionString::CK_RightAngle
);
3975 // For function templates, ResultType was the function's return type.
3976 // Give some clue this is a function. (Don't show the possibly-bulky params).
3977 if (isa
<FunctionTemplateDecl
>(TD
))
3978 Builder
.AddInformativeChunk("()");
3979 return Builder
.TakeString();
3982 CodeCompletionString
*
3983 CodeCompleteConsumer::OverloadCandidate::CreateSignatureString(
3984 unsigned CurrentArg
, Sema
&S
, CodeCompletionAllocator
&Allocator
,
3985 CodeCompletionTUInfo
&CCTUInfo
, bool IncludeBriefComments
,
3986 bool Braced
) const {
3987 PrintingPolicy Policy
= getCompletionPrintingPolicy(S
);
3988 // Show signatures of constructors as they are declared:
3989 // vector(int n) rather than vector<string>(int n)
3990 // This is less noisy without being less clear, and avoids tricky cases.
3991 Policy
.SuppressTemplateArgsInCXXConstructors
= true;
3993 // FIXME: Set priority, availability appropriately.
3994 CodeCompletionBuilder
Result(Allocator
, CCTUInfo
, 1,
3995 CXAvailability_Available
);
3997 if (getKind() == CK_Template
)
3998 return createTemplateSignatureString(getTemplate(), Result
, CurrentArg
,
4001 FunctionDecl
*FDecl
= getFunction();
4002 const FunctionProtoType
*Proto
=
4003 dyn_cast_or_null
<FunctionProtoType
>(getFunctionType());
4005 // First, the name/type of the callee.
4006 if (getKind() == CK_Aggregate
) {
4007 Result
.AddTextChunk(
4008 Result
.getAllocator().CopyString(getAggregate()->getName()));
4010 if (IncludeBriefComments
) {
4011 if (auto RC
= getParameterComment(S
.getASTContext(), *this, CurrentArg
))
4012 Result
.addBriefComment(RC
->getBriefText(S
.getASTContext()));
4014 AddResultTypeChunk(S
.Context
, Policy
, FDecl
, QualType(), Result
);
4017 llvm::raw_string_ostream
OS(Name
);
4018 FDecl
->getDeclName().print(OS
, Policy
);
4019 Result
.AddTextChunk(Result
.getAllocator().CopyString(OS
.str()));
4021 // Function without a declaration. Just give the return type.
4022 Result
.AddResultTypeChunk(Result
.getAllocator().CopyString(
4023 getFunctionType()->getReturnType().getAsString(Policy
)));
4026 // Next, the brackets and parameters.
4027 Result
.AddChunk(Braced
? CodeCompletionString::CK_LeftBrace
4028 : CodeCompletionString::CK_LeftParen
);
4029 if (getKind() == CK_Aggregate
)
4030 AddOverloadAggregateChunks(getAggregate(), Policy
, Result
, CurrentArg
);
4032 AddOverloadParameterChunks(S
.getASTContext(), Policy
, FDecl
, Proto
,
4033 getFunctionProtoTypeLoc(), Result
, CurrentArg
);
4034 Result
.AddChunk(Braced
? CodeCompletionString::CK_RightBrace
4035 : CodeCompletionString::CK_RightParen
);
4037 return Result
.TakeString();
4040 unsigned clang::getMacroUsagePriority(StringRef MacroName
,
4041 const LangOptions
&LangOpts
,
4042 bool PreferredTypeIsPointer
) {
4043 unsigned Priority
= CCP_Macro
;
4045 // Treat the "nil", "Nil" and "NULL" macros as null pointer constants.
4046 if (MacroName
.equals("nil") || MacroName
.equals("NULL") ||
4047 MacroName
.equals("Nil")) {
4048 Priority
= CCP_Constant
;
4049 if (PreferredTypeIsPointer
)
4050 Priority
= Priority
/ CCF_SimilarTypeMatch
;
4052 // Treat "YES", "NO", "true", and "false" as constants.
4053 else if (MacroName
.equals("YES") || MacroName
.equals("NO") ||
4054 MacroName
.equals("true") || MacroName
.equals("false"))
4055 Priority
= CCP_Constant
;
4056 // Treat "bool" as a type.
4057 else if (MacroName
.equals("bool"))
4058 Priority
= CCP_Type
+ (LangOpts
.ObjC
? CCD_bool_in_ObjC
: 0);
4063 CXCursorKind
clang::getCursorKindForDecl(const Decl
*D
) {
4065 return CXCursor_UnexposedDecl
;
4067 switch (D
->getKind()) {
4069 return CXCursor_EnumDecl
;
4070 case Decl::EnumConstant
:
4071 return CXCursor_EnumConstantDecl
;
4073 return CXCursor_FieldDecl
;
4074 case Decl::Function
:
4075 return CXCursor_FunctionDecl
;
4076 case Decl::ObjCCategory
:
4077 return CXCursor_ObjCCategoryDecl
;
4078 case Decl::ObjCCategoryImpl
:
4079 return CXCursor_ObjCCategoryImplDecl
;
4080 case Decl::ObjCImplementation
:
4081 return CXCursor_ObjCImplementationDecl
;
4083 case Decl::ObjCInterface
:
4084 return CXCursor_ObjCInterfaceDecl
;
4085 case Decl::ObjCIvar
:
4086 return CXCursor_ObjCIvarDecl
;
4087 case Decl::ObjCMethod
:
4088 return cast
<ObjCMethodDecl
>(D
)->isInstanceMethod()
4089 ? CXCursor_ObjCInstanceMethodDecl
4090 : CXCursor_ObjCClassMethodDecl
;
4091 case Decl::CXXMethod
:
4092 return CXCursor_CXXMethod
;
4093 case Decl::CXXConstructor
:
4094 return CXCursor_Constructor
;
4095 case Decl::CXXDestructor
:
4096 return CXCursor_Destructor
;
4097 case Decl::CXXConversion
:
4098 return CXCursor_ConversionFunction
;
4099 case Decl::ObjCProperty
:
4100 return CXCursor_ObjCPropertyDecl
;
4101 case Decl::ObjCProtocol
:
4102 return CXCursor_ObjCProtocolDecl
;
4104 return CXCursor_ParmDecl
;
4106 return CXCursor_TypedefDecl
;
4107 case Decl::TypeAlias
:
4108 return CXCursor_TypeAliasDecl
;
4109 case Decl::TypeAliasTemplate
:
4110 return CXCursor_TypeAliasTemplateDecl
;
4112 return CXCursor_VarDecl
;
4113 case Decl::Namespace
:
4114 return CXCursor_Namespace
;
4115 case Decl::NamespaceAlias
:
4116 return CXCursor_NamespaceAlias
;
4117 case Decl::TemplateTypeParm
:
4118 return CXCursor_TemplateTypeParameter
;
4119 case Decl::NonTypeTemplateParm
:
4120 return CXCursor_NonTypeTemplateParameter
;
4121 case Decl::TemplateTemplateParm
:
4122 return CXCursor_TemplateTemplateParameter
;
4123 case Decl::FunctionTemplate
:
4124 return CXCursor_FunctionTemplate
;
4125 case Decl::ClassTemplate
:
4126 return CXCursor_ClassTemplate
;
4127 case Decl::AccessSpec
:
4128 return CXCursor_CXXAccessSpecifier
;
4129 case Decl::ClassTemplatePartialSpecialization
:
4130 return CXCursor_ClassTemplatePartialSpecialization
;
4131 case Decl::UsingDirective
:
4132 return CXCursor_UsingDirective
;
4133 case Decl::StaticAssert
:
4134 return CXCursor_StaticAssert
;
4136 return CXCursor_FriendDecl
;
4137 case Decl::TranslationUnit
:
4138 return CXCursor_TranslationUnit
;
4141 case Decl::UnresolvedUsingValue
:
4142 case Decl::UnresolvedUsingTypename
:
4143 return CXCursor_UsingDeclaration
;
4145 case Decl::UsingEnum
:
4146 return CXCursor_EnumDecl
;
4148 case Decl::ObjCPropertyImpl
:
4149 switch (cast
<ObjCPropertyImplDecl
>(D
)->getPropertyImplementation()) {
4150 case ObjCPropertyImplDecl::Dynamic
:
4151 return CXCursor_ObjCDynamicDecl
;
4153 case ObjCPropertyImplDecl::Synthesize
:
4154 return CXCursor_ObjCSynthesizeDecl
;
4156 llvm_unreachable("Unexpected Kind!");
4159 return CXCursor_ModuleImportDecl
;
4161 case Decl::ObjCTypeParam
:
4162 return CXCursor_TemplateTypeParameter
;
4165 return CXCursor_ConceptDecl
;
4168 if (const auto *TD
= dyn_cast
<TagDecl
>(D
)) {
4169 switch (TD
->getTagKind()) {
4170 case TTK_Interface
: // fall through
4172 return CXCursor_StructDecl
;
4174 return CXCursor_ClassDecl
;
4176 return CXCursor_UnionDecl
;
4178 return CXCursor_EnumDecl
;
4183 return CXCursor_UnexposedDecl
;
4186 static void AddMacroResults(Preprocessor
&PP
, ResultBuilder
&Results
,
4187 bool LoadExternal
, bool IncludeUndefined
,
4188 bool TargetTypeIsPointer
= false) {
4189 typedef CodeCompletionResult Result
;
4191 Results
.EnterNewScope();
4193 for (Preprocessor::macro_iterator M
= PP
.macro_begin(LoadExternal
),
4194 MEnd
= PP
.macro_end(LoadExternal
);
4196 auto MD
= PP
.getMacroDefinition(M
->first
);
4197 if (IncludeUndefined
|| MD
) {
4198 MacroInfo
*MI
= MD
.getMacroInfo();
4199 if (MI
&& MI
->isUsedForHeaderGuard())
4203 Result(M
->first
, MI
,
4204 getMacroUsagePriority(M
->first
->getName(), PP
.getLangOpts(),
4205 TargetTypeIsPointer
)));
4209 Results
.ExitScope();
4212 static void AddPrettyFunctionResults(const LangOptions
&LangOpts
,
4213 ResultBuilder
&Results
) {
4214 typedef CodeCompletionResult Result
;
4216 Results
.EnterNewScope();
4218 Results
.AddResult(Result("__PRETTY_FUNCTION__", CCP_Constant
));
4219 Results
.AddResult(Result("__FUNCTION__", CCP_Constant
));
4220 if (LangOpts
.C99
|| LangOpts
.CPlusPlus11
)
4221 Results
.AddResult(Result("__func__", CCP_Constant
));
4222 Results
.ExitScope();
4225 static void HandleCodeCompleteResults(Sema
*S
,
4226 CodeCompleteConsumer
*CodeCompleter
,
4227 const CodeCompletionContext
&Context
,
4228 CodeCompletionResult
*Results
,
4229 unsigned NumResults
) {
4231 CodeCompleter
->ProcessCodeCompleteResults(*S
, Context
, Results
, NumResults
);
4234 static CodeCompletionContext
4235 mapCodeCompletionContext(Sema
&S
, Sema::ParserCompletionContext PCC
) {
4237 case Sema::PCC_Namespace
:
4238 return CodeCompletionContext::CCC_TopLevel
;
4240 case Sema::PCC_Class
:
4241 return CodeCompletionContext::CCC_ClassStructUnion
;
4243 case Sema::PCC_ObjCInterface
:
4244 return CodeCompletionContext::CCC_ObjCInterface
;
4246 case Sema::PCC_ObjCImplementation
:
4247 return CodeCompletionContext::CCC_ObjCImplementation
;
4249 case Sema::PCC_ObjCInstanceVariableList
:
4250 return CodeCompletionContext::CCC_ObjCIvarList
;
4252 case Sema::PCC_Template
:
4253 case Sema::PCC_MemberTemplate
:
4254 if (S
.CurContext
->isFileContext())
4255 return CodeCompletionContext::CCC_TopLevel
;
4256 if (S
.CurContext
->isRecord())
4257 return CodeCompletionContext::CCC_ClassStructUnion
;
4258 return CodeCompletionContext::CCC_Other
;
4260 case Sema::PCC_RecoveryInFunction
:
4261 return CodeCompletionContext::CCC_Recovery
;
4263 case Sema::PCC_ForInit
:
4264 if (S
.getLangOpts().CPlusPlus
|| S
.getLangOpts().C99
||
4265 S
.getLangOpts().ObjC
)
4266 return CodeCompletionContext::CCC_ParenthesizedExpression
;
4268 return CodeCompletionContext::CCC_Expression
;
4270 case Sema::PCC_Expression
:
4271 return CodeCompletionContext::CCC_Expression
;
4272 case Sema::PCC_Condition
:
4273 return CodeCompletionContext(CodeCompletionContext::CCC_Expression
,
4274 S
.getASTContext().BoolTy
);
4276 case Sema::PCC_Statement
:
4277 return CodeCompletionContext::CCC_Statement
;
4279 case Sema::PCC_Type
:
4280 return CodeCompletionContext::CCC_Type
;
4282 case Sema::PCC_ParenthesizedExpression
:
4283 return CodeCompletionContext::CCC_ParenthesizedExpression
;
4285 case Sema::PCC_LocalDeclarationSpecifiers
:
4286 return CodeCompletionContext::CCC_Type
;
4287 case Sema::PCC_TopLevelOrExpression
:
4288 return CodeCompletionContext::CCC_TopLevelOrExpression
;
4291 llvm_unreachable("Invalid ParserCompletionContext!");
4294 /// If we're in a C++ virtual member function, add completion results
4295 /// that invoke the functions we override, since it's common to invoke the
4296 /// overridden function as well as adding new functionality.
4298 /// \param S The semantic analysis object for which we are generating results.
4300 /// \param InContext This context in which the nested-name-specifier preceding
4301 /// the code-completion point
4302 static void MaybeAddOverrideCalls(Sema
&S
, DeclContext
*InContext
,
4303 ResultBuilder
&Results
) {
4304 // Look through blocks.
4305 DeclContext
*CurContext
= S
.CurContext
;
4306 while (isa
<BlockDecl
>(CurContext
))
4307 CurContext
= CurContext
->getParent();
4309 CXXMethodDecl
*Method
= dyn_cast
<CXXMethodDecl
>(CurContext
);
4310 if (!Method
|| !Method
->isVirtual())
4313 // We need to have names for all of the parameters, if we're going to
4314 // generate a forwarding call.
4315 for (auto *P
: Method
->parameters())
4316 if (!P
->getDeclName())
4319 PrintingPolicy Policy
= getCompletionPrintingPolicy(S
);
4320 for (const CXXMethodDecl
*Overridden
: Method
->overridden_methods()) {
4321 CodeCompletionBuilder
Builder(Results
.getAllocator(),
4322 Results
.getCodeCompletionTUInfo());
4323 if (Overridden
->getCanonicalDecl() == Method
->getCanonicalDecl())
4326 // If we need a nested-name-specifier, add one now.
4328 NestedNameSpecifier
*NNS
= getRequiredQualification(
4329 S
.Context
, CurContext
, Overridden
->getDeclContext());
4332 llvm::raw_string_ostream
OS(Str
);
4333 NNS
->print(OS
, Policy
);
4334 Builder
.AddTextChunk(Results
.getAllocator().CopyString(OS
.str()));
4336 } else if (!InContext
->Equals(Overridden
->getDeclContext()))
4339 Builder
.AddTypedTextChunk(
4340 Results
.getAllocator().CopyString(Overridden
->getNameAsString()));
4341 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
4342 bool FirstParam
= true;
4343 for (auto *P
: Method
->parameters()) {
4347 Builder
.AddChunk(CodeCompletionString::CK_Comma
);
4349 Builder
.AddPlaceholderChunk(
4350 Results
.getAllocator().CopyString(P
->getIdentifier()->getName()));
4352 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
4353 Results
.AddResult(CodeCompletionResult(
4354 Builder
.TakeString(), CCP_SuperCompletion
, CXCursor_CXXMethod
,
4355 CXAvailability_Available
, Overridden
));
4356 Results
.Ignore(Overridden
);
4360 void Sema::CodeCompleteModuleImport(SourceLocation ImportLoc
,
4361 ModuleIdPath Path
) {
4362 typedef CodeCompletionResult Result
;
4363 ResultBuilder
Results(*this, CodeCompleter
->getAllocator(),
4364 CodeCompleter
->getCodeCompletionTUInfo(),
4365 CodeCompletionContext::CCC_Other
);
4366 Results
.EnterNewScope();
4368 CodeCompletionAllocator
&Allocator
= Results
.getAllocator();
4369 CodeCompletionBuilder
Builder(Allocator
, Results
.getCodeCompletionTUInfo());
4370 typedef CodeCompletionResult Result
;
4372 // Enumerate all top-level modules.
4373 SmallVector
<Module
*, 8> Modules
;
4374 PP
.getHeaderSearchInfo().collectAllModules(Modules
);
4375 for (unsigned I
= 0, N
= Modules
.size(); I
!= N
; ++I
) {
4376 Builder
.AddTypedTextChunk(
4377 Builder
.getAllocator().CopyString(Modules
[I
]->Name
));
4378 Results
.AddResult(Result(
4379 Builder
.TakeString(), CCP_Declaration
, CXCursor_ModuleImportDecl
,
4380 Modules
[I
]->isAvailable() ? CXAvailability_Available
4381 : CXAvailability_NotAvailable
));
4383 } else if (getLangOpts().Modules
) {
4384 // Load the named module.
4386 PP
.getModuleLoader().loadModule(ImportLoc
, Path
, Module::AllVisible
,
4387 /*IsInclusionDirective=*/false);
4388 // Enumerate submodules.
4390 for (auto *Submodule
: Mod
->submodules()) {
4391 Builder
.AddTypedTextChunk(
4392 Builder
.getAllocator().CopyString(Submodule
->Name
));
4393 Results
.AddResult(Result(
4394 Builder
.TakeString(), CCP_Declaration
, CXCursor_ModuleImportDecl
,
4395 Submodule
->isAvailable() ? CXAvailability_Available
4396 : CXAvailability_NotAvailable
));
4400 Results
.ExitScope();
4401 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
4402 Results
.data(), Results
.size());
4405 void Sema::CodeCompleteOrdinaryName(Scope
*S
,
4406 ParserCompletionContext CompletionContext
) {
4407 ResultBuilder
Results(*this, CodeCompleter
->getAllocator(),
4408 CodeCompleter
->getCodeCompletionTUInfo(),
4409 mapCodeCompletionContext(*this, CompletionContext
));
4410 Results
.EnterNewScope();
4412 // Determine how to filter results, e.g., so that the names of
4413 // values (functions, enumerators, function templates, etc.) are
4414 // only allowed where we can have an expression.
4415 switch (CompletionContext
) {
4418 case PCC_ObjCInterface
:
4419 case PCC_ObjCImplementation
:
4420 case PCC_ObjCInstanceVariableList
:
4422 case PCC_MemberTemplate
:
4424 case PCC_LocalDeclarationSpecifiers
:
4425 Results
.setFilter(&ResultBuilder::IsOrdinaryNonValueName
);
4429 case PCC_TopLevelOrExpression
:
4430 case PCC_ParenthesizedExpression
:
4431 case PCC_Expression
:
4434 if (WantTypesInContext(CompletionContext
, getLangOpts()))
4435 Results
.setFilter(&ResultBuilder::IsOrdinaryName
);
4437 Results
.setFilter(&ResultBuilder::IsOrdinaryNonTypeName
);
4439 if (getLangOpts().CPlusPlus
)
4440 MaybeAddOverrideCalls(*this, /*InContext=*/nullptr, Results
);
4443 case PCC_RecoveryInFunction
:
4448 // If we are in a C++ non-static member function, check the qualifiers on
4449 // the member function to filter/prioritize the results list.
4450 auto ThisType
= getCurrentThisType();
4451 if (!ThisType
.isNull())
4452 Results
.setObjectTypeQualifiers(ThisType
->getPointeeType().getQualifiers(),
4455 CodeCompletionDeclConsumer
Consumer(Results
, CurContext
);
4456 LookupVisibleDecls(S
, LookupOrdinaryName
, Consumer
,
4457 CodeCompleter
->includeGlobals(),
4458 CodeCompleter
->loadExternal());
4460 AddOrdinaryNameResults(CompletionContext
, S
, *this, Results
);
4461 Results
.ExitScope();
4463 switch (CompletionContext
) {
4464 case PCC_ParenthesizedExpression
:
4465 case PCC_Expression
:
4467 case PCC_TopLevelOrExpression
:
4468 case PCC_RecoveryInFunction
:
4469 if (S
->getFnParent())
4470 AddPrettyFunctionResults(getLangOpts(), Results
);
4475 case PCC_ObjCInterface
:
4476 case PCC_ObjCImplementation
:
4477 case PCC_ObjCInstanceVariableList
:
4479 case PCC_MemberTemplate
:
4483 case PCC_LocalDeclarationSpecifiers
:
4487 if (CodeCompleter
->includeMacros())
4488 AddMacroResults(PP
, Results
, CodeCompleter
->loadExternal(), false);
4490 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
4491 Results
.data(), Results
.size());
4494 static void AddClassMessageCompletions(Sema
&SemaRef
, Scope
*S
,
4495 ParsedType Receiver
,
4496 ArrayRef
<IdentifierInfo
*> SelIdents
,
4497 bool AtArgumentExpression
, bool IsSuper
,
4498 ResultBuilder
&Results
);
4500 void Sema::CodeCompleteDeclSpec(Scope
*S
, DeclSpec
&DS
,
4501 bool AllowNonIdentifiers
,
4502 bool AllowNestedNameSpecifiers
) {
4503 typedef CodeCompletionResult Result
;
4504 ResultBuilder
Results(
4505 *this, CodeCompleter
->getAllocator(),
4506 CodeCompleter
->getCodeCompletionTUInfo(),
4507 AllowNestedNameSpecifiers
4508 // FIXME: Try to separate codepath leading here to deduce whether we
4509 // need an existing symbol or a new one.
4510 ? CodeCompletionContext::CCC_SymbolOrNewName
4511 : CodeCompletionContext::CCC_NewName
);
4512 Results
.EnterNewScope();
4514 // Type qualifiers can come after names.
4515 Results
.AddResult(Result("const"));
4516 Results
.AddResult(Result("volatile"));
4517 if (getLangOpts().C99
)
4518 Results
.AddResult(Result("restrict"));
4520 if (getLangOpts().CPlusPlus
) {
4521 if (getLangOpts().CPlusPlus11
&&
4522 (DS
.getTypeSpecType() == DeclSpec::TST_class
||
4523 DS
.getTypeSpecType() == DeclSpec::TST_struct
))
4524 Results
.AddResult("final");
4526 if (AllowNonIdentifiers
) {
4527 Results
.AddResult(Result("operator"));
4530 // Add nested-name-specifiers.
4531 if (AllowNestedNameSpecifiers
) {
4532 Results
.allowNestedNameSpecifiers();
4533 Results
.setFilter(&ResultBuilder::IsImpossibleToSatisfy
);
4534 CodeCompletionDeclConsumer
Consumer(Results
, CurContext
);
4535 LookupVisibleDecls(S
, LookupNestedNameSpecifierName
, Consumer
,
4536 CodeCompleter
->includeGlobals(),
4537 CodeCompleter
->loadExternal());
4538 Results
.setFilter(nullptr);
4541 Results
.ExitScope();
4543 // If we're in a context where we might have an expression (rather than a
4544 // declaration), and what we've seen so far is an Objective-C type that could
4545 // be a receiver of a class message, this may be a class message send with
4546 // the initial opening bracket '[' missing. Add appropriate completions.
4547 if (AllowNonIdentifiers
&& !AllowNestedNameSpecifiers
&&
4548 DS
.getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier
&&
4549 DS
.getTypeSpecType() == DeclSpec::TST_typename
&&
4550 DS
.getTypeSpecComplex() == DeclSpec::TSC_unspecified
&&
4551 DS
.getTypeSpecSign() == TypeSpecifierSign::Unspecified
&&
4552 !DS
.isTypeAltiVecVector() && S
&&
4553 (S
->getFlags() & Scope::DeclScope
) != 0 &&
4554 (S
->getFlags() & (Scope::ClassScope
| Scope::TemplateParamScope
|
4555 Scope::FunctionPrototypeScope
| Scope::AtCatchScope
)) ==
4557 ParsedType T
= DS
.getRepAsType();
4558 if (!T
.get().isNull() && T
.get()->isObjCObjectOrInterfaceType())
4559 AddClassMessageCompletions(*this, S
, T
, std::nullopt
, false, false,
4563 // Note that we intentionally suppress macro results here, since we do not
4564 // encourage using macros to produce the names of entities.
4566 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
4567 Results
.data(), Results
.size());
4570 static const char *underscoreAttrScope(llvm::StringRef Scope
) {
4571 if (Scope
== "clang")
4578 static const char *noUnderscoreAttrScope(llvm::StringRef Scope
) {
4579 if (Scope
== "_Clang")
4581 if (Scope
== "__gnu__")
4586 void Sema::CodeCompleteAttribute(AttributeCommonInfo::Syntax Syntax
,
4587 AttributeCompletion Completion
,
4588 const IdentifierInfo
*InScope
) {
4589 if (Completion
== AttributeCompletion::None
)
4591 ResultBuilder
Results(*this, CodeCompleter
->getAllocator(),
4592 CodeCompleter
->getCodeCompletionTUInfo(),
4593 CodeCompletionContext::CCC_Attribute
);
4595 // We're going to iterate over the normalized spellings of the attribute.
4596 // These don't include "underscore guarding": the normalized spelling is
4597 // clang::foo but you can also write _Clang::__foo__.
4599 // (Clang supports a mix like clang::__foo__ but we won't suggest it: either
4600 // you care about clashing with macros or you don't).
4602 // So if we're already in a scope, we determine its canonical spellings
4603 // (for comparison with normalized attr spelling) and remember whether it was
4604 // underscore-guarded (so we know how to spell contained attributes).
4605 llvm::StringRef InScopeName
;
4606 bool InScopeUnderscore
= false;
4608 InScopeName
= InScope
->getName();
4609 if (const char *NoUnderscore
= noUnderscoreAttrScope(InScopeName
)) {
4610 InScopeName
= NoUnderscore
;
4611 InScopeUnderscore
= true;
4614 bool SyntaxSupportsGuards
= Syntax
== AttributeCommonInfo::AS_GNU
||
4615 Syntax
== AttributeCommonInfo::AS_CXX11
||
4616 Syntax
== AttributeCommonInfo::AS_C23
;
4618 llvm::DenseSet
<llvm::StringRef
> FoundScopes
;
4619 auto AddCompletions
= [&](const ParsedAttrInfo
&A
) {
4620 if (A
.IsTargetSpecific
&& !A
.existsInTarget(Context
.getTargetInfo()))
4622 if (!A
.acceptsLangOpts(getLangOpts()))
4624 for (const auto &S
: A
.Spellings
) {
4625 if (S
.Syntax
!= Syntax
)
4627 llvm::StringRef Name
= S
.NormalizedFullName
;
4628 llvm::StringRef Scope
;
4629 if ((Syntax
== AttributeCommonInfo::AS_CXX11
||
4630 Syntax
== AttributeCommonInfo::AS_C23
)) {
4631 std::tie(Scope
, Name
) = Name
.split("::");
4632 if (Name
.empty()) // oops, unscoped
4633 std::swap(Name
, Scope
);
4636 // Do we just want a list of scopes rather than attributes?
4637 if (Completion
== AttributeCompletion::Scope
) {
4638 // Make sure to emit each scope only once.
4639 if (!Scope
.empty() && FoundScopes
.insert(Scope
).second
) {
4641 CodeCompletionResult(Results
.getAllocator().CopyString(Scope
)));
4642 // Include alternate form (__gnu__ instead of gnu).
4643 if (const char *Scope2
= underscoreAttrScope(Scope
))
4644 Results
.AddResult(CodeCompletionResult(Scope2
));
4649 // If a scope was specified, it must match but we don't need to print it.
4650 if (!InScopeName
.empty()) {
4651 if (Scope
!= InScopeName
)
4656 auto Add
= [&](llvm::StringRef Scope
, llvm::StringRef Name
,
4658 CodeCompletionBuilder
Builder(Results
.getAllocator(),
4659 Results
.getCodeCompletionTUInfo());
4660 llvm::SmallString
<32> Text
;
4661 if (!Scope
.empty()) {
4670 Builder
.AddTypedTextChunk(Results
.getAllocator().CopyString(Text
));
4672 if (!A
.ArgNames
.empty()) {
4673 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
, "(");
4675 for (const char *Arg
: A
.ArgNames
) {
4677 Builder
.AddChunk(CodeCompletionString::CK_Comma
, ", ");
4679 Builder
.AddPlaceholderChunk(Arg
);
4681 Builder
.AddChunk(CodeCompletionString::CK_RightParen
, ")");
4684 Results
.AddResult(Builder
.TakeString());
4687 // Generate the non-underscore-guarded result.
4688 // Note this is (a suffix of) the NormalizedFullName, no need to copy.
4689 // If an underscore-guarded scope was specified, only the
4690 // underscore-guarded attribute name is relevant.
4691 if (!InScopeUnderscore
)
4692 Add(Scope
, Name
, /*Underscores=*/false);
4694 // Generate the underscore-guarded version, for syntaxes that support it.
4695 // We skip this if the scope was already spelled and not guarded, or
4696 // we must spell it and can't guard it.
4697 if (!(InScope
&& !InScopeUnderscore
) && SyntaxSupportsGuards
) {
4698 llvm::SmallString
<32> Guarded
;
4699 if (Scope
.empty()) {
4700 Add(Scope
, Name
, /*Underscores=*/true);
4702 const char *GuardedScope
= underscoreAttrScope(Scope
);
4705 Add(GuardedScope
, Name
, /*Underscores=*/true);
4709 // It may be nice to include the Kind so we can look up the docs later.
4713 for (const auto *A
: ParsedAttrInfo::getAllBuiltin())
4715 for (const auto &Entry
: ParsedAttrInfoRegistry::entries())
4716 AddCompletions(*Entry
.instantiate());
4718 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
4719 Results
.data(), Results
.size());
4722 struct Sema::CodeCompleteExpressionData
{
4723 CodeCompleteExpressionData(QualType PreferredType
= QualType(),
4724 bool IsParenthesized
= false)
4725 : PreferredType(PreferredType
), IntegralConstantExpression(false),
4726 ObjCCollection(false), IsParenthesized(IsParenthesized
) {}
4728 QualType PreferredType
;
4729 bool IntegralConstantExpression
;
4730 bool ObjCCollection
;
4731 bool IsParenthesized
;
4732 SmallVector
<Decl
*, 4> IgnoreDecls
;
4736 /// Information that allows to avoid completing redundant enumerators.
4737 struct CoveredEnumerators
{
4738 llvm::SmallPtrSet
<EnumConstantDecl
*, 8> Seen
;
4739 NestedNameSpecifier
*SuggestedQualifier
= nullptr;
4743 static void AddEnumerators(ResultBuilder
&Results
, ASTContext
&Context
,
4744 EnumDecl
*Enum
, DeclContext
*CurContext
,
4745 const CoveredEnumerators
&Enumerators
) {
4746 NestedNameSpecifier
*Qualifier
= Enumerators
.SuggestedQualifier
;
4747 if (Context
.getLangOpts().CPlusPlus
&& !Qualifier
&& Enumerators
.Seen
.empty()) {
4748 // If there are no prior enumerators in C++, check whether we have to
4749 // qualify the names of the enumerators that we suggest, because they
4750 // may not be visible in this scope.
4751 Qualifier
= getRequiredQualification(Context
, CurContext
, Enum
);
4754 Results
.EnterNewScope();
4755 for (auto *E
: Enum
->enumerators()) {
4756 if (Enumerators
.Seen
.count(E
))
4759 CodeCompletionResult
R(E
, CCP_EnumInCase
, Qualifier
);
4760 Results
.AddResult(R
, CurContext
, nullptr, false);
4762 Results
.ExitScope();
4765 /// Try to find a corresponding FunctionProtoType for function-like types (e.g.
4766 /// function pointers, std::function, etc).
4767 static const FunctionProtoType
*TryDeconstructFunctionLike(QualType T
) {
4768 assert(!T
.isNull());
4769 // Try to extract first template argument from std::function<> and similar.
4770 // Note we only handle the sugared types, they closely match what users wrote.
4771 // We explicitly choose to not handle ClassTemplateSpecializationDecl.
4772 if (auto *Specialization
= T
->getAs
<TemplateSpecializationType
>()) {
4773 if (Specialization
->template_arguments().size() != 1)
4775 const TemplateArgument
&Argument
= Specialization
->template_arguments()[0];
4776 if (Argument
.getKind() != TemplateArgument::Type
)
4778 return Argument
.getAsType()->getAs
<FunctionProtoType
>();
4780 // Handle other cases.
4781 if (T
->isPointerType())
4782 T
= T
->getPointeeType();
4783 return T
->getAs
<FunctionProtoType
>();
4786 /// Adds a pattern completion for a lambda expression with the specified
4787 /// parameter types and placeholders for parameter names.
4788 static void AddLambdaCompletion(ResultBuilder
&Results
,
4789 llvm::ArrayRef
<QualType
> Parameters
,
4790 const LangOptions
&LangOpts
) {
4791 if (!Results
.includeCodePatterns())
4793 CodeCompletionBuilder
Completion(Results
.getAllocator(),
4794 Results
.getCodeCompletionTUInfo());
4795 // [](<parameters>) {}
4796 Completion
.AddChunk(CodeCompletionString::CK_LeftBracket
);
4797 Completion
.AddPlaceholderChunk("=");
4798 Completion
.AddChunk(CodeCompletionString::CK_RightBracket
);
4799 if (!Parameters
.empty()) {
4800 Completion
.AddChunk(CodeCompletionString::CK_LeftParen
);
4802 for (auto Parameter
: Parameters
) {
4804 Completion
.AddChunk(CodeCompletionString::ChunkKind::CK_Comma
);
4808 constexpr llvm::StringLiteral NamePlaceholder
= "!#!NAME_GOES_HERE!#!";
4809 std::string Type
= std::string(NamePlaceholder
);
4810 Parameter
.getAsStringInternal(Type
, PrintingPolicy(LangOpts
));
4811 llvm::StringRef Prefix
, Suffix
;
4812 std::tie(Prefix
, Suffix
) = llvm::StringRef(Type
).split(NamePlaceholder
);
4813 Prefix
= Prefix
.rtrim();
4814 Suffix
= Suffix
.ltrim();
4816 Completion
.AddTextChunk(Completion
.getAllocator().CopyString(Prefix
));
4817 Completion
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
4818 Completion
.AddPlaceholderChunk("parameter");
4819 Completion
.AddTextChunk(Completion
.getAllocator().CopyString(Suffix
));
4821 Completion
.AddChunk(CodeCompletionString::CK_RightParen
);
4823 Completion
.AddChunk(clang::CodeCompletionString::CK_HorizontalSpace
);
4824 Completion
.AddChunk(CodeCompletionString::CK_LeftBrace
);
4825 Completion
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
4826 Completion
.AddPlaceholderChunk("body");
4827 Completion
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
4828 Completion
.AddChunk(CodeCompletionString::CK_RightBrace
);
4830 Results
.AddResult(Completion
.TakeString());
4833 /// Perform code-completion in an expression context when we know what
4834 /// type we're looking for.
4835 void Sema::CodeCompleteExpression(Scope
*S
,
4836 const CodeCompleteExpressionData
&Data
) {
4837 ResultBuilder
Results(
4838 *this, CodeCompleter
->getAllocator(),
4839 CodeCompleter
->getCodeCompletionTUInfo(),
4840 CodeCompletionContext(
4841 Data
.IsParenthesized
4842 ? CodeCompletionContext::CCC_ParenthesizedExpression
4843 : CodeCompletionContext::CCC_Expression
,
4844 Data
.PreferredType
));
4846 Data
.IsParenthesized
? PCC_ParenthesizedExpression
: PCC_Expression
;
4847 if (Data
.ObjCCollection
)
4848 Results
.setFilter(&ResultBuilder::IsObjCCollection
);
4849 else if (Data
.IntegralConstantExpression
)
4850 Results
.setFilter(&ResultBuilder::IsIntegralConstantValue
);
4851 else if (WantTypesInContext(PCC
, getLangOpts()))
4852 Results
.setFilter(&ResultBuilder::IsOrdinaryName
);
4854 Results
.setFilter(&ResultBuilder::IsOrdinaryNonTypeName
);
4856 if (!Data
.PreferredType
.isNull())
4857 Results
.setPreferredType(Data
.PreferredType
.getNonReferenceType());
4859 // Ignore any declarations that we were told that we don't care about.
4860 for (unsigned I
= 0, N
= Data
.IgnoreDecls
.size(); I
!= N
; ++I
)
4861 Results
.Ignore(Data
.IgnoreDecls
[I
]);
4863 CodeCompletionDeclConsumer
Consumer(Results
, CurContext
);
4864 LookupVisibleDecls(S
, LookupOrdinaryName
, Consumer
,
4865 CodeCompleter
->includeGlobals(),
4866 CodeCompleter
->loadExternal());
4868 Results
.EnterNewScope();
4869 AddOrdinaryNameResults(PCC
, S
, *this, Results
);
4870 Results
.ExitScope();
4872 bool PreferredTypeIsPointer
= false;
4873 if (!Data
.PreferredType
.isNull()) {
4874 PreferredTypeIsPointer
= Data
.PreferredType
->isAnyPointerType() ||
4875 Data
.PreferredType
->isMemberPointerType() ||
4876 Data
.PreferredType
->isBlockPointerType();
4877 if (Data
.PreferredType
->isEnumeralType()) {
4878 EnumDecl
*Enum
= Data
.PreferredType
->castAs
<EnumType
>()->getDecl();
4879 if (auto *Def
= Enum
->getDefinition())
4881 // FIXME: collect covered enumerators in cases like:
4882 // if (x == my_enum::one) { ... } else if (x == ^) {}
4883 AddEnumerators(Results
, Context
, Enum
, CurContext
, CoveredEnumerators());
4887 if (S
->getFnParent() && !Data
.ObjCCollection
&&
4888 !Data
.IntegralConstantExpression
)
4889 AddPrettyFunctionResults(getLangOpts(), Results
);
4891 if (CodeCompleter
->includeMacros())
4892 AddMacroResults(PP
, Results
, CodeCompleter
->loadExternal(), false,
4893 PreferredTypeIsPointer
);
4895 // Complete a lambda expression when preferred type is a function.
4896 if (!Data
.PreferredType
.isNull() && getLangOpts().CPlusPlus11
) {
4897 if (const FunctionProtoType
*F
=
4898 TryDeconstructFunctionLike(Data
.PreferredType
))
4899 AddLambdaCompletion(Results
, F
->getParamTypes(), getLangOpts());
4902 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
4903 Results
.data(), Results
.size());
4906 void Sema::CodeCompleteExpression(Scope
*S
, QualType PreferredType
,
4907 bool IsParenthesized
) {
4908 return CodeCompleteExpression(
4909 S
, CodeCompleteExpressionData(PreferredType
, IsParenthesized
));
4912 void Sema::CodeCompletePostfixExpression(Scope
*S
, ExprResult E
,
4913 QualType PreferredType
) {
4915 CodeCompleteExpression(S
, PreferredType
);
4916 else if (getLangOpts().ObjC
)
4917 CodeCompleteObjCInstanceMessage(S
, E
.get(), std::nullopt
, false);
4920 /// The set of properties that have already been added, referenced by
4922 typedef llvm::SmallPtrSet
<IdentifierInfo
*, 16> AddedPropertiesSet
;
4924 /// Retrieve the container definition, if any?
4925 static ObjCContainerDecl
*getContainerDef(ObjCContainerDecl
*Container
) {
4926 if (ObjCInterfaceDecl
*Interface
= dyn_cast
<ObjCInterfaceDecl
>(Container
)) {
4927 if (Interface
->hasDefinition())
4928 return Interface
->getDefinition();
4933 if (ObjCProtocolDecl
*Protocol
= dyn_cast
<ObjCProtocolDecl
>(Container
)) {
4934 if (Protocol
->hasDefinition())
4935 return Protocol
->getDefinition();
4942 /// Adds a block invocation code completion result for the given block
4943 /// declaration \p BD.
4944 static void AddObjCBlockCall(ASTContext
&Context
, const PrintingPolicy
&Policy
,
4945 CodeCompletionBuilder
&Builder
,
4946 const NamedDecl
*BD
,
4947 const FunctionTypeLoc
&BlockLoc
,
4948 const FunctionProtoTypeLoc
&BlockProtoLoc
) {
4949 Builder
.AddResultTypeChunk(
4950 GetCompletionTypeString(BlockLoc
.getReturnLoc().getType(), Context
,
4951 Policy
, Builder
.getAllocator()));
4953 AddTypedNameChunk(Context
, Policy
, BD
, Builder
);
4954 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
4956 if (BlockProtoLoc
&& BlockProtoLoc
.getTypePtr()->isVariadic()) {
4957 Builder
.AddPlaceholderChunk("...");
4959 for (unsigned I
= 0, N
= BlockLoc
.getNumParams(); I
!= N
; ++I
) {
4961 Builder
.AddChunk(CodeCompletionString::CK_Comma
);
4963 // Format the placeholder string.
4964 std::string PlaceholderStr
=
4965 FormatFunctionParameter(Policy
, BlockLoc
.getParam(I
));
4967 if (I
== N
- 1 && BlockProtoLoc
&&
4968 BlockProtoLoc
.getTypePtr()->isVariadic())
4969 PlaceholderStr
+= ", ...";
4971 // Add the placeholder string.
4972 Builder
.AddPlaceholderChunk(
4973 Builder
.getAllocator().CopyString(PlaceholderStr
));
4977 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
4981 AddObjCProperties(const CodeCompletionContext
&CCContext
,
4982 ObjCContainerDecl
*Container
, bool AllowCategories
,
4983 bool AllowNullaryMethods
, DeclContext
*CurContext
,
4984 AddedPropertiesSet
&AddedProperties
, ResultBuilder
&Results
,
4985 bool IsBaseExprStatement
= false,
4986 bool IsClassProperty
= false, bool InOriginalClass
= true) {
4987 typedef CodeCompletionResult Result
;
4989 // Retrieve the definition.
4990 Container
= getContainerDef(Container
);
4992 // Add properties in this container.
4993 const auto AddProperty
= [&](const ObjCPropertyDecl
*P
) {
4994 if (!AddedProperties
.insert(P
->getIdentifier()).second
)
4997 // FIXME: Provide block invocation completion for non-statement
4999 if (!P
->getType().getTypePtr()->isBlockPointerType() ||
5000 !IsBaseExprStatement
) {
5001 Result R
= Result(P
, Results
.getBasePriority(P
), nullptr);
5002 if (!InOriginalClass
)
5004 Results
.MaybeAddResult(R
, CurContext
);
5008 // Block setter and invocation completion is provided only when we are able
5009 // to find the FunctionProtoTypeLoc with parameter names for the block.
5010 FunctionTypeLoc BlockLoc
;
5011 FunctionProtoTypeLoc BlockProtoLoc
;
5012 findTypeLocationForBlockDecl(P
->getTypeSourceInfo(), BlockLoc
,
5015 Result R
= Result(P
, Results
.getBasePriority(P
), nullptr);
5016 if (!InOriginalClass
)
5018 Results
.MaybeAddResult(R
, CurContext
);
5022 // The default completion result for block properties should be the block
5023 // invocation completion when the base expression is a statement.
5024 CodeCompletionBuilder
Builder(Results
.getAllocator(),
5025 Results
.getCodeCompletionTUInfo());
5026 AddObjCBlockCall(Container
->getASTContext(),
5027 getCompletionPrintingPolicy(Results
.getSema()), Builder
, P
,
5028 BlockLoc
, BlockProtoLoc
);
5029 Result R
= Result(Builder
.TakeString(), P
, Results
.getBasePriority(P
));
5030 if (!InOriginalClass
)
5032 Results
.MaybeAddResult(R
, CurContext
);
5034 // Provide additional block setter completion iff the base expression is a
5035 // statement and the block property is mutable.
5036 if (!P
->isReadOnly()) {
5037 CodeCompletionBuilder
Builder(Results
.getAllocator(),
5038 Results
.getCodeCompletionTUInfo());
5039 AddResultTypeChunk(Container
->getASTContext(),
5040 getCompletionPrintingPolicy(Results
.getSema()), P
,
5041 CCContext
.getBaseType(), Builder
);
5042 Builder
.AddTypedTextChunk(
5043 Results
.getAllocator().CopyString(P
->getName()));
5044 Builder
.AddChunk(CodeCompletionString::CK_Equal
);
5046 std::string PlaceholderStr
= formatBlockPlaceholder(
5047 getCompletionPrintingPolicy(Results
.getSema()), P
, BlockLoc
,
5048 BlockProtoLoc
, /*SuppressBlockName=*/true);
5049 // Add the placeholder string.
5050 Builder
.AddPlaceholderChunk(
5051 Builder
.getAllocator().CopyString(PlaceholderStr
));
5053 // When completing blocks properties that return void the default
5054 // property completion result should show up before the setter,
5055 // otherwise the setter completion should show up before the default
5056 // property completion, as we normally want to use the result of the
5059 Result(Builder
.TakeString(), P
,
5060 Results
.getBasePriority(P
) +
5061 (BlockLoc
.getTypePtr()->getReturnType()->isVoidType()
5062 ? CCD_BlockPropertySetter
5063 : -CCD_BlockPropertySetter
));
5064 if (!InOriginalClass
)
5066 Results
.MaybeAddResult(R
, CurContext
);
5070 if (IsClassProperty
) {
5071 for (const auto *P
: Container
->class_properties())
5074 for (const auto *P
: Container
->instance_properties())
5078 // Add nullary methods or implicit class properties
5079 if (AllowNullaryMethods
) {
5080 ASTContext
&Context
= Container
->getASTContext();
5081 PrintingPolicy Policy
= getCompletionPrintingPolicy(Results
.getSema());
5082 // Adds a method result
5083 const auto AddMethod
= [&](const ObjCMethodDecl
*M
) {
5084 IdentifierInfo
*Name
= M
->getSelector().getIdentifierInfoForSlot(0);
5087 if (!AddedProperties
.insert(Name
).second
)
5089 CodeCompletionBuilder
Builder(Results
.getAllocator(),
5090 Results
.getCodeCompletionTUInfo());
5091 AddResultTypeChunk(Context
, Policy
, M
, CCContext
.getBaseType(), Builder
);
5092 Builder
.AddTypedTextChunk(
5093 Results
.getAllocator().CopyString(Name
->getName()));
5094 Result R
= Result(Builder
.TakeString(), M
,
5095 CCP_MemberDeclaration
+ CCD_MethodAsProperty
);
5096 if (!InOriginalClass
)
5098 Results
.MaybeAddResult(R
, CurContext
);
5101 if (IsClassProperty
) {
5102 for (const auto *M
: Container
->methods()) {
5103 // Gather the class method that can be used as implicit property
5104 // getters. Methods with arguments or methods that return void aren't
5105 // added to the results as they can't be used as a getter.
5106 if (!M
->getSelector().isUnarySelector() ||
5107 M
->getReturnType()->isVoidType() || M
->isInstanceMethod())
5112 for (auto *M
: Container
->methods()) {
5113 if (M
->getSelector().isUnarySelector())
5119 // Add properties in referenced protocols.
5120 if (ObjCProtocolDecl
*Protocol
= dyn_cast
<ObjCProtocolDecl
>(Container
)) {
5121 for (auto *P
: Protocol
->protocols())
5122 AddObjCProperties(CCContext
, P
, AllowCategories
, AllowNullaryMethods
,
5123 CurContext
, AddedProperties
, Results
,
5124 IsBaseExprStatement
, IsClassProperty
,
5125 /*InOriginalClass*/ false);
5126 } else if (ObjCInterfaceDecl
*IFace
=
5127 dyn_cast
<ObjCInterfaceDecl
>(Container
)) {
5128 if (AllowCategories
) {
5129 // Look through categories.
5130 for (auto *Cat
: IFace
->known_categories())
5131 AddObjCProperties(CCContext
, Cat
, AllowCategories
, AllowNullaryMethods
,
5132 CurContext
, AddedProperties
, Results
,
5133 IsBaseExprStatement
, IsClassProperty
,
5137 // Look through protocols.
5138 for (auto *I
: IFace
->all_referenced_protocols())
5139 AddObjCProperties(CCContext
, I
, AllowCategories
, AllowNullaryMethods
,
5140 CurContext
, AddedProperties
, Results
,
5141 IsBaseExprStatement
, IsClassProperty
,
5142 /*InOriginalClass*/ false);
5144 // Look in the superclass.
5145 if (IFace
->getSuperClass())
5146 AddObjCProperties(CCContext
, IFace
->getSuperClass(), AllowCategories
,
5147 AllowNullaryMethods
, CurContext
, AddedProperties
,
5148 Results
, IsBaseExprStatement
, IsClassProperty
,
5149 /*InOriginalClass*/ false);
5150 } else if (const auto *Category
=
5151 dyn_cast
<ObjCCategoryDecl
>(Container
)) {
5152 // Look through protocols.
5153 for (auto *P
: Category
->protocols())
5154 AddObjCProperties(CCContext
, P
, AllowCategories
, AllowNullaryMethods
,
5155 CurContext
, AddedProperties
, Results
,
5156 IsBaseExprStatement
, IsClassProperty
,
5157 /*InOriginalClass*/ false);
5162 AddRecordMembersCompletionResults(Sema
&SemaRef
, ResultBuilder
&Results
,
5163 Scope
*S
, QualType BaseType
,
5164 ExprValueKind BaseKind
, RecordDecl
*RD
,
5165 std::optional
<FixItHint
> AccessOpFixIt
) {
5166 // Indicate that we are performing a member access, and the cv-qualifiers
5167 // for the base object type.
5168 Results
.setObjectTypeQualifiers(BaseType
.getQualifiers(), BaseKind
);
5170 // Access to a C/C++ class, struct, or union.
5171 Results
.allowNestedNameSpecifiers();
5172 std::vector
<FixItHint
> FixIts
;
5174 FixIts
.emplace_back(*AccessOpFixIt
);
5175 CodeCompletionDeclConsumer
Consumer(Results
, RD
, BaseType
, std::move(FixIts
));
5176 SemaRef
.LookupVisibleDecls(RD
, Sema::LookupMemberName
, Consumer
,
5177 SemaRef
.CodeCompleter
->includeGlobals(),
5178 /*IncludeDependentBases=*/true,
5179 SemaRef
.CodeCompleter
->loadExternal());
5181 if (SemaRef
.getLangOpts().CPlusPlus
) {
5182 if (!Results
.empty()) {
5183 // The "template" keyword can follow "->" or "." in the grammar.
5184 // However, we only want to suggest the template keyword if something
5186 bool IsDependent
= BaseType
->isDependentType();
5188 for (Scope
*DepScope
= S
; DepScope
; DepScope
= DepScope
->getParent())
5189 if (DeclContext
*Ctx
= DepScope
->getEntity()) {
5190 IsDependent
= Ctx
->isDependentContext();
5196 Results
.AddResult(CodeCompletionResult("template"));
5201 // Returns the RecordDecl inside the BaseType, falling back to primary template
5202 // in case of specializations. Since we might not have a decl for the
5203 // instantiation/specialization yet, e.g. dependent code.
5204 static RecordDecl
*getAsRecordDecl(QualType BaseType
) {
5205 BaseType
= BaseType
.getNonReferenceType();
5206 if (auto *RD
= BaseType
->getAsRecordDecl()) {
5207 if (const auto *CTSD
=
5208 llvm::dyn_cast
<ClassTemplateSpecializationDecl
>(RD
)) {
5209 // Template might not be instantiated yet, fall back to primary template
5211 if (CTSD
->getTemplateSpecializationKind() == TSK_Undeclared
)
5212 RD
= CTSD
->getSpecializedTemplate()->getTemplatedDecl();
5217 if (const auto *TST
= BaseType
->getAs
<TemplateSpecializationType
>()) {
5218 if (const auto *TD
= dyn_cast_or_null
<ClassTemplateDecl
>(
5219 TST
->getTemplateName().getAsTemplateDecl())) {
5220 return TD
->getTemplatedDecl();
5228 // Collects completion-relevant information about a concept-constrainted type T.
5229 // In particular, examines the constraint expressions to find members of T.
5231 // The design is very simple: we walk down each constraint looking for
5232 // expressions of the form T.foo().
5233 // If we're extra lucky, the return type is specified.
5234 // We don't do any clever handling of && or || in constraint expressions, we
5235 // take members from both branches.
5237 // For example, given:
5238 // template <class T> concept X = requires (T t, string& s) { t.print(s); };
5239 // template <X U> void foo(U u) { u.^ }
5240 // We want to suggest the inferred member function 'print(string)'.
5241 // We see that u has type U, so X<U> holds.
5242 // X<U> requires t.print(s) to be valid, where t has type U (substituted for T).
5243 // By looking at the CallExpr we find the signature of print().
5245 // While we tend to know in advance which kind of members (access via . -> ::)
5246 // we want, it's simpler just to gather them all and post-filter.
5248 // FIXME: some of this machinery could be used for non-concept type-parms too,
5249 // enabling completion for type parameters based on other uses of that param.
5251 // FIXME: there are other cases where a type can be constrained by a concept,
5252 // e.g. inside `if constexpr(ConceptSpecializationExpr) { ... }`
5255 // Describes a likely member of a type, inferred by concept constraints.
5256 // Offered as a code completion for T. T-> and T:: contexts.
5258 // Always non-null: we only handle members with ordinary identifier names.
5259 const IdentifierInfo
*Name
= nullptr;
5260 // Set for functions we've seen called.
5261 // We don't have the declared parameter types, only the actual types of
5262 // arguments we've seen. These are still valuable, as it's hard to render
5263 // a useful function completion with neither parameter types nor names!
5264 std::optional
<SmallVector
<QualType
, 1>> ArgTypes
;
5265 // Whether this is accessed as T.member, T->member, or T::member.
5266 enum AccessOperator
{
5271 // What's known about the type of a variable or return type of a function.
5272 const TypeConstraint
*ResultType
= nullptr;
5273 // FIXME: also track:
5274 // - kind of entity (function/variable/type), to expose structured results
5275 // - template args kinds/types, as a proxy for template params
5277 // For now we simply return these results as "pattern" strings.
5278 CodeCompletionString
*render(Sema
&S
, CodeCompletionAllocator
&Alloc
,
5279 CodeCompletionTUInfo
&Info
) const {
5280 CodeCompletionBuilder
B(Alloc
, Info
);
5283 std::string AsString
;
5285 llvm::raw_string_ostream
OS(AsString
);
5286 QualType ExactType
= deduceType(*ResultType
);
5287 if (!ExactType
.isNull())
5288 ExactType
.print(OS
, getCompletionPrintingPolicy(S
));
5290 ResultType
->print(OS
, getCompletionPrintingPolicy(S
));
5292 B
.AddResultTypeChunk(Alloc
.CopyString(AsString
));
5295 B
.AddTypedTextChunk(Alloc
.CopyString(Name
->getName()));
5296 // Function argument list
5298 B
.AddChunk(clang::CodeCompletionString::CK_LeftParen
);
5300 for (QualType Arg
: *ArgTypes
) {
5304 B
.AddChunk(clang::CodeCompletionString::CK_Comma
);
5305 B
.AddChunk(clang::CodeCompletionString::CK_HorizontalSpace
);
5307 B
.AddPlaceholderChunk(Alloc
.CopyString(
5308 Arg
.getAsString(getCompletionPrintingPolicy(S
))));
5310 B
.AddChunk(clang::CodeCompletionString::CK_RightParen
);
5312 return B
.TakeString();
5316 // BaseType is the type parameter T to infer members from.
5317 // T must be accessible within S, as we use it to find the template entity
5318 // that T is attached to in order to gather the relevant constraints.
5319 ConceptInfo(const TemplateTypeParmType
&BaseType
, Scope
*S
) {
5320 auto *TemplatedEntity
= getTemplatedEntity(BaseType
.getDecl(), S
);
5321 for (const Expr
*E
: constraintsForTemplatedEntity(TemplatedEntity
))
5322 believe(E
, &BaseType
);
5325 std::vector
<Member
> members() {
5326 std::vector
<Member
> Results
;
5327 for (const auto &E
: this->Results
)
5328 Results
.push_back(E
.second
);
5329 llvm::sort(Results
, [](const Member
&L
, const Member
&R
) {
5330 return L
.Name
->getName() < R
.Name
->getName();
5336 // Infer members of T, given that the expression E (dependent on T) is true.
5337 void believe(const Expr
*E
, const TemplateTypeParmType
*T
) {
5340 if (auto *CSE
= dyn_cast
<ConceptSpecializationExpr
>(E
)) {
5341 // If the concept is
5342 // template <class A, class B> concept CD = f<A, B>();
5343 // And the concept specialization is
5345 // Then we're substituting T for B, so we want to make f<A, B>() true
5346 // by adding members to B - i.e. believe(f<A, B>(), B);
5349 // - we don't attempt to substitute int for A
5350 // - when T is used in other ways (like CD<T*>) we ignore it
5351 ConceptDecl
*CD
= CSE
->getNamedConcept();
5352 TemplateParameterList
*Params
= CD
->getTemplateParameters();
5354 for (const auto &Arg
: CSE
->getTemplateArguments()) {
5355 if (Index
>= Params
->size())
5356 break; // Won't happen in valid code.
5357 if (isApprox(Arg
, T
)) {
5358 auto *TTPD
= dyn_cast
<TemplateTypeParmDecl
>(Params
->getParam(Index
));
5361 // T was used as an argument, and bound to the parameter TT.
5362 auto *TT
= cast
<TemplateTypeParmType
>(TTPD
->getTypeForDecl());
5363 // So now we know the constraint as a function of TT is true.
5364 believe(CD
->getConstraintExpr(), TT
);
5365 // (concepts themselves have no associated constraints to require)
5370 } else if (auto *BO
= dyn_cast
<BinaryOperator
>(E
)) {
5371 // For A && B, we can infer members from both branches.
5372 // For A || B, the union is still more useful than the intersection.
5373 if (BO
->getOpcode() == BO_LAnd
|| BO
->getOpcode() == BO_LOr
) {
5374 believe(BO
->getLHS(), T
);
5375 believe(BO
->getRHS(), T
);
5377 } else if (auto *RE
= dyn_cast
<RequiresExpr
>(E
)) {
5378 // A requires(){...} lets us infer members from each requirement.
5379 for (const concepts::Requirement
*Req
: RE
->getRequirements()) {
5380 if (!Req
->isDependent())
5381 continue; // Can't tell us anything about T.
5382 // Now Req cannot a substitution-error: those aren't dependent.
5384 if (auto *TR
= dyn_cast
<concepts::TypeRequirement
>(Req
)) {
5385 // Do a full traversal so we get `foo` from `typename T::foo::bar`.
5386 QualType AssertedType
= TR
->getType()->getType();
5387 ValidVisitor(this, T
).TraverseType(AssertedType
);
5388 } else if (auto *ER
= dyn_cast
<concepts::ExprRequirement
>(Req
)) {
5389 ValidVisitor
Visitor(this, T
);
5390 // If we have a type constraint on the value of the expression,
5391 // AND the whole outer expression describes a member, then we'll
5392 // be able to use the constraint to provide the return type.
5393 if (ER
->getReturnTypeRequirement().isTypeConstraint()) {
5395 ER
->getReturnTypeRequirement().getTypeConstraint();
5396 Visitor
.OuterExpr
= ER
->getExpr();
5398 Visitor
.TraverseStmt(ER
->getExpr());
5399 } else if (auto *NR
= dyn_cast
<concepts::NestedRequirement
>(Req
)) {
5400 believe(NR
->getConstraintExpr(), T
);
5406 // This visitor infers members of T based on traversing expressions/types
5407 // that involve T. It is invoked with code known to be valid for T.
5408 class ValidVisitor
: public RecursiveASTVisitor
<ValidVisitor
> {
5410 const TemplateTypeParmType
*T
;
5412 CallExpr
*Caller
= nullptr;
5413 Expr
*Callee
= nullptr;
5416 // If set, OuterExpr is constrained by OuterType.
5417 Expr
*OuterExpr
= nullptr;
5418 const TypeConstraint
*OuterType
= nullptr;
5420 ValidVisitor(ConceptInfo
*Outer
, const TemplateTypeParmType
*T
)
5421 : Outer(Outer
), T(T
) {
5425 // In T.foo or T->foo, `foo` is a member function/variable.
5426 bool VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr
*E
) {
5427 const Type
*Base
= E
->getBaseType().getTypePtr();
5428 bool IsArrow
= E
->isArrow();
5429 if (Base
->isPointerType() && IsArrow
) {
5431 Base
= Base
->getPointeeType().getTypePtr();
5433 if (isApprox(Base
, T
))
5434 addValue(E
, E
->getMember(), IsArrow
? Member::Arrow
: Member::Dot
);
5438 // In T::foo, `foo` is a static member function/variable.
5439 bool VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr
*E
) {
5440 if (E
->getQualifier() && isApprox(E
->getQualifier()->getAsType(), T
))
5441 addValue(E
, E
->getDeclName(), Member::Colons
);
5445 // In T::typename foo, `foo` is a type.
5446 bool VisitDependentNameType(DependentNameType
*DNT
) {
5447 const auto *Q
= DNT
->getQualifier();
5448 if (Q
&& isApprox(Q
->getAsType(), T
))
5449 addType(DNT
->getIdentifier());
5453 // In T::foo::bar, `foo` must be a type.
5454 // VisitNNS() doesn't exist, and TraverseNNS isn't always called :-(
5455 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNSL
) {
5457 NestedNameSpecifier
*NNS
= NNSL
.getNestedNameSpecifier();
5458 const auto *Q
= NNS
->getPrefix();
5459 if (Q
&& isApprox(Q
->getAsType(), T
))
5460 addType(NNS
->getAsIdentifier());
5462 // FIXME: also handle T::foo<X>::bar
5463 return RecursiveASTVisitor::TraverseNestedNameSpecifierLoc(NNSL
);
5466 // FIXME also handle T::foo<X>
5468 // Track the innermost caller/callee relationship so we can tell if a
5469 // nested expr is being called as a function.
5470 bool VisitCallExpr(CallExpr
*CE
) {
5472 Callee
= CE
->getCallee();
5477 void addResult(Member
&&M
) {
5478 auto R
= Outer
->Results
.try_emplace(M
.Name
);
5479 Member
&O
= R
.first
->second
;
5480 // Overwrite existing if the new member has more info.
5481 // The preference of . vs :: vs -> is fairly arbitrary.
5482 if (/*Inserted*/ R
.second
||
5483 std::make_tuple(M
.ArgTypes
.has_value(), M
.ResultType
!= nullptr,
5484 M
.Operator
) > std::make_tuple(O
.ArgTypes
.has_value(),
5485 O
.ResultType
!= nullptr,
5490 void addType(const IdentifierInfo
*Name
) {
5495 M
.Operator
= Member::Colons
;
5496 addResult(std::move(M
));
5499 void addValue(Expr
*E
, DeclarationName Name
,
5500 Member::AccessOperator Operator
) {
5501 if (!Name
.isIdentifier())
5504 Result
.Name
= Name
.getAsIdentifierInfo();
5505 Result
.Operator
= Operator
;
5506 // If this is the callee of an immediately-enclosing CallExpr, then
5507 // treat it as a method, otherwise it's a variable.
5508 if (Caller
!= nullptr && Callee
== E
) {
5509 Result
.ArgTypes
.emplace();
5510 for (const auto *Arg
: Caller
->arguments())
5511 Result
.ArgTypes
->push_back(Arg
->getType());
5512 if (Caller
== OuterExpr
) {
5513 Result
.ResultType
= OuterType
;
5517 Result
.ResultType
= OuterType
;
5519 addResult(std::move(Result
));
5523 static bool isApprox(const TemplateArgument
&Arg
, const Type
*T
) {
5524 return Arg
.getKind() == TemplateArgument::Type
&&
5525 isApprox(Arg
.getAsType().getTypePtr(), T
);
5528 static bool isApprox(const Type
*T1
, const Type
*T2
) {
5530 T1
->getCanonicalTypeUnqualified() ==
5531 T2
->getCanonicalTypeUnqualified();
5534 // Returns the DeclContext immediately enclosed by the template parameter
5535 // scope. For primary templates, this is the templated (e.g.) CXXRecordDecl.
5536 // For specializations, this is e.g. ClassTemplatePartialSpecializationDecl.
5537 static DeclContext
*getTemplatedEntity(const TemplateTypeParmDecl
*D
,
5541 Scope
*Inner
= nullptr;
5543 if (S
->isTemplateParamScope() && S
->isDeclScope(D
))
5544 return Inner
? Inner
->getEntity() : nullptr;
5551 // Gets all the type constraint expressions that might apply to the type
5552 // variables associated with DC (as returned by getTemplatedEntity()).
5553 static SmallVector
<const Expr
*, 1>
5554 constraintsForTemplatedEntity(DeclContext
*DC
) {
5555 SmallVector
<const Expr
*, 1> Result
;
5558 // Primary templates can have constraints.
5559 if (const auto *TD
= cast
<Decl
>(DC
)->getDescribedTemplate())
5560 TD
->getAssociatedConstraints(Result
);
5561 // Partial specializations may have constraints.
5562 if (const auto *CTPSD
=
5563 dyn_cast
<ClassTemplatePartialSpecializationDecl
>(DC
))
5564 CTPSD
->getAssociatedConstraints(Result
);
5565 if (const auto *VTPSD
= dyn_cast
<VarTemplatePartialSpecializationDecl
>(DC
))
5566 VTPSD
->getAssociatedConstraints(Result
);
5570 // Attempt to find the unique type satisfying a constraint.
5571 // This lets us show e.g. `int` instead of `std::same_as<int>`.
5572 static QualType
deduceType(const TypeConstraint
&T
) {
5573 // Assume a same_as<T> return type constraint is std::same_as or equivalent.
5574 // In this case the return type is T.
5575 DeclarationName DN
= T
.getNamedConcept()->getDeclName();
5576 if (DN
.isIdentifier() && DN
.getAsIdentifierInfo()->isStr("same_as"))
5577 if (const auto *Args
= T
.getTemplateArgsAsWritten())
5578 if (Args
->getNumTemplateArgs() == 1) {
5579 const auto &Arg
= Args
->arguments().front().getArgument();
5580 if (Arg
.getKind() == TemplateArgument::Type
)
5581 return Arg
.getAsType();
5586 llvm::DenseMap
<const IdentifierInfo
*, Member
> Results
;
5589 // Returns a type for E that yields acceptable member completions.
5590 // In particular, when E->getType() is DependentTy, try to guess a likely type.
5591 // We accept some lossiness (like dropping parameters).
5592 // We only try to handle common expressions on the LHS of MemberExpr.
5593 QualType
getApproximateType(const Expr
*E
) {
5594 if (E
->getType().isNull())
5596 E
= E
->IgnoreParenImpCasts();
5597 QualType Unresolved
= E
->getType();
5598 // We only resolve DependentTy, or undeduced autos (including auto* etc).
5599 if (!Unresolved
->isSpecificBuiltinType(BuiltinType::Dependent
)) {
5600 AutoType
*Auto
= Unresolved
->getContainedAutoType();
5601 if (!Auto
|| !Auto
->isUndeducedAutoType())
5604 // A call: approximate-resolve callee to a function type, get its return type
5605 if (const CallExpr
*CE
= llvm::dyn_cast
<CallExpr
>(E
)) {
5606 QualType Callee
= getApproximateType(CE
->getCallee());
5607 if (Callee
.isNull() ||
5608 Callee
->isSpecificPlaceholderType(BuiltinType::BoundMember
))
5609 Callee
= Expr::findBoundMemberType(CE
->getCallee());
5610 if (Callee
.isNull())
5613 if (const auto *FnTypePtr
= Callee
->getAs
<PointerType
>()) {
5614 Callee
= FnTypePtr
->getPointeeType();
5615 } else if (const auto *BPT
= Callee
->getAs
<BlockPointerType
>()) {
5616 Callee
= BPT
->getPointeeType();
5618 if (const FunctionType
*FnType
= Callee
->getAs
<FunctionType
>())
5619 return FnType
->getReturnType().getNonReferenceType();
5621 // Unresolved call: try to guess the return type.
5622 if (const auto *OE
= llvm::dyn_cast
<OverloadExpr
>(CE
->getCallee())) {
5623 // If all candidates have the same approximate return type, use it.
5624 // Discard references and const to allow more to be "the same".
5625 // (In particular, if there's one candidate + ADL, resolve it).
5626 const Type
*Common
= nullptr;
5627 for (const auto *D
: OE
->decls()) {
5628 QualType ReturnType
;
5629 if (const auto *FD
= llvm::dyn_cast
<FunctionDecl
>(D
))
5630 ReturnType
= FD
->getReturnType();
5631 else if (const auto *FTD
= llvm::dyn_cast
<FunctionTemplateDecl
>(D
))
5632 ReturnType
= FTD
->getTemplatedDecl()->getReturnType();
5633 if (ReturnType
.isNull())
5635 const Type
*Candidate
=
5636 ReturnType
.getNonReferenceType().getCanonicalType().getTypePtr();
5637 if (Common
&& Common
!= Candidate
)
5638 return Unresolved
; // Multiple candidates.
5641 if (Common
!= nullptr)
5642 return QualType(Common
, 0);
5645 // A dependent member: approximate-resolve the base, then lookup.
5646 if (const auto *CDSME
= llvm::dyn_cast
<CXXDependentScopeMemberExpr
>(E
)) {
5647 QualType Base
= CDSME
->isImplicitAccess()
5648 ? CDSME
->getBaseType()
5649 : getApproximateType(CDSME
->getBase());
5650 if (CDSME
->isArrow() && !Base
.isNull())
5651 Base
= Base
->getPointeeType(); // could handle unique_ptr etc here?
5655 : llvm::dyn_cast_or_null
<CXXRecordDecl
>(getAsRecordDecl(Base
));
5656 if (RD
&& RD
->isCompleteDefinition()) {
5657 // Look up member heuristically, including in bases.
5658 for (const auto *Member
: RD
->lookupDependentName(
5659 CDSME
->getMember(), [](const NamedDecl
*Member
) {
5660 return llvm::isa
<ValueDecl
>(Member
);
5662 return llvm::cast
<ValueDecl
>(Member
)->getType().getNonReferenceType();
5666 // A reference to an `auto` variable: approximate-resolve its initializer.
5667 if (const auto *DRE
= llvm::dyn_cast
<DeclRefExpr
>(E
)) {
5668 if (const auto *VD
= llvm::dyn_cast
<VarDecl
>(DRE
->getDecl())) {
5670 return getApproximateType(VD
->getInit());
5676 // If \p Base is ParenListExpr, assume a chain of comma operators and pick the
5677 // last expr. We expect other ParenListExprs to be resolved to e.g. constructor
5678 // calls before here. (So the ParenListExpr should be nonempty, but check just
5680 Expr
*unwrapParenList(Expr
*Base
) {
5681 if (auto *PLE
= llvm::dyn_cast_or_null
<ParenListExpr
>(Base
)) {
5682 if (PLE
->getNumExprs() == 0)
5684 Base
= PLE
->getExpr(PLE
->getNumExprs() - 1);
5691 void Sema::CodeCompleteMemberReferenceExpr(Scope
*S
, Expr
*Base
,
5693 SourceLocation OpLoc
, bool IsArrow
,
5694 bool IsBaseExprStatement
,
5695 QualType PreferredType
) {
5696 Base
= unwrapParenList(Base
);
5697 OtherOpBase
= unwrapParenList(OtherOpBase
);
5698 if (!Base
|| !CodeCompleter
)
5701 ExprResult ConvertedBase
= PerformMemberExprBaseConversion(Base
, IsArrow
);
5702 if (ConvertedBase
.isInvalid())
5704 QualType ConvertedBaseType
= getApproximateType(ConvertedBase
.get());
5706 enum CodeCompletionContext::Kind contextKind
;
5709 if (const auto *Ptr
= ConvertedBaseType
->getAs
<PointerType
>())
5710 ConvertedBaseType
= Ptr
->getPointeeType();
5714 contextKind
= CodeCompletionContext::CCC_ArrowMemberAccess
;
5716 if (ConvertedBaseType
->isObjCObjectPointerType() ||
5717 ConvertedBaseType
->isObjCObjectOrInterfaceType()) {
5718 contextKind
= CodeCompletionContext::CCC_ObjCPropertyAccess
;
5720 contextKind
= CodeCompletionContext::CCC_DotMemberAccess
;
5724 CodeCompletionContext
CCContext(contextKind
, ConvertedBaseType
);
5725 CCContext
.setPreferredType(PreferredType
);
5726 ResultBuilder
Results(*this, CodeCompleter
->getAllocator(),
5727 CodeCompleter
->getCodeCompletionTUInfo(), CCContext
,
5728 &ResultBuilder::IsMember
);
5730 auto DoCompletion
= [&](Expr
*Base
, bool IsArrow
,
5731 std::optional
<FixItHint
> AccessOpFixIt
) -> bool {
5735 ExprResult ConvertedBase
= PerformMemberExprBaseConversion(Base
, IsArrow
);
5736 if (ConvertedBase
.isInvalid())
5738 Base
= ConvertedBase
.get();
5740 QualType BaseType
= getApproximateType(Base
);
5741 if (BaseType
.isNull())
5743 ExprValueKind BaseKind
= Base
->getValueKind();
5746 if (const PointerType
*Ptr
= BaseType
->getAs
<PointerType
>()) {
5747 BaseType
= Ptr
->getPointeeType();
5748 BaseKind
= VK_LValue
;
5749 } else if (BaseType
->isObjCObjectPointerType() ||
5750 BaseType
->isTemplateTypeParmType()) {
5751 // Both cases (dot/arrow) handled below.
5757 if (RecordDecl
*RD
= getAsRecordDecl(BaseType
)) {
5758 AddRecordMembersCompletionResults(*this, Results
, S
, BaseType
, BaseKind
,
5759 RD
, std::move(AccessOpFixIt
));
5760 } else if (const auto *TTPT
=
5761 dyn_cast
<TemplateTypeParmType
>(BaseType
.getTypePtr())) {
5763 IsArrow
? ConceptInfo::Member::Arrow
: ConceptInfo::Member::Dot
;
5764 for (const auto &R
: ConceptInfo(*TTPT
, S
).members()) {
5765 if (R
.Operator
!= Operator
)
5767 CodeCompletionResult
Result(
5768 R
.render(*this, CodeCompleter
->getAllocator(),
5769 CodeCompleter
->getCodeCompletionTUInfo()));
5771 Result
.FixIts
.push_back(*AccessOpFixIt
);
5772 Results
.AddResult(std::move(Result
));
5774 } else if (!IsArrow
&& BaseType
->isObjCObjectPointerType()) {
5775 // Objective-C property reference. Bail if we're performing fix-it code
5776 // completion since Objective-C properties are normally backed by ivars,
5777 // most Objective-C fix-its here would have little value.
5778 if (AccessOpFixIt
) {
5781 AddedPropertiesSet AddedProperties
;
5783 if (const ObjCObjectPointerType
*ObjCPtr
=
5784 BaseType
->getAsObjCInterfacePointerType()) {
5785 // Add property results based on our interface.
5786 assert(ObjCPtr
&& "Non-NULL pointer guaranteed above!");
5787 AddObjCProperties(CCContext
, ObjCPtr
->getInterfaceDecl(), true,
5788 /*AllowNullaryMethods=*/true, CurContext
,
5789 AddedProperties
, Results
, IsBaseExprStatement
);
5792 // Add properties from the protocols in a qualified interface.
5793 for (auto *I
: BaseType
->castAs
<ObjCObjectPointerType
>()->quals())
5794 AddObjCProperties(CCContext
, I
, true, /*AllowNullaryMethods=*/true,
5795 CurContext
, AddedProperties
, Results
,
5796 IsBaseExprStatement
, /*IsClassProperty*/ false,
5797 /*InOriginalClass*/ false);
5798 } else if ((IsArrow
&& BaseType
->isObjCObjectPointerType()) ||
5799 (!IsArrow
&& BaseType
->isObjCObjectType())) {
5800 // Objective-C instance variable access. Bail if we're performing fix-it
5801 // code completion since Objective-C properties are normally backed by
5802 // ivars, most Objective-C fix-its here would have little value.
5803 if (AccessOpFixIt
) {
5806 ObjCInterfaceDecl
*Class
= nullptr;
5807 if (const ObjCObjectPointerType
*ObjCPtr
=
5808 BaseType
->getAs
<ObjCObjectPointerType
>())
5809 Class
= ObjCPtr
->getInterfaceDecl();
5811 Class
= BaseType
->castAs
<ObjCObjectType
>()->getInterface();
5813 // Add all ivars from this class and its superclasses.
5815 CodeCompletionDeclConsumer
Consumer(Results
, Class
, BaseType
);
5816 Results
.setFilter(&ResultBuilder::IsObjCIvar
);
5818 Class
, LookupMemberName
, Consumer
, CodeCompleter
->includeGlobals(),
5819 /*IncludeDependentBases=*/false, CodeCompleter
->loadExternal());
5823 // FIXME: How do we cope with isa?
5827 Results
.EnterNewScope();
5829 bool CompletionSucceded
= DoCompletion(Base
, IsArrow
, std::nullopt
);
5830 if (CodeCompleter
->includeFixIts()) {
5831 const CharSourceRange OpRange
=
5832 CharSourceRange::getTokenRange(OpLoc
, OpLoc
);
5833 CompletionSucceded
|= DoCompletion(
5834 OtherOpBase
, !IsArrow
,
5835 FixItHint::CreateReplacement(OpRange
, IsArrow
? "." : "->"));
5838 Results
.ExitScope();
5840 if (!CompletionSucceded
)
5843 // Hand off the results found for code completion.
5844 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
5845 Results
.data(), Results
.size());
5848 void Sema::CodeCompleteObjCClassPropertyRefExpr(Scope
*S
,
5849 IdentifierInfo
&ClassName
,
5850 SourceLocation ClassNameLoc
,
5851 bool IsBaseExprStatement
) {
5852 IdentifierInfo
*ClassNamePtr
= &ClassName
;
5853 ObjCInterfaceDecl
*IFace
= getObjCInterfaceDecl(ClassNamePtr
, ClassNameLoc
);
5856 CodeCompletionContext
CCContext(
5857 CodeCompletionContext::CCC_ObjCPropertyAccess
);
5858 ResultBuilder
Results(*this, CodeCompleter
->getAllocator(),
5859 CodeCompleter
->getCodeCompletionTUInfo(), CCContext
,
5860 &ResultBuilder::IsMember
);
5861 Results
.EnterNewScope();
5862 AddedPropertiesSet AddedProperties
;
5863 AddObjCProperties(CCContext
, IFace
, true,
5864 /*AllowNullaryMethods=*/true, CurContext
, AddedProperties
,
5865 Results
, IsBaseExprStatement
,
5866 /*IsClassProperty=*/true);
5867 Results
.ExitScope();
5868 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
5869 Results
.data(), Results
.size());
5872 void Sema::CodeCompleteTag(Scope
*S
, unsigned TagSpec
) {
5876 ResultBuilder::LookupFilter Filter
= nullptr;
5877 enum CodeCompletionContext::Kind ContextKind
=
5878 CodeCompletionContext::CCC_Other
;
5879 switch ((DeclSpec::TST
)TagSpec
) {
5880 case DeclSpec::TST_enum
:
5881 Filter
= &ResultBuilder::IsEnum
;
5882 ContextKind
= CodeCompletionContext::CCC_EnumTag
;
5885 case DeclSpec::TST_union
:
5886 Filter
= &ResultBuilder::IsUnion
;
5887 ContextKind
= CodeCompletionContext::CCC_UnionTag
;
5890 case DeclSpec::TST_struct
:
5891 case DeclSpec::TST_class
:
5892 case DeclSpec::TST_interface
:
5893 Filter
= &ResultBuilder::IsClassOrStruct
;
5894 ContextKind
= CodeCompletionContext::CCC_ClassOrStructTag
;
5898 llvm_unreachable("Unknown type specifier kind in CodeCompleteTag");
5901 ResultBuilder
Results(*this, CodeCompleter
->getAllocator(),
5902 CodeCompleter
->getCodeCompletionTUInfo(), ContextKind
);
5903 CodeCompletionDeclConsumer
Consumer(Results
, CurContext
);
5905 // First pass: look for tags.
5906 Results
.setFilter(Filter
);
5907 LookupVisibleDecls(S
, LookupTagName
, Consumer
,
5908 CodeCompleter
->includeGlobals(),
5909 CodeCompleter
->loadExternal());
5911 if (CodeCompleter
->includeGlobals()) {
5912 // Second pass: look for nested name specifiers.
5913 Results
.setFilter(&ResultBuilder::IsNestedNameSpecifier
);
5914 LookupVisibleDecls(S
, LookupNestedNameSpecifierName
, Consumer
,
5915 CodeCompleter
->includeGlobals(),
5916 CodeCompleter
->loadExternal());
5919 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
5920 Results
.data(), Results
.size());
5923 static void AddTypeQualifierResults(DeclSpec
&DS
, ResultBuilder
&Results
,
5924 const LangOptions
&LangOpts
) {
5925 if (!(DS
.getTypeQualifiers() & DeclSpec::TQ_const
))
5926 Results
.AddResult("const");
5927 if (!(DS
.getTypeQualifiers() & DeclSpec::TQ_volatile
))
5928 Results
.AddResult("volatile");
5929 if (LangOpts
.C99
&& !(DS
.getTypeQualifiers() & DeclSpec::TQ_restrict
))
5930 Results
.AddResult("restrict");
5931 if (LangOpts
.C11
&& !(DS
.getTypeQualifiers() & DeclSpec::TQ_atomic
))
5932 Results
.AddResult("_Atomic");
5933 if (LangOpts
.MSVCCompat
&& !(DS
.getTypeQualifiers() & DeclSpec::TQ_unaligned
))
5934 Results
.AddResult("__unaligned");
5937 void Sema::CodeCompleteTypeQualifiers(DeclSpec
&DS
) {
5938 ResultBuilder
Results(*this, CodeCompleter
->getAllocator(),
5939 CodeCompleter
->getCodeCompletionTUInfo(),
5940 CodeCompletionContext::CCC_TypeQualifiers
);
5941 Results
.EnterNewScope();
5942 AddTypeQualifierResults(DS
, Results
, LangOpts
);
5943 Results
.ExitScope();
5944 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
5945 Results
.data(), Results
.size());
5948 void Sema::CodeCompleteFunctionQualifiers(DeclSpec
&DS
, Declarator
&D
,
5949 const VirtSpecifiers
*VS
) {
5950 ResultBuilder
Results(*this, CodeCompleter
->getAllocator(),
5951 CodeCompleter
->getCodeCompletionTUInfo(),
5952 CodeCompletionContext::CCC_TypeQualifiers
);
5953 Results
.EnterNewScope();
5954 AddTypeQualifierResults(DS
, Results
, LangOpts
);
5955 if (LangOpts
.CPlusPlus11
) {
5956 Results
.AddResult("noexcept");
5957 if (D
.getContext() == DeclaratorContext::Member
&& !D
.isCtorOrDtor() &&
5958 !D
.isStaticMember()) {
5959 if (!VS
|| !VS
->isFinalSpecified())
5960 Results
.AddResult("final");
5961 if (!VS
|| !VS
->isOverrideSpecified())
5962 Results
.AddResult("override");
5965 Results
.ExitScope();
5966 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
5967 Results
.data(), Results
.size());
5970 void Sema::CodeCompleteBracketDeclarator(Scope
*S
) {
5971 CodeCompleteExpression(S
, QualType(getASTContext().getSizeType()));
5974 void Sema::CodeCompleteCase(Scope
*S
) {
5975 if (getCurFunction()->SwitchStack
.empty() || !CodeCompleter
)
5978 SwitchStmt
*Switch
= getCurFunction()->SwitchStack
.back().getPointer();
5979 // Condition expression might be invalid, do not continue in this case.
5980 if (!Switch
->getCond())
5982 QualType type
= Switch
->getCond()->IgnoreImplicit()->getType();
5983 if (!type
->isEnumeralType()) {
5984 CodeCompleteExpressionData
Data(type
);
5985 Data
.IntegralConstantExpression
= true;
5986 CodeCompleteExpression(S
, Data
);
5990 // Code-complete the cases of a switch statement over an enumeration type
5991 // by providing the list of
5992 EnumDecl
*Enum
= type
->castAs
<EnumType
>()->getDecl();
5993 if (EnumDecl
*Def
= Enum
->getDefinition())
5996 // Determine which enumerators we have already seen in the switch statement.
5997 // FIXME: Ideally, we would also be able to look *past* the code-completion
5998 // token, in case we are code-completing in the middle of the switch and not
5999 // at the end. However, we aren't able to do so at the moment.
6000 CoveredEnumerators Enumerators
;
6001 for (SwitchCase
*SC
= Switch
->getSwitchCaseList(); SC
;
6002 SC
= SC
->getNextSwitchCase()) {
6003 CaseStmt
*Case
= dyn_cast
<CaseStmt
>(SC
);
6007 Expr
*CaseVal
= Case
->getLHS()->IgnoreParenCasts();
6008 if (auto *DRE
= dyn_cast
<DeclRefExpr
>(CaseVal
))
6009 if (auto *Enumerator
=
6010 dyn_cast
<EnumConstantDecl
>(DRE
->getDecl())) {
6011 // We look into the AST of the case statement to determine which
6012 // enumerator was named. Alternatively, we could compute the value of
6013 // the integral constant expression, then compare it against the
6014 // values of each enumerator. However, value-based approach would not
6015 // work as well with C++ templates where enumerators declared within a
6016 // template are type- and value-dependent.
6017 Enumerators
.Seen
.insert(Enumerator
);
6019 // If this is a qualified-id, keep track of the nested-name-specifier
6020 // so that we can reproduce it as part of code completion, e.g.,
6022 // switch (TagD.getKind()) {
6023 // case TagDecl::TK_enum:
6027 // At the XXX, our completions are TagDecl::TK_union,
6028 // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
6029 // TK_struct, and TK_class.
6030 Enumerators
.SuggestedQualifier
= DRE
->getQualifier();
6034 // Add any enumerators that have not yet been mentioned.
6035 ResultBuilder
Results(*this, CodeCompleter
->getAllocator(),
6036 CodeCompleter
->getCodeCompletionTUInfo(),
6037 CodeCompletionContext::CCC_Expression
);
6038 AddEnumerators(Results
, Context
, Enum
, CurContext
, Enumerators
);
6040 if (CodeCompleter
->includeMacros()) {
6041 AddMacroResults(PP
, Results
, CodeCompleter
->loadExternal(), false);
6043 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
6044 Results
.data(), Results
.size());
6047 static bool anyNullArguments(ArrayRef
<Expr
*> Args
) {
6048 if (Args
.size() && !Args
.data())
6051 for (unsigned I
= 0; I
!= Args
.size(); ++I
)
6058 typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate
;
6060 static void mergeCandidatesWithResults(
6061 Sema
&SemaRef
, SmallVectorImpl
<ResultCandidate
> &Results
,
6062 OverloadCandidateSet
&CandidateSet
, SourceLocation Loc
, size_t ArgSize
) {
6063 // Sort the overload candidate set by placing the best overloads first.
6064 llvm::stable_sort(CandidateSet
, [&](const OverloadCandidate
&X
,
6065 const OverloadCandidate
&Y
) {
6066 return isBetterOverloadCandidate(SemaRef
, X
, Y
, Loc
,
6067 CandidateSet
.getKind());
6070 // Add the remaining viable overload candidates as code-completion results.
6071 for (OverloadCandidate
&Candidate
: CandidateSet
) {
6072 if (Candidate
.Function
) {
6073 if (Candidate
.Function
->isDeleted())
6075 if (shouldEnforceArgLimit(/*PartialOverloading=*/true,
6076 Candidate
.Function
) &&
6077 Candidate
.Function
->getNumParams() <= ArgSize
&&
6078 // Having zero args is annoying, normally we don't surface a function
6079 // with 2 params, if you already have 2 params, because you are
6080 // inserting the 3rd now. But with zero, it helps the user to figure
6081 // out there are no overloads that take any arguments. Hence we are
6082 // keeping the overload.
6086 if (Candidate
.Viable
)
6087 Results
.push_back(ResultCandidate(Candidate
.Function
));
6091 /// Get the type of the Nth parameter from a given set of overload
6093 static QualType
getParamType(Sema
&SemaRef
,
6094 ArrayRef
<ResultCandidate
> Candidates
, unsigned N
) {
6096 // Given the overloads 'Candidates' for a function call matching all arguments
6097 // up to N, return the type of the Nth parameter if it is the same for all
6098 // overload candidates.
6100 for (auto &Candidate
: Candidates
) {
6101 QualType CandidateParamType
= Candidate
.getParamType(N
);
6102 if (CandidateParamType
.isNull())
6104 if (ParamType
.isNull()) {
6105 ParamType
= CandidateParamType
;
6108 if (!SemaRef
.Context
.hasSameUnqualifiedType(
6109 ParamType
.getNonReferenceType(),
6110 CandidateParamType
.getNonReferenceType()))
6111 // Two conflicting types, give up.
6119 ProduceSignatureHelp(Sema
&SemaRef
, MutableArrayRef
<ResultCandidate
> Candidates
,
6120 unsigned CurrentArg
, SourceLocation OpenParLoc
,
6122 if (Candidates
.empty())
6124 if (SemaRef
.getPreprocessor().isCodeCompletionReached())
6125 SemaRef
.CodeCompleter
->ProcessOverloadCandidates(
6126 SemaRef
, CurrentArg
, Candidates
.data(), Candidates
.size(), OpenParLoc
,
6128 return getParamType(SemaRef
, Candidates
, CurrentArg
);
6131 // Given a callee expression `Fn`, if the call is through a function pointer,
6132 // try to find the declaration of the corresponding function pointer type,
6133 // so that we can recover argument names from it.
6134 static FunctionProtoTypeLoc
GetPrototypeLoc(Expr
*Fn
) {
6136 if (const auto *T
= Fn
->getType().getTypePtr()->getAs
<TypedefType
>()) {
6137 Target
= T
->getDecl()->getTypeSourceInfo()->getTypeLoc();
6139 } else if (const auto *DR
= dyn_cast
<DeclRefExpr
>(Fn
)) {
6140 const auto *D
= DR
->getDecl();
6141 if (const auto *const VD
= dyn_cast
<VarDecl
>(D
)) {
6142 Target
= VD
->getTypeSourceInfo()->getTypeLoc();
6149 // Unwrap types that may be wrapping the function type
6151 if (auto P
= Target
.getAs
<PointerTypeLoc
>()) {
6152 Target
= P
.getPointeeLoc();
6155 if (auto A
= Target
.getAs
<AttributedTypeLoc
>()) {
6156 Target
= A
.getModifiedLoc();
6159 if (auto P
= Target
.getAs
<ParenTypeLoc
>()) {
6160 Target
= P
.getInnerLoc();
6166 if (auto F
= Target
.getAs
<FunctionProtoTypeLoc
>()) {
6173 QualType
Sema::ProduceCallSignatureHelp(Expr
*Fn
, ArrayRef
<Expr
*> Args
,
6174 SourceLocation OpenParLoc
) {
6175 Fn
= unwrapParenList(Fn
);
6176 if (!CodeCompleter
|| !Fn
)
6179 // FIXME: Provide support for variadic template functions.
6180 // Ignore type-dependent call expressions entirely.
6181 if (Fn
->isTypeDependent() || anyNullArguments(Args
))
6183 // In presence of dependent args we surface all possible signatures using the
6184 // non-dependent args in the prefix. Afterwards we do a post filtering to make
6185 // sure provided candidates satisfy parameter count restrictions.
6186 auto ArgsWithoutDependentTypes
=
6187 Args
.take_while([](Expr
*Arg
) { return !Arg
->isTypeDependent(); });
6189 SmallVector
<ResultCandidate
, 8> Results
;
6191 Expr
*NakedFn
= Fn
->IgnoreParenCasts();
6192 // Build an overload candidate set based on the functions we find.
6193 SourceLocation Loc
= Fn
->getExprLoc();
6194 OverloadCandidateSet
CandidateSet(Loc
, OverloadCandidateSet::CSK_Normal
);
6196 if (auto ULE
= dyn_cast
<UnresolvedLookupExpr
>(NakedFn
)) {
6197 AddOverloadedCallCandidates(ULE
, ArgsWithoutDependentTypes
, CandidateSet
,
6198 /*PartialOverloading=*/true);
6199 } else if (auto UME
= dyn_cast
<UnresolvedMemberExpr
>(NakedFn
)) {
6200 TemplateArgumentListInfo TemplateArgsBuffer
, *TemplateArgs
= nullptr;
6201 if (UME
->hasExplicitTemplateArgs()) {
6202 UME
->copyTemplateArgumentsInto(TemplateArgsBuffer
);
6203 TemplateArgs
= &TemplateArgsBuffer
;
6206 // Add the base as first argument (use a nullptr if the base is implicit).
6207 SmallVector
<Expr
*, 12> ArgExprs(
6208 1, UME
->isImplicitAccess() ? nullptr : UME
->getBase());
6209 ArgExprs
.append(ArgsWithoutDependentTypes
.begin(),
6210 ArgsWithoutDependentTypes
.end());
6211 UnresolvedSet
<8> Decls
;
6212 Decls
.append(UME
->decls_begin(), UME
->decls_end());
6213 const bool FirstArgumentIsBase
= !UME
->isImplicitAccess() && UME
->getBase();
6214 AddFunctionCandidates(Decls
, ArgExprs
, CandidateSet
, TemplateArgs
,
6215 /*SuppressUserConversions=*/false,
6216 /*PartialOverloading=*/true, FirstArgumentIsBase
);
6218 FunctionDecl
*FD
= nullptr;
6219 if (auto *MCE
= dyn_cast
<MemberExpr
>(NakedFn
))
6220 FD
= dyn_cast
<FunctionDecl
>(MCE
->getMemberDecl());
6221 else if (auto *DRE
= dyn_cast
<DeclRefExpr
>(NakedFn
))
6222 FD
= dyn_cast
<FunctionDecl
>(DRE
->getDecl());
6223 if (FD
) { // We check whether it's a resolved function declaration.
6224 if (!getLangOpts().CPlusPlus
||
6225 !FD
->getType()->getAs
<FunctionProtoType
>())
6226 Results
.push_back(ResultCandidate(FD
));
6228 AddOverloadCandidate(FD
, DeclAccessPair::make(FD
, FD
->getAccess()),
6229 ArgsWithoutDependentTypes
, CandidateSet
,
6230 /*SuppressUserConversions=*/false,
6231 /*PartialOverloading=*/true);
6233 } else if (auto DC
= NakedFn
->getType()->getAsCXXRecordDecl()) {
6234 // If expression's type is CXXRecordDecl, it may overload the function
6235 // call operator, so we check if it does and add them as candidates.
6236 // A complete type is needed to lookup for member function call operators.
6237 if (isCompleteType(Loc
, NakedFn
->getType())) {
6238 DeclarationName OpName
=
6239 Context
.DeclarationNames
.getCXXOperatorName(OO_Call
);
6240 LookupResult
R(*this, OpName
, Loc
, LookupOrdinaryName
);
6241 LookupQualifiedName(R
, DC
);
6242 R
.suppressDiagnostics();
6243 SmallVector
<Expr
*, 12> ArgExprs(1, NakedFn
);
6244 ArgExprs
.append(ArgsWithoutDependentTypes
.begin(),
6245 ArgsWithoutDependentTypes
.end());
6246 AddFunctionCandidates(R
.asUnresolvedSet(), ArgExprs
, CandidateSet
,
6247 /*ExplicitArgs=*/nullptr,
6248 /*SuppressUserConversions=*/false,
6249 /*PartialOverloading=*/true);
6252 // Lastly we check whether expression's type is function pointer or
6255 FunctionProtoTypeLoc P
= GetPrototypeLoc(NakedFn
);
6256 QualType T
= NakedFn
->getType();
6257 if (!T
->getPointeeType().isNull())
6258 T
= T
->getPointeeType();
6260 if (auto FP
= T
->getAs
<FunctionProtoType
>()) {
6261 if (!TooManyArguments(FP
->getNumParams(),
6262 ArgsWithoutDependentTypes
.size(),
6263 /*PartialOverloading=*/true) ||
6266 Results
.push_back(ResultCandidate(P
));
6268 Results
.push_back(ResultCandidate(FP
));
6271 } else if (auto FT
= T
->getAs
<FunctionType
>())
6272 // No prototype and declaration, it may be a K & R style function.
6273 Results
.push_back(ResultCandidate(FT
));
6276 mergeCandidatesWithResults(*this, Results
, CandidateSet
, Loc
, Args
.size());
6277 QualType ParamType
= ProduceSignatureHelp(*this, Results
, Args
.size(),
6278 OpenParLoc
, /*Braced=*/false);
6279 return !CandidateSet
.empty() ? ParamType
: QualType();
6282 // Determine which param to continue aggregate initialization from after
6283 // a designated initializer.
6285 // Given struct S { int a,b,c,d,e; }:
6286 // after `S{.b=1,` we want to suggest c to continue
6287 // after `S{.b=1, 2,` we continue with d (this is legal C and ext in C++)
6288 // after `S{.b=1, .a=2,` we continue with b (this is legal C and ext in C++)
6290 // Possible outcomes:
6291 // - we saw a designator for a field, and continue from the returned index.
6292 // Only aggregate initialization is allowed.
6293 // - we saw a designator, but it was complex or we couldn't find the field.
6294 // Only aggregate initialization is possible, but we can't assist with it.
6295 // Returns an out-of-range index.
6296 // - we saw no designators, just positional arguments.
6297 // Returns std::nullopt.
6298 static std::optional
<unsigned>
6299 getNextAggregateIndexAfterDesignatedInit(const ResultCandidate
&Aggregate
,
6300 ArrayRef
<Expr
*> Args
) {
6301 static constexpr unsigned Invalid
= std::numeric_limits
<unsigned>::max();
6302 assert(Aggregate
.getKind() == ResultCandidate::CK_Aggregate
);
6304 // Look for designated initializers.
6305 // They're in their syntactic form, not yet resolved to fields.
6306 const IdentifierInfo
*DesignatedFieldName
= nullptr;
6307 unsigned ArgsAfterDesignator
= 0;
6308 for (const Expr
*Arg
: Args
) {
6309 if (const auto *DIE
= dyn_cast
<DesignatedInitExpr
>(Arg
)) {
6310 if (DIE
->size() == 1 && DIE
->getDesignator(0)->isFieldDesignator()) {
6311 DesignatedFieldName
= DIE
->getDesignator(0)->getFieldName();
6312 ArgsAfterDesignator
= 0;
6314 return Invalid
; // Complicated designator.
6316 } else if (isa
<DesignatedInitUpdateExpr
>(Arg
)) {
6317 return Invalid
; // Unsupported.
6319 ++ArgsAfterDesignator
;
6322 if (!DesignatedFieldName
)
6323 return std::nullopt
;
6325 // Find the index within the class's fields.
6326 // (Probing getParamDecl() directly would be quadratic in number of fields).
6327 unsigned DesignatedIndex
= 0;
6328 const FieldDecl
*DesignatedField
= nullptr;
6329 for (const auto *Field
: Aggregate
.getAggregate()->fields()) {
6330 if (Field
->getIdentifier() == DesignatedFieldName
) {
6331 DesignatedField
= Field
;
6336 if (!DesignatedField
)
6337 return Invalid
; // Designator referred to a missing field, give up.
6339 // Find the index within the aggregate (which may have leading bases).
6340 unsigned AggregateSize
= Aggregate
.getNumParams();
6341 while (DesignatedIndex
< AggregateSize
&&
6342 Aggregate
.getParamDecl(DesignatedIndex
) != DesignatedField
)
6345 // Continue from the index after the last named field.
6346 return DesignatedIndex
+ ArgsAfterDesignator
+ 1;
6349 QualType
Sema::ProduceConstructorSignatureHelp(QualType Type
,
6351 ArrayRef
<Expr
*> Args
,
6352 SourceLocation OpenParLoc
,
6356 SmallVector
<ResultCandidate
, 8> Results
;
6358 // A complete type is needed to lookup for constructors.
6360 isCompleteType(Loc
, Type
) ? Type
->getAsRecordDecl() : nullptr;
6363 CXXRecordDecl
*CRD
= dyn_cast
<CXXRecordDecl
>(RD
);
6365 // Consider aggregate initialization.
6366 // We don't check that types so far are correct.
6367 // We also don't handle C99/C++17 brace-elision, we assume init-list elements
6368 // are 1:1 with fields.
6369 // FIXME: it would be nice to support "unwrapping" aggregates that contain
6370 // a single subaggregate, like std::array<T, N> -> T __elements[N].
6371 if (Braced
&& !RD
->isUnion() &&
6372 (!LangOpts
.CPlusPlus
|| (CRD
&& CRD
->isAggregate()))) {
6373 ResultCandidate
AggregateSig(RD
);
6374 unsigned AggregateSize
= AggregateSig
.getNumParams();
6376 if (auto NextIndex
=
6377 getNextAggregateIndexAfterDesignatedInit(AggregateSig
, Args
)) {
6378 // A designator was used, only aggregate init is possible.
6379 if (*NextIndex
>= AggregateSize
)
6381 Results
.push_back(AggregateSig
);
6382 return ProduceSignatureHelp(*this, Results
, *NextIndex
, OpenParLoc
,
6386 // Describe aggregate initialization, but also constructors below.
6387 if (Args
.size() < AggregateSize
)
6388 Results
.push_back(AggregateSig
);
6391 // FIXME: Provide support for member initializers.
6392 // FIXME: Provide support for variadic template constructors.
6395 OverloadCandidateSet
CandidateSet(Loc
, OverloadCandidateSet::CSK_Normal
);
6396 for (NamedDecl
*C
: LookupConstructors(CRD
)) {
6397 if (auto *FD
= dyn_cast
<FunctionDecl
>(C
)) {
6398 // FIXME: we can't yet provide correct signature help for initializer
6399 // list constructors, so skip them entirely.
6400 if (Braced
&& LangOpts
.CPlusPlus
&& isInitListConstructor(FD
))
6402 AddOverloadCandidate(FD
, DeclAccessPair::make(FD
, C
->getAccess()), Args
,
6404 /*SuppressUserConversions=*/false,
6405 /*PartialOverloading=*/true,
6406 /*AllowExplicit*/ true);
6407 } else if (auto *FTD
= dyn_cast
<FunctionTemplateDecl
>(C
)) {
6408 if (Braced
&& LangOpts
.CPlusPlus
&&
6409 isInitListConstructor(FTD
->getTemplatedDecl()))
6412 AddTemplateOverloadCandidate(
6413 FTD
, DeclAccessPair::make(FTD
, C
->getAccess()),
6414 /*ExplicitTemplateArgs=*/nullptr, Args
, CandidateSet
,
6415 /*SuppressUserConversions=*/false,
6416 /*PartialOverloading=*/true);
6419 mergeCandidatesWithResults(*this, Results
, CandidateSet
, Loc
, Args
.size());
6422 return ProduceSignatureHelp(*this, Results
, Args
.size(), OpenParLoc
, Braced
);
6425 QualType
Sema::ProduceCtorInitMemberSignatureHelp(
6426 Decl
*ConstructorDecl
, CXXScopeSpec SS
, ParsedType TemplateTypeTy
,
6427 ArrayRef
<Expr
*> ArgExprs
, IdentifierInfo
*II
, SourceLocation OpenParLoc
,
6432 CXXConstructorDecl
*Constructor
=
6433 dyn_cast
<CXXConstructorDecl
>(ConstructorDecl
);
6436 // FIXME: Add support for Base class constructors as well.
6437 if (ValueDecl
*MemberDecl
= tryLookupCtorInitMemberDecl(
6438 Constructor
->getParent(), SS
, TemplateTypeTy
, II
))
6439 return ProduceConstructorSignatureHelp(MemberDecl
->getType(),
6440 MemberDecl
->getLocation(), ArgExprs
,
6441 OpenParLoc
, Braced
);
6445 static bool argMatchesTemplateParams(const ParsedTemplateArgument
&Arg
,
6447 const TemplateParameterList
&Params
) {
6448 const NamedDecl
*Param
;
6449 if (Index
< Params
.size())
6450 Param
= Params
.getParam(Index
);
6451 else if (Params
.hasParameterPack())
6452 Param
= Params
.asArray().back();
6454 return false; // too many args
6456 switch (Arg
.getKind()) {
6457 case ParsedTemplateArgument::Type
:
6458 return llvm::isa
<TemplateTypeParmDecl
>(Param
); // constraints not checked
6459 case ParsedTemplateArgument::NonType
:
6460 return llvm::isa
<NonTypeTemplateParmDecl
>(Param
); // type not checked
6461 case ParsedTemplateArgument::Template
:
6462 return llvm::isa
<TemplateTemplateParmDecl
>(Param
); // signature not checked
6464 llvm_unreachable("Unhandled switch case");
6467 QualType
Sema::ProduceTemplateArgumentSignatureHelp(
6468 TemplateTy ParsedTemplate
, ArrayRef
<ParsedTemplateArgument
> Args
,
6469 SourceLocation LAngleLoc
) {
6470 if (!CodeCompleter
|| !ParsedTemplate
)
6473 SmallVector
<ResultCandidate
, 8> Results
;
6474 auto Consider
= [&](const TemplateDecl
*TD
) {
6475 // Only add if the existing args are compatible with the template.
6476 bool Matches
= true;
6477 for (unsigned I
= 0; I
< Args
.size(); ++I
) {
6478 if (!argMatchesTemplateParams(Args
[I
], I
, *TD
->getTemplateParameters())) {
6484 Results
.emplace_back(TD
);
6487 TemplateName Template
= ParsedTemplate
.get();
6488 if (const auto *TD
= Template
.getAsTemplateDecl()) {
6490 } else if (const auto *OTS
= Template
.getAsOverloadedTemplate()) {
6491 for (const NamedDecl
*ND
: *OTS
)
6492 if (const auto *TD
= llvm::dyn_cast
<TemplateDecl
>(ND
))
6495 return ProduceSignatureHelp(*this, Results
, Args
.size(), LAngleLoc
,
6499 static QualType
getDesignatedType(QualType BaseType
, const Designation
&Desig
) {
6500 for (unsigned I
= 0; I
< Desig
.getNumDesignators(); ++I
) {
6501 if (BaseType
.isNull())
6504 const auto &D
= Desig
.getDesignator(I
);
6505 if (D
.isArrayDesignator() || D
.isArrayRangeDesignator()) {
6506 if (BaseType
->isArrayType())
6507 NextType
= BaseType
->getAsArrayTypeUnsafe()->getElementType();
6509 assert(D
.isFieldDesignator());
6510 auto *RD
= getAsRecordDecl(BaseType
);
6511 if (RD
&& RD
->isCompleteDefinition()) {
6512 for (const auto *Member
: RD
->lookup(D
.getFieldDecl()))
6513 if (const FieldDecl
*FD
= llvm::dyn_cast
<FieldDecl
>(Member
)) {
6514 NextType
= FD
->getType();
6519 BaseType
= NextType
;
6524 void Sema::CodeCompleteDesignator(QualType BaseType
,
6525 llvm::ArrayRef
<Expr
*> InitExprs
,
6526 const Designation
&D
) {
6527 BaseType
= getDesignatedType(BaseType
, D
);
6528 if (BaseType
.isNull())
6530 const auto *RD
= getAsRecordDecl(BaseType
);
6531 if (!RD
|| RD
->fields().empty())
6534 CodeCompletionContext
CCC(CodeCompletionContext::CCC_DotMemberAccess
,
6536 ResultBuilder
Results(*this, CodeCompleter
->getAllocator(),
6537 CodeCompleter
->getCodeCompletionTUInfo(), CCC
);
6539 Results
.EnterNewScope();
6540 for (const Decl
*D
: RD
->decls()) {
6541 const FieldDecl
*FD
;
6542 if (auto *IFD
= dyn_cast
<IndirectFieldDecl
>(D
))
6543 FD
= IFD
->getAnonField();
6544 else if (auto *DFD
= dyn_cast
<FieldDecl
>(D
))
6549 // FIXME: Make use of previous designators to mark any fields before those
6550 // inaccessible, and also compute the next initializer priority.
6551 ResultBuilder::Result
Result(FD
, Results
.getBasePriority(FD
));
6552 Results
.AddResult(Result
, CurContext
, /*Hiding=*/nullptr);
6554 Results
.ExitScope();
6555 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
6556 Results
.data(), Results
.size());
6559 void Sema::CodeCompleteInitializer(Scope
*S
, Decl
*D
) {
6560 ValueDecl
*VD
= dyn_cast_or_null
<ValueDecl
>(D
);
6562 CodeCompleteOrdinaryName(S
, PCC_Expression
);
6566 CodeCompleteExpressionData Data
;
6567 Data
.PreferredType
= VD
->getType();
6568 // Ignore VD to avoid completing the variable itself, e.g. in 'int foo = ^'.
6569 Data
.IgnoreDecls
.push_back(VD
);
6571 CodeCompleteExpression(S
, Data
);
6574 void Sema::CodeCompleteAfterIf(Scope
*S
, bool IsBracedThen
) {
6575 ResultBuilder
Results(*this, CodeCompleter
->getAllocator(),
6576 CodeCompleter
->getCodeCompletionTUInfo(),
6577 mapCodeCompletionContext(*this, PCC_Statement
));
6578 Results
.setFilter(&ResultBuilder::IsOrdinaryName
);
6579 Results
.EnterNewScope();
6581 CodeCompletionDeclConsumer
Consumer(Results
, CurContext
);
6582 LookupVisibleDecls(S
, LookupOrdinaryName
, Consumer
,
6583 CodeCompleter
->includeGlobals(),
6584 CodeCompleter
->loadExternal());
6586 AddOrdinaryNameResults(PCC_Statement
, S
, *this, Results
);
6589 CodeCompletionBuilder
Builder(Results
.getAllocator(),
6590 Results
.getCodeCompletionTUInfo());
6592 auto AddElseBodyPattern
= [&] {
6594 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
6595 Builder
.AddChunk(CodeCompletionString::CK_LeftBrace
);
6596 Builder
.AddChunk(CodeCompletionString::CK_VerticalSpace
);
6597 Builder
.AddPlaceholderChunk("statements");
6598 Builder
.AddChunk(CodeCompletionString::CK_VerticalSpace
);
6599 Builder
.AddChunk(CodeCompletionString::CK_RightBrace
);
6601 Builder
.AddChunk(CodeCompletionString::CK_VerticalSpace
);
6602 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
6603 Builder
.AddPlaceholderChunk("statement");
6604 Builder
.AddChunk(CodeCompletionString::CK_SemiColon
);
6607 Builder
.AddTypedTextChunk("else");
6608 if (Results
.includeCodePatterns())
6609 AddElseBodyPattern();
6610 Results
.AddResult(Builder
.TakeString());
6613 Builder
.AddTypedTextChunk("else if");
6614 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
6615 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
6616 if (getLangOpts().CPlusPlus
)
6617 Builder
.AddPlaceholderChunk("condition");
6619 Builder
.AddPlaceholderChunk("expression");
6620 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
6621 if (Results
.includeCodePatterns()) {
6622 AddElseBodyPattern();
6624 Results
.AddResult(Builder
.TakeString());
6626 Results
.ExitScope();
6628 if (S
->getFnParent())
6629 AddPrettyFunctionResults(getLangOpts(), Results
);
6631 if (CodeCompleter
->includeMacros())
6632 AddMacroResults(PP
, Results
, CodeCompleter
->loadExternal(), false);
6634 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
6635 Results
.data(), Results
.size());
6638 void Sema::CodeCompleteQualifiedId(Scope
*S
, CXXScopeSpec
&SS
,
6639 bool EnteringContext
,
6640 bool IsUsingDeclaration
, QualType BaseType
,
6641 QualType PreferredType
) {
6642 if (SS
.isEmpty() || !CodeCompleter
)
6645 CodeCompletionContext
CC(CodeCompletionContext::CCC_Symbol
, PreferredType
);
6646 CC
.setIsUsingDeclaration(IsUsingDeclaration
);
6647 CC
.setCXXScopeSpecifier(SS
);
6649 // We want to keep the scope specifier even if it's invalid (e.g. the scope
6650 // "a::b::" is not corresponding to any context/namespace in the AST), since
6651 // it can be useful for global code completion which have information about
6652 // contexts/symbols that are not in the AST.
6653 if (SS
.isInvalid()) {
6654 // As SS is invalid, we try to collect accessible contexts from the current
6655 // scope with a dummy lookup so that the completion consumer can try to
6656 // guess what the specified scope is.
6657 ResultBuilder
DummyResults(*this, CodeCompleter
->getAllocator(),
6658 CodeCompleter
->getCodeCompletionTUInfo(), CC
);
6659 if (!PreferredType
.isNull())
6660 DummyResults
.setPreferredType(PreferredType
);
6661 if (S
->getEntity()) {
6662 CodeCompletionDeclConsumer
Consumer(DummyResults
, S
->getEntity(),
6664 LookupVisibleDecls(S
, LookupOrdinaryName
, Consumer
,
6665 /*IncludeGlobalScope=*/false,
6666 /*LoadExternal=*/false);
6668 HandleCodeCompleteResults(this, CodeCompleter
,
6669 DummyResults
.getCompletionContext(), nullptr, 0);
6672 // Always pretend to enter a context to ensure that a dependent type
6673 // resolves to a dependent record.
6674 DeclContext
*Ctx
= computeDeclContext(SS
, /*EnteringContext=*/true);
6676 // Try to instantiate any non-dependent declaration contexts before
6677 // we look in them. Bail out if we fail.
6678 NestedNameSpecifier
*NNS
= SS
.getScopeRep();
6679 if (NNS
!= nullptr && SS
.isValid() && !NNS
->isDependent()) {
6680 if (Ctx
== nullptr || RequireCompleteDeclContext(SS
, Ctx
))
6684 ResultBuilder
Results(*this, CodeCompleter
->getAllocator(),
6685 CodeCompleter
->getCodeCompletionTUInfo(), CC
);
6686 if (!PreferredType
.isNull())
6687 Results
.setPreferredType(PreferredType
);
6688 Results
.EnterNewScope();
6690 // The "template" keyword can follow "::" in the grammar, but only
6691 // put it into the grammar if the nested-name-specifier is dependent.
6692 // FIXME: results is always empty, this appears to be dead.
6693 if (!Results
.empty() && NNS
&& NNS
->isDependent())
6694 Results
.AddResult("template");
6696 // If the scope is a concept-constrained type parameter, infer nested
6697 // members based on the constraints.
6698 if (const auto *TTPT
=
6699 dyn_cast_or_null
<TemplateTypeParmType
>(NNS
->getAsType())) {
6700 for (const auto &R
: ConceptInfo(*TTPT
, S
).members()) {
6701 if (R
.Operator
!= ConceptInfo::Member::Colons
)
6703 Results
.AddResult(CodeCompletionResult(
6704 R
.render(*this, CodeCompleter
->getAllocator(),
6705 CodeCompleter
->getCodeCompletionTUInfo())));
6709 // Add calls to overridden virtual functions, if there are any.
6711 // FIXME: This isn't wonderful, because we don't know whether we're actually
6712 // in a context that permits expressions. This is a general issue with
6713 // qualified-id completions.
6714 if (Ctx
&& !EnteringContext
)
6715 MaybeAddOverrideCalls(*this, Ctx
, Results
);
6716 Results
.ExitScope();
6719 (CodeCompleter
->includeNamespaceLevelDecls() || !Ctx
->isFileContext())) {
6720 CodeCompletionDeclConsumer
Consumer(Results
, Ctx
, BaseType
);
6721 LookupVisibleDecls(Ctx
, LookupOrdinaryName
, Consumer
,
6722 /*IncludeGlobalScope=*/true,
6723 /*IncludeDependentBases=*/true,
6724 CodeCompleter
->loadExternal());
6727 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
6728 Results
.data(), Results
.size());
6731 void Sema::CodeCompleteUsing(Scope
*S
) {
6735 // This can be both a using alias or using declaration, in the former we
6736 // expect a new name and a symbol in the latter case.
6737 CodeCompletionContext
Context(CodeCompletionContext::CCC_SymbolOrNewName
);
6738 Context
.setIsUsingDeclaration(true);
6740 ResultBuilder
Results(*this, CodeCompleter
->getAllocator(),
6741 CodeCompleter
->getCodeCompletionTUInfo(), Context
,
6742 &ResultBuilder::IsNestedNameSpecifier
);
6743 Results
.EnterNewScope();
6745 // If we aren't in class scope, we could see the "namespace" keyword.
6746 if (!S
->isClassScope())
6747 Results
.AddResult(CodeCompletionResult("namespace"));
6749 // After "using", we can see anything that would start a
6750 // nested-name-specifier.
6751 CodeCompletionDeclConsumer
Consumer(Results
, CurContext
);
6752 LookupVisibleDecls(S
, LookupOrdinaryName
, Consumer
,
6753 CodeCompleter
->includeGlobals(),
6754 CodeCompleter
->loadExternal());
6755 Results
.ExitScope();
6757 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
6758 Results
.data(), Results
.size());
6761 void Sema::CodeCompleteUsingDirective(Scope
*S
) {
6765 // After "using namespace", we expect to see a namespace name or namespace
6767 ResultBuilder
Results(*this, CodeCompleter
->getAllocator(),
6768 CodeCompleter
->getCodeCompletionTUInfo(),
6769 CodeCompletionContext::CCC_Namespace
,
6770 &ResultBuilder::IsNamespaceOrAlias
);
6771 Results
.EnterNewScope();
6772 CodeCompletionDeclConsumer
Consumer(Results
, CurContext
);
6773 LookupVisibleDecls(S
, LookupOrdinaryName
, Consumer
,
6774 CodeCompleter
->includeGlobals(),
6775 CodeCompleter
->loadExternal());
6776 Results
.ExitScope();
6777 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
6778 Results
.data(), Results
.size());
6781 void Sema::CodeCompleteNamespaceDecl(Scope
*S
) {
6785 DeclContext
*Ctx
= S
->getEntity();
6786 if (!S
->getParent())
6787 Ctx
= Context
.getTranslationUnitDecl();
6789 bool SuppressedGlobalResults
=
6790 Ctx
&& !CodeCompleter
->includeGlobals() && isa
<TranslationUnitDecl
>(Ctx
);
6792 ResultBuilder
Results(*this, CodeCompleter
->getAllocator(),
6793 CodeCompleter
->getCodeCompletionTUInfo(),
6794 SuppressedGlobalResults
6795 ? CodeCompletionContext::CCC_Namespace
6796 : CodeCompletionContext::CCC_Other
,
6797 &ResultBuilder::IsNamespace
);
6799 if (Ctx
&& Ctx
->isFileContext() && !SuppressedGlobalResults
) {
6800 // We only want to see those namespaces that have already been defined
6801 // within this scope, because its likely that the user is creating an
6802 // extended namespace declaration. Keep track of the most recent
6803 // definition of each namespace.
6804 std::map
<NamespaceDecl
*, NamespaceDecl
*> OrigToLatest
;
6805 for (DeclContext::specific_decl_iterator
<NamespaceDecl
>
6806 NS(Ctx
->decls_begin()),
6807 NSEnd(Ctx
->decls_end());
6809 OrigToLatest
[NS
->getOriginalNamespace()] = *NS
;
6811 // Add the most recent definition (or extended definition) of each
6812 // namespace to the list of results.
6813 Results
.EnterNewScope();
6814 for (std::map
<NamespaceDecl
*, NamespaceDecl
*>::iterator
6815 NS
= OrigToLatest
.begin(),
6816 NSEnd
= OrigToLatest
.end();
6819 CodeCompletionResult(NS
->second
, Results
.getBasePriority(NS
->second
),
6821 CurContext
, nullptr, false);
6822 Results
.ExitScope();
6825 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
6826 Results
.data(), Results
.size());
6829 void Sema::CodeCompleteNamespaceAliasDecl(Scope
*S
) {
6833 // After "namespace", we expect to see a namespace or alias.
6834 ResultBuilder
Results(*this, CodeCompleter
->getAllocator(),
6835 CodeCompleter
->getCodeCompletionTUInfo(),
6836 CodeCompletionContext::CCC_Namespace
,
6837 &ResultBuilder::IsNamespaceOrAlias
);
6838 CodeCompletionDeclConsumer
Consumer(Results
, CurContext
);
6839 LookupVisibleDecls(S
, LookupOrdinaryName
, Consumer
,
6840 CodeCompleter
->includeGlobals(),
6841 CodeCompleter
->loadExternal());
6842 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
6843 Results
.data(), Results
.size());
6846 void Sema::CodeCompleteOperatorName(Scope
*S
) {
6850 typedef CodeCompletionResult Result
;
6851 ResultBuilder
Results(*this, CodeCompleter
->getAllocator(),
6852 CodeCompleter
->getCodeCompletionTUInfo(),
6853 CodeCompletionContext::CCC_Type
,
6854 &ResultBuilder::IsType
);
6855 Results
.EnterNewScope();
6857 // Add the names of overloadable operators. Note that OO_Conditional is not
6858 // actually overloadable.
6859 #define OVERLOADED_OPERATOR(Name, Spelling, Token, Unary, Binary, MemberOnly) \
6860 if (OO_##Name != OO_Conditional) \
6861 Results.AddResult(Result(Spelling));
6862 #include "clang/Basic/OperatorKinds.def"
6864 // Add any type names visible from the current scope
6865 Results
.allowNestedNameSpecifiers();
6866 CodeCompletionDeclConsumer
Consumer(Results
, CurContext
);
6867 LookupVisibleDecls(S
, LookupOrdinaryName
, Consumer
,
6868 CodeCompleter
->includeGlobals(),
6869 CodeCompleter
->loadExternal());
6871 // Add any type specifiers
6872 AddTypeSpecifierResults(getLangOpts(), Results
);
6873 Results
.ExitScope();
6875 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
6876 Results
.data(), Results
.size());
6879 void Sema::CodeCompleteConstructorInitializer(
6880 Decl
*ConstructorD
, ArrayRef
<CXXCtorInitializer
*> Initializers
) {
6884 AdjustDeclIfTemplate(ConstructorD
);
6886 auto *Constructor
= dyn_cast
<CXXConstructorDecl
>(ConstructorD
);
6890 ResultBuilder
Results(*this, CodeCompleter
->getAllocator(),
6891 CodeCompleter
->getCodeCompletionTUInfo(),
6892 CodeCompletionContext::CCC_Symbol
);
6893 Results
.EnterNewScope();
6895 // Fill in any already-initialized fields or base classes.
6896 llvm::SmallPtrSet
<FieldDecl
*, 4> InitializedFields
;
6897 llvm::SmallPtrSet
<CanQualType
, 4> InitializedBases
;
6898 for (unsigned I
= 0, E
= Initializers
.size(); I
!= E
; ++I
) {
6899 if (Initializers
[I
]->isBaseInitializer())
6900 InitializedBases
.insert(Context
.getCanonicalType(
6901 QualType(Initializers
[I
]->getBaseClass(), 0)));
6903 InitializedFields
.insert(
6904 cast
<FieldDecl
>(Initializers
[I
]->getAnyMember()));
6907 // Add completions for base classes.
6908 PrintingPolicy Policy
= getCompletionPrintingPolicy(*this);
6909 bool SawLastInitializer
= Initializers
.empty();
6910 CXXRecordDecl
*ClassDecl
= Constructor
->getParent();
6912 auto GenerateCCS
= [&](const NamedDecl
*ND
, const char *Name
) {
6913 CodeCompletionBuilder
Builder(Results
.getAllocator(),
6914 Results
.getCodeCompletionTUInfo());
6915 Builder
.AddTypedTextChunk(Name
);
6916 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
6917 if (const auto *Function
= dyn_cast
<FunctionDecl
>(ND
))
6918 AddFunctionParameterChunks(PP
, Policy
, Function
, Builder
);
6919 else if (const auto *FunTemplDecl
= dyn_cast
<FunctionTemplateDecl
>(ND
))
6920 AddFunctionParameterChunks(PP
, Policy
, FunTemplDecl
->getTemplatedDecl(),
6922 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
6923 return Builder
.TakeString();
6925 auto AddDefaultCtorInit
= [&](const char *Name
, const char *Type
,
6926 const NamedDecl
*ND
) {
6927 CodeCompletionBuilder
Builder(Results
.getAllocator(),
6928 Results
.getCodeCompletionTUInfo());
6929 Builder
.AddTypedTextChunk(Name
);
6930 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
6931 Builder
.AddPlaceholderChunk(Type
);
6932 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
6934 auto CCR
= CodeCompletionResult(
6935 Builder
.TakeString(), ND
,
6936 SawLastInitializer
? CCP_NextInitializer
: CCP_MemberDeclaration
);
6937 if (isa
<FieldDecl
>(ND
))
6938 CCR
.CursorKind
= CXCursor_MemberRef
;
6939 return Results
.AddResult(CCR
);
6941 return Results
.AddResult(CodeCompletionResult(
6942 Builder
.TakeString(),
6943 SawLastInitializer
? CCP_NextInitializer
: CCP_MemberDeclaration
));
6945 auto AddCtorsWithName
= [&](const CXXRecordDecl
*RD
, unsigned int Priority
,
6946 const char *Name
, const FieldDecl
*FD
) {
6948 return AddDefaultCtorInit(Name
,
6949 FD
? Results
.getAllocator().CopyString(
6950 FD
->getType().getAsString(Policy
))
6953 auto Ctors
= getConstructors(Context
, RD
);
6954 if (Ctors
.begin() == Ctors
.end())
6955 return AddDefaultCtorInit(Name
, Name
, RD
);
6956 for (const NamedDecl
*Ctor
: Ctors
) {
6957 auto CCR
= CodeCompletionResult(GenerateCCS(Ctor
, Name
), RD
, Priority
);
6958 CCR
.CursorKind
= getCursorKindForDecl(Ctor
);
6959 Results
.AddResult(CCR
);
6962 auto AddBase
= [&](const CXXBaseSpecifier
&Base
) {
6963 const char *BaseName
=
6964 Results
.getAllocator().CopyString(Base
.getType().getAsString(Policy
));
6965 const auto *RD
= Base
.getType()->getAsCXXRecordDecl();
6967 RD
, SawLastInitializer
? CCP_NextInitializer
: CCP_MemberDeclaration
,
6970 auto AddField
= [&](const FieldDecl
*FD
) {
6971 const char *FieldName
=
6972 Results
.getAllocator().CopyString(FD
->getIdentifier()->getName());
6973 const CXXRecordDecl
*RD
= FD
->getType()->getAsCXXRecordDecl();
6975 RD
, SawLastInitializer
? CCP_NextInitializer
: CCP_MemberDeclaration
,
6979 for (const auto &Base
: ClassDecl
->bases()) {
6980 if (!InitializedBases
.insert(Context
.getCanonicalType(Base
.getType()))
6982 SawLastInitializer
=
6983 !Initializers
.empty() && Initializers
.back()->isBaseInitializer() &&
6984 Context
.hasSameUnqualifiedType(
6985 Base
.getType(), QualType(Initializers
.back()->getBaseClass(), 0));
6990 SawLastInitializer
= false;
6993 // Add completions for virtual base classes.
6994 for (const auto &Base
: ClassDecl
->vbases()) {
6995 if (!InitializedBases
.insert(Context
.getCanonicalType(Base
.getType()))
6997 SawLastInitializer
=
6998 !Initializers
.empty() && Initializers
.back()->isBaseInitializer() &&
6999 Context
.hasSameUnqualifiedType(
7000 Base
.getType(), QualType(Initializers
.back()->getBaseClass(), 0));
7005 SawLastInitializer
= false;
7008 // Add completions for members.
7009 for (auto *Field
: ClassDecl
->fields()) {
7010 if (!InitializedFields
.insert(cast
<FieldDecl
>(Field
->getCanonicalDecl()))
7012 SawLastInitializer
= !Initializers
.empty() &&
7013 Initializers
.back()->isAnyMemberInitializer() &&
7014 Initializers
.back()->getAnyMember() == Field
;
7018 if (!Field
->getDeclName())
7022 SawLastInitializer
= false;
7024 Results
.ExitScope();
7026 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
7027 Results
.data(), Results
.size());
7030 /// Determine whether this scope denotes a namespace.
7031 static bool isNamespaceScope(Scope
*S
) {
7032 DeclContext
*DC
= S
->getEntity();
7036 return DC
->isFileContext();
7039 void Sema::CodeCompleteLambdaIntroducer(Scope
*S
, LambdaIntroducer
&Intro
,
7040 bool AfterAmpersand
) {
7041 ResultBuilder
Results(*this, CodeCompleter
->getAllocator(),
7042 CodeCompleter
->getCodeCompletionTUInfo(),
7043 CodeCompletionContext::CCC_Other
);
7044 Results
.EnterNewScope();
7046 // Note what has already been captured.
7047 llvm::SmallPtrSet
<IdentifierInfo
*, 4> Known
;
7048 bool IncludedThis
= false;
7049 for (const auto &C
: Intro
.Captures
) {
7050 if (C
.Kind
== LCK_This
) {
7051 IncludedThis
= true;
7058 // Look for other capturable variables.
7059 for (; S
&& !isNamespaceScope(S
); S
= S
->getParent()) {
7060 for (const auto *D
: S
->decls()) {
7061 const auto *Var
= dyn_cast
<VarDecl
>(D
);
7062 if (!Var
|| !Var
->hasLocalStorage() || Var
->hasAttr
<BlocksAttr
>())
7065 if (Known
.insert(Var
->getIdentifier()).second
)
7066 Results
.AddResult(CodeCompletionResult(Var
, CCP_LocalDeclaration
),
7067 CurContext
, nullptr, false);
7071 // Add 'this', if it would be valid.
7072 if (!IncludedThis
&& !AfterAmpersand
&& Intro
.Default
!= LCD_ByCopy
)
7073 addThisCompletion(*this, Results
);
7075 Results
.ExitScope();
7077 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
7078 Results
.data(), Results
.size());
7081 void Sema::CodeCompleteAfterFunctionEquals(Declarator
&D
) {
7082 if (!LangOpts
.CPlusPlus11
)
7084 ResultBuilder
Results(*this, CodeCompleter
->getAllocator(),
7085 CodeCompleter
->getCodeCompletionTUInfo(),
7086 CodeCompletionContext::CCC_Other
);
7087 auto ShouldAddDefault
= [&D
, this]() {
7088 if (!D
.isFunctionDeclarator())
7090 auto &Id
= D
.getName();
7091 if (Id
.getKind() == UnqualifiedIdKind::IK_DestructorName
)
7093 // FIXME(liuhui): Ideally, we should check the constructor parameter list to
7094 // verify that it is the default, copy or move constructor?
7095 if (Id
.getKind() == UnqualifiedIdKind::IK_ConstructorName
&&
7096 D
.getFunctionTypeInfo().NumParams
<= 1)
7098 if (Id
.getKind() == UnqualifiedIdKind::IK_OperatorFunctionId
) {
7099 auto Op
= Id
.OperatorFunctionId
.Operator
;
7100 // FIXME(liuhui): Ideally, we should check the function parameter list to
7101 // verify that it is the copy or move assignment?
7102 if (Op
== OverloadedOperatorKind::OO_Equal
)
7104 if (LangOpts
.CPlusPlus20
&&
7105 (Op
== OverloadedOperatorKind::OO_EqualEqual
||
7106 Op
== OverloadedOperatorKind::OO_ExclaimEqual
||
7107 Op
== OverloadedOperatorKind::OO_Less
||
7108 Op
== OverloadedOperatorKind::OO_LessEqual
||
7109 Op
== OverloadedOperatorKind::OO_Greater
||
7110 Op
== OverloadedOperatorKind::OO_GreaterEqual
||
7111 Op
== OverloadedOperatorKind::OO_Spaceship
))
7117 Results
.EnterNewScope();
7118 if (ShouldAddDefault())
7119 Results
.AddResult("default");
7120 // FIXME(liuhui): Ideally, we should only provide `delete` completion for the
7121 // first function declaration.
7122 Results
.AddResult("delete");
7123 Results
.ExitScope();
7124 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
7125 Results
.data(), Results
.size());
7128 /// Macro that optionally prepends an "@" to the string literal passed in via
7129 /// Keyword, depending on whether NeedAt is true or false.
7130 #define OBJC_AT_KEYWORD_NAME(NeedAt, Keyword) ((NeedAt) ? "@" Keyword : Keyword)
7132 static void AddObjCImplementationResults(const LangOptions
&LangOpts
,
7133 ResultBuilder
&Results
, bool NeedAt
) {
7134 typedef CodeCompletionResult Result
;
7135 // Since we have an implementation, we can end it.
7136 Results
.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt
, "end")));
7138 CodeCompletionBuilder
Builder(Results
.getAllocator(),
7139 Results
.getCodeCompletionTUInfo());
7140 if (LangOpts
.ObjC
) {
7142 Builder
.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt
, "dynamic"));
7143 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
7144 Builder
.AddPlaceholderChunk("property");
7145 Results
.AddResult(Result(Builder
.TakeString()));
7148 Builder
.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt
, "synthesize"));
7149 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
7150 Builder
.AddPlaceholderChunk("property");
7151 Results
.AddResult(Result(Builder
.TakeString()));
7155 static void AddObjCInterfaceResults(const LangOptions
&LangOpts
,
7156 ResultBuilder
&Results
, bool NeedAt
) {
7157 typedef CodeCompletionResult Result
;
7159 // Since we have an interface or protocol, we can end it.
7160 Results
.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt
, "end")));
7162 if (LangOpts
.ObjC
) {
7164 Results
.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt
, "property")));
7167 Results
.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt
, "required")));
7170 Results
.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt
, "optional")));
7174 static void AddObjCTopLevelResults(ResultBuilder
&Results
, bool NeedAt
) {
7175 typedef CodeCompletionResult Result
;
7176 CodeCompletionBuilder
Builder(Results
.getAllocator(),
7177 Results
.getCodeCompletionTUInfo());
7180 Builder
.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt
, "class"));
7181 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
7182 Builder
.AddPlaceholderChunk("name");
7183 Results
.AddResult(Result(Builder
.TakeString()));
7185 if (Results
.includeCodePatterns()) {
7187 // FIXME: Could introduce the whole pattern, including superclasses and
7189 Builder
.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt
, "interface"));
7190 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
7191 Builder
.AddPlaceholderChunk("class");
7192 Results
.AddResult(Result(Builder
.TakeString()));
7195 Builder
.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt
, "protocol"));
7196 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
7197 Builder
.AddPlaceholderChunk("protocol");
7198 Results
.AddResult(Result(Builder
.TakeString()));
7200 // @implementation name
7201 Builder
.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt
, "implementation"));
7202 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
7203 Builder
.AddPlaceholderChunk("class");
7204 Results
.AddResult(Result(Builder
.TakeString()));
7207 // @compatibility_alias name
7208 Builder
.AddTypedTextChunk(
7209 OBJC_AT_KEYWORD_NAME(NeedAt
, "compatibility_alias"));
7210 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
7211 Builder
.AddPlaceholderChunk("alias");
7212 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
7213 Builder
.AddPlaceholderChunk("class");
7214 Results
.AddResult(Result(Builder
.TakeString()));
7216 if (Results
.getSema().getLangOpts().Modules
) {
7218 Builder
.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt
, "import"));
7219 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
7220 Builder
.AddPlaceholderChunk("module");
7221 Results
.AddResult(Result(Builder
.TakeString()));
7225 void Sema::CodeCompleteObjCAtDirective(Scope
*S
) {
7226 ResultBuilder
Results(*this, CodeCompleter
->getAllocator(),
7227 CodeCompleter
->getCodeCompletionTUInfo(),
7228 CodeCompletionContext::CCC_Other
);
7229 Results
.EnterNewScope();
7230 if (isa
<ObjCImplDecl
>(CurContext
))
7231 AddObjCImplementationResults(getLangOpts(), Results
, false);
7232 else if (CurContext
->isObjCContainer())
7233 AddObjCInterfaceResults(getLangOpts(), Results
, false);
7235 AddObjCTopLevelResults(Results
, false);
7236 Results
.ExitScope();
7237 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
7238 Results
.data(), Results
.size());
7241 static void AddObjCExpressionResults(ResultBuilder
&Results
, bool NeedAt
) {
7242 typedef CodeCompletionResult Result
;
7243 CodeCompletionBuilder
Builder(Results
.getAllocator(),
7244 Results
.getCodeCompletionTUInfo());
7246 // @encode ( type-name )
7247 const char *EncodeType
= "char[]";
7248 if (Results
.getSema().getLangOpts().CPlusPlus
||
7249 Results
.getSema().getLangOpts().ConstStrings
)
7250 EncodeType
= "const char[]";
7251 Builder
.AddResultTypeChunk(EncodeType
);
7252 Builder
.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt
, "encode"));
7253 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
7254 Builder
.AddPlaceholderChunk("type-name");
7255 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
7256 Results
.AddResult(Result(Builder
.TakeString()));
7258 // @protocol ( protocol-name )
7259 Builder
.AddResultTypeChunk("Protocol *");
7260 Builder
.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt
, "protocol"));
7261 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
7262 Builder
.AddPlaceholderChunk("protocol-name");
7263 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
7264 Results
.AddResult(Result(Builder
.TakeString()));
7266 // @selector ( selector )
7267 Builder
.AddResultTypeChunk("SEL");
7268 Builder
.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt
, "selector"));
7269 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
7270 Builder
.AddPlaceholderChunk("selector");
7271 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
7272 Results
.AddResult(Result(Builder
.TakeString()));
7275 Builder
.AddResultTypeChunk("NSString *");
7276 Builder
.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt
, "\""));
7277 Builder
.AddPlaceholderChunk("string");
7278 Builder
.AddTextChunk("\"");
7279 Results
.AddResult(Result(Builder
.TakeString()));
7282 Builder
.AddResultTypeChunk("NSArray *");
7283 Builder
.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt
, "["));
7284 Builder
.AddPlaceholderChunk("objects, ...");
7285 Builder
.AddChunk(CodeCompletionString::CK_RightBracket
);
7286 Results
.AddResult(Result(Builder
.TakeString()));
7288 // @{key : object, ...}
7289 Builder
.AddResultTypeChunk("NSDictionary *");
7290 Builder
.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt
, "{"));
7291 Builder
.AddPlaceholderChunk("key");
7292 Builder
.AddChunk(CodeCompletionString::CK_Colon
);
7293 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
7294 Builder
.AddPlaceholderChunk("object, ...");
7295 Builder
.AddChunk(CodeCompletionString::CK_RightBrace
);
7296 Results
.AddResult(Result(Builder
.TakeString()));
7299 Builder
.AddResultTypeChunk("id");
7300 Builder
.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt
, "("));
7301 Builder
.AddPlaceholderChunk("expression");
7302 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
7303 Results
.AddResult(Result(Builder
.TakeString()));
7306 static void AddObjCStatementResults(ResultBuilder
&Results
, bool NeedAt
) {
7307 typedef CodeCompletionResult Result
;
7308 CodeCompletionBuilder
Builder(Results
.getAllocator(),
7309 Results
.getCodeCompletionTUInfo());
7311 if (Results
.includeCodePatterns()) {
7312 // @try { statements } @catch ( declaration ) { statements } @finally
7314 Builder
.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt
, "try"));
7315 Builder
.AddChunk(CodeCompletionString::CK_LeftBrace
);
7316 Builder
.AddPlaceholderChunk("statements");
7317 Builder
.AddChunk(CodeCompletionString::CK_RightBrace
);
7318 Builder
.AddTextChunk("@catch");
7319 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
7320 Builder
.AddPlaceholderChunk("parameter");
7321 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
7322 Builder
.AddChunk(CodeCompletionString::CK_LeftBrace
);
7323 Builder
.AddPlaceholderChunk("statements");
7324 Builder
.AddChunk(CodeCompletionString::CK_RightBrace
);
7325 Builder
.AddTextChunk("@finally");
7326 Builder
.AddChunk(CodeCompletionString::CK_LeftBrace
);
7327 Builder
.AddPlaceholderChunk("statements");
7328 Builder
.AddChunk(CodeCompletionString::CK_RightBrace
);
7329 Results
.AddResult(Result(Builder
.TakeString()));
7333 Builder
.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt
, "throw"));
7334 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
7335 Builder
.AddPlaceholderChunk("expression");
7336 Results
.AddResult(Result(Builder
.TakeString()));
7338 if (Results
.includeCodePatterns()) {
7339 // @synchronized ( expression ) { statements }
7340 Builder
.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt
, "synchronized"));
7341 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
7342 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
7343 Builder
.AddPlaceholderChunk("expression");
7344 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
7345 Builder
.AddChunk(CodeCompletionString::CK_LeftBrace
);
7346 Builder
.AddPlaceholderChunk("statements");
7347 Builder
.AddChunk(CodeCompletionString::CK_RightBrace
);
7348 Results
.AddResult(Result(Builder
.TakeString()));
7352 static void AddObjCVisibilityResults(const LangOptions
&LangOpts
,
7353 ResultBuilder
&Results
, bool NeedAt
) {
7354 typedef CodeCompletionResult Result
;
7355 Results
.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt
, "private")));
7356 Results
.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt
, "protected")));
7357 Results
.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt
, "public")));
7359 Results
.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt
, "package")));
7362 void Sema::CodeCompleteObjCAtVisibility(Scope
*S
) {
7363 ResultBuilder
Results(*this, CodeCompleter
->getAllocator(),
7364 CodeCompleter
->getCodeCompletionTUInfo(),
7365 CodeCompletionContext::CCC_Other
);
7366 Results
.EnterNewScope();
7367 AddObjCVisibilityResults(getLangOpts(), Results
, false);
7368 Results
.ExitScope();
7369 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
7370 Results
.data(), Results
.size());
7373 void Sema::CodeCompleteObjCAtStatement(Scope
*S
) {
7374 ResultBuilder
Results(*this, CodeCompleter
->getAllocator(),
7375 CodeCompleter
->getCodeCompletionTUInfo(),
7376 CodeCompletionContext::CCC_Other
);
7377 Results
.EnterNewScope();
7378 AddObjCStatementResults(Results
, false);
7379 AddObjCExpressionResults(Results
, false);
7380 Results
.ExitScope();
7381 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
7382 Results
.data(), Results
.size());
7385 void Sema::CodeCompleteObjCAtExpression(Scope
*S
) {
7386 ResultBuilder
Results(*this, CodeCompleter
->getAllocator(),
7387 CodeCompleter
->getCodeCompletionTUInfo(),
7388 CodeCompletionContext::CCC_Other
);
7389 Results
.EnterNewScope();
7390 AddObjCExpressionResults(Results
, false);
7391 Results
.ExitScope();
7392 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
7393 Results
.data(), Results
.size());
7396 /// Determine whether the addition of the given flag to an Objective-C
7397 /// property's attributes will cause a conflict.
7398 static bool ObjCPropertyFlagConflicts(unsigned Attributes
, unsigned NewFlag
) {
7399 // Check if we've already added this flag.
7400 if (Attributes
& NewFlag
)
7403 Attributes
|= NewFlag
;
7405 // Check for collisions with "readonly".
7406 if ((Attributes
& ObjCPropertyAttribute::kind_readonly
) &&
7407 (Attributes
& ObjCPropertyAttribute::kind_readwrite
))
7410 // Check for more than one of { assign, copy, retain, strong, weak }.
7411 unsigned AssignCopyRetMask
=
7413 (ObjCPropertyAttribute::kind_assign
|
7414 ObjCPropertyAttribute::kind_unsafe_unretained
|
7415 ObjCPropertyAttribute::kind_copy
| ObjCPropertyAttribute::kind_retain
|
7416 ObjCPropertyAttribute::kind_strong
| ObjCPropertyAttribute::kind_weak
);
7417 if (AssignCopyRetMask
&&
7418 AssignCopyRetMask
!= ObjCPropertyAttribute::kind_assign
&&
7419 AssignCopyRetMask
!= ObjCPropertyAttribute::kind_unsafe_unretained
&&
7420 AssignCopyRetMask
!= ObjCPropertyAttribute::kind_copy
&&
7421 AssignCopyRetMask
!= ObjCPropertyAttribute::kind_retain
&&
7422 AssignCopyRetMask
!= ObjCPropertyAttribute::kind_strong
&&
7423 AssignCopyRetMask
!= ObjCPropertyAttribute::kind_weak
)
7429 void Sema::CodeCompleteObjCPropertyFlags(Scope
*S
, ObjCDeclSpec
&ODS
) {
7433 unsigned Attributes
= ODS
.getPropertyAttributes();
7435 ResultBuilder
Results(*this, CodeCompleter
->getAllocator(),
7436 CodeCompleter
->getCodeCompletionTUInfo(),
7437 CodeCompletionContext::CCC_Other
);
7438 Results
.EnterNewScope();
7439 if (!ObjCPropertyFlagConflicts(Attributes
,
7440 ObjCPropertyAttribute::kind_readonly
))
7441 Results
.AddResult(CodeCompletionResult("readonly"));
7442 if (!ObjCPropertyFlagConflicts(Attributes
,
7443 ObjCPropertyAttribute::kind_assign
))
7444 Results
.AddResult(CodeCompletionResult("assign"));
7445 if (!ObjCPropertyFlagConflicts(Attributes
,
7446 ObjCPropertyAttribute::kind_unsafe_unretained
))
7447 Results
.AddResult(CodeCompletionResult("unsafe_unretained"));
7448 if (!ObjCPropertyFlagConflicts(Attributes
,
7449 ObjCPropertyAttribute::kind_readwrite
))
7450 Results
.AddResult(CodeCompletionResult("readwrite"));
7451 if (!ObjCPropertyFlagConflicts(Attributes
,
7452 ObjCPropertyAttribute::kind_retain
))
7453 Results
.AddResult(CodeCompletionResult("retain"));
7454 if (!ObjCPropertyFlagConflicts(Attributes
,
7455 ObjCPropertyAttribute::kind_strong
))
7456 Results
.AddResult(CodeCompletionResult("strong"));
7457 if (!ObjCPropertyFlagConflicts(Attributes
, ObjCPropertyAttribute::kind_copy
))
7458 Results
.AddResult(CodeCompletionResult("copy"));
7459 if (!ObjCPropertyFlagConflicts(Attributes
,
7460 ObjCPropertyAttribute::kind_nonatomic
))
7461 Results
.AddResult(CodeCompletionResult("nonatomic"));
7462 if (!ObjCPropertyFlagConflicts(Attributes
,
7463 ObjCPropertyAttribute::kind_atomic
))
7464 Results
.AddResult(CodeCompletionResult("atomic"));
7466 // Only suggest "weak" if we're compiling for ARC-with-weak-references or GC.
7467 if (getLangOpts().ObjCWeak
|| getLangOpts().getGC() != LangOptions::NonGC
)
7468 if (!ObjCPropertyFlagConflicts(Attributes
,
7469 ObjCPropertyAttribute::kind_weak
))
7470 Results
.AddResult(CodeCompletionResult("weak"));
7472 if (!ObjCPropertyFlagConflicts(Attributes
,
7473 ObjCPropertyAttribute::kind_setter
)) {
7474 CodeCompletionBuilder
Setter(Results
.getAllocator(),
7475 Results
.getCodeCompletionTUInfo());
7476 Setter
.AddTypedTextChunk("setter");
7477 Setter
.AddTextChunk("=");
7478 Setter
.AddPlaceholderChunk("method");
7479 Results
.AddResult(CodeCompletionResult(Setter
.TakeString()));
7481 if (!ObjCPropertyFlagConflicts(Attributes
,
7482 ObjCPropertyAttribute::kind_getter
)) {
7483 CodeCompletionBuilder
Getter(Results
.getAllocator(),
7484 Results
.getCodeCompletionTUInfo());
7485 Getter
.AddTypedTextChunk("getter");
7486 Getter
.AddTextChunk("=");
7487 Getter
.AddPlaceholderChunk("method");
7488 Results
.AddResult(CodeCompletionResult(Getter
.TakeString()));
7490 if (!ObjCPropertyFlagConflicts(Attributes
,
7491 ObjCPropertyAttribute::kind_nullability
)) {
7492 Results
.AddResult(CodeCompletionResult("nonnull"));
7493 Results
.AddResult(CodeCompletionResult("nullable"));
7494 Results
.AddResult(CodeCompletionResult("null_unspecified"));
7495 Results
.AddResult(CodeCompletionResult("null_resettable"));
7497 Results
.ExitScope();
7498 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
7499 Results
.data(), Results
.size());
7502 /// Describes the kind of Objective-C method that we want to find
7503 /// via code completion.
7504 enum ObjCMethodKind
{
7505 MK_Any
, ///< Any kind of method, provided it means other specified criteria.
7506 MK_ZeroArgSelector
, ///< Zero-argument (unary) selector.
7507 MK_OneArgSelector
///< One-argument selector.
7510 static bool isAcceptableObjCSelector(Selector Sel
, ObjCMethodKind WantKind
,
7511 ArrayRef
<IdentifierInfo
*> SelIdents
,
7512 bool AllowSameLength
= true) {
7513 unsigned NumSelIdents
= SelIdents
.size();
7514 if (NumSelIdents
> Sel
.getNumArgs())
7520 case MK_ZeroArgSelector
:
7521 return Sel
.isUnarySelector();
7522 case MK_OneArgSelector
:
7523 return Sel
.getNumArgs() == 1;
7526 if (!AllowSameLength
&& NumSelIdents
&& NumSelIdents
== Sel
.getNumArgs())
7529 for (unsigned I
= 0; I
!= NumSelIdents
; ++I
)
7530 if (SelIdents
[I
] != Sel
.getIdentifierInfoForSlot(I
))
7536 static bool isAcceptableObjCMethod(ObjCMethodDecl
*Method
,
7537 ObjCMethodKind WantKind
,
7538 ArrayRef
<IdentifierInfo
*> SelIdents
,
7539 bool AllowSameLength
= true) {
7540 return isAcceptableObjCSelector(Method
->getSelector(), WantKind
, SelIdents
,
7544 /// A set of selectors, which is used to avoid introducing multiple
7545 /// completions with the same selector into the result set.
7546 typedef llvm::SmallPtrSet
<Selector
, 16> VisitedSelectorSet
;
7548 /// Add all of the Objective-C methods in the given Objective-C
7549 /// container to the set of results.
7551 /// The container will be a class, protocol, category, or implementation of
7552 /// any of the above. This mether will recurse to include methods from
7553 /// the superclasses of classes along with their categories, protocols, and
7554 /// implementations.
7556 /// \param Container the container in which we'll look to find methods.
7558 /// \param WantInstanceMethods Whether to add instance methods (only); if
7559 /// false, this routine will add factory methods (only).
7561 /// \param CurContext the context in which we're performing the lookup that
7564 /// \param AllowSameLength Whether we allow a method to be added to the list
7565 /// when it has the same number of parameters as we have selector identifiers.
7567 /// \param Results the structure into which we'll add results.
7568 static void AddObjCMethods(ObjCContainerDecl
*Container
,
7569 bool WantInstanceMethods
, ObjCMethodKind WantKind
,
7570 ArrayRef
<IdentifierInfo
*> SelIdents
,
7571 DeclContext
*CurContext
,
7572 VisitedSelectorSet
&Selectors
, bool AllowSameLength
,
7573 ResultBuilder
&Results
, bool InOriginalClass
= true,
7574 bool IsRootClass
= false) {
7575 typedef CodeCompletionResult Result
;
7576 Container
= getContainerDef(Container
);
7577 ObjCInterfaceDecl
*IFace
= dyn_cast
<ObjCInterfaceDecl
>(Container
);
7578 IsRootClass
= IsRootClass
|| (IFace
&& !IFace
->getSuperClass());
7579 for (ObjCMethodDecl
*M
: Container
->methods()) {
7580 // The instance methods on the root class can be messaged via the
7582 if (M
->isInstanceMethod() == WantInstanceMethods
||
7583 (IsRootClass
&& !WantInstanceMethods
)) {
7584 // Check whether the selector identifiers we've been given are a
7585 // subset of the identifiers for this particular method.
7586 if (!isAcceptableObjCMethod(M
, WantKind
, SelIdents
, AllowSameLength
))
7589 if (!Selectors
.insert(M
->getSelector()).second
)
7592 Result R
= Result(M
, Results
.getBasePriority(M
), nullptr);
7593 R
.StartParameter
= SelIdents
.size();
7594 R
.AllParametersAreInformative
= (WantKind
!= MK_Any
);
7595 if (!InOriginalClass
)
7597 Results
.MaybeAddResult(R
, CurContext
);
7601 // Visit the protocols of protocols.
7602 if (const auto *Protocol
= dyn_cast
<ObjCProtocolDecl
>(Container
)) {
7603 if (Protocol
->hasDefinition()) {
7604 const ObjCList
<ObjCProtocolDecl
> &Protocols
=
7605 Protocol
->getReferencedProtocols();
7606 for (ObjCList
<ObjCProtocolDecl
>::iterator I
= Protocols
.begin(),
7607 E
= Protocols
.end();
7609 AddObjCMethods(*I
, WantInstanceMethods
, WantKind
, SelIdents
, CurContext
,
7610 Selectors
, AllowSameLength
, Results
, false, IsRootClass
);
7614 if (!IFace
|| !IFace
->hasDefinition())
7617 // Add methods in protocols.
7618 for (ObjCProtocolDecl
*I
: IFace
->protocols())
7619 AddObjCMethods(I
, WantInstanceMethods
, WantKind
, SelIdents
, CurContext
,
7620 Selectors
, AllowSameLength
, Results
, false, IsRootClass
);
7622 // Add methods in categories.
7623 for (ObjCCategoryDecl
*CatDecl
: IFace
->known_categories()) {
7624 AddObjCMethods(CatDecl
, WantInstanceMethods
, WantKind
, SelIdents
,
7625 CurContext
, Selectors
, AllowSameLength
, Results
,
7626 InOriginalClass
, IsRootClass
);
7628 // Add a categories protocol methods.
7629 const ObjCList
<ObjCProtocolDecl
> &Protocols
=
7630 CatDecl
->getReferencedProtocols();
7631 for (ObjCList
<ObjCProtocolDecl
>::iterator I
= Protocols
.begin(),
7632 E
= Protocols
.end();
7634 AddObjCMethods(*I
, WantInstanceMethods
, WantKind
, SelIdents
, CurContext
,
7635 Selectors
, AllowSameLength
, Results
, false, IsRootClass
);
7637 // Add methods in category implementations.
7638 if (ObjCCategoryImplDecl
*Impl
= CatDecl
->getImplementation())
7639 AddObjCMethods(Impl
, WantInstanceMethods
, WantKind
, SelIdents
, CurContext
,
7640 Selectors
, AllowSameLength
, Results
, InOriginalClass
,
7644 // Add methods in superclass.
7645 // Avoid passing in IsRootClass since root classes won't have super classes.
7646 if (IFace
->getSuperClass())
7647 AddObjCMethods(IFace
->getSuperClass(), WantInstanceMethods
, WantKind
,
7648 SelIdents
, CurContext
, Selectors
, AllowSameLength
, Results
,
7649 /*IsRootClass=*/false);
7651 // Add methods in our implementation, if any.
7652 if (ObjCImplementationDecl
*Impl
= IFace
->getImplementation())
7653 AddObjCMethods(Impl
, WantInstanceMethods
, WantKind
, SelIdents
, CurContext
,
7654 Selectors
, AllowSameLength
, Results
, InOriginalClass
,
7658 void Sema::CodeCompleteObjCPropertyGetter(Scope
*S
) {
7659 // Try to find the interface where getters might live.
7660 ObjCInterfaceDecl
*Class
= dyn_cast_or_null
<ObjCInterfaceDecl
>(CurContext
);
7662 if (ObjCCategoryDecl
*Category
=
7663 dyn_cast_or_null
<ObjCCategoryDecl
>(CurContext
))
7664 Class
= Category
->getClassInterface();
7670 // Find all of the potential getters.
7671 ResultBuilder
Results(*this, CodeCompleter
->getAllocator(),
7672 CodeCompleter
->getCodeCompletionTUInfo(),
7673 CodeCompletionContext::CCC_Other
);
7674 Results
.EnterNewScope();
7676 VisitedSelectorSet Selectors
;
7677 AddObjCMethods(Class
, true, MK_ZeroArgSelector
, std::nullopt
, CurContext
,
7679 /*AllowSameLength=*/true, Results
);
7680 Results
.ExitScope();
7681 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
7682 Results
.data(), Results
.size());
7685 void Sema::CodeCompleteObjCPropertySetter(Scope
*S
) {
7686 // Try to find the interface where setters might live.
7687 ObjCInterfaceDecl
*Class
= dyn_cast_or_null
<ObjCInterfaceDecl
>(CurContext
);
7689 if (ObjCCategoryDecl
*Category
=
7690 dyn_cast_or_null
<ObjCCategoryDecl
>(CurContext
))
7691 Class
= Category
->getClassInterface();
7697 // Find all of the potential getters.
7698 ResultBuilder
Results(*this, CodeCompleter
->getAllocator(),
7699 CodeCompleter
->getCodeCompletionTUInfo(),
7700 CodeCompletionContext::CCC_Other
);
7701 Results
.EnterNewScope();
7703 VisitedSelectorSet Selectors
;
7704 AddObjCMethods(Class
, true, MK_OneArgSelector
, std::nullopt
, CurContext
,
7706 /*AllowSameLength=*/true, Results
);
7708 Results
.ExitScope();
7709 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
7710 Results
.data(), Results
.size());
7713 void Sema::CodeCompleteObjCPassingType(Scope
*S
, ObjCDeclSpec
&DS
,
7715 ResultBuilder
Results(*this, CodeCompleter
->getAllocator(),
7716 CodeCompleter
->getCodeCompletionTUInfo(),
7717 CodeCompletionContext::CCC_Type
);
7718 Results
.EnterNewScope();
7720 // Add context-sensitive, Objective-C parameter-passing keywords.
7721 bool AddedInOut
= false;
7722 if ((DS
.getObjCDeclQualifier() &
7723 (ObjCDeclSpec::DQ_In
| ObjCDeclSpec::DQ_Inout
)) == 0) {
7724 Results
.AddResult("in");
7725 Results
.AddResult("inout");
7728 if ((DS
.getObjCDeclQualifier() &
7729 (ObjCDeclSpec::DQ_Out
| ObjCDeclSpec::DQ_Inout
)) == 0) {
7730 Results
.AddResult("out");
7732 Results
.AddResult("inout");
7734 if ((DS
.getObjCDeclQualifier() &
7735 (ObjCDeclSpec::DQ_Bycopy
| ObjCDeclSpec::DQ_Byref
|
7736 ObjCDeclSpec::DQ_Oneway
)) == 0) {
7737 Results
.AddResult("bycopy");
7738 Results
.AddResult("byref");
7739 Results
.AddResult("oneway");
7741 if ((DS
.getObjCDeclQualifier() & ObjCDeclSpec::DQ_CSNullability
) == 0) {
7742 Results
.AddResult("nonnull");
7743 Results
.AddResult("nullable");
7744 Results
.AddResult("null_unspecified");
7747 // If we're completing the return type of an Objective-C method and the
7748 // identifier IBAction refers to a macro, provide a completion item for
7750 // IBAction)<#selector#>:(id)sender
7751 if (DS
.getObjCDeclQualifier() == 0 && !IsParameter
&&
7752 PP
.isMacroDefined("IBAction")) {
7753 CodeCompletionBuilder
Builder(Results
.getAllocator(),
7754 Results
.getCodeCompletionTUInfo(),
7755 CCP_CodePattern
, CXAvailability_Available
);
7756 Builder
.AddTypedTextChunk("IBAction");
7757 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
7758 Builder
.AddPlaceholderChunk("selector");
7759 Builder
.AddChunk(CodeCompletionString::CK_Colon
);
7760 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
7761 Builder
.AddTextChunk("id");
7762 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
7763 Builder
.AddTextChunk("sender");
7764 Results
.AddResult(CodeCompletionResult(Builder
.TakeString()));
7767 // If we're completing the return type, provide 'instancetype'.
7769 Results
.AddResult(CodeCompletionResult("instancetype"));
7772 // Add various builtin type names and specifiers.
7773 AddOrdinaryNameResults(PCC_Type
, S
, *this, Results
);
7774 Results
.ExitScope();
7776 // Add the various type names
7777 Results
.setFilter(&ResultBuilder::IsOrdinaryNonValueName
);
7778 CodeCompletionDeclConsumer
Consumer(Results
, CurContext
);
7779 LookupVisibleDecls(S
, LookupOrdinaryName
, Consumer
,
7780 CodeCompleter
->includeGlobals(),
7781 CodeCompleter
->loadExternal());
7783 if (CodeCompleter
->includeMacros())
7784 AddMacroResults(PP
, Results
, CodeCompleter
->loadExternal(), false);
7786 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
7787 Results
.data(), Results
.size());
7790 /// When we have an expression with type "id", we may assume
7791 /// that it has some more-specific class type based on knowledge of
7792 /// common uses of Objective-C. This routine returns that class type,
7793 /// or NULL if no better result could be determined.
7794 static ObjCInterfaceDecl
*GetAssumedMessageSendExprType(Expr
*E
) {
7795 auto *Msg
= dyn_cast_or_null
<ObjCMessageExpr
>(E
);
7799 Selector Sel
= Msg
->getSelector();
7803 IdentifierInfo
*Id
= Sel
.getIdentifierInfoForSlot(0);
7807 ObjCMethodDecl
*Method
= Msg
->getMethodDecl();
7811 // Determine the class that we're sending the message to.
7812 ObjCInterfaceDecl
*IFace
= nullptr;
7813 switch (Msg
->getReceiverKind()) {
7814 case ObjCMessageExpr::Class
:
7815 if (const ObjCObjectType
*ObjType
=
7816 Msg
->getClassReceiver()->getAs
<ObjCObjectType
>())
7817 IFace
= ObjType
->getInterface();
7820 case ObjCMessageExpr::Instance
: {
7821 QualType T
= Msg
->getInstanceReceiver()->getType();
7822 if (const ObjCObjectPointerType
*Ptr
= T
->getAs
<ObjCObjectPointerType
>())
7823 IFace
= Ptr
->getInterfaceDecl();
7827 case ObjCMessageExpr::SuperInstance
:
7828 case ObjCMessageExpr::SuperClass
:
7835 ObjCInterfaceDecl
*Super
= IFace
->getSuperClass();
7836 if (Method
->isInstanceMethod())
7837 return llvm::StringSwitch
<ObjCInterfaceDecl
*>(Id
->getName())
7838 .Case("retain", IFace
)
7839 .Case("strong", IFace
)
7840 .Case("autorelease", IFace
)
7841 .Case("copy", IFace
)
7842 .Case("copyWithZone", IFace
)
7843 .Case("mutableCopy", IFace
)
7844 .Case("mutableCopyWithZone", IFace
)
7845 .Case("awakeFromCoder", IFace
)
7846 .Case("replacementObjectFromCoder", IFace
)
7847 .Case("class", IFace
)
7848 .Case("classForCoder", IFace
)
7849 .Case("superclass", Super
)
7852 return llvm::StringSwitch
<ObjCInterfaceDecl
*>(Id
->getName())
7854 .Case("alloc", IFace
)
7855 .Case("allocWithZone", IFace
)
7856 .Case("class", IFace
)
7857 .Case("superclass", Super
)
7861 // Add a special completion for a message send to "super", which fills in the
7862 // most likely case of forwarding all of our arguments to the superclass
7865 /// \param S The semantic analysis object.
7867 /// \param NeedSuperKeyword Whether we need to prefix this completion with
7868 /// the "super" keyword. Otherwise, we just need to provide the arguments.
7870 /// \param SelIdents The identifiers in the selector that have already been
7871 /// provided as arguments for a send to "super".
7873 /// \param Results The set of results to augment.
7875 /// \returns the Objective-C method declaration that would be invoked by
7876 /// this "super" completion. If NULL, no completion was added.
7877 static ObjCMethodDecl
*
7878 AddSuperSendCompletion(Sema
&S
, bool NeedSuperKeyword
,
7879 ArrayRef
<IdentifierInfo
*> SelIdents
,
7880 ResultBuilder
&Results
) {
7881 ObjCMethodDecl
*CurMethod
= S
.getCurMethodDecl();
7885 ObjCInterfaceDecl
*Class
= CurMethod
->getClassInterface();
7889 // Try to find a superclass method with the same selector.
7890 ObjCMethodDecl
*SuperMethod
= nullptr;
7891 while ((Class
= Class
->getSuperClass()) && !SuperMethod
) {
7892 // Check in the class
7893 SuperMethod
= Class
->getMethod(CurMethod
->getSelector(),
7894 CurMethod
->isInstanceMethod());
7896 // Check in categories or class extensions.
7898 for (const auto *Cat
: Class
->known_categories()) {
7899 if ((SuperMethod
= Cat
->getMethod(CurMethod
->getSelector(),
7900 CurMethod
->isInstanceMethod())))
7909 // Check whether the superclass method has the same signature.
7910 if (CurMethod
->param_size() != SuperMethod
->param_size() ||
7911 CurMethod
->isVariadic() != SuperMethod
->isVariadic())
7914 for (ObjCMethodDecl::param_iterator CurP
= CurMethod
->param_begin(),
7915 CurPEnd
= CurMethod
->param_end(),
7916 SuperP
= SuperMethod
->param_begin();
7917 CurP
!= CurPEnd
; ++CurP
, ++SuperP
) {
7918 // Make sure the parameter types are compatible.
7919 if (!S
.Context
.hasSameUnqualifiedType((*CurP
)->getType(),
7920 (*SuperP
)->getType()))
7923 // Make sure we have a parameter name to forward!
7924 if (!(*CurP
)->getIdentifier())
7928 // We have a superclass method. Now, form the send-to-super completion.
7929 CodeCompletionBuilder
Builder(Results
.getAllocator(),
7930 Results
.getCodeCompletionTUInfo());
7932 // Give this completion a return type.
7933 AddResultTypeChunk(S
.Context
, getCompletionPrintingPolicy(S
), SuperMethod
,
7934 Results
.getCompletionContext().getBaseType(), Builder
);
7936 // If we need the "super" keyword, add it (plus some spacing).
7937 if (NeedSuperKeyword
) {
7938 Builder
.AddTypedTextChunk("super");
7939 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
7942 Selector Sel
= CurMethod
->getSelector();
7943 if (Sel
.isUnarySelector()) {
7944 if (NeedSuperKeyword
)
7945 Builder
.AddTextChunk(
7946 Builder
.getAllocator().CopyString(Sel
.getNameForSlot(0)));
7948 Builder
.AddTypedTextChunk(
7949 Builder
.getAllocator().CopyString(Sel
.getNameForSlot(0)));
7951 ObjCMethodDecl::param_iterator CurP
= CurMethod
->param_begin();
7952 for (unsigned I
= 0, N
= Sel
.getNumArgs(); I
!= N
; ++I
, ++CurP
) {
7953 if (I
> SelIdents
.size())
7954 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
7956 if (I
< SelIdents
.size())
7957 Builder
.AddInformativeChunk(
7958 Builder
.getAllocator().CopyString(Sel
.getNameForSlot(I
) + ":"));
7959 else if (NeedSuperKeyword
|| I
> SelIdents
.size()) {
7960 Builder
.AddTextChunk(
7961 Builder
.getAllocator().CopyString(Sel
.getNameForSlot(I
) + ":"));
7962 Builder
.AddPlaceholderChunk(Builder
.getAllocator().CopyString(
7963 (*CurP
)->getIdentifier()->getName()));
7965 Builder
.AddTypedTextChunk(
7966 Builder
.getAllocator().CopyString(Sel
.getNameForSlot(I
) + ":"));
7967 Builder
.AddPlaceholderChunk(Builder
.getAllocator().CopyString(
7968 (*CurP
)->getIdentifier()->getName()));
7973 Results
.AddResult(CodeCompletionResult(Builder
.TakeString(), SuperMethod
,
7974 CCP_SuperCompletion
));
7978 void Sema::CodeCompleteObjCMessageReceiver(Scope
*S
) {
7979 typedef CodeCompletionResult Result
;
7980 ResultBuilder
Results(
7981 *this, CodeCompleter
->getAllocator(),
7982 CodeCompleter
->getCodeCompletionTUInfo(),
7983 CodeCompletionContext::CCC_ObjCMessageReceiver
,
7984 getLangOpts().CPlusPlus11
7985 ? &ResultBuilder::IsObjCMessageReceiverOrLambdaCapture
7986 : &ResultBuilder::IsObjCMessageReceiver
);
7988 CodeCompletionDeclConsumer
Consumer(Results
, CurContext
);
7989 Results
.EnterNewScope();
7990 LookupVisibleDecls(S
, LookupOrdinaryName
, Consumer
,
7991 CodeCompleter
->includeGlobals(),
7992 CodeCompleter
->loadExternal());
7994 // If we are in an Objective-C method inside a class that has a superclass,
7995 // add "super" as an option.
7996 if (ObjCMethodDecl
*Method
= getCurMethodDecl())
7997 if (ObjCInterfaceDecl
*Iface
= Method
->getClassInterface())
7998 if (Iface
->getSuperClass()) {
7999 Results
.AddResult(Result("super"));
8001 AddSuperSendCompletion(*this, /*NeedSuperKeyword=*/true, std::nullopt
,
8005 if (getLangOpts().CPlusPlus11
)
8006 addThisCompletion(*this, Results
);
8008 Results
.ExitScope();
8010 if (CodeCompleter
->includeMacros())
8011 AddMacroResults(PP
, Results
, CodeCompleter
->loadExternal(), false);
8012 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
8013 Results
.data(), Results
.size());
8016 void Sema::CodeCompleteObjCSuperMessage(Scope
*S
, SourceLocation SuperLoc
,
8017 ArrayRef
<IdentifierInfo
*> SelIdents
,
8018 bool AtArgumentExpression
) {
8019 ObjCInterfaceDecl
*CDecl
= nullptr;
8020 if (ObjCMethodDecl
*CurMethod
= getCurMethodDecl()) {
8021 // Figure out which interface we're in.
8022 CDecl
= CurMethod
->getClassInterface();
8026 // Find the superclass of this class.
8027 CDecl
= CDecl
->getSuperClass();
8031 if (CurMethod
->isInstanceMethod()) {
8032 // We are inside an instance method, which means that the message
8033 // send [super ...] is actually calling an instance method on the
8035 return CodeCompleteObjCInstanceMessage(S
, nullptr, SelIdents
,
8036 AtArgumentExpression
, CDecl
);
8039 // Fall through to send to the superclass in CDecl.
8041 // "super" may be the name of a type or variable. Figure out which
8043 IdentifierInfo
*Super
= getSuperIdentifier();
8044 NamedDecl
*ND
= LookupSingleName(S
, Super
, SuperLoc
, LookupOrdinaryName
);
8045 if ((CDecl
= dyn_cast_or_null
<ObjCInterfaceDecl
>(ND
))) {
8046 // "super" names an interface. Use it.
8047 } else if (TypeDecl
*TD
= dyn_cast_or_null
<TypeDecl
>(ND
)) {
8048 if (const ObjCObjectType
*Iface
=
8049 Context
.getTypeDeclType(TD
)->getAs
<ObjCObjectType
>())
8050 CDecl
= Iface
->getInterface();
8051 } else if (ND
&& isa
<UnresolvedUsingTypenameDecl
>(ND
)) {
8052 // "super" names an unresolved type; we can't be more specific.
8054 // Assume that "super" names some kind of value and parse that way.
8056 SourceLocation TemplateKWLoc
;
8058 id
.setIdentifier(Super
, SuperLoc
);
8059 ExprResult SuperExpr
= ActOnIdExpression(S
, SS
, TemplateKWLoc
, id
,
8060 /*HasTrailingLParen=*/false,
8061 /*IsAddressOfOperand=*/false);
8062 return CodeCompleteObjCInstanceMessage(S
, (Expr
*)SuperExpr
.get(),
8063 SelIdents
, AtArgumentExpression
);
8069 ParsedType Receiver
;
8071 Receiver
= ParsedType::make(Context
.getObjCInterfaceType(CDecl
));
8072 return CodeCompleteObjCClassMessage(S
, Receiver
, SelIdents
,
8073 AtArgumentExpression
,
8077 /// Given a set of code-completion results for the argument of a message
8078 /// send, determine the preferred type (if any) for that argument expression.
8079 static QualType
getPreferredArgumentTypeForMessageSend(ResultBuilder
&Results
,
8080 unsigned NumSelIdents
) {
8081 typedef CodeCompletionResult Result
;
8082 ASTContext
&Context
= Results
.getSema().Context
;
8084 QualType PreferredType
;
8085 unsigned BestPriority
= CCP_Unlikely
* 2;
8086 Result
*ResultsData
= Results
.data();
8087 for (unsigned I
= 0, N
= Results
.size(); I
!= N
; ++I
) {
8088 Result
&R
= ResultsData
[I
];
8089 if (R
.Kind
== Result::RK_Declaration
&&
8090 isa
<ObjCMethodDecl
>(R
.Declaration
)) {
8091 if (R
.Priority
<= BestPriority
) {
8092 const ObjCMethodDecl
*Method
= cast
<ObjCMethodDecl
>(R
.Declaration
);
8093 if (NumSelIdents
<= Method
->param_size()) {
8094 QualType MyPreferredType
=
8095 Method
->parameters()[NumSelIdents
- 1]->getType();
8096 if (R
.Priority
< BestPriority
|| PreferredType
.isNull()) {
8097 BestPriority
= R
.Priority
;
8098 PreferredType
= MyPreferredType
;
8099 } else if (!Context
.hasSameUnqualifiedType(PreferredType
,
8101 PreferredType
= QualType();
8108 return PreferredType
;
8111 static void AddClassMessageCompletions(Sema
&SemaRef
, Scope
*S
,
8112 ParsedType Receiver
,
8113 ArrayRef
<IdentifierInfo
*> SelIdents
,
8114 bool AtArgumentExpression
, bool IsSuper
,
8115 ResultBuilder
&Results
) {
8116 typedef CodeCompletionResult Result
;
8117 ObjCInterfaceDecl
*CDecl
= nullptr;
8119 // If the given name refers to an interface type, retrieve the
8120 // corresponding declaration.
8122 QualType T
= SemaRef
.GetTypeFromParser(Receiver
, nullptr);
8124 if (const ObjCObjectType
*Interface
= T
->getAs
<ObjCObjectType
>())
8125 CDecl
= Interface
->getInterface();
8128 // Add all of the factory methods in this Objective-C class, its protocols,
8129 // superclasses, categories, implementation, etc.
8130 Results
.EnterNewScope();
8132 // If this is a send-to-super, try to add the special "super" send
8135 if (ObjCMethodDecl
*SuperMethod
=
8136 AddSuperSendCompletion(SemaRef
, false, SelIdents
, Results
))
8137 Results
.Ignore(SuperMethod
);
8140 // If we're inside an Objective-C method definition, prefer its selector to
8142 if (ObjCMethodDecl
*CurMethod
= SemaRef
.getCurMethodDecl())
8143 Results
.setPreferredSelector(CurMethod
->getSelector());
8145 VisitedSelectorSet Selectors
;
8147 AddObjCMethods(CDecl
, false, MK_Any
, SelIdents
, SemaRef
.CurContext
,
8148 Selectors
, AtArgumentExpression
, Results
);
8150 // We're messaging "id" as a type; provide all class/factory methods.
8152 // If we have an external source, load the entire class method
8153 // pool from the AST file.
8154 if (SemaRef
.getExternalSource()) {
8155 for (uint32_t I
= 0,
8156 N
= SemaRef
.getExternalSource()->GetNumExternalSelectors();
8158 Selector Sel
= SemaRef
.getExternalSource()->GetExternalSelector(I
);
8159 if (Sel
.isNull() || SemaRef
.MethodPool
.count(Sel
))
8162 SemaRef
.ReadMethodPool(Sel
);
8166 for (Sema::GlobalMethodPool::iterator M
= SemaRef
.MethodPool
.begin(),
8167 MEnd
= SemaRef
.MethodPool
.end();
8169 for (ObjCMethodList
*MethList
= &M
->second
.second
;
8170 MethList
&& MethList
->getMethod(); MethList
= MethList
->getNext()) {
8171 if (!isAcceptableObjCMethod(MethList
->getMethod(), MK_Any
, SelIdents
))
8174 Result
R(MethList
->getMethod(),
8175 Results
.getBasePriority(MethList
->getMethod()), nullptr);
8176 R
.StartParameter
= SelIdents
.size();
8177 R
.AllParametersAreInformative
= false;
8178 Results
.MaybeAddResult(R
, SemaRef
.CurContext
);
8183 Results
.ExitScope();
8186 void Sema::CodeCompleteObjCClassMessage(Scope
*S
, ParsedType Receiver
,
8187 ArrayRef
<IdentifierInfo
*> SelIdents
,
8188 bool AtArgumentExpression
,
8191 QualType T
= this->GetTypeFromParser(Receiver
);
8193 ResultBuilder
Results(
8194 *this, CodeCompleter
->getAllocator(),
8195 CodeCompleter
->getCodeCompletionTUInfo(),
8196 CodeCompletionContext(CodeCompletionContext::CCC_ObjCClassMessage
, T
,
8199 AddClassMessageCompletions(*this, S
, Receiver
, SelIdents
,
8200 AtArgumentExpression
, IsSuper
, Results
);
8202 // If we're actually at the argument expression (rather than prior to the
8203 // selector), we're actually performing code completion for an expression.
8204 // Determine whether we have a single, best method. If so, we can
8205 // code-complete the expression using the corresponding parameter type as
8206 // our preferred type, improving completion results.
8207 if (AtArgumentExpression
) {
8208 QualType PreferredType
=
8209 getPreferredArgumentTypeForMessageSend(Results
, SelIdents
.size());
8210 if (PreferredType
.isNull())
8211 CodeCompleteOrdinaryName(S
, PCC_Expression
);
8213 CodeCompleteExpression(S
, PreferredType
);
8217 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
8218 Results
.data(), Results
.size());
8221 void Sema::CodeCompleteObjCInstanceMessage(Scope
*S
, Expr
*Receiver
,
8222 ArrayRef
<IdentifierInfo
*> SelIdents
,
8223 bool AtArgumentExpression
,
8224 ObjCInterfaceDecl
*Super
) {
8225 typedef CodeCompletionResult Result
;
8227 Expr
*RecExpr
= static_cast<Expr
*>(Receiver
);
8229 // If necessary, apply function/array conversion to the receiver.
8230 // C99 6.7.5.3p[7,8].
8232 ExprResult Conv
= DefaultFunctionArrayLvalueConversion(RecExpr
);
8233 if (Conv
.isInvalid()) // conversion failed. bail.
8235 RecExpr
= Conv
.get();
8237 QualType ReceiverType
= RecExpr
8238 ? RecExpr
->getType()
8239 : Super
? Context
.getObjCObjectPointerType(
8240 Context
.getObjCInterfaceType(Super
))
8241 : Context
.getObjCIdType();
8243 // If we're messaging an expression with type "id" or "Class", check
8244 // whether we know something special about the receiver that allows
8245 // us to assume a more-specific receiver type.
8246 if (ReceiverType
->isObjCIdType() || ReceiverType
->isObjCClassType()) {
8247 if (ObjCInterfaceDecl
*IFace
= GetAssumedMessageSendExprType(RecExpr
)) {
8248 if (ReceiverType
->isObjCClassType())
8249 return CodeCompleteObjCClassMessage(
8250 S
, ParsedType::make(Context
.getObjCInterfaceType(IFace
)), SelIdents
,
8251 AtArgumentExpression
, Super
);
8254 Context
.getObjCObjectPointerType(Context
.getObjCInterfaceType(IFace
));
8256 } else if (RecExpr
&& getLangOpts().CPlusPlus
) {
8257 ExprResult Conv
= PerformContextuallyConvertToObjCPointer(RecExpr
);
8258 if (Conv
.isUsable()) {
8259 RecExpr
= Conv
.get();
8260 ReceiverType
= RecExpr
->getType();
8264 // Build the set of methods we can see.
8265 ResultBuilder
Results(
8266 *this, CodeCompleter
->getAllocator(),
8267 CodeCompleter
->getCodeCompletionTUInfo(),
8268 CodeCompletionContext(CodeCompletionContext::CCC_ObjCInstanceMessage
,
8269 ReceiverType
, SelIdents
));
8271 Results
.EnterNewScope();
8273 // If this is a send-to-super, try to add the special "super" send
8276 if (ObjCMethodDecl
*SuperMethod
=
8277 AddSuperSendCompletion(*this, false, SelIdents
, Results
))
8278 Results
.Ignore(SuperMethod
);
8281 // If we're inside an Objective-C method definition, prefer its selector to
8283 if (ObjCMethodDecl
*CurMethod
= getCurMethodDecl())
8284 Results
.setPreferredSelector(CurMethod
->getSelector());
8286 // Keep track of the selectors we've already added.
8287 VisitedSelectorSet Selectors
;
8289 // Handle messages to Class. This really isn't a message to an instance
8290 // method, so we treat it the same way we would treat a message send to a
8292 if (ReceiverType
->isObjCClassType() ||
8293 ReceiverType
->isObjCQualifiedClassType()) {
8294 if (ObjCMethodDecl
*CurMethod
= getCurMethodDecl()) {
8295 if (ObjCInterfaceDecl
*ClassDecl
= CurMethod
->getClassInterface())
8296 AddObjCMethods(ClassDecl
, false, MK_Any
, SelIdents
, CurContext
,
8297 Selectors
, AtArgumentExpression
, Results
);
8300 // Handle messages to a qualified ID ("id<foo>").
8301 else if (const ObjCObjectPointerType
*QualID
=
8302 ReceiverType
->getAsObjCQualifiedIdType()) {
8303 // Search protocols for instance methods.
8304 for (auto *I
: QualID
->quals())
8305 AddObjCMethods(I
, true, MK_Any
, SelIdents
, CurContext
, Selectors
,
8306 AtArgumentExpression
, Results
);
8308 // Handle messages to a pointer to interface type.
8309 else if (const ObjCObjectPointerType
*IFacePtr
=
8310 ReceiverType
->getAsObjCInterfacePointerType()) {
8311 // Search the class, its superclasses, etc., for instance methods.
8312 AddObjCMethods(IFacePtr
->getInterfaceDecl(), true, MK_Any
, SelIdents
,
8313 CurContext
, Selectors
, AtArgumentExpression
, Results
);
8315 // Search protocols for instance methods.
8316 for (auto *I
: IFacePtr
->quals())
8317 AddObjCMethods(I
, true, MK_Any
, SelIdents
, CurContext
, Selectors
,
8318 AtArgumentExpression
, Results
);
8320 // Handle messages to "id".
8321 else if (ReceiverType
->isObjCIdType()) {
8322 // We're messaging "id", so provide all instance methods we know
8323 // about as code-completion results.
8325 // If we have an external source, load the entire class method
8326 // pool from the AST file.
8327 if (ExternalSource
) {
8328 for (uint32_t I
= 0, N
= ExternalSource
->GetNumExternalSelectors();
8330 Selector Sel
= ExternalSource
->GetExternalSelector(I
);
8331 if (Sel
.isNull() || MethodPool
.count(Sel
))
8334 ReadMethodPool(Sel
);
8338 for (GlobalMethodPool::iterator M
= MethodPool
.begin(),
8339 MEnd
= MethodPool
.end();
8341 for (ObjCMethodList
*MethList
= &M
->second
.first
;
8342 MethList
&& MethList
->getMethod(); MethList
= MethList
->getNext()) {
8343 if (!isAcceptableObjCMethod(MethList
->getMethod(), MK_Any
, SelIdents
))
8346 if (!Selectors
.insert(MethList
->getMethod()->getSelector()).second
)
8349 Result
R(MethList
->getMethod(),
8350 Results
.getBasePriority(MethList
->getMethod()), nullptr);
8351 R
.StartParameter
= SelIdents
.size();
8352 R
.AllParametersAreInformative
= false;
8353 Results
.MaybeAddResult(R
, CurContext
);
8357 Results
.ExitScope();
8359 // If we're actually at the argument expression (rather than prior to the
8360 // selector), we're actually performing code completion for an expression.
8361 // Determine whether we have a single, best method. If so, we can
8362 // code-complete the expression using the corresponding parameter type as
8363 // our preferred type, improving completion results.
8364 if (AtArgumentExpression
) {
8365 QualType PreferredType
=
8366 getPreferredArgumentTypeForMessageSend(Results
, SelIdents
.size());
8367 if (PreferredType
.isNull())
8368 CodeCompleteOrdinaryName(S
, PCC_Expression
);
8370 CodeCompleteExpression(S
, PreferredType
);
8374 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
8375 Results
.data(), Results
.size());
8378 void Sema::CodeCompleteObjCForCollection(Scope
*S
,
8379 DeclGroupPtrTy IterationVar
) {
8380 CodeCompleteExpressionData Data
;
8381 Data
.ObjCCollection
= true;
8383 if (IterationVar
.getAsOpaquePtr()) {
8384 DeclGroupRef DG
= IterationVar
.get();
8385 for (DeclGroupRef::iterator I
= DG
.begin(), End
= DG
.end(); I
!= End
; ++I
) {
8387 Data
.IgnoreDecls
.push_back(*I
);
8391 CodeCompleteExpression(S
, Data
);
8394 void Sema::CodeCompleteObjCSelector(Scope
*S
,
8395 ArrayRef
<IdentifierInfo
*> SelIdents
) {
8396 // If we have an external source, load the entire class method
8397 // pool from the AST file.
8398 if (ExternalSource
) {
8399 for (uint32_t I
= 0, N
= ExternalSource
->GetNumExternalSelectors(); I
!= N
;
8401 Selector Sel
= ExternalSource
->GetExternalSelector(I
);
8402 if (Sel
.isNull() || MethodPool
.count(Sel
))
8405 ReadMethodPool(Sel
);
8409 ResultBuilder
Results(*this, CodeCompleter
->getAllocator(),
8410 CodeCompleter
->getCodeCompletionTUInfo(),
8411 CodeCompletionContext::CCC_SelectorName
);
8412 Results
.EnterNewScope();
8413 for (GlobalMethodPool::iterator M
= MethodPool
.begin(),
8414 MEnd
= MethodPool
.end();
8417 Selector Sel
= M
->first
;
8418 if (!isAcceptableObjCSelector(Sel
, MK_Any
, SelIdents
))
8421 CodeCompletionBuilder
Builder(Results
.getAllocator(),
8422 Results
.getCodeCompletionTUInfo());
8423 if (Sel
.isUnarySelector()) {
8424 Builder
.AddTypedTextChunk(
8425 Builder
.getAllocator().CopyString(Sel
.getNameForSlot(0)));
8426 Results
.AddResult(Builder
.TakeString());
8430 std::string Accumulator
;
8431 for (unsigned I
= 0, N
= Sel
.getNumArgs(); I
!= N
; ++I
) {
8432 if (I
== SelIdents
.size()) {
8433 if (!Accumulator
.empty()) {
8434 Builder
.AddInformativeChunk(
8435 Builder
.getAllocator().CopyString(Accumulator
));
8436 Accumulator
.clear();
8440 Accumulator
+= Sel
.getNameForSlot(I
);
8443 Builder
.AddTypedTextChunk(Builder
.getAllocator().CopyString(Accumulator
));
8444 Results
.AddResult(Builder
.TakeString());
8446 Results
.ExitScope();
8448 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
8449 Results
.data(), Results
.size());
8452 /// Add all of the protocol declarations that we find in the given
8453 /// (translation unit) context.
8454 static void AddProtocolResults(DeclContext
*Ctx
, DeclContext
*CurContext
,
8455 bool OnlyForwardDeclarations
,
8456 ResultBuilder
&Results
) {
8457 typedef CodeCompletionResult Result
;
8459 for (const auto *D
: Ctx
->decls()) {
8460 // Record any protocols we find.
8461 if (const auto *Proto
= dyn_cast
<ObjCProtocolDecl
>(D
))
8462 if (!OnlyForwardDeclarations
|| !Proto
->hasDefinition())
8464 Result(Proto
, Results
.getBasePriority(Proto
), nullptr), CurContext
,
8469 void Sema::CodeCompleteObjCProtocolReferences(
8470 ArrayRef
<IdentifierLocPair
> Protocols
) {
8471 ResultBuilder
Results(*this, CodeCompleter
->getAllocator(),
8472 CodeCompleter
->getCodeCompletionTUInfo(),
8473 CodeCompletionContext::CCC_ObjCProtocolName
);
8475 if (CodeCompleter
->includeGlobals()) {
8476 Results
.EnterNewScope();
8478 // Tell the result set to ignore all of the protocols we have
8480 // FIXME: This doesn't work when caching code-completion results.
8481 for (const IdentifierLocPair
&Pair
: Protocols
)
8482 if (ObjCProtocolDecl
*Protocol
= LookupProtocol(Pair
.first
, Pair
.second
))
8483 Results
.Ignore(Protocol
);
8485 // Add all protocols.
8486 AddProtocolResults(Context
.getTranslationUnitDecl(), CurContext
, false,
8489 Results
.ExitScope();
8492 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
8493 Results
.data(), Results
.size());
8496 void Sema::CodeCompleteObjCProtocolDecl(Scope
*) {
8497 ResultBuilder
Results(*this, CodeCompleter
->getAllocator(),
8498 CodeCompleter
->getCodeCompletionTUInfo(),
8499 CodeCompletionContext::CCC_ObjCProtocolName
);
8501 if (CodeCompleter
->includeGlobals()) {
8502 Results
.EnterNewScope();
8504 // Add all protocols.
8505 AddProtocolResults(Context
.getTranslationUnitDecl(), CurContext
, true,
8508 Results
.ExitScope();
8511 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
8512 Results
.data(), Results
.size());
8515 /// Add all of the Objective-C interface declarations that we find in
8516 /// the given (translation unit) context.
8517 static void AddInterfaceResults(DeclContext
*Ctx
, DeclContext
*CurContext
,
8518 bool OnlyForwardDeclarations
,
8519 bool OnlyUnimplemented
,
8520 ResultBuilder
&Results
) {
8521 typedef CodeCompletionResult Result
;
8523 for (const auto *D
: Ctx
->decls()) {
8524 // Record any interfaces we find.
8525 if (const auto *Class
= dyn_cast
<ObjCInterfaceDecl
>(D
))
8526 if ((!OnlyForwardDeclarations
|| !Class
->hasDefinition()) &&
8527 (!OnlyUnimplemented
|| !Class
->getImplementation()))
8529 Result(Class
, Results
.getBasePriority(Class
), nullptr), CurContext
,
8534 void Sema::CodeCompleteObjCInterfaceDecl(Scope
*S
) {
8535 ResultBuilder
Results(*this, CodeCompleter
->getAllocator(),
8536 CodeCompleter
->getCodeCompletionTUInfo(),
8537 CodeCompletionContext::CCC_ObjCInterfaceName
);
8538 Results
.EnterNewScope();
8540 if (CodeCompleter
->includeGlobals()) {
8542 AddInterfaceResults(Context
.getTranslationUnitDecl(), CurContext
, false,
8546 Results
.ExitScope();
8548 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
8549 Results
.data(), Results
.size());
8552 void Sema::CodeCompleteObjCClassForwardDecl(Scope
*S
) {
8553 ResultBuilder
Results(*this, CodeCompleter
->getAllocator(),
8554 CodeCompleter
->getCodeCompletionTUInfo(),
8555 CodeCompletionContext::CCC_ObjCClassForwardDecl
);
8556 Results
.EnterNewScope();
8558 if (CodeCompleter
->includeGlobals()) {
8560 AddInterfaceResults(Context
.getTranslationUnitDecl(), CurContext
, false,
8564 Results
.ExitScope();
8566 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
8567 Results
.data(), Results
.size());
8570 void Sema::CodeCompleteObjCSuperclass(Scope
*S
, IdentifierInfo
*ClassName
,
8571 SourceLocation ClassNameLoc
) {
8572 ResultBuilder
Results(*this, CodeCompleter
->getAllocator(),
8573 CodeCompleter
->getCodeCompletionTUInfo(),
8574 CodeCompletionContext::CCC_ObjCInterfaceName
);
8575 Results
.EnterNewScope();
8577 // Make sure that we ignore the class we're currently defining.
8578 NamedDecl
*CurClass
=
8579 LookupSingleName(TUScope
, ClassName
, ClassNameLoc
, LookupOrdinaryName
);
8580 if (CurClass
&& isa
<ObjCInterfaceDecl
>(CurClass
))
8581 Results
.Ignore(CurClass
);
8583 if (CodeCompleter
->includeGlobals()) {
8585 AddInterfaceResults(Context
.getTranslationUnitDecl(), CurContext
, false,
8589 Results
.ExitScope();
8591 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
8592 Results
.data(), Results
.size());
8595 void Sema::CodeCompleteObjCImplementationDecl(Scope
*S
) {
8596 ResultBuilder
Results(*this, CodeCompleter
->getAllocator(),
8597 CodeCompleter
->getCodeCompletionTUInfo(),
8598 CodeCompletionContext::CCC_ObjCImplementation
);
8599 Results
.EnterNewScope();
8601 if (CodeCompleter
->includeGlobals()) {
8602 // Add all unimplemented classes.
8603 AddInterfaceResults(Context
.getTranslationUnitDecl(), CurContext
, false,
8607 Results
.ExitScope();
8609 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
8610 Results
.data(), Results
.size());
8613 void Sema::CodeCompleteObjCInterfaceCategory(Scope
*S
,
8614 IdentifierInfo
*ClassName
,
8615 SourceLocation ClassNameLoc
) {
8616 typedef CodeCompletionResult Result
;
8618 ResultBuilder
Results(*this, CodeCompleter
->getAllocator(),
8619 CodeCompleter
->getCodeCompletionTUInfo(),
8620 CodeCompletionContext::CCC_ObjCCategoryName
);
8622 // Ignore any categories we find that have already been implemented by this
8624 llvm::SmallPtrSet
<IdentifierInfo
*, 16> CategoryNames
;
8625 NamedDecl
*CurClass
=
8626 LookupSingleName(TUScope
, ClassName
, ClassNameLoc
, LookupOrdinaryName
);
8627 if (ObjCInterfaceDecl
*Class
=
8628 dyn_cast_or_null
<ObjCInterfaceDecl
>(CurClass
)) {
8629 for (const auto *Cat
: Class
->visible_categories())
8630 CategoryNames
.insert(Cat
->getIdentifier());
8633 // Add all of the categories we know about.
8634 Results
.EnterNewScope();
8635 TranslationUnitDecl
*TU
= Context
.getTranslationUnitDecl();
8636 for (const auto *D
: TU
->decls())
8637 if (const auto *Category
= dyn_cast
<ObjCCategoryDecl
>(D
))
8638 if (CategoryNames
.insert(Category
->getIdentifier()).second
)
8640 Result(Category
, Results
.getBasePriority(Category
), nullptr),
8641 CurContext
, nullptr, false);
8642 Results
.ExitScope();
8644 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
8645 Results
.data(), Results
.size());
8648 void Sema::CodeCompleteObjCImplementationCategory(Scope
*S
,
8649 IdentifierInfo
*ClassName
,
8650 SourceLocation ClassNameLoc
) {
8651 typedef CodeCompletionResult Result
;
8653 // Find the corresponding interface. If we couldn't find the interface, the
8654 // program itself is ill-formed. However, we'll try to be helpful still by
8655 // providing the list of all of the categories we know about.
8656 NamedDecl
*CurClass
=
8657 LookupSingleName(TUScope
, ClassName
, ClassNameLoc
, LookupOrdinaryName
);
8658 ObjCInterfaceDecl
*Class
= dyn_cast_or_null
<ObjCInterfaceDecl
>(CurClass
);
8660 return CodeCompleteObjCInterfaceCategory(S
, ClassName
, ClassNameLoc
);
8662 ResultBuilder
Results(*this, CodeCompleter
->getAllocator(),
8663 CodeCompleter
->getCodeCompletionTUInfo(),
8664 CodeCompletionContext::CCC_ObjCCategoryName
);
8666 // Add all of the categories that have corresponding interface
8667 // declarations in this class and any of its superclasses, except for
8668 // already-implemented categories in the class itself.
8669 llvm::SmallPtrSet
<IdentifierInfo
*, 16> CategoryNames
;
8670 Results
.EnterNewScope();
8671 bool IgnoreImplemented
= true;
8673 for (const auto *Cat
: Class
->visible_categories()) {
8674 if ((!IgnoreImplemented
|| !Cat
->getImplementation()) &&
8675 CategoryNames
.insert(Cat
->getIdentifier()).second
)
8676 Results
.AddResult(Result(Cat
, Results
.getBasePriority(Cat
), nullptr),
8677 CurContext
, nullptr, false);
8680 Class
= Class
->getSuperClass();
8681 IgnoreImplemented
= false;
8683 Results
.ExitScope();
8685 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
8686 Results
.data(), Results
.size());
8689 void Sema::CodeCompleteObjCPropertyDefinition(Scope
*S
) {
8690 CodeCompletionContext
CCContext(CodeCompletionContext::CCC_Other
);
8691 ResultBuilder
Results(*this, CodeCompleter
->getAllocator(),
8692 CodeCompleter
->getCodeCompletionTUInfo(), CCContext
);
8694 // Figure out where this @synthesize lives.
8695 ObjCContainerDecl
*Container
=
8696 dyn_cast_or_null
<ObjCContainerDecl
>(CurContext
);
8697 if (!Container
|| (!isa
<ObjCImplementationDecl
>(Container
) &&
8698 !isa
<ObjCCategoryImplDecl
>(Container
)))
8701 // Ignore any properties that have already been implemented.
8702 Container
= getContainerDef(Container
);
8703 for (const auto *D
: Container
->decls())
8704 if (const auto *PropertyImpl
= dyn_cast
<ObjCPropertyImplDecl
>(D
))
8705 Results
.Ignore(PropertyImpl
->getPropertyDecl());
8707 // Add any properties that we find.
8708 AddedPropertiesSet AddedProperties
;
8709 Results
.EnterNewScope();
8710 if (ObjCImplementationDecl
*ClassImpl
=
8711 dyn_cast
<ObjCImplementationDecl
>(Container
))
8712 AddObjCProperties(CCContext
, ClassImpl
->getClassInterface(), false,
8713 /*AllowNullaryMethods=*/false, CurContext
,
8714 AddedProperties
, Results
);
8716 AddObjCProperties(CCContext
,
8717 cast
<ObjCCategoryImplDecl
>(Container
)->getCategoryDecl(),
8718 false, /*AllowNullaryMethods=*/false, CurContext
,
8719 AddedProperties
, Results
);
8720 Results
.ExitScope();
8722 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
8723 Results
.data(), Results
.size());
8726 void Sema::CodeCompleteObjCPropertySynthesizeIvar(
8727 Scope
*S
, IdentifierInfo
*PropertyName
) {
8728 typedef CodeCompletionResult Result
;
8729 ResultBuilder
Results(*this, CodeCompleter
->getAllocator(),
8730 CodeCompleter
->getCodeCompletionTUInfo(),
8731 CodeCompletionContext::CCC_Other
);
8733 // Figure out where this @synthesize lives.
8734 ObjCContainerDecl
*Container
=
8735 dyn_cast_or_null
<ObjCContainerDecl
>(CurContext
);
8736 if (!Container
|| (!isa
<ObjCImplementationDecl
>(Container
) &&
8737 !isa
<ObjCCategoryImplDecl
>(Container
)))
8740 // Figure out which interface we're looking into.
8741 ObjCInterfaceDecl
*Class
= nullptr;
8742 if (ObjCImplementationDecl
*ClassImpl
=
8743 dyn_cast
<ObjCImplementationDecl
>(Container
))
8744 Class
= ClassImpl
->getClassInterface();
8746 Class
= cast
<ObjCCategoryImplDecl
>(Container
)
8748 ->getClassInterface();
8750 // Determine the type of the property we're synthesizing.
8751 QualType PropertyType
= Context
.getObjCIdType();
8753 if (ObjCPropertyDecl
*Property
= Class
->FindPropertyDeclaration(
8754 PropertyName
, ObjCPropertyQueryKind::OBJC_PR_query_instance
)) {
8756 Property
->getType().getNonReferenceType().getUnqualifiedType();
8758 // Give preference to ivars
8759 Results
.setPreferredType(PropertyType
);
8763 // Add all of the instance variables in this class and its superclasses.
8764 Results
.EnterNewScope();
8765 bool SawSimilarlyNamedIvar
= false;
8766 std::string NameWithPrefix
;
8767 NameWithPrefix
+= '_';
8768 NameWithPrefix
+= PropertyName
->getName();
8769 std::string NameWithSuffix
= PropertyName
->getName().str();
8770 NameWithSuffix
+= '_';
8771 for (; Class
; Class
= Class
->getSuperClass()) {
8772 for (ObjCIvarDecl
*Ivar
= Class
->all_declared_ivar_begin(); Ivar
;
8773 Ivar
= Ivar
->getNextIvar()) {
8774 Results
.AddResult(Result(Ivar
, Results
.getBasePriority(Ivar
), nullptr),
8775 CurContext
, nullptr, false);
8777 // Determine whether we've seen an ivar with a name similar to the
8779 if ((PropertyName
== Ivar
->getIdentifier() ||
8780 NameWithPrefix
== Ivar
->getName() ||
8781 NameWithSuffix
== Ivar
->getName())) {
8782 SawSimilarlyNamedIvar
= true;
8784 // Reduce the priority of this result by one, to give it a slight
8785 // advantage over other results whose names don't match so closely.
8786 if (Results
.size() &&
8787 Results
.data()[Results
.size() - 1].Kind
==
8788 CodeCompletionResult::RK_Declaration
&&
8789 Results
.data()[Results
.size() - 1].Declaration
== Ivar
)
8790 Results
.data()[Results
.size() - 1].Priority
--;
8795 if (!SawSimilarlyNamedIvar
) {
8796 // Create ivar result _propName, that the user can use to synthesize
8797 // an ivar of the appropriate type.
8798 unsigned Priority
= CCP_MemberDeclaration
+ 1;
8799 typedef CodeCompletionResult Result
;
8800 CodeCompletionAllocator
&Allocator
= Results
.getAllocator();
8801 CodeCompletionBuilder
Builder(Allocator
, Results
.getCodeCompletionTUInfo(),
8802 Priority
, CXAvailability_Available
);
8804 PrintingPolicy Policy
= getCompletionPrintingPolicy(*this);
8805 Builder
.AddResultTypeChunk(
8806 GetCompletionTypeString(PropertyType
, Context
, Policy
, Allocator
));
8807 Builder
.AddTypedTextChunk(Allocator
.CopyString(NameWithPrefix
));
8809 Result(Builder
.TakeString(), Priority
, CXCursor_ObjCIvarDecl
));
8812 Results
.ExitScope();
8814 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
8815 Results
.data(), Results
.size());
8818 // Mapping from selectors to the methods that implement that selector, along
8819 // with the "in original class" flag.
8820 typedef llvm::DenseMap
<Selector
,
8821 llvm::PointerIntPair
<ObjCMethodDecl
*, 1, bool>>
8824 /// Find all of the methods that reside in the given container
8825 /// (and its superclasses, protocols, etc.) that meet the given
8826 /// criteria. Insert those methods into the map of known methods,
8827 /// indexed by selector so they can be easily found.
8828 static void FindImplementableMethods(ASTContext
&Context
,
8829 ObjCContainerDecl
*Container
,
8830 std::optional
<bool> WantInstanceMethods
,
8831 QualType ReturnType
,
8832 KnownMethodsMap
&KnownMethods
,
8833 bool InOriginalClass
= true) {
8834 if (ObjCInterfaceDecl
*IFace
= dyn_cast
<ObjCInterfaceDecl
>(Container
)) {
8835 // Make sure we have a definition; that's what we'll walk.
8836 if (!IFace
->hasDefinition())
8839 IFace
= IFace
->getDefinition();
8842 const ObjCList
<ObjCProtocolDecl
> &Protocols
=
8843 IFace
->getReferencedProtocols();
8844 for (ObjCList
<ObjCProtocolDecl
>::iterator I
= Protocols
.begin(),
8845 E
= Protocols
.end();
8847 FindImplementableMethods(Context
, *I
, WantInstanceMethods
, ReturnType
,
8848 KnownMethods
, InOriginalClass
);
8850 // Add methods from any class extensions and categories.
8851 for (auto *Cat
: IFace
->visible_categories()) {
8852 FindImplementableMethods(Context
, Cat
, WantInstanceMethods
, ReturnType
,
8853 KnownMethods
, false);
8856 // Visit the superclass.
8857 if (IFace
->getSuperClass())
8858 FindImplementableMethods(Context
, IFace
->getSuperClass(),
8859 WantInstanceMethods
, ReturnType
, KnownMethods
,
8863 if (ObjCCategoryDecl
*Category
= dyn_cast
<ObjCCategoryDecl
>(Container
)) {
8864 // Recurse into protocols.
8865 const ObjCList
<ObjCProtocolDecl
> &Protocols
=
8866 Category
->getReferencedProtocols();
8867 for (ObjCList
<ObjCProtocolDecl
>::iterator I
= Protocols
.begin(),
8868 E
= Protocols
.end();
8870 FindImplementableMethods(Context
, *I
, WantInstanceMethods
, ReturnType
,
8871 KnownMethods
, InOriginalClass
);
8873 // If this category is the original class, jump to the interface.
8874 if (InOriginalClass
&& Category
->getClassInterface())
8875 FindImplementableMethods(Context
, Category
->getClassInterface(),
8876 WantInstanceMethods
, ReturnType
, KnownMethods
,
8880 if (ObjCProtocolDecl
*Protocol
= dyn_cast
<ObjCProtocolDecl
>(Container
)) {
8881 // Make sure we have a definition; that's what we'll walk.
8882 if (!Protocol
->hasDefinition())
8884 Protocol
= Protocol
->getDefinition();
8885 Container
= Protocol
;
8887 // Recurse into protocols.
8888 const ObjCList
<ObjCProtocolDecl
> &Protocols
=
8889 Protocol
->getReferencedProtocols();
8890 for (ObjCList
<ObjCProtocolDecl
>::iterator I
= Protocols
.begin(),
8891 E
= Protocols
.end();
8893 FindImplementableMethods(Context
, *I
, WantInstanceMethods
, ReturnType
,
8894 KnownMethods
, false);
8897 // Add methods in this container. This operation occurs last because
8898 // we want the methods from this container to override any methods
8899 // we've previously seen with the same selector.
8900 for (auto *M
: Container
->methods()) {
8901 if (!WantInstanceMethods
|| M
->isInstanceMethod() == *WantInstanceMethods
) {
8902 if (!ReturnType
.isNull() &&
8903 !Context
.hasSameUnqualifiedType(ReturnType
, M
->getReturnType()))
8906 KnownMethods
[M
->getSelector()] =
8907 KnownMethodsMap::mapped_type(M
, InOriginalClass
);
8912 /// Add the parenthesized return or parameter type chunk to a code
8913 /// completion string.
8914 static void AddObjCPassingTypeChunk(QualType Type
, unsigned ObjCDeclQuals
,
8915 ASTContext
&Context
,
8916 const PrintingPolicy
&Policy
,
8917 CodeCompletionBuilder
&Builder
) {
8918 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
8919 std::string Quals
= formatObjCParamQualifiers(ObjCDeclQuals
, Type
);
8921 Builder
.AddTextChunk(Builder
.getAllocator().CopyString(Quals
));
8922 Builder
.AddTextChunk(
8923 GetCompletionTypeString(Type
, Context
, Policy
, Builder
.getAllocator()));
8924 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
8927 /// Determine whether the given class is or inherits from a class by
8929 static bool InheritsFromClassNamed(ObjCInterfaceDecl
*Class
, StringRef Name
) {
8933 if (Class
->getIdentifier() && Class
->getIdentifier()->getName() == Name
)
8936 return InheritsFromClassNamed(Class
->getSuperClass(), Name
);
8939 /// Add code completions for Objective-C Key-Value Coding (KVC) and
8940 /// Key-Value Observing (KVO).
8941 static void AddObjCKeyValueCompletions(ObjCPropertyDecl
*Property
,
8942 bool IsInstanceMethod
,
8943 QualType ReturnType
, ASTContext
&Context
,
8944 VisitedSelectorSet
&KnownSelectors
,
8945 ResultBuilder
&Results
) {
8946 IdentifierInfo
*PropName
= Property
->getIdentifier();
8947 if (!PropName
|| PropName
->getLength() == 0)
8950 PrintingPolicy Policy
= getCompletionPrintingPolicy(Results
.getSema());
8952 // Builder that will create each code completion.
8953 typedef CodeCompletionResult Result
;
8954 CodeCompletionAllocator
&Allocator
= Results
.getAllocator();
8955 CodeCompletionBuilder
Builder(Allocator
, Results
.getCodeCompletionTUInfo());
8957 // The selector table.
8958 SelectorTable
&Selectors
= Context
.Selectors
;
8960 // The property name, copied into the code completion allocation region
8963 CodeCompletionAllocator
&Allocator
;
8965 const char *CopiedKey
;
8967 KeyHolder(CodeCompletionAllocator
&Allocator
, StringRef Key
)
8968 : Allocator(Allocator
), Key(Key
), CopiedKey(nullptr) {}
8970 operator const char *() {
8974 return CopiedKey
= Allocator
.CopyString(Key
);
8976 } Key(Allocator
, PropName
->getName());
8978 // The uppercased name of the property name.
8979 std::string UpperKey
= std::string(PropName
->getName());
8980 if (!UpperKey
.empty())
8981 UpperKey
[0] = toUppercase(UpperKey
[0]);
8983 bool ReturnTypeMatchesProperty
=
8984 ReturnType
.isNull() ||
8985 Context
.hasSameUnqualifiedType(ReturnType
.getNonReferenceType(),
8986 Property
->getType());
8987 bool ReturnTypeMatchesVoid
= ReturnType
.isNull() || ReturnType
->isVoidType();
8989 // Add the normal accessor -(type)key.
8990 if (IsInstanceMethod
&&
8991 KnownSelectors
.insert(Selectors
.getNullarySelector(PropName
)).second
&&
8992 ReturnTypeMatchesProperty
&& !Property
->getGetterMethodDecl()) {
8993 if (ReturnType
.isNull())
8994 AddObjCPassingTypeChunk(Property
->getType(), /*Quals=*/0, Context
, Policy
,
8997 Builder
.AddTypedTextChunk(Key
);
8998 Results
.AddResult(Result(Builder
.TakeString(), CCP_CodePattern
,
8999 CXCursor_ObjCInstanceMethodDecl
));
9002 // If we have an integral or boolean property (or the user has provided
9003 // an integral or boolean return type), add the accessor -(type)isKey.
9004 if (IsInstanceMethod
&&
9005 ((!ReturnType
.isNull() &&
9006 (ReturnType
->isIntegerType() || ReturnType
->isBooleanType())) ||
9007 (ReturnType
.isNull() && (Property
->getType()->isIntegerType() ||
9008 Property
->getType()->isBooleanType())))) {
9009 std::string SelectorName
= (Twine("is") + UpperKey
).str();
9010 IdentifierInfo
*SelectorId
= &Context
.Idents
.get(SelectorName
);
9011 if (KnownSelectors
.insert(Selectors
.getNullarySelector(SelectorId
))
9013 if (ReturnType
.isNull()) {
9014 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9015 Builder
.AddTextChunk("BOOL");
9016 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9019 Builder
.AddTypedTextChunk(Allocator
.CopyString(SelectorId
->getName()));
9020 Results
.AddResult(Result(Builder
.TakeString(), CCP_CodePattern
,
9021 CXCursor_ObjCInstanceMethodDecl
));
9025 // Add the normal mutator.
9026 if (IsInstanceMethod
&& ReturnTypeMatchesVoid
&&
9027 !Property
->getSetterMethodDecl()) {
9028 std::string SelectorName
= (Twine("set") + UpperKey
).str();
9029 IdentifierInfo
*SelectorId
= &Context
.Idents
.get(SelectorName
);
9030 if (KnownSelectors
.insert(Selectors
.getUnarySelector(SelectorId
)).second
) {
9031 if (ReturnType
.isNull()) {
9032 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9033 Builder
.AddTextChunk("void");
9034 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9037 Builder
.AddTypedTextChunk(
9038 Allocator
.CopyString(SelectorId
->getName() + ":"));
9039 AddObjCPassingTypeChunk(Property
->getType(), /*Quals=*/0, Context
, Policy
,
9041 Builder
.AddTextChunk(Key
);
9042 Results
.AddResult(Result(Builder
.TakeString(), CCP_CodePattern
,
9043 CXCursor_ObjCInstanceMethodDecl
));
9047 // Indexed and unordered accessors
9048 unsigned IndexedGetterPriority
= CCP_CodePattern
;
9049 unsigned IndexedSetterPriority
= CCP_CodePattern
;
9050 unsigned UnorderedGetterPriority
= CCP_CodePattern
;
9051 unsigned UnorderedSetterPriority
= CCP_CodePattern
;
9052 if (const auto *ObjCPointer
=
9053 Property
->getType()->getAs
<ObjCObjectPointerType
>()) {
9054 if (ObjCInterfaceDecl
*IFace
= ObjCPointer
->getInterfaceDecl()) {
9055 // If this interface type is not provably derived from a known
9056 // collection, penalize the corresponding completions.
9057 if (!InheritsFromClassNamed(IFace
, "NSMutableArray")) {
9058 IndexedSetterPriority
+= CCD_ProbablyNotObjCCollection
;
9059 if (!InheritsFromClassNamed(IFace
, "NSArray"))
9060 IndexedGetterPriority
+= CCD_ProbablyNotObjCCollection
;
9063 if (!InheritsFromClassNamed(IFace
, "NSMutableSet")) {
9064 UnorderedSetterPriority
+= CCD_ProbablyNotObjCCollection
;
9065 if (!InheritsFromClassNamed(IFace
, "NSSet"))
9066 UnorderedGetterPriority
+= CCD_ProbablyNotObjCCollection
;
9070 IndexedGetterPriority
+= CCD_ProbablyNotObjCCollection
;
9071 IndexedSetterPriority
+= CCD_ProbablyNotObjCCollection
;
9072 UnorderedGetterPriority
+= CCD_ProbablyNotObjCCollection
;
9073 UnorderedSetterPriority
+= CCD_ProbablyNotObjCCollection
;
9076 // Add -(NSUInteger)countOf<key>
9077 if (IsInstanceMethod
&&
9078 (ReturnType
.isNull() || ReturnType
->isIntegerType())) {
9079 std::string SelectorName
= (Twine("countOf") + UpperKey
).str();
9080 IdentifierInfo
*SelectorId
= &Context
.Idents
.get(SelectorName
);
9081 if (KnownSelectors
.insert(Selectors
.getNullarySelector(SelectorId
))
9083 if (ReturnType
.isNull()) {
9084 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9085 Builder
.AddTextChunk("NSUInteger");
9086 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9089 Builder
.AddTypedTextChunk(Allocator
.CopyString(SelectorId
->getName()));
9091 Result(Builder
.TakeString(),
9092 std::min(IndexedGetterPriority
, UnorderedGetterPriority
),
9093 CXCursor_ObjCInstanceMethodDecl
));
9098 // Add -(id)objectInKeyAtIndex:(NSUInteger)index
9099 if (IsInstanceMethod
&&
9100 (ReturnType
.isNull() || ReturnType
->isObjCObjectPointerType())) {
9101 std::string SelectorName
= (Twine("objectIn") + UpperKey
+ "AtIndex").str();
9102 IdentifierInfo
*SelectorId
= &Context
.Idents
.get(SelectorName
);
9103 if (KnownSelectors
.insert(Selectors
.getUnarySelector(SelectorId
)).second
) {
9104 if (ReturnType
.isNull()) {
9105 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9106 Builder
.AddTextChunk("id");
9107 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9110 Builder
.AddTypedTextChunk(Allocator
.CopyString(SelectorName
+ ":"));
9111 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9112 Builder
.AddTextChunk("NSUInteger");
9113 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9114 Builder
.AddTextChunk("index");
9115 Results
.AddResult(Result(Builder
.TakeString(), IndexedGetterPriority
,
9116 CXCursor_ObjCInstanceMethodDecl
));
9120 // Add -(NSArray *)keyAtIndexes:(NSIndexSet *)indexes
9121 if (IsInstanceMethod
&&
9122 (ReturnType
.isNull() ||
9123 (ReturnType
->isObjCObjectPointerType() &&
9124 ReturnType
->castAs
<ObjCObjectPointerType
>()->getInterfaceDecl() &&
9125 ReturnType
->castAs
<ObjCObjectPointerType
>()
9126 ->getInterfaceDecl()
9127 ->getName() == "NSArray"))) {
9128 std::string SelectorName
= (Twine(Property
->getName()) + "AtIndexes").str();
9129 IdentifierInfo
*SelectorId
= &Context
.Idents
.get(SelectorName
);
9130 if (KnownSelectors
.insert(Selectors
.getUnarySelector(SelectorId
)).second
) {
9131 if (ReturnType
.isNull()) {
9132 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9133 Builder
.AddTextChunk("NSArray *");
9134 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9137 Builder
.AddTypedTextChunk(Allocator
.CopyString(SelectorName
+ ":"));
9138 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9139 Builder
.AddTextChunk("NSIndexSet *");
9140 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9141 Builder
.AddTextChunk("indexes");
9142 Results
.AddResult(Result(Builder
.TakeString(), IndexedGetterPriority
,
9143 CXCursor_ObjCInstanceMethodDecl
));
9147 // Add -(void)getKey:(type **)buffer range:(NSRange)inRange
9148 if (IsInstanceMethod
&& ReturnTypeMatchesVoid
) {
9149 std::string SelectorName
= (Twine("get") + UpperKey
).str();
9150 IdentifierInfo
*SelectorIds
[2] = {&Context
.Idents
.get(SelectorName
),
9151 &Context
.Idents
.get("range")};
9153 if (KnownSelectors
.insert(Selectors
.getSelector(2, SelectorIds
)).second
) {
9154 if (ReturnType
.isNull()) {
9155 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9156 Builder
.AddTextChunk("void");
9157 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9160 Builder
.AddTypedTextChunk(Allocator
.CopyString(SelectorName
+ ":"));
9161 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9162 Builder
.AddPlaceholderChunk("object-type");
9163 Builder
.AddTextChunk(" **");
9164 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9165 Builder
.AddTextChunk("buffer");
9166 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
9167 Builder
.AddTypedTextChunk("range:");
9168 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9169 Builder
.AddTextChunk("NSRange");
9170 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9171 Builder
.AddTextChunk("inRange");
9172 Results
.AddResult(Result(Builder
.TakeString(), IndexedGetterPriority
,
9173 CXCursor_ObjCInstanceMethodDecl
));
9177 // Mutable indexed accessors
9179 // - (void)insertObject:(type *)object inKeyAtIndex:(NSUInteger)index
9180 if (IsInstanceMethod
&& ReturnTypeMatchesVoid
) {
9181 std::string SelectorName
= (Twine("in") + UpperKey
+ "AtIndex").str();
9182 IdentifierInfo
*SelectorIds
[2] = {&Context
.Idents
.get("insertObject"),
9183 &Context
.Idents
.get(SelectorName
)};
9185 if (KnownSelectors
.insert(Selectors
.getSelector(2, SelectorIds
)).second
) {
9186 if (ReturnType
.isNull()) {
9187 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9188 Builder
.AddTextChunk("void");
9189 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9192 Builder
.AddTypedTextChunk("insertObject:");
9193 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9194 Builder
.AddPlaceholderChunk("object-type");
9195 Builder
.AddTextChunk(" *");
9196 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9197 Builder
.AddTextChunk("object");
9198 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
9199 Builder
.AddTypedTextChunk(Allocator
.CopyString(SelectorName
+ ":"));
9200 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9201 Builder
.AddPlaceholderChunk("NSUInteger");
9202 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9203 Builder
.AddTextChunk("index");
9204 Results
.AddResult(Result(Builder
.TakeString(), IndexedSetterPriority
,
9205 CXCursor_ObjCInstanceMethodDecl
));
9209 // - (void)insertKey:(NSArray *)array atIndexes:(NSIndexSet *)indexes
9210 if (IsInstanceMethod
&& ReturnTypeMatchesVoid
) {
9211 std::string SelectorName
= (Twine("insert") + UpperKey
).str();
9212 IdentifierInfo
*SelectorIds
[2] = {&Context
.Idents
.get(SelectorName
),
9213 &Context
.Idents
.get("atIndexes")};
9215 if (KnownSelectors
.insert(Selectors
.getSelector(2, SelectorIds
)).second
) {
9216 if (ReturnType
.isNull()) {
9217 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9218 Builder
.AddTextChunk("void");
9219 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9222 Builder
.AddTypedTextChunk(Allocator
.CopyString(SelectorName
+ ":"));
9223 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9224 Builder
.AddTextChunk("NSArray *");
9225 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9226 Builder
.AddTextChunk("array");
9227 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
9228 Builder
.AddTypedTextChunk("atIndexes:");
9229 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9230 Builder
.AddPlaceholderChunk("NSIndexSet *");
9231 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9232 Builder
.AddTextChunk("indexes");
9233 Results
.AddResult(Result(Builder
.TakeString(), IndexedSetterPriority
,
9234 CXCursor_ObjCInstanceMethodDecl
));
9238 // -(void)removeObjectFromKeyAtIndex:(NSUInteger)index
9239 if (IsInstanceMethod
&& ReturnTypeMatchesVoid
) {
9240 std::string SelectorName
=
9241 (Twine("removeObjectFrom") + UpperKey
+ "AtIndex").str();
9242 IdentifierInfo
*SelectorId
= &Context
.Idents
.get(SelectorName
);
9243 if (KnownSelectors
.insert(Selectors
.getUnarySelector(SelectorId
)).second
) {
9244 if (ReturnType
.isNull()) {
9245 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9246 Builder
.AddTextChunk("void");
9247 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9250 Builder
.AddTypedTextChunk(Allocator
.CopyString(SelectorName
+ ":"));
9251 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9252 Builder
.AddTextChunk("NSUInteger");
9253 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9254 Builder
.AddTextChunk("index");
9255 Results
.AddResult(Result(Builder
.TakeString(), IndexedSetterPriority
,
9256 CXCursor_ObjCInstanceMethodDecl
));
9260 // -(void)removeKeyAtIndexes:(NSIndexSet *)indexes
9261 if (IsInstanceMethod
&& ReturnTypeMatchesVoid
) {
9262 std::string SelectorName
= (Twine("remove") + UpperKey
+ "AtIndexes").str();
9263 IdentifierInfo
*SelectorId
= &Context
.Idents
.get(SelectorName
);
9264 if (KnownSelectors
.insert(Selectors
.getUnarySelector(SelectorId
)).second
) {
9265 if (ReturnType
.isNull()) {
9266 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9267 Builder
.AddTextChunk("void");
9268 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9271 Builder
.AddTypedTextChunk(Allocator
.CopyString(SelectorName
+ ":"));
9272 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9273 Builder
.AddTextChunk("NSIndexSet *");
9274 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9275 Builder
.AddTextChunk("indexes");
9276 Results
.AddResult(Result(Builder
.TakeString(), IndexedSetterPriority
,
9277 CXCursor_ObjCInstanceMethodDecl
));
9281 // - (void)replaceObjectInKeyAtIndex:(NSUInteger)index withObject:(id)object
9282 if (IsInstanceMethod
&& ReturnTypeMatchesVoid
) {
9283 std::string SelectorName
=
9284 (Twine("replaceObjectIn") + UpperKey
+ "AtIndex").str();
9285 IdentifierInfo
*SelectorIds
[2] = {&Context
.Idents
.get(SelectorName
),
9286 &Context
.Idents
.get("withObject")};
9288 if (KnownSelectors
.insert(Selectors
.getSelector(2, SelectorIds
)).second
) {
9289 if (ReturnType
.isNull()) {
9290 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9291 Builder
.AddTextChunk("void");
9292 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9295 Builder
.AddTypedTextChunk(Allocator
.CopyString(SelectorName
+ ":"));
9296 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9297 Builder
.AddPlaceholderChunk("NSUInteger");
9298 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9299 Builder
.AddTextChunk("index");
9300 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
9301 Builder
.AddTypedTextChunk("withObject:");
9302 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9303 Builder
.AddTextChunk("id");
9304 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9305 Builder
.AddTextChunk("object");
9306 Results
.AddResult(Result(Builder
.TakeString(), IndexedSetterPriority
,
9307 CXCursor_ObjCInstanceMethodDecl
));
9311 // - (void)replaceKeyAtIndexes:(NSIndexSet *)indexes withKey:(NSArray *)array
9312 if (IsInstanceMethod
&& ReturnTypeMatchesVoid
) {
9313 std::string SelectorName1
=
9314 (Twine("replace") + UpperKey
+ "AtIndexes").str();
9315 std::string SelectorName2
= (Twine("with") + UpperKey
).str();
9316 IdentifierInfo
*SelectorIds
[2] = {&Context
.Idents
.get(SelectorName1
),
9317 &Context
.Idents
.get(SelectorName2
)};
9319 if (KnownSelectors
.insert(Selectors
.getSelector(2, SelectorIds
)).second
) {
9320 if (ReturnType
.isNull()) {
9321 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9322 Builder
.AddTextChunk("void");
9323 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9326 Builder
.AddTypedTextChunk(Allocator
.CopyString(SelectorName1
+ ":"));
9327 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9328 Builder
.AddPlaceholderChunk("NSIndexSet *");
9329 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9330 Builder
.AddTextChunk("indexes");
9331 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
9332 Builder
.AddTypedTextChunk(Allocator
.CopyString(SelectorName2
+ ":"));
9333 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9334 Builder
.AddTextChunk("NSArray *");
9335 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9336 Builder
.AddTextChunk("array");
9337 Results
.AddResult(Result(Builder
.TakeString(), IndexedSetterPriority
,
9338 CXCursor_ObjCInstanceMethodDecl
));
9342 // Unordered getters
9343 // - (NSEnumerator *)enumeratorOfKey
9344 if (IsInstanceMethod
&&
9345 (ReturnType
.isNull() ||
9346 (ReturnType
->isObjCObjectPointerType() &&
9347 ReturnType
->castAs
<ObjCObjectPointerType
>()->getInterfaceDecl() &&
9348 ReturnType
->castAs
<ObjCObjectPointerType
>()
9349 ->getInterfaceDecl()
9350 ->getName() == "NSEnumerator"))) {
9351 std::string SelectorName
= (Twine("enumeratorOf") + UpperKey
).str();
9352 IdentifierInfo
*SelectorId
= &Context
.Idents
.get(SelectorName
);
9353 if (KnownSelectors
.insert(Selectors
.getNullarySelector(SelectorId
))
9355 if (ReturnType
.isNull()) {
9356 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9357 Builder
.AddTextChunk("NSEnumerator *");
9358 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9361 Builder
.AddTypedTextChunk(Allocator
.CopyString(SelectorName
));
9362 Results
.AddResult(Result(Builder
.TakeString(), UnorderedGetterPriority
,
9363 CXCursor_ObjCInstanceMethodDecl
));
9367 // - (type *)memberOfKey:(type *)object
9368 if (IsInstanceMethod
&&
9369 (ReturnType
.isNull() || ReturnType
->isObjCObjectPointerType())) {
9370 std::string SelectorName
= (Twine("memberOf") + UpperKey
).str();
9371 IdentifierInfo
*SelectorId
= &Context
.Idents
.get(SelectorName
);
9372 if (KnownSelectors
.insert(Selectors
.getUnarySelector(SelectorId
)).second
) {
9373 if (ReturnType
.isNull()) {
9374 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9375 Builder
.AddPlaceholderChunk("object-type");
9376 Builder
.AddTextChunk(" *");
9377 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9380 Builder
.AddTypedTextChunk(Allocator
.CopyString(SelectorName
+ ":"));
9381 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9382 if (ReturnType
.isNull()) {
9383 Builder
.AddPlaceholderChunk("object-type");
9384 Builder
.AddTextChunk(" *");
9386 Builder
.AddTextChunk(GetCompletionTypeString(
9387 ReturnType
, Context
, Policy
, Builder
.getAllocator()));
9389 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9390 Builder
.AddTextChunk("object");
9391 Results
.AddResult(Result(Builder
.TakeString(), UnorderedGetterPriority
,
9392 CXCursor_ObjCInstanceMethodDecl
));
9396 // Mutable unordered accessors
9397 // - (void)addKeyObject:(type *)object
9398 if (IsInstanceMethod
&& ReturnTypeMatchesVoid
) {
9399 std::string SelectorName
=
9400 (Twine("add") + UpperKey
+ Twine("Object")).str();
9401 IdentifierInfo
*SelectorId
= &Context
.Idents
.get(SelectorName
);
9402 if (KnownSelectors
.insert(Selectors
.getUnarySelector(SelectorId
)).second
) {
9403 if (ReturnType
.isNull()) {
9404 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9405 Builder
.AddTextChunk("void");
9406 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9409 Builder
.AddTypedTextChunk(Allocator
.CopyString(SelectorName
+ ":"));
9410 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9411 Builder
.AddPlaceholderChunk("object-type");
9412 Builder
.AddTextChunk(" *");
9413 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9414 Builder
.AddTextChunk("object");
9415 Results
.AddResult(Result(Builder
.TakeString(), UnorderedSetterPriority
,
9416 CXCursor_ObjCInstanceMethodDecl
));
9420 // - (void)addKey:(NSSet *)objects
9421 if (IsInstanceMethod
&& ReturnTypeMatchesVoid
) {
9422 std::string SelectorName
= (Twine("add") + UpperKey
).str();
9423 IdentifierInfo
*SelectorId
= &Context
.Idents
.get(SelectorName
);
9424 if (KnownSelectors
.insert(Selectors
.getUnarySelector(SelectorId
)).second
) {
9425 if (ReturnType
.isNull()) {
9426 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9427 Builder
.AddTextChunk("void");
9428 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9431 Builder
.AddTypedTextChunk(Allocator
.CopyString(SelectorName
+ ":"));
9432 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9433 Builder
.AddTextChunk("NSSet *");
9434 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9435 Builder
.AddTextChunk("objects");
9436 Results
.AddResult(Result(Builder
.TakeString(), UnorderedSetterPriority
,
9437 CXCursor_ObjCInstanceMethodDecl
));
9441 // - (void)removeKeyObject:(type *)object
9442 if (IsInstanceMethod
&& ReturnTypeMatchesVoid
) {
9443 std::string SelectorName
=
9444 (Twine("remove") + UpperKey
+ Twine("Object")).str();
9445 IdentifierInfo
*SelectorId
= &Context
.Idents
.get(SelectorName
);
9446 if (KnownSelectors
.insert(Selectors
.getUnarySelector(SelectorId
)).second
) {
9447 if (ReturnType
.isNull()) {
9448 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9449 Builder
.AddTextChunk("void");
9450 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9453 Builder
.AddTypedTextChunk(Allocator
.CopyString(SelectorName
+ ":"));
9454 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9455 Builder
.AddPlaceholderChunk("object-type");
9456 Builder
.AddTextChunk(" *");
9457 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9458 Builder
.AddTextChunk("object");
9459 Results
.AddResult(Result(Builder
.TakeString(), UnorderedSetterPriority
,
9460 CXCursor_ObjCInstanceMethodDecl
));
9464 // - (void)removeKey:(NSSet *)objects
9465 if (IsInstanceMethod
&& ReturnTypeMatchesVoid
) {
9466 std::string SelectorName
= (Twine("remove") + UpperKey
).str();
9467 IdentifierInfo
*SelectorId
= &Context
.Idents
.get(SelectorName
);
9468 if (KnownSelectors
.insert(Selectors
.getUnarySelector(SelectorId
)).second
) {
9469 if (ReturnType
.isNull()) {
9470 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9471 Builder
.AddTextChunk("void");
9472 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9475 Builder
.AddTypedTextChunk(Allocator
.CopyString(SelectorName
+ ":"));
9476 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9477 Builder
.AddTextChunk("NSSet *");
9478 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9479 Builder
.AddTextChunk("objects");
9480 Results
.AddResult(Result(Builder
.TakeString(), UnorderedSetterPriority
,
9481 CXCursor_ObjCInstanceMethodDecl
));
9485 // - (void)intersectKey:(NSSet *)objects
9486 if (IsInstanceMethod
&& ReturnTypeMatchesVoid
) {
9487 std::string SelectorName
= (Twine("intersect") + UpperKey
).str();
9488 IdentifierInfo
*SelectorId
= &Context
.Idents
.get(SelectorName
);
9489 if (KnownSelectors
.insert(Selectors
.getUnarySelector(SelectorId
)).second
) {
9490 if (ReturnType
.isNull()) {
9491 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9492 Builder
.AddTextChunk("void");
9493 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9496 Builder
.AddTypedTextChunk(Allocator
.CopyString(SelectorName
+ ":"));
9497 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9498 Builder
.AddTextChunk("NSSet *");
9499 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9500 Builder
.AddTextChunk("objects");
9501 Results
.AddResult(Result(Builder
.TakeString(), UnorderedSetterPriority
,
9502 CXCursor_ObjCInstanceMethodDecl
));
9506 // Key-Value Observing
9507 // + (NSSet *)keyPathsForValuesAffectingKey
9508 if (!IsInstanceMethod
&&
9509 (ReturnType
.isNull() ||
9510 (ReturnType
->isObjCObjectPointerType() &&
9511 ReturnType
->castAs
<ObjCObjectPointerType
>()->getInterfaceDecl() &&
9512 ReturnType
->castAs
<ObjCObjectPointerType
>()
9513 ->getInterfaceDecl()
9514 ->getName() == "NSSet"))) {
9515 std::string SelectorName
=
9516 (Twine("keyPathsForValuesAffecting") + UpperKey
).str();
9517 IdentifierInfo
*SelectorId
= &Context
.Idents
.get(SelectorName
);
9518 if (KnownSelectors
.insert(Selectors
.getNullarySelector(SelectorId
))
9520 if (ReturnType
.isNull()) {
9521 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9522 Builder
.AddTextChunk("NSSet<NSString *> *");
9523 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9526 Builder
.AddTypedTextChunk(Allocator
.CopyString(SelectorName
));
9527 Results
.AddResult(Result(Builder
.TakeString(), CCP_CodePattern
,
9528 CXCursor_ObjCClassMethodDecl
));
9532 // + (BOOL)automaticallyNotifiesObserversForKey
9533 if (!IsInstanceMethod
&&
9534 (ReturnType
.isNull() || ReturnType
->isIntegerType() ||
9535 ReturnType
->isBooleanType())) {
9536 std::string SelectorName
=
9537 (Twine("automaticallyNotifiesObserversOf") + UpperKey
).str();
9538 IdentifierInfo
*SelectorId
= &Context
.Idents
.get(SelectorName
);
9539 if (KnownSelectors
.insert(Selectors
.getNullarySelector(SelectorId
))
9541 if (ReturnType
.isNull()) {
9542 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9543 Builder
.AddTextChunk("BOOL");
9544 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9547 Builder
.AddTypedTextChunk(Allocator
.CopyString(SelectorName
));
9548 Results
.AddResult(Result(Builder
.TakeString(), CCP_CodePattern
,
9549 CXCursor_ObjCClassMethodDecl
));
9554 void Sema::CodeCompleteObjCMethodDecl(Scope
*S
,
9555 std::optional
<bool> IsInstanceMethod
,
9556 ParsedType ReturnTy
) {
9557 // Determine the return type of the method we're declaring, if
9559 QualType ReturnType
= GetTypeFromParser(ReturnTy
);
9560 Decl
*IDecl
= nullptr;
9561 if (CurContext
->isObjCContainer()) {
9562 ObjCContainerDecl
*OCD
= dyn_cast
<ObjCContainerDecl
>(CurContext
);
9565 // Determine where we should start searching for methods.
9566 ObjCContainerDecl
*SearchDecl
= nullptr;
9567 bool IsInImplementation
= false;
9568 if (Decl
*D
= IDecl
) {
9569 if (ObjCImplementationDecl
*Impl
= dyn_cast
<ObjCImplementationDecl
>(D
)) {
9570 SearchDecl
= Impl
->getClassInterface();
9571 IsInImplementation
= true;
9572 } else if (ObjCCategoryImplDecl
*CatImpl
=
9573 dyn_cast
<ObjCCategoryImplDecl
>(D
)) {
9574 SearchDecl
= CatImpl
->getCategoryDecl();
9575 IsInImplementation
= true;
9577 SearchDecl
= dyn_cast
<ObjCContainerDecl
>(D
);
9580 if (!SearchDecl
&& S
) {
9581 if (DeclContext
*DC
= S
->getEntity())
9582 SearchDecl
= dyn_cast
<ObjCContainerDecl
>(DC
);
9586 HandleCodeCompleteResults(this, CodeCompleter
,
9587 CodeCompletionContext::CCC_Other
, nullptr, 0);
9591 // Find all of the methods that we could declare/implement here.
9592 KnownMethodsMap KnownMethods
;
9593 FindImplementableMethods(Context
, SearchDecl
, IsInstanceMethod
, ReturnType
,
9596 // Add declarations or definitions for each of the known methods.
9597 typedef CodeCompletionResult Result
;
9598 ResultBuilder
Results(*this, CodeCompleter
->getAllocator(),
9599 CodeCompleter
->getCodeCompletionTUInfo(),
9600 CodeCompletionContext::CCC_Other
);
9601 Results
.EnterNewScope();
9602 PrintingPolicy Policy
= getCompletionPrintingPolicy(*this);
9603 for (KnownMethodsMap::iterator M
= KnownMethods
.begin(),
9604 MEnd
= KnownMethods
.end();
9606 ObjCMethodDecl
*Method
= M
->second
.getPointer();
9607 CodeCompletionBuilder
Builder(Results
.getAllocator(),
9608 Results
.getCodeCompletionTUInfo());
9610 // Add the '-'/'+' prefix if it wasn't provided yet.
9611 if (!IsInstanceMethod
) {
9612 Builder
.AddTextChunk(Method
->isInstanceMethod() ? "-" : "+");
9613 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
9616 // If the result type was not already provided, add it to the
9617 // pattern as (type).
9618 if (ReturnType
.isNull()) {
9619 QualType ResTy
= Method
->getSendResultType().stripObjCKindOfType(Context
);
9620 AttributedType::stripOuterNullability(ResTy
);
9621 AddObjCPassingTypeChunk(ResTy
, Method
->getObjCDeclQualifier(), Context
,
9625 Selector Sel
= Method
->getSelector();
9627 if (Sel
.isUnarySelector()) {
9628 // Unary selectors have no arguments.
9629 Builder
.AddTypedTextChunk(
9630 Builder
.getAllocator().CopyString(Sel
.getNameForSlot(0)));
9632 // Add all parameters to the pattern.
9634 for (ObjCMethodDecl::param_iterator P
= Method
->param_begin(),
9635 PEnd
= Method
->param_end();
9636 P
!= PEnd
; (void)++P
, ++I
) {
9637 // Add the part of the selector name.
9639 Builder
.AddTypedTextChunk(
9640 Builder
.getAllocator().CopyString(Sel
.getNameForSlot(I
) + ":"));
9641 else if (I
< Sel
.getNumArgs()) {
9642 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
9643 Builder
.AddTypedTextChunk(
9644 Builder
.getAllocator().CopyString(Sel
.getNameForSlot(I
) + ":"));
9648 // Add the parameter type.
9650 if ((*P
)->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability
)
9651 ParamType
= (*P
)->getType();
9653 ParamType
= (*P
)->getOriginalType();
9654 ParamType
= ParamType
.substObjCTypeArgs(
9655 Context
, {}, ObjCSubstitutionContext::Parameter
);
9656 AttributedType::stripOuterNullability(ParamType
);
9657 AddObjCPassingTypeChunk(ParamType
, (*P
)->getObjCDeclQualifier(),
9658 Context
, Policy
, Builder
);
9660 if (IdentifierInfo
*Id
= (*P
)->getIdentifier())
9661 Builder
.AddTextChunk(
9662 Builder
.getAllocator().CopyString(Id
->getName()));
9666 if (Method
->isVariadic()) {
9667 if (Method
->param_size() > 0)
9668 Builder
.AddChunk(CodeCompletionString::CK_Comma
);
9669 Builder
.AddTextChunk("...");
9672 if (IsInImplementation
&& Results
.includeCodePatterns()) {
9673 // We will be defining the method here, so add a compound statement.
9674 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
9675 Builder
.AddChunk(CodeCompletionString::CK_LeftBrace
);
9676 Builder
.AddChunk(CodeCompletionString::CK_VerticalSpace
);
9677 if (!Method
->getReturnType()->isVoidType()) {
9678 // If the result type is not void, add a return clause.
9679 Builder
.AddTextChunk("return");
9680 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
9681 Builder
.AddPlaceholderChunk("expression");
9682 Builder
.AddChunk(CodeCompletionString::CK_SemiColon
);
9684 Builder
.AddPlaceholderChunk("statements");
9686 Builder
.AddChunk(CodeCompletionString::CK_VerticalSpace
);
9687 Builder
.AddChunk(CodeCompletionString::CK_RightBrace
);
9690 unsigned Priority
= CCP_CodePattern
;
9691 auto R
= Result(Builder
.TakeString(), Method
, Priority
);
9692 if (!M
->second
.getInt())
9694 Results
.AddResult(std::move(R
));
9697 // Add Key-Value-Coding and Key-Value-Observing accessor methods for all of
9698 // the properties in this class and its categories.
9699 if (Context
.getLangOpts().ObjC
) {
9700 SmallVector
<ObjCContainerDecl
*, 4> Containers
;
9701 Containers
.push_back(SearchDecl
);
9703 VisitedSelectorSet KnownSelectors
;
9704 for (KnownMethodsMap::iterator M
= KnownMethods
.begin(),
9705 MEnd
= KnownMethods
.end();
9707 KnownSelectors
.insert(M
->first
);
9709 ObjCInterfaceDecl
*IFace
= dyn_cast
<ObjCInterfaceDecl
>(SearchDecl
);
9711 if (ObjCCategoryDecl
*Category
= dyn_cast
<ObjCCategoryDecl
>(SearchDecl
))
9712 IFace
= Category
->getClassInterface();
9715 llvm::append_range(Containers
, IFace
->visible_categories());
9717 if (IsInstanceMethod
) {
9718 for (unsigned I
= 0, N
= Containers
.size(); I
!= N
; ++I
)
9719 for (auto *P
: Containers
[I
]->instance_properties())
9720 AddObjCKeyValueCompletions(P
, *IsInstanceMethod
, ReturnType
, Context
,
9721 KnownSelectors
, Results
);
9725 Results
.ExitScope();
9727 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
9728 Results
.data(), Results
.size());
9731 void Sema::CodeCompleteObjCMethodDeclSelector(
9732 Scope
*S
, bool IsInstanceMethod
, bool AtParameterName
, ParsedType ReturnTy
,
9733 ArrayRef
<IdentifierInfo
*> SelIdents
) {
9734 // If we have an external source, load the entire class method
9735 // pool from the AST file.
9736 if (ExternalSource
) {
9737 for (uint32_t I
= 0, N
= ExternalSource
->GetNumExternalSelectors(); I
!= N
;
9739 Selector Sel
= ExternalSource
->GetExternalSelector(I
);
9740 if (Sel
.isNull() || MethodPool
.count(Sel
))
9743 ReadMethodPool(Sel
);
9747 // Build the set of methods we can see.
9748 typedef CodeCompletionResult Result
;
9749 ResultBuilder
Results(*this, CodeCompleter
->getAllocator(),
9750 CodeCompleter
->getCodeCompletionTUInfo(),
9751 CodeCompletionContext::CCC_Other
);
9754 Results
.setPreferredType(GetTypeFromParser(ReturnTy
).getNonReferenceType());
9756 Results
.EnterNewScope();
9757 for (GlobalMethodPool::iterator M
= MethodPool
.begin(),
9758 MEnd
= MethodPool
.end();
9760 for (ObjCMethodList
*MethList
= IsInstanceMethod
? &M
->second
.first
9761 : &M
->second
.second
;
9762 MethList
&& MethList
->getMethod(); MethList
= MethList
->getNext()) {
9763 if (!isAcceptableObjCMethod(MethList
->getMethod(), MK_Any
, SelIdents
))
9766 if (AtParameterName
) {
9767 // Suggest parameter names we've seen before.
9768 unsigned NumSelIdents
= SelIdents
.size();
9770 NumSelIdents
<= MethList
->getMethod()->param_size()) {
9771 ParmVarDecl
*Param
=
9772 MethList
->getMethod()->parameters()[NumSelIdents
- 1];
9773 if (Param
->getIdentifier()) {
9774 CodeCompletionBuilder
Builder(Results
.getAllocator(),
9775 Results
.getCodeCompletionTUInfo());
9776 Builder
.AddTypedTextChunk(Builder
.getAllocator().CopyString(
9777 Param
->getIdentifier()->getName()));
9778 Results
.AddResult(Builder
.TakeString());
9785 Result
R(MethList
->getMethod(),
9786 Results
.getBasePriority(MethList
->getMethod()), nullptr);
9787 R
.StartParameter
= SelIdents
.size();
9788 R
.AllParametersAreInformative
= false;
9789 R
.DeclaringEntity
= true;
9790 Results
.MaybeAddResult(R
, CurContext
);
9794 Results
.ExitScope();
9796 if (!AtParameterName
&& !SelIdents
.empty() &&
9797 SelIdents
.front()->getName().startswith("init")) {
9798 for (const auto &M
: PP
.macros()) {
9799 if (M
.first
->getName() != "NS_DESIGNATED_INITIALIZER")
9801 Results
.EnterNewScope();
9802 CodeCompletionBuilder
Builder(Results
.getAllocator(),
9803 Results
.getCodeCompletionTUInfo());
9804 Builder
.AddTypedTextChunk(
9805 Builder
.getAllocator().CopyString(M
.first
->getName()));
9806 Results
.AddResult(CodeCompletionResult(Builder
.TakeString(), CCP_Macro
,
9807 CXCursor_MacroDefinition
));
9808 Results
.ExitScope();
9812 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
9813 Results
.data(), Results
.size());
9816 void Sema::CodeCompletePreprocessorDirective(bool InConditional
) {
9817 ResultBuilder
Results(*this, CodeCompleter
->getAllocator(),
9818 CodeCompleter
->getCodeCompletionTUInfo(),
9819 CodeCompletionContext::CCC_PreprocessorDirective
);
9820 Results
.EnterNewScope();
9823 CodeCompletionBuilder
Builder(Results
.getAllocator(),
9824 Results
.getCodeCompletionTUInfo());
9825 Builder
.AddTypedTextChunk("if");
9826 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
9827 Builder
.AddPlaceholderChunk("condition");
9828 Results
.AddResult(Builder
.TakeString());
9831 Builder
.AddTypedTextChunk("ifdef");
9832 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
9833 Builder
.AddPlaceholderChunk("macro");
9834 Results
.AddResult(Builder
.TakeString());
9837 Builder
.AddTypedTextChunk("ifndef");
9838 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
9839 Builder
.AddPlaceholderChunk("macro");
9840 Results
.AddResult(Builder
.TakeString());
9842 if (InConditional
) {
9843 // #elif <condition>
9844 Builder
.AddTypedTextChunk("elif");
9845 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
9846 Builder
.AddPlaceholderChunk("condition");
9847 Results
.AddResult(Builder
.TakeString());
9850 Builder
.AddTypedTextChunk("elifdef");
9851 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
9852 Builder
.AddPlaceholderChunk("macro");
9853 Results
.AddResult(Builder
.TakeString());
9855 // #elifndef <macro>
9856 Builder
.AddTypedTextChunk("elifndef");
9857 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
9858 Builder
.AddPlaceholderChunk("macro");
9859 Results
.AddResult(Builder
.TakeString());
9862 Builder
.AddTypedTextChunk("else");
9863 Results
.AddResult(Builder
.TakeString());
9866 Builder
.AddTypedTextChunk("endif");
9867 Results
.AddResult(Builder
.TakeString());
9870 // #include "header"
9871 Builder
.AddTypedTextChunk("include");
9872 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
9873 Builder
.AddTextChunk("\"");
9874 Builder
.AddPlaceholderChunk("header");
9875 Builder
.AddTextChunk("\"");
9876 Results
.AddResult(Builder
.TakeString());
9878 // #include <header>
9879 Builder
.AddTypedTextChunk("include");
9880 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
9881 Builder
.AddTextChunk("<");
9882 Builder
.AddPlaceholderChunk("header");
9883 Builder
.AddTextChunk(">");
9884 Results
.AddResult(Builder
.TakeString());
9887 Builder
.AddTypedTextChunk("define");
9888 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
9889 Builder
.AddPlaceholderChunk("macro");
9890 Results
.AddResult(Builder
.TakeString());
9892 // #define <macro>(<args>)
9893 Builder
.AddTypedTextChunk("define");
9894 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
9895 Builder
.AddPlaceholderChunk("macro");
9896 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9897 Builder
.AddPlaceholderChunk("args");
9898 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9899 Results
.AddResult(Builder
.TakeString());
9902 Builder
.AddTypedTextChunk("undef");
9903 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
9904 Builder
.AddPlaceholderChunk("macro");
9905 Results
.AddResult(Builder
.TakeString());
9908 Builder
.AddTypedTextChunk("line");
9909 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
9910 Builder
.AddPlaceholderChunk("number");
9911 Results
.AddResult(Builder
.TakeString());
9913 // #line <number> "filename"
9914 Builder
.AddTypedTextChunk("line");
9915 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
9916 Builder
.AddPlaceholderChunk("number");
9917 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
9918 Builder
.AddTextChunk("\"");
9919 Builder
.AddPlaceholderChunk("filename");
9920 Builder
.AddTextChunk("\"");
9921 Results
.AddResult(Builder
.TakeString());
9924 Builder
.AddTypedTextChunk("error");
9925 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
9926 Builder
.AddPlaceholderChunk("message");
9927 Results
.AddResult(Builder
.TakeString());
9929 // #pragma <arguments>
9930 Builder
.AddTypedTextChunk("pragma");
9931 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
9932 Builder
.AddPlaceholderChunk("arguments");
9933 Results
.AddResult(Builder
.TakeString());
9935 if (getLangOpts().ObjC
) {
9937 Builder
.AddTypedTextChunk("import");
9938 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
9939 Builder
.AddTextChunk("\"");
9940 Builder
.AddPlaceholderChunk("header");
9941 Builder
.AddTextChunk("\"");
9942 Results
.AddResult(Builder
.TakeString());
9945 Builder
.AddTypedTextChunk("import");
9946 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
9947 Builder
.AddTextChunk("<");
9948 Builder
.AddPlaceholderChunk("header");
9949 Builder
.AddTextChunk(">");
9950 Results
.AddResult(Builder
.TakeString());
9953 // #include_next "header"
9954 Builder
.AddTypedTextChunk("include_next");
9955 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
9956 Builder
.AddTextChunk("\"");
9957 Builder
.AddPlaceholderChunk("header");
9958 Builder
.AddTextChunk("\"");
9959 Results
.AddResult(Builder
.TakeString());
9961 // #include_next <header>
9962 Builder
.AddTypedTextChunk("include_next");
9963 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
9964 Builder
.AddTextChunk("<");
9965 Builder
.AddPlaceholderChunk("header");
9966 Builder
.AddTextChunk(">");
9967 Results
.AddResult(Builder
.TakeString());
9969 // #warning <message>
9970 Builder
.AddTypedTextChunk("warning");
9971 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
9972 Builder
.AddPlaceholderChunk("message");
9973 Results
.AddResult(Builder
.TakeString());
9975 // Note: #ident and #sccs are such crazy anachronisms that we don't provide
9976 // completions for them. And __include_macros is a Clang-internal extension
9977 // that we don't want to encourage anyone to use.
9979 // FIXME: we don't support #assert or #unassert, so don't suggest them.
9980 Results
.ExitScope();
9982 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
9983 Results
.data(), Results
.size());
9986 void Sema::CodeCompleteInPreprocessorConditionalExclusion(Scope
*S
) {
9987 CodeCompleteOrdinaryName(S
, S
->getFnParent() ? Sema::PCC_RecoveryInFunction
9988 : Sema::PCC_Namespace
);
9991 void Sema::CodeCompletePreprocessorMacroName(bool IsDefinition
) {
9992 ResultBuilder
Results(*this, CodeCompleter
->getAllocator(),
9993 CodeCompleter
->getCodeCompletionTUInfo(),
9994 IsDefinition
? CodeCompletionContext::CCC_MacroName
9995 : CodeCompletionContext::CCC_MacroNameUse
);
9996 if (!IsDefinition
&& CodeCompleter
->includeMacros()) {
9997 // Add just the names of macros, not their arguments.
9998 CodeCompletionBuilder
Builder(Results
.getAllocator(),
9999 Results
.getCodeCompletionTUInfo());
10000 Results
.EnterNewScope();
10001 for (Preprocessor::macro_iterator M
= PP
.macro_begin(),
10002 MEnd
= PP
.macro_end();
10004 Builder
.AddTypedTextChunk(
10005 Builder
.getAllocator().CopyString(M
->first
->getName()));
10006 Results
.AddResult(CodeCompletionResult(
10007 Builder
.TakeString(), CCP_CodePattern
, CXCursor_MacroDefinition
));
10009 Results
.ExitScope();
10010 } else if (IsDefinition
) {
10011 // FIXME: Can we detect when the user just wrote an include guard above?
10014 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
10015 Results
.data(), Results
.size());
10018 void Sema::CodeCompletePreprocessorExpression() {
10019 ResultBuilder
Results(*this, CodeCompleter
->getAllocator(),
10020 CodeCompleter
->getCodeCompletionTUInfo(),
10021 CodeCompletionContext::CCC_PreprocessorExpression
);
10023 if (CodeCompleter
->includeMacros())
10024 AddMacroResults(PP
, Results
, CodeCompleter
->loadExternal(), true);
10026 // defined (<macro>)
10027 Results
.EnterNewScope();
10028 CodeCompletionBuilder
Builder(Results
.getAllocator(),
10029 Results
.getCodeCompletionTUInfo());
10030 Builder
.AddTypedTextChunk("defined");
10031 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
10032 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
10033 Builder
.AddPlaceholderChunk("macro");
10034 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
10035 Results
.AddResult(Builder
.TakeString());
10036 Results
.ExitScope();
10038 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
10039 Results
.data(), Results
.size());
10042 void Sema::CodeCompletePreprocessorMacroArgument(Scope
*S
,
10043 IdentifierInfo
*Macro
,
10044 MacroInfo
*MacroInfo
,
10045 unsigned Argument
) {
10046 // FIXME: In the future, we could provide "overload" results, much like we
10047 // do for function calls.
10049 // Now just ignore this. There will be another code-completion callback
10050 // for the expanded tokens.
10053 // This handles completion inside an #include filename, e.g. #include <foo/ba
10054 // We look for the directory "foo" under each directory on the include path,
10055 // list its files, and reassemble the appropriate #include.
10056 void Sema::CodeCompleteIncludedFile(llvm::StringRef Dir
, bool Angled
) {
10057 // RelDir should use /, but unescaped \ is possible on windows!
10058 // Our completions will normalize to / for simplicity, this case is rare.
10059 std::string RelDir
= llvm::sys::path::convert_to_slash(Dir
);
10060 // We need the native slashes for the actual file system interactions.
10061 SmallString
<128> NativeRelDir
= StringRef(RelDir
);
10062 llvm::sys::path::native(NativeRelDir
);
10063 llvm::vfs::FileSystem
&FS
=
10064 getSourceManager().getFileManager().getVirtualFileSystem();
10066 ResultBuilder
Results(*this, CodeCompleter
->getAllocator(),
10067 CodeCompleter
->getCodeCompletionTUInfo(),
10068 CodeCompletionContext::CCC_IncludedFile
);
10069 llvm::DenseSet
<StringRef
> SeenResults
; // To deduplicate results.
10071 // Helper: adds one file or directory completion result.
10072 auto AddCompletion
= [&](StringRef Filename
, bool IsDirectory
) {
10073 SmallString
<64> TypedChunk
= Filename
;
10074 // Directory completion is up to the slash, e.g. <sys/
10075 TypedChunk
.push_back(IsDirectory
? '/' : Angled
? '>' : '"');
10076 auto R
= SeenResults
.insert(TypedChunk
);
10077 if (R
.second
) { // New completion
10078 const char *InternedTyped
= Results
.getAllocator().CopyString(TypedChunk
);
10079 *R
.first
= InternedTyped
; // Avoid dangling StringRef.
10080 CodeCompletionBuilder
Builder(CodeCompleter
->getAllocator(),
10081 CodeCompleter
->getCodeCompletionTUInfo());
10082 Builder
.AddTypedTextChunk(InternedTyped
);
10083 // The result is a "Pattern", which is pretty opaque.
10084 // We may want to include the real filename to allow smart ranking.
10085 Results
.AddResult(CodeCompletionResult(Builder
.TakeString()));
10089 // Helper: scans IncludeDir for nice files, and adds results for each.
10090 auto AddFilesFromIncludeDir
= [&](StringRef IncludeDir
,
10092 DirectoryLookup::LookupType_t LookupType
) {
10093 llvm::SmallString
<128> Dir
= IncludeDir
;
10094 if (!NativeRelDir
.empty()) {
10095 if (LookupType
== DirectoryLookup::LT_Framework
) {
10096 // For a framework dir, #include <Foo/Bar/> actually maps to
10097 // a path of Foo.framework/Headers/Bar/.
10098 auto Begin
= llvm::sys::path::begin(NativeRelDir
);
10099 auto End
= llvm::sys::path::end(NativeRelDir
);
10101 llvm::sys::path::append(Dir
, *Begin
+ ".framework", "Headers");
10102 llvm::sys::path::append(Dir
, ++Begin
, End
);
10104 llvm::sys::path::append(Dir
, NativeRelDir
);
10108 const StringRef
&Dirname
= llvm::sys::path::filename(Dir
);
10109 const bool isQt
= Dirname
.startswith("Qt") || Dirname
== "ActiveQt";
10110 const bool ExtensionlessHeaders
=
10111 IsSystem
|| isQt
|| Dir
.endswith(".framework/Headers");
10112 std::error_code EC
;
10113 unsigned Count
= 0;
10114 for (auto It
= FS
.dir_begin(Dir
, EC
);
10115 !EC
&& It
!= llvm::vfs::directory_iterator(); It
.increment(EC
)) {
10116 if (++Count
== 2500) // If we happen to hit a huge directory,
10117 break; // bail out early so we're not too slow.
10118 StringRef Filename
= llvm::sys::path::filename(It
->path());
10120 // To know whether a symlink should be treated as file or a directory, we
10121 // have to stat it. This should be cheap enough as there shouldn't be many
10123 llvm::sys::fs::file_type Type
= It
->type();
10124 if (Type
== llvm::sys::fs::file_type::symlink_file
) {
10125 if (auto FileStatus
= FS
.status(It
->path()))
10126 Type
= FileStatus
->getType();
10129 case llvm::sys::fs::file_type::directory_file
:
10130 // All entries in a framework directory must have a ".framework" suffix,
10131 // but the suffix does not appear in the source code's include/import.
10132 if (LookupType
== DirectoryLookup::LT_Framework
&&
10133 NativeRelDir
.empty() && !Filename
.consume_back(".framework"))
10136 AddCompletion(Filename
, /*IsDirectory=*/true);
10138 case llvm::sys::fs::file_type::regular_file
: {
10139 // Only files that really look like headers. (Except in special dirs).
10140 const bool IsHeader
= Filename
.ends_with_insensitive(".h") ||
10141 Filename
.ends_with_insensitive(".hh") ||
10142 Filename
.ends_with_insensitive(".hpp") ||
10143 Filename
.ends_with_insensitive(".hxx") ||
10144 Filename
.ends_with_insensitive(".inc") ||
10145 (ExtensionlessHeaders
&& !Filename
.contains('.'));
10148 AddCompletion(Filename
, /*IsDirectory=*/false);
10157 // Helper: adds results relative to IncludeDir, if possible.
10158 auto AddFilesFromDirLookup
= [&](const DirectoryLookup
&IncludeDir
,
10160 switch (IncludeDir
.getLookupType()) {
10161 case DirectoryLookup::LT_HeaderMap
:
10162 // header maps are not (currently) enumerable.
10164 case DirectoryLookup::LT_NormalDir
:
10165 AddFilesFromIncludeDir(IncludeDir
.getDirRef()->getName(), IsSystem
,
10166 DirectoryLookup::LT_NormalDir
);
10168 case DirectoryLookup::LT_Framework
:
10169 AddFilesFromIncludeDir(IncludeDir
.getFrameworkDirRef()->getName(),
10170 IsSystem
, DirectoryLookup::LT_Framework
);
10175 // Finally with all our helpers, we can scan the include path.
10176 // Do this in standard order so deduplication keeps the right file.
10177 // (In case we decide to add more details to the results later).
10178 const auto &S
= PP
.getHeaderSearchInfo();
10179 using llvm::make_range
;
10181 // The current directory is on the include path for "quoted" includes.
10182 if (auto CurFile
= PP
.getCurrentFileLexer()->getFileEntry())
10183 AddFilesFromIncludeDir(CurFile
->getDir().getName(), false,
10184 DirectoryLookup::LT_NormalDir
);
10185 for (const auto &D
: make_range(S
.quoted_dir_begin(), S
.quoted_dir_end()))
10186 AddFilesFromDirLookup(D
, false);
10188 for (const auto &D
: make_range(S
.angled_dir_begin(), S
.angled_dir_end()))
10189 AddFilesFromDirLookup(D
, false);
10190 for (const auto &D
: make_range(S
.system_dir_begin(), S
.system_dir_end()))
10191 AddFilesFromDirLookup(D
, true);
10193 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
10194 Results
.data(), Results
.size());
10197 void Sema::CodeCompleteNaturalLanguage() {
10198 HandleCodeCompleteResults(this, CodeCompleter
,
10199 CodeCompletionContext::CCC_NaturalLanguage
, nullptr,
10203 void Sema::CodeCompleteAvailabilityPlatformName() {
10204 ResultBuilder
Results(*this, CodeCompleter
->getAllocator(),
10205 CodeCompleter
->getCodeCompletionTUInfo(),
10206 CodeCompletionContext::CCC_Other
);
10207 Results
.EnterNewScope();
10208 static const char *Platforms
[] = {"macOS", "iOS", "watchOS", "tvOS"};
10209 for (const char *Platform
: llvm::ArrayRef(Platforms
)) {
10210 Results
.AddResult(CodeCompletionResult(Platform
));
10211 Results
.AddResult(CodeCompletionResult(Results
.getAllocator().CopyString(
10212 Twine(Platform
) + "ApplicationExtension")));
10214 Results
.ExitScope();
10215 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
10216 Results
.data(), Results
.size());
10219 void Sema::GatherGlobalCodeCompletions(
10220 CodeCompletionAllocator
&Allocator
, CodeCompletionTUInfo
&CCTUInfo
,
10221 SmallVectorImpl
<CodeCompletionResult
> &Results
) {
10222 ResultBuilder
Builder(*this, Allocator
, CCTUInfo
,
10223 CodeCompletionContext::CCC_Recovery
);
10224 if (!CodeCompleter
|| CodeCompleter
->includeGlobals()) {
10225 CodeCompletionDeclConsumer
Consumer(Builder
,
10226 Context
.getTranslationUnitDecl());
10227 LookupVisibleDecls(Context
.getTranslationUnitDecl(), LookupAnyName
,
10229 !CodeCompleter
|| CodeCompleter
->loadExternal());
10232 if (!CodeCompleter
|| CodeCompleter
->includeMacros())
10233 AddMacroResults(PP
, Builder
,
10234 !CodeCompleter
|| CodeCompleter
->loadExternal(), true);
10237 Results
.insert(Results
.end(), Builder
.data(),
10238 Builder
.data() + Builder
.size());