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/DynamicRecursiveASTVisitor.h"
19 #include "clang/AST/Expr.h"
20 #include "clang/AST/ExprCXX.h"
21 #include "clang/AST/ExprConcepts.h"
22 #include "clang/AST/ExprObjC.h"
23 #include "clang/AST/NestedNameSpecifier.h"
24 #include "clang/AST/OperationKinds.h"
25 #include "clang/AST/QualTypeNames.h"
26 #include "clang/AST/Type.h"
27 #include "clang/Basic/AttributeCommonInfo.h"
28 #include "clang/Basic/CharInfo.h"
29 #include "clang/Basic/OperatorKinds.h"
30 #include "clang/Basic/Specifiers.h"
31 #include "clang/Lex/HeaderSearch.h"
32 #include "clang/Lex/MacroInfo.h"
33 #include "clang/Lex/Preprocessor.h"
34 #include "clang/Sema/CodeCompleteConsumer.h"
35 #include "clang/Sema/DeclSpec.h"
36 #include "clang/Sema/Designator.h"
37 #include "clang/Sema/Lookup.h"
38 #include "clang/Sema/Overload.h"
39 #include "clang/Sema/ParsedAttr.h"
40 #include "clang/Sema/ParsedTemplate.h"
41 #include "clang/Sema/Scope.h"
42 #include "clang/Sema/ScopeInfo.h"
43 #include "clang/Sema/Sema.h"
44 #include "clang/Sema/SemaCodeCompletion.h"
45 #include "clang/Sema/SemaObjC.h"
46 #include "llvm/ADT/ArrayRef.h"
47 #include "llvm/ADT/DenseSet.h"
48 #include "llvm/ADT/SmallBitVector.h"
49 #include "llvm/ADT/SmallPtrSet.h"
50 #include "llvm/ADT/SmallString.h"
51 #include "llvm/ADT/StringSwitch.h"
52 #include "llvm/ADT/Twine.h"
53 #include "llvm/ADT/iterator_range.h"
54 #include "llvm/Support/Casting.h"
55 #include "llvm/Support/Path.h"
56 #include "llvm/Support/raw_ostream.h"
64 using namespace clang
;
68 /// A container of code-completion results.
71 /// The type of a name-lookup filter, which can be provided to the
72 /// name-lookup routines to specify which declarations should be included in
73 /// the result set (when it returns true) and which declarations should be
74 /// filtered out (returns false).
75 typedef bool (ResultBuilder::*LookupFilter
)(const NamedDecl
*) const;
77 typedef CodeCompletionResult Result
;
80 /// The actual results we have found.
81 std::vector
<Result
> Results
;
83 /// A record of all of the declarations we have found and placed
84 /// into the result set, used to ensure that no declaration ever gets into
85 /// the result set twice.
86 llvm::SmallPtrSet
<const Decl
*, 16> AllDeclsFound
;
88 typedef std::pair
<const NamedDecl
*, unsigned> DeclIndexPair
;
90 /// An entry in the shadow map, which is optimized to store
91 /// a single (declaration, index) mapping (the common case) but
92 /// can also store a list of (declaration, index) mappings.
93 class ShadowMapEntry
{
94 typedef SmallVector
<DeclIndexPair
, 4> DeclIndexPairVector
;
96 /// Contains either the solitary NamedDecl * or a vector
97 /// of (declaration, index) pairs.
98 llvm::PointerUnion
<const NamedDecl
*, DeclIndexPairVector
*> DeclOrVector
;
100 /// When the entry contains a single declaration, this is
101 /// the index associated with that entry.
102 unsigned SingleDeclIndex
= 0;
105 ShadowMapEntry() = default;
106 ShadowMapEntry(const ShadowMapEntry
&) = delete;
107 ShadowMapEntry(ShadowMapEntry
&&Move
) { *this = std::move(Move
); }
108 ShadowMapEntry
&operator=(const ShadowMapEntry
&) = delete;
109 ShadowMapEntry
&operator=(ShadowMapEntry
&&Move
) {
110 SingleDeclIndex
= Move
.SingleDeclIndex
;
111 DeclOrVector
= Move
.DeclOrVector
;
112 Move
.DeclOrVector
= nullptr;
116 void Add(const NamedDecl
*ND
, unsigned Index
) {
117 if (DeclOrVector
.isNull()) {
118 // 0 - > 1 elements: just set the single element information.
120 SingleDeclIndex
= Index
;
124 if (const NamedDecl
*PrevND
=
125 DeclOrVector
.dyn_cast
<const NamedDecl
*>()) {
126 // 1 -> 2 elements: create the vector of results and push in the
127 // existing declaration.
128 DeclIndexPairVector
*Vec
= new DeclIndexPairVector
;
129 Vec
->push_back(DeclIndexPair(PrevND
, SingleDeclIndex
));
133 // Add the new element to the end of the vector.
134 cast
<DeclIndexPairVector
*>(DeclOrVector
)
135 ->push_back(DeclIndexPair(ND
, Index
));
139 if (DeclIndexPairVector
*Vec
=
140 DeclOrVector
.dyn_cast
<DeclIndexPairVector
*>()) {
142 DeclOrVector
= ((NamedDecl
*)nullptr);
148 iterator
begin() const;
149 iterator
end() const;
152 /// A mapping from declaration names to the declarations that have
153 /// this name within a particular scope and their index within the list of
155 typedef llvm::DenseMap
<DeclarationName
, ShadowMapEntry
> ShadowMap
;
157 /// The semantic analysis object for which results are being
161 /// The allocator used to allocate new code-completion strings.
162 CodeCompletionAllocator
&Allocator
;
164 CodeCompletionTUInfo
&CCTUInfo
;
166 /// If non-NULL, a filter function used to remove any code-completion
167 /// results that are not desirable.
170 /// Whether we should allow declarations as
171 /// nested-name-specifiers that would otherwise be filtered out.
172 bool AllowNestedNameSpecifiers
;
174 /// If set, the type that we would prefer our resulting value
175 /// declarations to have.
177 /// Closely matching the preferred type gives a boost to a result's
179 CanQualType PreferredType
;
181 /// A list of shadow maps, which is used to model name hiding at
182 /// different levels of, e.g., the inheritance hierarchy.
183 std::list
<ShadowMap
> ShadowMaps
;
185 /// Overloaded C++ member functions found by SemaLookup.
186 /// Used to determine when one overload is dominated by another.
187 llvm::DenseMap
<std::pair
<DeclContext
*, /*Name*/uintptr_t>, ShadowMapEntry
>
190 /// If we're potentially referring to a C++ member function, the set
191 /// of qualifiers applied to the object type.
192 Qualifiers ObjectTypeQualifiers
;
193 /// The kind of the object expression, for rvalue/lvalue overloads.
194 ExprValueKind ObjectKind
;
196 /// Whether the \p ObjectTypeQualifiers field is active.
197 bool HasObjectTypeQualifiers
;
199 /// The selector that we prefer.
200 Selector PreferredSelector
;
202 /// The completion context in which we are gathering results.
203 CodeCompletionContext CompletionContext
;
205 /// If we are in an instance method definition, the \@implementation
207 ObjCImplementationDecl
*ObjCImplementation
;
209 void AdjustResultPriorityForDecl(Result
&R
);
211 void MaybeAddConstructorResults(Result R
);
214 explicit ResultBuilder(Sema
&SemaRef
, CodeCompletionAllocator
&Allocator
,
215 CodeCompletionTUInfo
&CCTUInfo
,
216 const CodeCompletionContext
&CompletionContext
,
217 LookupFilter Filter
= nullptr)
218 : SemaRef(SemaRef
), Allocator(Allocator
), CCTUInfo(CCTUInfo
),
219 Filter(Filter
), AllowNestedNameSpecifiers(false),
220 HasObjectTypeQualifiers(false), CompletionContext(CompletionContext
),
221 ObjCImplementation(nullptr) {
222 // If this is an Objective-C instance method definition, dig out the
223 // corresponding implementation.
224 switch (CompletionContext
.getKind()) {
225 case CodeCompletionContext::CCC_Expression
:
226 case CodeCompletionContext::CCC_ObjCMessageReceiver
:
227 case CodeCompletionContext::CCC_ParenthesizedExpression
:
228 case CodeCompletionContext::CCC_Statement
:
229 case CodeCompletionContext::CCC_TopLevelOrExpression
:
230 case CodeCompletionContext::CCC_Recovery
:
231 if (ObjCMethodDecl
*Method
= SemaRef
.getCurMethodDecl())
232 if (Method
->isInstanceMethod())
233 if (ObjCInterfaceDecl
*Interface
= Method
->getClassInterface())
234 ObjCImplementation
= Interface
->getImplementation();
242 /// Determine the priority for a reference to the given declaration.
243 unsigned getBasePriority(const NamedDecl
*D
);
245 /// Whether we should include code patterns in the completion
247 bool includeCodePatterns() const {
248 return SemaRef
.CodeCompletion().CodeCompleter
&&
249 SemaRef
.CodeCompletion().CodeCompleter
->includeCodePatterns();
252 /// Set the filter used for code-completion results.
253 void setFilter(LookupFilter Filter
) { this->Filter
= Filter
; }
255 Result
*data() { return Results
.empty() ? nullptr : &Results
.front(); }
256 unsigned size() const { return Results
.size(); }
257 bool empty() const { return Results
.empty(); }
259 /// Specify the preferred type.
260 void setPreferredType(QualType T
) {
261 PreferredType
= SemaRef
.Context
.getCanonicalType(T
);
264 /// Set the cv-qualifiers on the object type, for us in filtering
265 /// calls to member functions.
267 /// When there are qualifiers in this set, they will be used to filter
268 /// out member functions that aren't available (because there will be a
269 /// cv-qualifier mismatch) or prefer functions with an exact qualifier
271 void setObjectTypeQualifiers(Qualifiers Quals
, ExprValueKind Kind
) {
272 ObjectTypeQualifiers
= Quals
;
274 HasObjectTypeQualifiers
= true;
277 /// Set the preferred selector.
279 /// When an Objective-C method declaration result is added, and that
280 /// method's selector matches this preferred selector, we give that method
281 /// a slight priority boost.
282 void setPreferredSelector(Selector Sel
) { PreferredSelector
= Sel
; }
284 /// Retrieve the code-completion context for which results are
286 const CodeCompletionContext
&getCompletionContext() const {
287 return CompletionContext
;
290 /// Specify whether nested-name-specifiers are allowed.
291 void allowNestedNameSpecifiers(bool Allow
= true) {
292 AllowNestedNameSpecifiers
= Allow
;
295 /// Return the semantic analysis object for which we are collecting
296 /// code completion results.
297 Sema
&getSema() const { return SemaRef
; }
299 /// Retrieve the allocator used to allocate code completion strings.
300 CodeCompletionAllocator
&getAllocator() const { return Allocator
; }
302 CodeCompletionTUInfo
&getCodeCompletionTUInfo() const { return CCTUInfo
; }
304 /// Determine whether the given declaration is at all interesting
305 /// as a code-completion result.
307 /// \param ND the declaration that we are inspecting.
309 /// \param AsNestedNameSpecifier will be set true if this declaration is
310 /// only interesting when it is a nested-name-specifier.
311 bool isInterestingDecl(const NamedDecl
*ND
,
312 bool &AsNestedNameSpecifier
) const;
314 /// Decide whether or not a use of function Decl can be a call.
316 /// \param ND the function declaration.
318 /// \param BaseExprType the object type in a member access expression,
320 bool canFunctionBeCalled(const NamedDecl
*ND
, QualType BaseExprType
) const;
322 /// Decide whether or not a use of member function Decl can be a call.
324 /// \param Method the function declaration.
326 /// \param BaseExprType the object type in a member access expression,
328 bool canCxxMethodBeCalled(const CXXMethodDecl
*Method
,
329 QualType BaseExprType
) const;
331 /// Check whether the result is hidden by the Hiding declaration.
333 /// \returns true if the result is hidden and cannot be found, false if
334 /// the hidden result could still be found. When false, \p R may be
335 /// modified to describe how the result can be found (e.g., via extra
337 bool CheckHiddenResult(Result
&R
, DeclContext
*CurContext
,
338 const NamedDecl
*Hiding
);
340 /// Add a new result to this result set (if it isn't already in one
341 /// of the shadow maps), or replace an existing result (for, e.g., a
344 /// \param R the result to add (if it is unique).
346 /// \param CurContext the context in which this result will be named.
347 void MaybeAddResult(Result R
, DeclContext
*CurContext
= nullptr);
349 /// Add a new result to this result set, where we already know
350 /// the hiding declaration (if any).
352 /// \param R the result to add (if it is unique).
354 /// \param CurContext the context in which this result will be named.
356 /// \param Hiding the declaration that hides the result.
358 /// \param InBaseClass whether the result was found in a base
359 /// class of the searched context.
361 /// \param BaseExprType the type of expression that precedes the "." or "->"
362 /// in a member access expression.
363 void AddResult(Result R
, DeclContext
*CurContext
, NamedDecl
*Hiding
,
364 bool InBaseClass
, QualType BaseExprType
);
366 /// Add a new non-declaration result to this result set.
367 void AddResult(Result R
);
369 /// Enter into a new scope.
370 void EnterNewScope();
372 /// Exit from the current scope.
375 /// Ignore this declaration, if it is seen again.
376 void Ignore(const Decl
*D
) { AllDeclsFound
.insert(D
->getCanonicalDecl()); }
378 /// Add a visited context.
379 void addVisitedContext(DeclContext
*Ctx
) {
380 CompletionContext
.addVisitedContext(Ctx
);
383 /// \name Name lookup predicates
385 /// These predicates can be passed to the name lookup functions to filter the
386 /// results of name lookup. All of the predicates have the same type, so that
389 bool IsOrdinaryName(const NamedDecl
*ND
) const;
390 bool IsOrdinaryNonTypeName(const NamedDecl
*ND
) const;
391 bool IsIntegralConstantValue(const NamedDecl
*ND
) const;
392 bool IsOrdinaryNonValueName(const NamedDecl
*ND
) const;
393 bool IsNestedNameSpecifier(const NamedDecl
*ND
) const;
394 bool IsEnum(const NamedDecl
*ND
) const;
395 bool IsClassOrStruct(const NamedDecl
*ND
) const;
396 bool IsUnion(const NamedDecl
*ND
) const;
397 bool IsNamespace(const NamedDecl
*ND
) const;
398 bool IsNamespaceOrAlias(const NamedDecl
*ND
) const;
399 bool IsType(const NamedDecl
*ND
) const;
400 bool IsMember(const NamedDecl
*ND
) const;
401 bool IsObjCIvar(const NamedDecl
*ND
) const;
402 bool IsObjCMessageReceiver(const NamedDecl
*ND
) const;
403 bool IsObjCMessageReceiverOrLambdaCapture(const NamedDecl
*ND
) const;
404 bool IsObjCCollection(const NamedDecl
*ND
) const;
405 bool IsImpossibleToSatisfy(const NamedDecl
*ND
) const;
410 void PreferredTypeBuilder::enterReturn(Sema
&S
, SourceLocation Tok
) {
413 if (isa
<BlockDecl
>(S
.CurContext
)) {
414 if (sema::BlockScopeInfo
*BSI
= S
.getCurBlock()) {
415 ComputeType
= nullptr;
416 Type
= BSI
->ReturnType
;
419 } else if (const auto *Function
= dyn_cast
<FunctionDecl
>(S
.CurContext
)) {
420 ComputeType
= nullptr;
421 Type
= Function
->getReturnType();
423 } else if (const auto *Method
= dyn_cast
<ObjCMethodDecl
>(S
.CurContext
)) {
424 ComputeType
= nullptr;
425 Type
= Method
->getReturnType();
430 void PreferredTypeBuilder::enterVariableInit(SourceLocation Tok
, Decl
*D
) {
433 auto *VD
= llvm::dyn_cast_or_null
<ValueDecl
>(D
);
434 ComputeType
= nullptr;
435 Type
= VD
? VD
->getType() : QualType();
439 static QualType
getDesignatedType(QualType BaseType
, const Designation
&Desig
);
441 void PreferredTypeBuilder::enterDesignatedInitializer(SourceLocation Tok
,
443 const Designation
&D
) {
446 ComputeType
= nullptr;
447 Type
= getDesignatedType(BaseType
, D
);
451 void PreferredTypeBuilder::enterFunctionArgument(
452 SourceLocation Tok
, llvm::function_ref
<QualType()> ComputeType
) {
455 this->ComputeType
= ComputeType
;
460 void PreferredTypeBuilder::enterParenExpr(SourceLocation Tok
,
461 SourceLocation LParLoc
) {
464 // expected type for parenthesized expression does not change.
465 if (ExpectedLoc
== LParLoc
)
469 static QualType
getPreferredTypeOfBinaryRHS(Sema
&S
, Expr
*LHS
,
474 QualType LHSType
= LHS
->getType();
475 if (LHSType
->isPointerType()) {
476 if (Op
== tok::plus
|| Op
== tok::plusequal
|| Op
== tok::minusequal
)
477 return S
.getASTContext().getPointerDiffType();
478 // Pointer difference is more common than subtracting an int from a pointer.
479 if (Op
== tok::minus
)
484 // No way to infer the type of RHS from LHS.
487 // Prefer the type of the left operand for all of these.
488 // Arithmetic operations.
492 case tok::minusequal
:
494 case tok::percentequal
:
496 case tok::slashequal
:
501 // Comparison operators.
502 case tok::equalequal
:
503 case tok::exclaimequal
:
507 case tok::greaterequal
:
509 return LHS
->getType();
510 // Binary shifts are often overloaded, so don't try to guess those.
511 case tok::greatergreater
:
512 case tok::greatergreaterequal
:
514 case tok::lesslessequal
:
515 if (LHSType
->isIntegralOrEnumerationType())
516 return S
.getASTContext().IntTy
;
518 // Logical operators, assume we want bool.
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 (isa
<const NamedDecl
*>(DeclOrIterator
)) {
663 DeclOrIterator
= (NamedDecl
*)nullptr;
668 const DeclIndexPair
*I
= cast
<const DeclIndexPair
*>(DeclOrIterator
);
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 *cast
<const DeclIndexPair
*>(DeclOrIterator
);
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(cast
<DeclIndexPairVector
*>(DeclOrVector
)->begin());
711 ResultBuilder::ShadowMapEntry::iterator
712 ResultBuilder::ShadowMapEntry::end() const {
713 if (isa
<const NamedDecl
*>(DeclOrVector
) || DeclOrVector
.isNull())
716 return iterator(cast
<DeclIndexPairVector
*>(DeclOrVector
)->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 // Debuggers want access to all identifiers, including reserved ones.
768 if (SemaRef
.getLangOpts().DebuggerSupport
)
771 ReservedIdentifierStatus Status
= ND
->isReserved(SemaRef
.getLangOpts());
772 // Ignore reserved names for compiler provided decls.
773 if (isReservedInAllContexts(Status
) && ND
->getLocation().isInvalid())
776 // For system headers ignore only double-underscore names.
777 // This allows for system headers providing private symbols with a single
779 if (Status
== ReservedIdentifierStatus::StartsWithDoubleUnderscore
&&
780 SemaRef
.SourceMgr
.isInSystemHeader(
781 SemaRef
.SourceMgr
.getSpellingLoc(ND
->getLocation())))
787 bool ResultBuilder::isInterestingDecl(const NamedDecl
*ND
,
788 bool &AsNestedNameSpecifier
) const {
789 AsNestedNameSpecifier
= false;
792 ND
= ND
->getUnderlyingDecl();
794 // Skip unnamed entities.
795 if (!ND
->getDeclName())
798 // Friend declarations and declarations introduced due to friends are never
800 if (ND
->getFriendObjectKind() == Decl::FOK_Undeclared
)
803 // Class template (partial) specializations are never added as results.
804 if (isa
<ClassTemplateSpecializationDecl
>(ND
) ||
805 isa
<ClassTemplatePartialSpecializationDecl
>(ND
))
808 // Using declarations themselves are never added as results.
809 if (isa
<UsingDecl
>(ND
))
812 if (shouldIgnoreDueToReservedName(ND
, SemaRef
))
815 if (Filter
== &ResultBuilder::IsNestedNameSpecifier
||
816 (isa
<NamespaceDecl
>(ND
) && Filter
!= &ResultBuilder::IsNamespace
&&
817 Filter
!= &ResultBuilder::IsNamespaceOrAlias
&& Filter
!= nullptr))
818 AsNestedNameSpecifier
= true;
820 // Filter out any unwanted results.
821 if (Filter
&& !(this->*Filter
)(Named
)) {
822 // Check whether it is interesting as a nested-name-specifier.
823 if (AllowNestedNameSpecifiers
&& SemaRef
.getLangOpts().CPlusPlus
&&
824 IsNestedNameSpecifier(ND
) &&
825 (Filter
!= &ResultBuilder::IsMember
||
826 (isa
<CXXRecordDecl
>(ND
) &&
827 cast
<CXXRecordDecl
>(ND
)->isInjectedClassName()))) {
828 AsNestedNameSpecifier
= true;
834 // ... then it must be interesting!
838 bool ResultBuilder::CheckHiddenResult(Result
&R
, DeclContext
*CurContext
,
839 const NamedDecl
*Hiding
) {
840 // In C, there is no way to refer to a hidden name.
841 // FIXME: This isn't true; we can find a tag name hidden by an ordinary
842 // name if we introduce the tag type.
843 if (!SemaRef
.getLangOpts().CPlusPlus
)
846 const DeclContext
*HiddenCtx
=
847 R
.Declaration
->getDeclContext()->getRedeclContext();
849 // There is no way to qualify a name declared in a function or method.
850 if (HiddenCtx
->isFunctionOrMethod())
853 if (HiddenCtx
== Hiding
->getDeclContext()->getRedeclContext())
856 // We can refer to the result with the appropriate qualification. Do it.
858 R
.QualifierIsInformative
= false;
861 R
.Qualifier
= getRequiredQualification(SemaRef
.Context
, CurContext
,
862 R
.Declaration
->getDeclContext());
866 /// A simplified classification of types used to determine whether two
867 /// types are "similar enough" when adjusting priorities.
868 SimplifiedTypeClass
clang::getSimplifiedTypeClass(CanQualType T
) {
869 switch (T
->getTypeClass()) {
871 switch (cast
<BuiltinType
>(T
)->getKind()) {
872 case BuiltinType::Void
:
875 case BuiltinType::NullPtr
:
878 case BuiltinType::Overload
:
879 case BuiltinType::Dependent
:
882 case BuiltinType::ObjCId
:
883 case BuiltinType::ObjCClass
:
884 case BuiltinType::ObjCSel
:
885 return STC_ObjectiveC
;
888 return STC_Arithmetic
;
892 return STC_Arithmetic
;
897 case Type::BlockPointer
:
900 case Type::LValueReference
:
901 case Type::RValueReference
:
902 return getSimplifiedTypeClass(T
->getAs
<ReferenceType
>()->getPointeeType());
904 case Type::ConstantArray
:
905 case Type::IncompleteArray
:
906 case Type::VariableArray
:
907 case Type::DependentSizedArray
:
910 case Type::DependentSizedExtVector
:
912 case Type::ExtVector
:
913 return STC_Arithmetic
;
915 case Type::FunctionProto
:
916 case Type::FunctionNoProto
:
923 return STC_Arithmetic
;
925 case Type::ObjCObject
:
926 case Type::ObjCInterface
:
927 case Type::ObjCObjectPointer
:
928 return STC_ObjectiveC
;
935 /// Get the type that a given expression will have if this declaration
936 /// is used as an expression in its "typical" code-completion form.
937 QualType
clang::getDeclUsageType(ASTContext
&C
, const NamedDecl
*ND
) {
938 ND
= ND
->getUnderlyingDecl();
940 if (const auto *Type
= dyn_cast
<TypeDecl
>(ND
))
941 return C
.getTypeDeclType(Type
);
942 if (const auto *Iface
= dyn_cast
<ObjCInterfaceDecl
>(ND
))
943 return C
.getObjCInterfaceType(Iface
);
946 if (const FunctionDecl
*Function
= ND
->getAsFunction())
947 T
= Function
->getCallResultType();
948 else if (const auto *Method
= dyn_cast
<ObjCMethodDecl
>(ND
))
949 T
= Method
->getSendResultType();
950 else if (const auto *Enumerator
= dyn_cast
<EnumConstantDecl
>(ND
))
951 T
= C
.getTypeDeclType(cast
<EnumDecl
>(Enumerator
->getDeclContext()));
952 else if (const auto *Property
= dyn_cast
<ObjCPropertyDecl
>(ND
))
953 T
= Property
->getType();
954 else if (const auto *Value
= dyn_cast
<ValueDecl
>(ND
))
955 T
= Value
->getType();
960 // Dig through references, function pointers, and block pointers to
961 // get down to the likely type of an expression when the entity is
964 if (const auto *Ref
= T
->getAs
<ReferenceType
>()) {
965 T
= Ref
->getPointeeType();
969 if (const auto *Pointer
= T
->getAs
<PointerType
>()) {
970 if (Pointer
->getPointeeType()->isFunctionType()) {
971 T
= Pointer
->getPointeeType();
978 if (const auto *Block
= T
->getAs
<BlockPointerType
>()) {
979 T
= Block
->getPointeeType();
983 if (const auto *Function
= T
->getAs
<FunctionType
>()) {
984 T
= Function
->getReturnType();
994 unsigned ResultBuilder::getBasePriority(const NamedDecl
*ND
) {
998 // Context-based decisions.
999 const DeclContext
*LexicalDC
= ND
->getLexicalDeclContext();
1000 if (LexicalDC
->isFunctionOrMethod()) {
1001 // _cmd is relatively rare
1002 if (const auto *ImplicitParam
= dyn_cast
<ImplicitParamDecl
>(ND
))
1003 if (ImplicitParam
->getIdentifier() &&
1004 ImplicitParam
->getIdentifier()->isStr("_cmd"))
1005 return CCP_ObjC_cmd
;
1007 return CCP_LocalDeclaration
;
1010 const DeclContext
*DC
= ND
->getDeclContext()->getRedeclContext();
1011 if (DC
->isRecord() || isa
<ObjCContainerDecl
>(DC
)) {
1012 // Explicit destructor calls are very rare.
1013 if (isa
<CXXDestructorDecl
>(ND
))
1014 return CCP_Unlikely
;
1015 // Explicit operator and conversion function calls are also very rare.
1016 auto DeclNameKind
= ND
->getDeclName().getNameKind();
1017 if (DeclNameKind
== DeclarationName::CXXOperatorName
||
1018 DeclNameKind
== DeclarationName::CXXLiteralOperatorName
||
1019 DeclNameKind
== DeclarationName::CXXConversionFunctionName
)
1020 return CCP_Unlikely
;
1021 return CCP_MemberDeclaration
;
1024 // Content-based decisions.
1025 if (isa
<EnumConstantDecl
>(ND
))
1026 return CCP_Constant
;
1028 // Use CCP_Type for type declarations unless we're in a statement, Objective-C
1029 // message receiver, or parenthesized expression context. There, it's as
1030 // likely that the user will want to write a type as other declarations.
1031 if ((isa
<TypeDecl
>(ND
) || isa
<ObjCInterfaceDecl
>(ND
)) &&
1032 !(CompletionContext
.getKind() == CodeCompletionContext::CCC_Statement
||
1033 CompletionContext
.getKind() ==
1034 CodeCompletionContext::CCC_ObjCMessageReceiver
||
1035 CompletionContext
.getKind() ==
1036 CodeCompletionContext::CCC_ParenthesizedExpression
))
1039 return CCP_Declaration
;
1042 void ResultBuilder::AdjustResultPriorityForDecl(Result
&R
) {
1043 // If this is an Objective-C method declaration whose selector matches our
1044 // preferred selector, give it a priority boost.
1045 if (!PreferredSelector
.isNull())
1046 if (const auto *Method
= dyn_cast
<ObjCMethodDecl
>(R
.Declaration
))
1047 if (PreferredSelector
== Method
->getSelector())
1048 R
.Priority
+= CCD_SelectorMatch
;
1050 // If we have a preferred type, adjust the priority for results with exactly-
1051 // matching or nearly-matching types.
1052 if (!PreferredType
.isNull()) {
1053 QualType T
= getDeclUsageType(SemaRef
.Context
, R
.Declaration
);
1055 CanQualType TC
= SemaRef
.Context
.getCanonicalType(T
);
1056 // Check for exactly-matching types (modulo qualifiers).
1057 if (SemaRef
.Context
.hasSameUnqualifiedType(PreferredType
, TC
))
1058 R
.Priority
/= CCF_ExactTypeMatch
;
1059 // Check for nearly-matching types, based on classification of each.
1060 else if ((getSimplifiedTypeClass(PreferredType
) ==
1061 getSimplifiedTypeClass(TC
)) &&
1062 !(PreferredType
->isEnumeralType() && TC
->isEnumeralType()))
1063 R
.Priority
/= CCF_SimilarTypeMatch
;
1068 static DeclContext::lookup_result
getConstructors(ASTContext
&Context
,
1069 const CXXRecordDecl
*Record
) {
1070 QualType RecordTy
= Context
.getTypeDeclType(Record
);
1071 DeclarationName ConstructorName
=
1072 Context
.DeclarationNames
.getCXXConstructorName(
1073 Context
.getCanonicalType(RecordTy
));
1074 return Record
->lookup(ConstructorName
);
1077 void ResultBuilder::MaybeAddConstructorResults(Result R
) {
1078 if (!SemaRef
.getLangOpts().CPlusPlus
|| !R
.Declaration
||
1079 !CompletionContext
.wantConstructorResults())
1082 const NamedDecl
*D
= R
.Declaration
;
1083 const CXXRecordDecl
*Record
= nullptr;
1084 if (const ClassTemplateDecl
*ClassTemplate
= dyn_cast
<ClassTemplateDecl
>(D
))
1085 Record
= ClassTemplate
->getTemplatedDecl();
1086 else if ((Record
= dyn_cast
<CXXRecordDecl
>(D
))) {
1087 // Skip specializations and partial specializations.
1088 if (isa
<ClassTemplateSpecializationDecl
>(Record
))
1091 // There are no constructors here.
1095 Record
= Record
->getDefinition();
1099 for (NamedDecl
*Ctor
: getConstructors(SemaRef
.Context
, Record
)) {
1100 R
.Declaration
= Ctor
;
1101 R
.CursorKind
= getCursorKindForDecl(R
.Declaration
);
1102 Results
.push_back(R
);
1106 static bool isConstructor(const Decl
*ND
) {
1107 if (const auto *Tmpl
= dyn_cast
<FunctionTemplateDecl
>(ND
))
1108 ND
= Tmpl
->getTemplatedDecl();
1109 return isa
<CXXConstructorDecl
>(ND
);
1112 void ResultBuilder::MaybeAddResult(Result R
, DeclContext
*CurContext
) {
1113 assert(!ShadowMaps
.empty() && "Must enter into a results scope");
1115 if (R
.Kind
!= Result::RK_Declaration
) {
1116 // For non-declaration results, just add the result.
1117 Results
.push_back(R
);
1121 // Look through using declarations.
1122 if (const UsingShadowDecl
*Using
= dyn_cast
<UsingShadowDecl
>(R
.Declaration
)) {
1123 CodeCompletionResult
Result(Using
->getTargetDecl(),
1124 getBasePriority(Using
->getTargetDecl()),
1126 (R
.Availability
== CXAvailability_Available
||
1127 R
.Availability
== CXAvailability_Deprecated
),
1128 std::move(R
.FixIts
));
1129 Result
.ShadowDecl
= Using
;
1130 MaybeAddResult(Result
, CurContext
);
1134 const Decl
*CanonDecl
= R
.Declaration
->getCanonicalDecl();
1135 unsigned IDNS
= CanonDecl
->getIdentifierNamespace();
1137 bool AsNestedNameSpecifier
= false;
1138 if (!isInterestingDecl(R
.Declaration
, AsNestedNameSpecifier
))
1141 // C++ constructors are never found by name lookup.
1142 if (isConstructor(R
.Declaration
))
1145 ShadowMap
&SMap
= ShadowMaps
.back();
1146 ShadowMapEntry::iterator I
, IEnd
;
1147 ShadowMap::iterator NamePos
= SMap
.find(R
.Declaration
->getDeclName());
1148 if (NamePos
!= SMap
.end()) {
1149 I
= NamePos
->second
.begin();
1150 IEnd
= NamePos
->second
.end();
1153 for (; I
!= IEnd
; ++I
) {
1154 const NamedDecl
*ND
= I
->first
;
1155 unsigned Index
= I
->second
;
1156 if (ND
->getCanonicalDecl() == CanonDecl
) {
1157 // This is a redeclaration. Always pick the newer declaration.
1158 Results
[Index
].Declaration
= R
.Declaration
;
1165 // This is a new declaration in this scope. However, check whether this
1166 // declaration name is hidden by a similarly-named declaration in an outer
1168 std::list
<ShadowMap
>::iterator SM
, SMEnd
= ShadowMaps
.end();
1170 for (SM
= ShadowMaps
.begin(); SM
!= SMEnd
; ++SM
) {
1171 ShadowMapEntry::iterator I
, IEnd
;
1172 ShadowMap::iterator NamePos
= SM
->find(R
.Declaration
->getDeclName());
1173 if (NamePos
!= SM
->end()) {
1174 I
= NamePos
->second
.begin();
1175 IEnd
= NamePos
->second
.end();
1177 for (; I
!= IEnd
; ++I
) {
1178 // A tag declaration does not hide a non-tag declaration.
1179 if (I
->first
->hasTagIdentifierNamespace() &&
1180 (IDNS
& (Decl::IDNS_Member
| Decl::IDNS_Ordinary
|
1181 Decl::IDNS_LocalExtern
| Decl::IDNS_ObjCProtocol
)))
1184 // Protocols are in distinct namespaces from everything else.
1185 if (((I
->first
->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol
) ||
1186 (IDNS
& Decl::IDNS_ObjCProtocol
)) &&
1187 I
->first
->getIdentifierNamespace() != IDNS
)
1190 // The newly-added result is hidden by an entry in the shadow map.
1191 if (CheckHiddenResult(R
, CurContext
, I
->first
))
1198 // Make sure that any given declaration only shows up in the result set once.
1199 if (!AllDeclsFound
.insert(CanonDecl
).second
)
1202 // If the filter is for nested-name-specifiers, then this result starts a
1203 // nested-name-specifier.
1204 if (AsNestedNameSpecifier
) {
1205 R
.StartsNestedNameSpecifier
= true;
1206 R
.Priority
= CCP_NestedNameSpecifier
;
1208 AdjustResultPriorityForDecl(R
);
1210 // If this result is supposed to have an informative qualifier, add one.
1211 if (R
.QualifierIsInformative
&& !R
.Qualifier
&&
1212 !R
.StartsNestedNameSpecifier
) {
1213 const DeclContext
*Ctx
= R
.Declaration
->getDeclContext();
1214 if (const NamespaceDecl
*Namespace
= dyn_cast
<NamespaceDecl
>(Ctx
))
1216 NestedNameSpecifier::Create(SemaRef
.Context
, nullptr, Namespace
);
1217 else if (const TagDecl
*Tag
= dyn_cast
<TagDecl
>(Ctx
))
1218 R
.Qualifier
= NestedNameSpecifier::Create(
1219 SemaRef
.Context
, nullptr, false,
1220 SemaRef
.Context
.getTypeDeclType(Tag
).getTypePtr());
1222 R
.QualifierIsInformative
= false;
1225 // Insert this result into the set of results and into the current shadow
1227 SMap
[R
.Declaration
->getDeclName()].Add(R
.Declaration
, Results
.size());
1228 Results
.push_back(R
);
1230 if (!AsNestedNameSpecifier
)
1231 MaybeAddConstructorResults(R
);
1234 static void setInBaseClass(ResultBuilder::Result
&R
) {
1235 R
.Priority
+= CCD_InBaseClass
;
1236 R
.InBaseClass
= true;
1239 enum class OverloadCompare
{ BothViable
, Dominates
, Dominated
};
1240 // Will Candidate ever be called on the object, when overloaded with Incumbent?
1241 // Returns Dominates if Candidate is always called, Dominated if Incumbent is
1242 // always called, BothViable if either may be called depending on arguments.
1243 // Precondition: must actually be overloads!
1244 static OverloadCompare
compareOverloads(const CXXMethodDecl
&Candidate
,
1245 const CXXMethodDecl
&Incumbent
,
1246 const Qualifiers
&ObjectQuals
,
1247 ExprValueKind ObjectKind
,
1248 const ASTContext
&Ctx
) {
1249 // Base/derived shadowing is handled elsewhere.
1250 if (Candidate
.getDeclContext() != Incumbent
.getDeclContext())
1251 return OverloadCompare::BothViable
;
1252 if (Candidate
.isVariadic() != Incumbent
.isVariadic() ||
1253 Candidate
.getNumParams() != Incumbent
.getNumParams() ||
1254 Candidate
.getMinRequiredArguments() !=
1255 Incumbent
.getMinRequiredArguments())
1256 return OverloadCompare::BothViable
;
1257 for (unsigned I
= 0, E
= Candidate
.getNumParams(); I
!= E
; ++I
)
1258 if (Candidate
.parameters()[I
]->getType().getCanonicalType() !=
1259 Incumbent
.parameters()[I
]->getType().getCanonicalType())
1260 return OverloadCompare::BothViable
;
1261 if (!Candidate
.specific_attrs
<EnableIfAttr
>().empty() ||
1262 !Incumbent
.specific_attrs
<EnableIfAttr
>().empty())
1263 return OverloadCompare::BothViable
;
1264 // At this point, we know calls can't pick one or the other based on
1265 // arguments, so one of the two must win. (Or both fail, handled elsewhere).
1266 RefQualifierKind CandidateRef
= Candidate
.getRefQualifier();
1267 RefQualifierKind IncumbentRef
= Incumbent
.getRefQualifier();
1268 if (CandidateRef
!= IncumbentRef
) {
1269 // If the object kind is LValue/RValue, there's one acceptable ref-qualifier
1270 // and it can't be mixed with ref-unqualified overloads (in valid code).
1272 // For xvalue objects, we prefer the rvalue overload even if we have to
1273 // add qualifiers (which is rare, because const&& is rare).
1274 if (ObjectKind
== clang::VK_XValue
)
1275 return CandidateRef
== RQ_RValue
? OverloadCompare::Dominates
1276 : OverloadCompare::Dominated
;
1278 // Now the ref qualifiers are the same (or we're in some invalid state).
1279 // So make some decision based on the qualifiers.
1280 Qualifiers CandidateQual
= Candidate
.getMethodQualifiers();
1281 Qualifiers IncumbentQual
= Incumbent
.getMethodQualifiers();
1282 bool CandidateSuperset
= CandidateQual
.compatiblyIncludes(IncumbentQual
, Ctx
);
1283 bool IncumbentSuperset
= IncumbentQual
.compatiblyIncludes(CandidateQual
, Ctx
);
1284 if (CandidateSuperset
== IncumbentSuperset
)
1285 return OverloadCompare::BothViable
;
1286 return IncumbentSuperset
? OverloadCompare::Dominates
1287 : OverloadCompare::Dominated
;
1290 bool ResultBuilder::canCxxMethodBeCalled(const CXXMethodDecl
*Method
,
1291 QualType BaseExprType
) const {
1292 // Find the class scope that we're currently in.
1293 // We could e.g. be inside a lambda, so walk up the DeclContext until we
1294 // find a CXXMethodDecl.
1295 DeclContext
*CurContext
= SemaRef
.CurContext
;
1296 const auto *CurrentClassScope
= [&]() -> const CXXRecordDecl
* {
1297 for (DeclContext
*Ctx
= CurContext
; Ctx
; Ctx
= Ctx
->getParent()) {
1298 const auto *CtxMethod
= llvm::dyn_cast
<CXXMethodDecl
>(Ctx
);
1299 if (CtxMethod
&& !CtxMethod
->getParent()->isLambda()) {
1300 return CtxMethod
->getParent();
1306 // If we're not inside the scope of the method's class, it can't be a call.
1307 bool FunctionCanBeCall
=
1308 CurrentClassScope
&&
1309 (CurrentClassScope
== Method
->getParent() ||
1310 CurrentClassScope
->isDerivedFrom(Method
->getParent()));
1312 // We skip the following calculation for exceptions if it's already true.
1313 if (FunctionCanBeCall
)
1316 // Exception: foo->FooBase::bar() or foo->Foo::bar() *is* a call.
1317 if (const CXXRecordDecl
*MaybeDerived
=
1318 BaseExprType
.isNull() ? nullptr
1319 : BaseExprType
->getAsCXXRecordDecl()) {
1320 auto *MaybeBase
= Method
->getParent();
1322 MaybeDerived
== MaybeBase
|| MaybeDerived
->isDerivedFrom(MaybeBase
);
1325 return FunctionCanBeCall
;
1328 bool ResultBuilder::canFunctionBeCalled(const NamedDecl
*ND
,
1329 QualType BaseExprType
) const {
1330 // We apply heuristics only to CCC_Symbol:
1331 // * CCC_{Arrow,Dot}MemberAccess reflect member access expressions:
1332 // f.method() and f->method(). These are always calls.
1333 // * A qualified name to a member function may *not* be a call. We have to
1334 // subdivide the cases: For example, f.Base::method(), which is regarded as
1335 // CCC_Symbol, should be a call.
1336 // * Non-member functions and static member functions are always considered
1338 if (CompletionContext
.getKind() == clang::CodeCompletionContext::CCC_Symbol
) {
1339 if (const auto *FuncTmpl
= dyn_cast
<FunctionTemplateDecl
>(ND
)) {
1340 ND
= FuncTmpl
->getTemplatedDecl();
1342 const auto *Method
= dyn_cast
<CXXMethodDecl
>(ND
);
1343 if (Method
&& !Method
->isStatic()) {
1344 return canCxxMethodBeCalled(Method
, BaseExprType
);
1350 void ResultBuilder::AddResult(Result R
, DeclContext
*CurContext
,
1351 NamedDecl
*Hiding
, bool InBaseClass
= false,
1352 QualType BaseExprType
= QualType()) {
1353 if (R
.Kind
!= Result::RK_Declaration
) {
1354 // For non-declaration results, just add the result.
1355 Results
.push_back(R
);
1359 // Look through using declarations.
1360 if (const auto *Using
= dyn_cast
<UsingShadowDecl
>(R
.Declaration
)) {
1361 CodeCompletionResult
Result(Using
->getTargetDecl(),
1362 getBasePriority(Using
->getTargetDecl()),
1364 (R
.Availability
== CXAvailability_Available
||
1365 R
.Availability
== CXAvailability_Deprecated
),
1366 std::move(R
.FixIts
));
1367 Result
.ShadowDecl
= Using
;
1368 AddResult(Result
, CurContext
, Hiding
, /*InBaseClass=*/false,
1369 /*BaseExprType=*/BaseExprType
);
1373 bool AsNestedNameSpecifier
= false;
1374 if (!isInterestingDecl(R
.Declaration
, AsNestedNameSpecifier
))
1377 // C++ constructors are never found by name lookup.
1378 if (isConstructor(R
.Declaration
))
1381 if (Hiding
&& CheckHiddenResult(R
, CurContext
, Hiding
))
1384 // Make sure that any given declaration only shows up in the result set once.
1385 if (!AllDeclsFound
.insert(R
.Declaration
->getCanonicalDecl()).second
)
1388 // If the filter is for nested-name-specifiers, then this result starts a
1389 // nested-name-specifier.
1390 if (AsNestedNameSpecifier
) {
1391 R
.StartsNestedNameSpecifier
= true;
1392 R
.Priority
= CCP_NestedNameSpecifier
;
1393 } else if (Filter
== &ResultBuilder::IsMember
&& !R
.Qualifier
&&
1396 R
.Declaration
->getDeclContext()->getRedeclContext()))
1397 R
.QualifierIsInformative
= true;
1399 // If this result is supposed to have an informative qualifier, add one.
1400 if (R
.QualifierIsInformative
&& !R
.Qualifier
&&
1401 !R
.StartsNestedNameSpecifier
) {
1402 const DeclContext
*Ctx
= R
.Declaration
->getDeclContext();
1403 if (const auto *Namespace
= dyn_cast
<NamespaceDecl
>(Ctx
))
1405 NestedNameSpecifier::Create(SemaRef
.Context
, nullptr, Namespace
);
1406 else if (const auto *Tag
= dyn_cast
<TagDecl
>(Ctx
))
1407 R
.Qualifier
= NestedNameSpecifier::Create(
1408 SemaRef
.Context
, nullptr, false,
1409 SemaRef
.Context
.getTypeDeclType(Tag
).getTypePtr());
1411 R
.QualifierIsInformative
= false;
1414 // Adjust the priority if this result comes from a base class.
1418 AdjustResultPriorityForDecl(R
);
1420 if (HasObjectTypeQualifiers
)
1421 if (const auto *Method
= dyn_cast
<CXXMethodDecl
>(R
.Declaration
))
1422 if (Method
->isInstance()) {
1423 Qualifiers MethodQuals
= Method
->getMethodQualifiers();
1424 if (ObjectTypeQualifiers
== MethodQuals
)
1425 R
.Priority
+= CCD_ObjectQualifierMatch
;
1426 else if (ObjectTypeQualifiers
- MethodQuals
) {
1427 // The method cannot be invoked, because doing so would drop
1431 // Detect cases where a ref-qualified method cannot be invoked.
1432 switch (Method
->getRefQualifier()) {
1434 if (ObjectKind
!= VK_LValue
&& !MethodQuals
.hasConst())
1438 if (ObjectKind
== VK_LValue
)
1445 /// Check whether this dominates another overloaded method, which should
1446 /// be suppressed (or vice versa).
1447 /// Motivating case is const_iterator begin() const vs iterator begin().
1448 auto &OverloadSet
= OverloadMap
[std::make_pair(
1449 CurContext
, Method
->getDeclName().getAsOpaqueInteger())];
1450 for (const DeclIndexPair Entry
: OverloadSet
) {
1451 Result
&Incumbent
= Results
[Entry
.second
];
1452 switch (compareOverloads(*Method
,
1453 *cast
<CXXMethodDecl
>(Incumbent
.Declaration
),
1454 ObjectTypeQualifiers
, ObjectKind
,
1455 CurContext
->getParentASTContext())) {
1456 case OverloadCompare::Dominates
:
1457 // Replace the dominated overload with this one.
1458 // FIXME: if the overload dominates multiple incumbents then we
1459 // should remove all. But two overloads is by far the common case.
1460 Incumbent
= std::move(R
);
1462 case OverloadCompare::Dominated
:
1463 // This overload can't be called, drop it.
1465 case OverloadCompare::BothViable
:
1469 OverloadSet
.Add(Method
, Results
.size());
1472 R
.FunctionCanBeCall
= canFunctionBeCalled(R
.getDeclaration(), BaseExprType
);
1474 // Insert this result into the set of results.
1475 Results
.push_back(R
);
1477 if (!AsNestedNameSpecifier
)
1478 MaybeAddConstructorResults(R
);
1481 void ResultBuilder::AddResult(Result R
) {
1482 assert(R
.Kind
!= Result::RK_Declaration
&&
1483 "Declaration results need more context");
1484 Results
.push_back(R
);
1487 /// Enter into a new scope.
1488 void ResultBuilder::EnterNewScope() { ShadowMaps
.emplace_back(); }
1490 /// Exit from the current scope.
1491 void ResultBuilder::ExitScope() {
1492 ShadowMaps
.pop_back();
1495 /// Determines whether this given declaration will be found by
1496 /// ordinary name lookup.
1497 bool ResultBuilder::IsOrdinaryName(const NamedDecl
*ND
) const {
1498 ND
= ND
->getUnderlyingDecl();
1500 // If name lookup finds a local extern declaration, then we are in a
1501 // context where it behaves like an ordinary name.
1502 unsigned IDNS
= Decl::IDNS_Ordinary
| Decl::IDNS_LocalExtern
;
1503 if (SemaRef
.getLangOpts().CPlusPlus
)
1504 IDNS
|= Decl::IDNS_Tag
| Decl::IDNS_Namespace
| Decl::IDNS_Member
;
1505 else if (SemaRef
.getLangOpts().ObjC
) {
1506 if (isa
<ObjCIvarDecl
>(ND
))
1510 return ND
->getIdentifierNamespace() & IDNS
;
1513 /// Determines whether this given declaration will be found by
1514 /// ordinary name lookup but is not a type name.
1515 bool ResultBuilder::IsOrdinaryNonTypeName(const NamedDecl
*ND
) const {
1516 ND
= ND
->getUnderlyingDecl();
1517 if (isa
<TypeDecl
>(ND
))
1519 // Objective-C interfaces names are not filtered by this method because they
1520 // can be used in a class property expression. We can still filter out
1521 // @class declarations though.
1522 if (const auto *ID
= dyn_cast
<ObjCInterfaceDecl
>(ND
)) {
1523 if (!ID
->getDefinition())
1527 unsigned IDNS
= Decl::IDNS_Ordinary
| Decl::IDNS_LocalExtern
;
1528 if (SemaRef
.getLangOpts().CPlusPlus
)
1529 IDNS
|= Decl::IDNS_Tag
| Decl::IDNS_Namespace
| Decl::IDNS_Member
;
1530 else if (SemaRef
.getLangOpts().ObjC
) {
1531 if (isa
<ObjCIvarDecl
>(ND
))
1535 return ND
->getIdentifierNamespace() & IDNS
;
1538 bool ResultBuilder::IsIntegralConstantValue(const NamedDecl
*ND
) const {
1539 if (!IsOrdinaryNonTypeName(ND
))
1542 if (const auto *VD
= dyn_cast
<ValueDecl
>(ND
->getUnderlyingDecl()))
1543 if (VD
->getType()->isIntegralOrEnumerationType())
1549 /// Determines whether this given declaration will be found by
1550 /// ordinary name lookup.
1551 bool ResultBuilder::IsOrdinaryNonValueName(const NamedDecl
*ND
) const {
1552 ND
= ND
->getUnderlyingDecl();
1554 unsigned IDNS
= Decl::IDNS_Ordinary
| Decl::IDNS_LocalExtern
;
1555 if (SemaRef
.getLangOpts().CPlusPlus
)
1556 IDNS
|= Decl::IDNS_Tag
| Decl::IDNS_Namespace
;
1558 return (ND
->getIdentifierNamespace() & IDNS
) && !isa
<ValueDecl
>(ND
) &&
1559 !isa
<FunctionTemplateDecl
>(ND
) && !isa
<ObjCPropertyDecl
>(ND
);
1562 /// Determines whether the given declaration is suitable as the
1563 /// start of a C++ nested-name-specifier, e.g., a class or namespace.
1564 bool ResultBuilder::IsNestedNameSpecifier(const NamedDecl
*ND
) const {
1565 // Allow us to find class templates, too.
1566 if (const auto *ClassTemplate
= dyn_cast
<ClassTemplateDecl
>(ND
))
1567 ND
= ClassTemplate
->getTemplatedDecl();
1569 return SemaRef
.isAcceptableNestedNameSpecifier(ND
);
1572 /// Determines whether the given declaration is an enumeration.
1573 bool ResultBuilder::IsEnum(const NamedDecl
*ND
) const {
1574 return isa
<EnumDecl
>(ND
);
1577 /// Determines whether the given declaration is a class or struct.
1578 bool ResultBuilder::IsClassOrStruct(const NamedDecl
*ND
) const {
1579 // Allow us to find class templates, too.
1580 if (const auto *ClassTemplate
= dyn_cast
<ClassTemplateDecl
>(ND
))
1581 ND
= ClassTemplate
->getTemplatedDecl();
1583 // For purposes of this check, interfaces match too.
1584 if (const auto *RD
= dyn_cast
<RecordDecl
>(ND
))
1585 return RD
->getTagKind() == TagTypeKind::Class
||
1586 RD
->getTagKind() == TagTypeKind::Struct
||
1587 RD
->getTagKind() == TagTypeKind::Interface
;
1592 /// Determines whether the given declaration is a union.
1593 bool ResultBuilder::IsUnion(const NamedDecl
*ND
) const {
1594 // Allow us to find class templates, too.
1595 if (const auto *ClassTemplate
= dyn_cast
<ClassTemplateDecl
>(ND
))
1596 ND
= ClassTemplate
->getTemplatedDecl();
1598 if (const auto *RD
= dyn_cast
<RecordDecl
>(ND
))
1599 return RD
->getTagKind() == TagTypeKind::Union
;
1604 /// Determines whether the given declaration is a namespace.
1605 bool ResultBuilder::IsNamespace(const NamedDecl
*ND
) const {
1606 return isa
<NamespaceDecl
>(ND
);
1609 /// Determines whether the given declaration is a namespace or
1610 /// namespace alias.
1611 bool ResultBuilder::IsNamespaceOrAlias(const NamedDecl
*ND
) const {
1612 return isa
<NamespaceDecl
>(ND
->getUnderlyingDecl());
1615 /// Determines whether the given declaration is a type.
1616 bool ResultBuilder::IsType(const NamedDecl
*ND
) const {
1617 ND
= ND
->getUnderlyingDecl();
1618 return isa
<TypeDecl
>(ND
) || isa
<ObjCInterfaceDecl
>(ND
);
1621 /// Determines which members of a class should be visible via
1622 /// "." or "->". Only value declarations, nested name specifiers, and
1623 /// using declarations thereof should show up.
1624 bool ResultBuilder::IsMember(const NamedDecl
*ND
) const {
1625 ND
= ND
->getUnderlyingDecl();
1626 return isa
<ValueDecl
>(ND
) || isa
<FunctionTemplateDecl
>(ND
) ||
1627 isa
<ObjCPropertyDecl
>(ND
);
1630 static bool isObjCReceiverType(ASTContext
&C
, QualType T
) {
1631 T
= C
.getCanonicalType(T
);
1632 switch (T
->getTypeClass()) {
1633 case Type::ObjCObject
:
1634 case Type::ObjCInterface
:
1635 case Type::ObjCObjectPointer
:
1639 switch (cast
<BuiltinType
>(T
)->getKind()) {
1640 case BuiltinType::ObjCId
:
1641 case BuiltinType::ObjCClass
:
1642 case BuiltinType::ObjCSel
:
1654 if (!C
.getLangOpts().CPlusPlus
)
1657 // FIXME: We could perform more analysis here to determine whether a
1658 // particular class type has any conversions to Objective-C types. For now,
1659 // just accept all class types.
1660 return T
->isDependentType() || T
->isRecordType();
1663 bool ResultBuilder::IsObjCMessageReceiver(const NamedDecl
*ND
) const {
1664 QualType T
= getDeclUsageType(SemaRef
.Context
, ND
);
1668 T
= SemaRef
.Context
.getBaseElementType(T
);
1669 return isObjCReceiverType(SemaRef
.Context
, T
);
1672 bool ResultBuilder::IsObjCMessageReceiverOrLambdaCapture(
1673 const NamedDecl
*ND
) const {
1674 if (IsObjCMessageReceiver(ND
))
1677 const auto *Var
= dyn_cast
<VarDecl
>(ND
);
1681 return Var
->hasLocalStorage() && !Var
->hasAttr
<BlocksAttr
>();
1684 bool ResultBuilder::IsObjCCollection(const NamedDecl
*ND
) const {
1685 if ((SemaRef
.getLangOpts().CPlusPlus
&& !IsOrdinaryName(ND
)) ||
1686 (!SemaRef
.getLangOpts().CPlusPlus
&& !IsOrdinaryNonTypeName(ND
)))
1689 QualType T
= getDeclUsageType(SemaRef
.Context
, ND
);
1693 T
= SemaRef
.Context
.getBaseElementType(T
);
1694 return T
->isObjCObjectType() || T
->isObjCObjectPointerType() ||
1695 T
->isObjCIdType() ||
1696 (SemaRef
.getLangOpts().CPlusPlus
&& T
->isRecordType());
1699 bool ResultBuilder::IsImpossibleToSatisfy(const NamedDecl
*ND
) const {
1703 /// Determines whether the given declaration is an Objective-C
1704 /// instance variable.
1705 bool ResultBuilder::IsObjCIvar(const NamedDecl
*ND
) const {
1706 return isa
<ObjCIvarDecl
>(ND
);
1711 /// Visible declaration consumer that adds a code-completion result
1712 /// for each visible declaration.
1713 class CodeCompletionDeclConsumer
: public VisibleDeclConsumer
{
1714 ResultBuilder
&Results
;
1715 DeclContext
*InitialLookupCtx
;
1716 // NamingClass and BaseType are used for access-checking. See
1717 // Sema::IsSimplyAccessible for details.
1718 CXXRecordDecl
*NamingClass
;
1720 std::vector
<FixItHint
> FixIts
;
1723 CodeCompletionDeclConsumer(
1724 ResultBuilder
&Results
, DeclContext
*InitialLookupCtx
,
1725 QualType BaseType
= QualType(),
1726 std::vector
<FixItHint
> FixIts
= std::vector
<FixItHint
>())
1727 : Results(Results
), InitialLookupCtx(InitialLookupCtx
),
1728 FixIts(std::move(FixIts
)) {
1729 NamingClass
= llvm::dyn_cast
<CXXRecordDecl
>(InitialLookupCtx
);
1730 // If BaseType was not provided explicitly, emulate implicit 'this->'.
1731 if (BaseType
.isNull()) {
1732 auto ThisType
= Results
.getSema().getCurrentThisType();
1733 if (!ThisType
.isNull()) {
1734 assert(ThisType
->isPointerType());
1735 BaseType
= ThisType
->getPointeeType();
1737 NamingClass
= BaseType
->getAsCXXRecordDecl();
1740 this->BaseType
= BaseType
;
1743 void FoundDecl(NamedDecl
*ND
, NamedDecl
*Hiding
, DeclContext
*Ctx
,
1744 bool InBaseClass
) override
{
1745 ResultBuilder::Result
Result(ND
, Results
.getBasePriority(ND
), nullptr,
1746 false, IsAccessible(ND
, Ctx
), FixIts
);
1747 Results
.AddResult(Result
, InitialLookupCtx
, Hiding
, InBaseClass
, BaseType
);
1750 void EnteredContext(DeclContext
*Ctx
) override
{
1751 Results
.addVisitedContext(Ctx
);
1755 bool IsAccessible(NamedDecl
*ND
, DeclContext
*Ctx
) {
1756 // Naming class to use for access check. In most cases it was provided
1757 // explicitly (e.g. member access (lhs.foo) or qualified lookup (X::)),
1758 // for unqualified lookup we fallback to the \p Ctx in which we found the
1760 auto *NamingClass
= this->NamingClass
;
1761 QualType BaseType
= this->BaseType
;
1762 if (auto *Cls
= llvm::dyn_cast_or_null
<CXXRecordDecl
>(Ctx
)) {
1765 // When we emulate implicit 'this->' in an unqualified lookup, we might
1766 // end up with an invalid naming class. In that case, we avoid emulating
1767 // 'this->' qualifier to satisfy preconditions of the access checking.
1768 if (NamingClass
->getCanonicalDecl() != Cls
->getCanonicalDecl() &&
1769 !NamingClass
->isDerivedFrom(Cls
)) {
1771 BaseType
= QualType();
1774 // The decl was found outside the C++ class, so only ObjC access checks
1775 // apply. Those do not rely on NamingClass and BaseType, so we clear them
1777 NamingClass
= nullptr;
1778 BaseType
= QualType();
1780 return Results
.getSema().IsSimplyAccessible(ND
, NamingClass
, BaseType
);
1785 /// Add type specifiers for the current language as keyword results.
1786 static void AddTypeSpecifierResults(const LangOptions
&LangOpts
,
1787 ResultBuilder
&Results
) {
1788 typedef CodeCompletionResult Result
;
1789 Results
.AddResult(Result("short", CCP_Type
));
1790 Results
.AddResult(Result("long", CCP_Type
));
1791 Results
.AddResult(Result("signed", CCP_Type
));
1792 Results
.AddResult(Result("unsigned", CCP_Type
));
1793 Results
.AddResult(Result("void", CCP_Type
));
1794 Results
.AddResult(Result("char", CCP_Type
));
1795 Results
.AddResult(Result("int", CCP_Type
));
1796 Results
.AddResult(Result("float", CCP_Type
));
1797 Results
.AddResult(Result("double", CCP_Type
));
1798 Results
.AddResult(Result("enum", CCP_Type
));
1799 Results
.AddResult(Result("struct", CCP_Type
));
1800 Results
.AddResult(Result("union", CCP_Type
));
1801 Results
.AddResult(Result("const", CCP_Type
));
1802 Results
.AddResult(Result("volatile", CCP_Type
));
1806 Results
.AddResult(Result("_Complex", CCP_Type
));
1808 Results
.AddResult(Result("_Imaginary", CCP_Type
));
1809 Results
.AddResult(Result("_Bool", CCP_Type
));
1810 Results
.AddResult(Result("restrict", CCP_Type
));
1813 CodeCompletionBuilder
Builder(Results
.getAllocator(),
1814 Results
.getCodeCompletionTUInfo());
1815 if (LangOpts
.CPlusPlus
) {
1818 Result("bool", CCP_Type
+ (LangOpts
.ObjC
? CCD_bool_in_ObjC
: 0)));
1819 Results
.AddResult(Result("class", CCP_Type
));
1820 Results
.AddResult(Result("wchar_t", CCP_Type
));
1823 Builder
.AddTypedTextChunk("typename");
1824 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
1825 Builder
.AddPlaceholderChunk("name");
1826 Results
.AddResult(Result(Builder
.TakeString()));
1828 if (LangOpts
.CPlusPlus11
) {
1829 Results
.AddResult(Result("auto", CCP_Type
));
1830 Results
.AddResult(Result("char16_t", CCP_Type
));
1831 Results
.AddResult(Result("char32_t", CCP_Type
));
1833 Builder
.AddTypedTextChunk("decltype");
1834 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
1835 Builder
.AddPlaceholderChunk("expression");
1836 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
1837 Results
.AddResult(Result(Builder
.TakeString()));
1840 if (LangOpts
.Char8
|| LangOpts
.CPlusPlus20
)
1841 Results
.AddResult(Result("char8_t", CCP_Type
));
1843 Results
.AddResult(Result("__auto_type", CCP_Type
));
1846 if (LangOpts
.GNUKeywords
) {
1847 // FIXME: Enable when we actually support decimal floating point.
1848 // Results.AddResult(Result("_Decimal32"));
1849 // Results.AddResult(Result("_Decimal64"));
1850 // Results.AddResult(Result("_Decimal128"));
1852 Builder
.AddTypedTextChunk("typeof");
1853 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
1854 Builder
.AddPlaceholderChunk("expression");
1855 Results
.AddResult(Result(Builder
.TakeString()));
1857 Builder
.AddTypedTextChunk("typeof");
1858 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
1859 Builder
.AddPlaceholderChunk("type");
1860 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
1861 Results
.AddResult(Result(Builder
.TakeString()));
1865 Results
.AddResult(Result("_Nonnull", CCP_Type
));
1866 Results
.AddResult(Result("_Null_unspecified", CCP_Type
));
1867 Results
.AddResult(Result("_Nullable", CCP_Type
));
1871 AddStorageSpecifiers(SemaCodeCompletion::ParserCompletionContext CCC
,
1872 const LangOptions
&LangOpts
, ResultBuilder
&Results
) {
1873 typedef CodeCompletionResult Result
;
1874 // Note: we don't suggest either "auto" or "register", because both
1875 // are pointless as storage specifiers. Elsewhere, we suggest "auto"
1876 // in C++0x as a type specifier.
1877 Results
.AddResult(Result("extern"));
1878 Results
.AddResult(Result("static"));
1880 if (LangOpts
.CPlusPlus11
) {
1881 CodeCompletionAllocator
&Allocator
= Results
.getAllocator();
1882 CodeCompletionBuilder
Builder(Allocator
, Results
.getCodeCompletionTUInfo());
1885 Builder
.AddTypedTextChunk("alignas");
1886 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
1887 Builder
.AddPlaceholderChunk("expression");
1888 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
1889 Results
.AddResult(Result(Builder
.TakeString()));
1891 Results
.AddResult(Result("constexpr"));
1892 Results
.AddResult(Result("thread_local"));
1895 if (LangOpts
.CPlusPlus20
)
1896 Results
.AddResult(Result("constinit"));
1900 AddFunctionSpecifiers(SemaCodeCompletion::ParserCompletionContext CCC
,
1901 const LangOptions
&LangOpts
, ResultBuilder
&Results
) {
1902 typedef CodeCompletionResult Result
;
1904 case SemaCodeCompletion::PCC_Class
:
1905 case SemaCodeCompletion::PCC_MemberTemplate
:
1906 if (LangOpts
.CPlusPlus
) {
1907 Results
.AddResult(Result("explicit"));
1908 Results
.AddResult(Result("friend"));
1909 Results
.AddResult(Result("mutable"));
1910 Results
.AddResult(Result("virtual"));
1914 case SemaCodeCompletion::PCC_ObjCInterface
:
1915 case SemaCodeCompletion::PCC_ObjCImplementation
:
1916 case SemaCodeCompletion::PCC_Namespace
:
1917 case SemaCodeCompletion::PCC_Template
:
1918 if (LangOpts
.CPlusPlus
|| LangOpts
.C99
)
1919 Results
.AddResult(Result("inline"));
1921 if (LangOpts
.CPlusPlus20
)
1922 Results
.AddResult(Result("consteval"));
1925 case SemaCodeCompletion::PCC_ObjCInstanceVariableList
:
1926 case SemaCodeCompletion::PCC_Expression
:
1927 case SemaCodeCompletion::PCC_Statement
:
1928 case SemaCodeCompletion::PCC_TopLevelOrExpression
:
1929 case SemaCodeCompletion::PCC_ForInit
:
1930 case SemaCodeCompletion::PCC_Condition
:
1931 case SemaCodeCompletion::PCC_RecoveryInFunction
:
1932 case SemaCodeCompletion::PCC_Type
:
1933 case SemaCodeCompletion::PCC_ParenthesizedExpression
:
1934 case SemaCodeCompletion::PCC_LocalDeclarationSpecifiers
:
1939 static void AddObjCExpressionResults(ResultBuilder
&Results
, bool NeedAt
);
1940 static void AddObjCStatementResults(ResultBuilder
&Results
, bool NeedAt
);
1941 static void AddObjCVisibilityResults(const LangOptions
&LangOpts
,
1942 ResultBuilder
&Results
, bool NeedAt
);
1943 static void AddObjCImplementationResults(const LangOptions
&LangOpts
,
1944 ResultBuilder
&Results
, bool NeedAt
);
1945 static void AddObjCInterfaceResults(const LangOptions
&LangOpts
,
1946 ResultBuilder
&Results
, bool NeedAt
);
1947 static void AddObjCTopLevelResults(ResultBuilder
&Results
, bool NeedAt
);
1949 static void AddTypedefResult(ResultBuilder
&Results
) {
1950 CodeCompletionBuilder
Builder(Results
.getAllocator(),
1951 Results
.getCodeCompletionTUInfo());
1952 Builder
.AddTypedTextChunk("typedef");
1953 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
1954 Builder
.AddPlaceholderChunk("type");
1955 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
1956 Builder
.AddPlaceholderChunk("name");
1957 Builder
.AddChunk(CodeCompletionString::CK_SemiColon
);
1958 Results
.AddResult(CodeCompletionResult(Builder
.TakeString()));
1961 // using name = type
1962 static void AddUsingAliasResult(CodeCompletionBuilder
&Builder
,
1963 ResultBuilder
&Results
) {
1964 Builder
.AddTypedTextChunk("using");
1965 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
1966 Builder
.AddPlaceholderChunk("name");
1967 Builder
.AddChunk(CodeCompletionString::CK_Equal
);
1968 Builder
.AddPlaceholderChunk("type");
1969 Builder
.AddChunk(CodeCompletionString::CK_SemiColon
);
1970 Results
.AddResult(CodeCompletionResult(Builder
.TakeString()));
1973 static bool WantTypesInContext(SemaCodeCompletion::ParserCompletionContext CCC
,
1974 const LangOptions
&LangOpts
) {
1976 case SemaCodeCompletion::PCC_Namespace
:
1977 case SemaCodeCompletion::PCC_Class
:
1978 case SemaCodeCompletion::PCC_ObjCInstanceVariableList
:
1979 case SemaCodeCompletion::PCC_Template
:
1980 case SemaCodeCompletion::PCC_MemberTemplate
:
1981 case SemaCodeCompletion::PCC_Statement
:
1982 case SemaCodeCompletion::PCC_RecoveryInFunction
:
1983 case SemaCodeCompletion::PCC_Type
:
1984 case SemaCodeCompletion::PCC_ParenthesizedExpression
:
1985 case SemaCodeCompletion::PCC_LocalDeclarationSpecifiers
:
1986 case SemaCodeCompletion::PCC_TopLevelOrExpression
:
1989 case SemaCodeCompletion::PCC_Expression
:
1990 case SemaCodeCompletion::PCC_Condition
:
1991 return LangOpts
.CPlusPlus
;
1993 case SemaCodeCompletion::PCC_ObjCInterface
:
1994 case SemaCodeCompletion::PCC_ObjCImplementation
:
1997 case SemaCodeCompletion::PCC_ForInit
:
1998 return LangOpts
.CPlusPlus
|| LangOpts
.ObjC
|| LangOpts
.C99
;
2001 llvm_unreachable("Invalid ParserCompletionContext!");
2004 static PrintingPolicy
getCompletionPrintingPolicy(const ASTContext
&Context
,
2005 const Preprocessor
&PP
) {
2006 PrintingPolicy Policy
= Sema::getPrintingPolicy(Context
, PP
);
2007 Policy
.AnonymousTagLocations
= false;
2008 Policy
.SuppressStrongLifetime
= true;
2009 Policy
.SuppressUnwrittenScope
= true;
2010 Policy
.SuppressScope
= true;
2011 Policy
.CleanUglifiedParameters
= true;
2015 /// Retrieve a printing policy suitable for code completion.
2016 static PrintingPolicy
getCompletionPrintingPolicy(Sema
&S
) {
2017 return getCompletionPrintingPolicy(S
.Context
, S
.PP
);
2020 /// Retrieve the string representation of the given type as a string
2021 /// that has the appropriate lifetime for code completion.
2023 /// This routine provides a fast path where we provide constant strings for
2024 /// common type names.
2025 static const char *GetCompletionTypeString(QualType T
, ASTContext
&Context
,
2026 const PrintingPolicy
&Policy
,
2027 CodeCompletionAllocator
&Allocator
) {
2028 if (!T
.getLocalQualifiers()) {
2029 // Built-in type names are constant strings.
2030 if (const BuiltinType
*BT
= dyn_cast
<BuiltinType
>(T
))
2031 return BT
->getNameAsCString(Policy
);
2033 // Anonymous tag types are constant strings.
2034 if (const TagType
*TagT
= dyn_cast
<TagType
>(T
))
2035 if (TagDecl
*Tag
= TagT
->getDecl())
2036 if (!Tag
->hasNameForLinkage()) {
2037 switch (Tag
->getTagKind()) {
2038 case TagTypeKind::Struct
:
2039 return "struct <anonymous>";
2040 case TagTypeKind::Interface
:
2041 return "__interface <anonymous>";
2042 case TagTypeKind::Class
:
2043 return "class <anonymous>";
2044 case TagTypeKind::Union
:
2045 return "union <anonymous>";
2046 case TagTypeKind::Enum
:
2047 return "enum <anonymous>";
2052 // Slow path: format the type as a string.
2054 T
.getAsStringInternal(Result
, Policy
);
2055 return Allocator
.CopyString(Result
);
2058 /// Add a completion for "this", if we're in a member function.
2059 static void addThisCompletion(Sema
&S
, ResultBuilder
&Results
) {
2060 QualType ThisTy
= S
.getCurrentThisType();
2061 if (ThisTy
.isNull())
2064 CodeCompletionAllocator
&Allocator
= Results
.getAllocator();
2065 CodeCompletionBuilder
Builder(Allocator
, Results
.getCodeCompletionTUInfo());
2066 PrintingPolicy Policy
= getCompletionPrintingPolicy(S
);
2067 Builder
.AddResultTypeChunk(
2068 GetCompletionTypeString(ThisTy
, S
.Context
, Policy
, Allocator
));
2069 Builder
.AddTypedTextChunk("this");
2070 Results
.AddResult(CodeCompletionResult(Builder
.TakeString()));
2073 static void AddStaticAssertResult(CodeCompletionBuilder
&Builder
,
2074 ResultBuilder
&Results
,
2075 const LangOptions
&LangOpts
) {
2076 if (!LangOpts
.CPlusPlus11
)
2079 Builder
.AddTypedTextChunk("static_assert");
2080 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
2081 Builder
.AddPlaceholderChunk("expression");
2082 Builder
.AddChunk(CodeCompletionString::CK_Comma
);
2083 Builder
.AddPlaceholderChunk("message");
2084 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
2085 Builder
.AddChunk(CodeCompletionString::CK_SemiColon
);
2086 Results
.AddResult(CodeCompletionResult(Builder
.TakeString()));
2089 static void AddOverrideResults(ResultBuilder
&Results
,
2090 const CodeCompletionContext
&CCContext
,
2091 CodeCompletionBuilder
&Builder
) {
2092 Sema
&S
= Results
.getSema();
2093 const auto *CR
= llvm::dyn_cast
<CXXRecordDecl
>(S
.CurContext
);
2094 // If not inside a class/struct/union return empty.
2097 // First store overrides within current class.
2098 // These are stored by name to make querying fast in the later step.
2099 llvm::StringMap
<std::vector
<FunctionDecl
*>> Overrides
;
2100 for (auto *Method
: CR
->methods()) {
2101 if (!Method
->isVirtual() || !Method
->getIdentifier())
2103 Overrides
[Method
->getName()].push_back(Method
);
2106 for (const auto &Base
: CR
->bases()) {
2107 const auto *BR
= Base
.getType().getTypePtr()->getAsCXXRecordDecl();
2110 for (auto *Method
: BR
->methods()) {
2111 if (!Method
->isVirtual() || !Method
->getIdentifier())
2113 const auto it
= Overrides
.find(Method
->getName());
2114 bool IsOverriden
= false;
2115 if (it
!= Overrides
.end()) {
2116 for (auto *MD
: it
->second
) {
2117 // If the method in current body is not an overload of this virtual
2118 // function, then it overrides this one.
2119 if (!S
.IsOverload(MD
, Method
, false)) {
2126 // Generates a new CodeCompletionResult by taking this function and
2127 // converting it into an override declaration with only one chunk in the
2128 // final CodeCompletionString as a TypedTextChunk.
2129 CodeCompletionResult
CCR(Method
, 0);
2130 PrintingPolicy Policy
=
2131 getCompletionPrintingPolicy(S
.getASTContext(), S
.getPreprocessor());
2132 auto *CCS
= CCR
.createCodeCompletionStringForOverride(
2133 S
.getPreprocessor(), S
.getASTContext(), Builder
,
2134 /*IncludeBriefComments=*/false, CCContext
, Policy
);
2135 Results
.AddResult(CodeCompletionResult(CCS
, Method
, CCP_CodePattern
));
2141 /// Add language constructs that show up for "ordinary" names.
2143 AddOrdinaryNameResults(SemaCodeCompletion::ParserCompletionContext CCC
,
2144 Scope
*S
, Sema
&SemaRef
, ResultBuilder
&Results
) {
2145 CodeCompletionAllocator
&Allocator
= Results
.getAllocator();
2146 CodeCompletionBuilder
Builder(Allocator
, Results
.getCodeCompletionTUInfo());
2148 typedef CodeCompletionResult Result
;
2150 case SemaCodeCompletion::PCC_Namespace
:
2151 if (SemaRef
.getLangOpts().CPlusPlus
) {
2152 if (Results
.includeCodePatterns()) {
2153 // namespace <identifier> { declarations }
2154 Builder
.AddTypedTextChunk("namespace");
2155 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2156 Builder
.AddPlaceholderChunk("identifier");
2157 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2158 Builder
.AddChunk(CodeCompletionString::CK_LeftBrace
);
2159 Builder
.AddChunk(CodeCompletionString::CK_VerticalSpace
);
2160 Builder
.AddPlaceholderChunk("declarations");
2161 Builder
.AddChunk(CodeCompletionString::CK_VerticalSpace
);
2162 Builder
.AddChunk(CodeCompletionString::CK_RightBrace
);
2163 Results
.AddResult(Result(Builder
.TakeString()));
2166 // namespace identifier = identifier ;
2167 Builder
.AddTypedTextChunk("namespace");
2168 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2169 Builder
.AddPlaceholderChunk("name");
2170 Builder
.AddChunk(CodeCompletionString::CK_Equal
);
2171 Builder
.AddPlaceholderChunk("namespace");
2172 Builder
.AddChunk(CodeCompletionString::CK_SemiColon
);
2173 Results
.AddResult(Result(Builder
.TakeString()));
2176 Builder
.AddTypedTextChunk("using namespace");
2177 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2178 Builder
.AddPlaceholderChunk("identifier");
2179 Builder
.AddChunk(CodeCompletionString::CK_SemiColon
);
2180 Results
.AddResult(Result(Builder
.TakeString()));
2182 // asm(string-literal)
2183 Builder
.AddTypedTextChunk("asm");
2184 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
2185 Builder
.AddPlaceholderChunk("string-literal");
2186 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
2187 Results
.AddResult(Result(Builder
.TakeString()));
2189 if (Results
.includeCodePatterns()) {
2190 // Explicit template instantiation
2191 Builder
.AddTypedTextChunk("template");
2192 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2193 Builder
.AddPlaceholderChunk("declaration");
2194 Results
.AddResult(Result(Builder
.TakeString()));
2196 Results
.AddResult(Result("template", CodeCompletionResult::RK_Keyword
));
2199 if (SemaRef
.getLangOpts().CPlusPlus20
&&
2200 SemaRef
.getLangOpts().CPlusPlusModules
) {
2201 clang::Module
*CurrentModule
= SemaRef
.getCurrentModule();
2202 if (SemaRef
.CurContext
->isTranslationUnit()) {
2203 /// Global module fragment can only be declared in the beginning of
2204 /// the file. CurrentModule should be null in this case.
2205 if (!CurrentModule
) {
2207 Builder
.AddTypedTextChunk("module");
2208 Builder
.AddChunk(CodeCompletionString::CK_SemiColon
);
2209 Builder
.AddChunk(CodeCompletionString::CK_VerticalSpace
);
2210 Results
.AddResult(Result(Builder
.TakeString()));
2213 /// Named module should be declared in the beginning of the file,
2214 /// or after the global module fragment.
2215 if (!CurrentModule
||
2216 CurrentModule
->Kind
== Module::ExplicitGlobalModuleFragment
||
2217 CurrentModule
->Kind
== Module::ImplicitGlobalModuleFragment
) {
2220 Builder
.AddTypedTextChunk("module");
2221 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2222 Builder
.AddPlaceholderChunk("name");
2223 Builder
.AddChunk(CodeCompletionString::CK_SemiColon
);
2224 Builder
.AddChunk(CodeCompletionString::CK_VerticalSpace
);
2225 Results
.AddResult(Result(Builder
.TakeString()));
2228 /// Import can occur in non module file or after the named module
2230 if (!CurrentModule
||
2231 CurrentModule
->Kind
== Module::ModuleInterfaceUnit
||
2232 CurrentModule
->Kind
== Module::ModulePartitionInterface
) {
2234 Builder
.AddTypedTextChunk("import");
2235 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2236 Builder
.AddPlaceholderChunk("name");
2237 Builder
.AddChunk(CodeCompletionString::CK_SemiColon
);
2238 Builder
.AddChunk(CodeCompletionString::CK_VerticalSpace
);
2239 Results
.AddResult(Result(Builder
.TakeString()));
2242 if (CurrentModule
&&
2243 (CurrentModule
->Kind
== Module::ModuleInterfaceUnit
||
2244 CurrentModule
->Kind
== Module::ModulePartitionInterface
)) {
2246 Builder
.AddTypedTextChunk("module");
2247 Builder
.AddChunk(CodeCompletionString::CK_Colon
);
2248 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2249 Builder
.AddTypedTextChunk("private");
2250 Builder
.AddChunk(CodeCompletionString::CK_SemiColon
);
2251 Builder
.AddChunk(CodeCompletionString::CK_VerticalSpace
);
2252 Results
.AddResult(Result(Builder
.TakeString()));
2257 if (!CurrentModule
||
2258 CurrentModule
->Kind
!= Module::ModuleKind::PrivateModuleFragment
)
2259 Results
.AddResult(Result("export", CodeCompletionResult::RK_Keyword
));
2263 if (SemaRef
.getLangOpts().ObjC
)
2264 AddObjCTopLevelResults(Results
, true);
2266 AddTypedefResult(Results
);
2269 case SemaCodeCompletion::PCC_Class
:
2270 if (SemaRef
.getLangOpts().CPlusPlus
) {
2271 // Using declaration
2272 Builder
.AddTypedTextChunk("using");
2273 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2274 Builder
.AddPlaceholderChunk("qualifier");
2275 Builder
.AddTextChunk("::");
2276 Builder
.AddPlaceholderChunk("name");
2277 Builder
.AddChunk(CodeCompletionString::CK_SemiColon
);
2278 Results
.AddResult(Result(Builder
.TakeString()));
2280 if (SemaRef
.getLangOpts().CPlusPlus11
)
2281 AddUsingAliasResult(Builder
, Results
);
2283 // using typename qualifier::name (only in a dependent context)
2284 if (SemaRef
.CurContext
->isDependentContext()) {
2285 Builder
.AddTypedTextChunk("using typename");
2286 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2287 Builder
.AddPlaceholderChunk("qualifier");
2288 Builder
.AddTextChunk("::");
2289 Builder
.AddPlaceholderChunk("name");
2290 Builder
.AddChunk(CodeCompletionString::CK_SemiColon
);
2291 Results
.AddResult(Result(Builder
.TakeString()));
2294 AddStaticAssertResult(Builder
, Results
, SemaRef
.getLangOpts());
2296 if (CCC
== SemaCodeCompletion::PCC_Class
) {
2297 AddTypedefResult(Results
);
2299 bool IsNotInheritanceScope
= !S
->isClassInheritanceScope();
2301 Builder
.AddTypedTextChunk("public");
2302 if (IsNotInheritanceScope
&& Results
.includeCodePatterns())
2303 Builder
.AddChunk(CodeCompletionString::CK_Colon
);
2304 Results
.AddResult(Result(Builder
.TakeString()));
2307 Builder
.AddTypedTextChunk("protected");
2308 if (IsNotInheritanceScope
&& Results
.includeCodePatterns())
2309 Builder
.AddChunk(CodeCompletionString::CK_Colon
);
2310 Results
.AddResult(Result(Builder
.TakeString()));
2313 Builder
.AddTypedTextChunk("private");
2314 if (IsNotInheritanceScope
&& Results
.includeCodePatterns())
2315 Builder
.AddChunk(CodeCompletionString::CK_Colon
);
2316 Results
.AddResult(Result(Builder
.TakeString()));
2318 // FIXME: This adds override results only if we are at the first word of
2319 // the declaration/definition. Also call this from other sides to have
2321 AddOverrideResults(Results
, CodeCompletionContext::CCC_ClassStructUnion
,
2327 case SemaCodeCompletion::PCC_Template
:
2328 if (SemaRef
.getLangOpts().CPlusPlus20
&&
2329 CCC
== SemaCodeCompletion::PCC_Template
)
2330 Results
.AddResult(Result("concept", CCP_Keyword
));
2333 case SemaCodeCompletion::PCC_MemberTemplate
:
2334 if (SemaRef
.getLangOpts().CPlusPlus
&& Results
.includeCodePatterns()) {
2335 // template < parameters >
2336 Builder
.AddTypedTextChunk("template");
2337 Builder
.AddChunk(CodeCompletionString::CK_LeftAngle
);
2338 Builder
.AddPlaceholderChunk("parameters");
2339 Builder
.AddChunk(CodeCompletionString::CK_RightAngle
);
2340 Results
.AddResult(Result(Builder
.TakeString()));
2342 Results
.AddResult(Result("template", CodeCompletionResult::RK_Keyword
));
2345 if (SemaRef
.getLangOpts().CPlusPlus20
&&
2346 (CCC
== SemaCodeCompletion::PCC_Template
||
2347 CCC
== SemaCodeCompletion::PCC_MemberTemplate
))
2348 Results
.AddResult(Result("requires", CCP_Keyword
));
2350 AddStorageSpecifiers(CCC
, SemaRef
.getLangOpts(), Results
);
2351 AddFunctionSpecifiers(CCC
, SemaRef
.getLangOpts(), Results
);
2354 case SemaCodeCompletion::PCC_ObjCInterface
:
2355 AddObjCInterfaceResults(SemaRef
.getLangOpts(), Results
, true);
2356 AddStorageSpecifiers(CCC
, SemaRef
.getLangOpts(), Results
);
2357 AddFunctionSpecifiers(CCC
, SemaRef
.getLangOpts(), Results
);
2360 case SemaCodeCompletion::PCC_ObjCImplementation
:
2361 AddObjCImplementationResults(SemaRef
.getLangOpts(), Results
, true);
2362 AddStorageSpecifiers(CCC
, SemaRef
.getLangOpts(), Results
);
2363 AddFunctionSpecifiers(CCC
, SemaRef
.getLangOpts(), Results
);
2366 case SemaCodeCompletion::PCC_ObjCInstanceVariableList
:
2367 AddObjCVisibilityResults(SemaRef
.getLangOpts(), Results
, true);
2370 case SemaCodeCompletion::PCC_RecoveryInFunction
:
2371 case SemaCodeCompletion::PCC_TopLevelOrExpression
:
2372 case SemaCodeCompletion::PCC_Statement
: {
2373 if (SemaRef
.getLangOpts().CPlusPlus11
)
2374 AddUsingAliasResult(Builder
, Results
);
2376 AddTypedefResult(Results
);
2378 if (SemaRef
.getLangOpts().CPlusPlus
&& Results
.includeCodePatterns() &&
2379 SemaRef
.getLangOpts().CXXExceptions
) {
2380 Builder
.AddTypedTextChunk("try");
2381 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2382 Builder
.AddChunk(CodeCompletionString::CK_LeftBrace
);
2383 Builder
.AddChunk(CodeCompletionString::CK_VerticalSpace
);
2384 Builder
.AddPlaceholderChunk("statements");
2385 Builder
.AddChunk(CodeCompletionString::CK_VerticalSpace
);
2386 Builder
.AddChunk(CodeCompletionString::CK_RightBrace
);
2387 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2388 Builder
.AddTextChunk("catch");
2389 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2390 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
2391 Builder
.AddPlaceholderChunk("declaration");
2392 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
2393 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2394 Builder
.AddChunk(CodeCompletionString::CK_LeftBrace
);
2395 Builder
.AddChunk(CodeCompletionString::CK_VerticalSpace
);
2396 Builder
.AddPlaceholderChunk("statements");
2397 Builder
.AddChunk(CodeCompletionString::CK_VerticalSpace
);
2398 Builder
.AddChunk(CodeCompletionString::CK_RightBrace
);
2399 Results
.AddResult(Result(Builder
.TakeString()));
2401 if (SemaRef
.getLangOpts().ObjC
)
2402 AddObjCStatementResults(Results
, true);
2404 if (Results
.includeCodePatterns()) {
2405 // if (condition) { statements }
2406 Builder
.AddTypedTextChunk("if");
2407 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2408 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
2409 if (SemaRef
.getLangOpts().CPlusPlus
)
2410 Builder
.AddPlaceholderChunk("condition");
2412 Builder
.AddPlaceholderChunk("expression");
2413 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
2414 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2415 Builder
.AddChunk(CodeCompletionString::CK_LeftBrace
);
2416 Builder
.AddChunk(CodeCompletionString::CK_VerticalSpace
);
2417 Builder
.AddPlaceholderChunk("statements");
2418 Builder
.AddChunk(CodeCompletionString::CK_VerticalSpace
);
2419 Builder
.AddChunk(CodeCompletionString::CK_RightBrace
);
2420 Results
.AddResult(Result(Builder
.TakeString()));
2422 // switch (condition) { }
2423 Builder
.AddTypedTextChunk("switch");
2424 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2425 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
2426 if (SemaRef
.getLangOpts().CPlusPlus
)
2427 Builder
.AddPlaceholderChunk("condition");
2429 Builder
.AddPlaceholderChunk("expression");
2430 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
2431 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2432 Builder
.AddChunk(CodeCompletionString::CK_LeftBrace
);
2433 Builder
.AddChunk(CodeCompletionString::CK_VerticalSpace
);
2434 Builder
.AddPlaceholderChunk("cases");
2435 Builder
.AddChunk(CodeCompletionString::CK_VerticalSpace
);
2436 Builder
.AddChunk(CodeCompletionString::CK_RightBrace
);
2437 Results
.AddResult(Result(Builder
.TakeString()));
2440 // Switch-specific statements.
2441 if (SemaRef
.getCurFunction() &&
2442 !SemaRef
.getCurFunction()->SwitchStack
.empty()) {
2444 Builder
.AddTypedTextChunk("case");
2445 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2446 Builder
.AddPlaceholderChunk("expression");
2447 Builder
.AddChunk(CodeCompletionString::CK_Colon
);
2448 Results
.AddResult(Result(Builder
.TakeString()));
2451 Builder
.AddTypedTextChunk("default");
2452 Builder
.AddChunk(CodeCompletionString::CK_Colon
);
2453 Results
.AddResult(Result(Builder
.TakeString()));
2456 if (Results
.includeCodePatterns()) {
2457 /// while (condition) { statements }
2458 Builder
.AddTypedTextChunk("while");
2459 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2460 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
2461 if (SemaRef
.getLangOpts().CPlusPlus
)
2462 Builder
.AddPlaceholderChunk("condition");
2464 Builder
.AddPlaceholderChunk("expression");
2465 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
2466 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2467 Builder
.AddChunk(CodeCompletionString::CK_LeftBrace
);
2468 Builder
.AddChunk(CodeCompletionString::CK_VerticalSpace
);
2469 Builder
.AddPlaceholderChunk("statements");
2470 Builder
.AddChunk(CodeCompletionString::CK_VerticalSpace
);
2471 Builder
.AddChunk(CodeCompletionString::CK_RightBrace
);
2472 Results
.AddResult(Result(Builder
.TakeString()));
2474 // do { statements } while ( expression );
2475 Builder
.AddTypedTextChunk("do");
2476 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2477 Builder
.AddChunk(CodeCompletionString::CK_LeftBrace
);
2478 Builder
.AddChunk(CodeCompletionString::CK_VerticalSpace
);
2479 Builder
.AddPlaceholderChunk("statements");
2480 Builder
.AddChunk(CodeCompletionString::CK_VerticalSpace
);
2481 Builder
.AddChunk(CodeCompletionString::CK_RightBrace
);
2482 Builder
.AddTextChunk("while");
2483 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2484 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
2485 Builder
.AddPlaceholderChunk("expression");
2486 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
2487 Results
.AddResult(Result(Builder
.TakeString()));
2489 // for ( for-init-statement ; condition ; expression ) { statements }
2490 Builder
.AddTypedTextChunk("for");
2491 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2492 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
2493 if (SemaRef
.getLangOpts().CPlusPlus
|| SemaRef
.getLangOpts().C99
)
2494 Builder
.AddPlaceholderChunk("init-statement");
2496 Builder
.AddPlaceholderChunk("init-expression");
2497 Builder
.AddChunk(CodeCompletionString::CK_SemiColon
);
2498 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2499 Builder
.AddPlaceholderChunk("condition");
2500 Builder
.AddChunk(CodeCompletionString::CK_SemiColon
);
2501 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2502 Builder
.AddPlaceholderChunk("inc-expression");
2503 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
2504 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2505 Builder
.AddChunk(CodeCompletionString::CK_LeftBrace
);
2506 Builder
.AddChunk(CodeCompletionString::CK_VerticalSpace
);
2507 Builder
.AddPlaceholderChunk("statements");
2508 Builder
.AddChunk(CodeCompletionString::CK_VerticalSpace
);
2509 Builder
.AddChunk(CodeCompletionString::CK_RightBrace
);
2510 Results
.AddResult(Result(Builder
.TakeString()));
2512 if (SemaRef
.getLangOpts().CPlusPlus11
|| SemaRef
.getLangOpts().ObjC
) {
2513 // for ( range_declaration (:|in) range_expression ) { statements }
2514 Builder
.AddTypedTextChunk("for");
2515 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2516 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
2517 Builder
.AddPlaceholderChunk("range-declaration");
2518 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2519 if (SemaRef
.getLangOpts().ObjC
)
2520 Builder
.AddTextChunk("in");
2522 Builder
.AddChunk(CodeCompletionString::CK_Colon
);
2523 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2524 Builder
.AddPlaceholderChunk("range-expression");
2525 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
2526 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2527 Builder
.AddChunk(CodeCompletionString::CK_LeftBrace
);
2528 Builder
.AddChunk(CodeCompletionString::CK_VerticalSpace
);
2529 Builder
.AddPlaceholderChunk("statements");
2530 Builder
.AddChunk(CodeCompletionString::CK_VerticalSpace
);
2531 Builder
.AddChunk(CodeCompletionString::CK_RightBrace
);
2532 Results
.AddResult(Result(Builder
.TakeString()));
2536 if (S
->getContinueParent()) {
2538 Builder
.AddTypedTextChunk("continue");
2539 Builder
.AddChunk(CodeCompletionString::CK_SemiColon
);
2540 Results
.AddResult(Result(Builder
.TakeString()));
2543 if (S
->getBreakParent()) {
2545 Builder
.AddTypedTextChunk("break");
2546 Builder
.AddChunk(CodeCompletionString::CK_SemiColon
);
2547 Results
.AddResult(Result(Builder
.TakeString()));
2550 // "return expression ;" or "return ;", depending on the return type.
2551 QualType ReturnType
;
2552 if (const auto *Function
= dyn_cast
<FunctionDecl
>(SemaRef
.CurContext
))
2553 ReturnType
= Function
->getReturnType();
2554 else if (const auto *Method
= dyn_cast
<ObjCMethodDecl
>(SemaRef
.CurContext
))
2555 ReturnType
= Method
->getReturnType();
2556 else if (SemaRef
.getCurBlock() &&
2557 !SemaRef
.getCurBlock()->ReturnType
.isNull())
2558 ReturnType
= SemaRef
.getCurBlock()->ReturnType
;;
2559 if (ReturnType
.isNull() || ReturnType
->isVoidType()) {
2560 Builder
.AddTypedTextChunk("return");
2561 Builder
.AddChunk(CodeCompletionString::CK_SemiColon
);
2562 Results
.AddResult(Result(Builder
.TakeString()));
2564 assert(!ReturnType
.isNull());
2565 // "return expression ;"
2566 Builder
.AddTypedTextChunk("return");
2567 Builder
.AddChunk(clang::CodeCompletionString::CK_HorizontalSpace
);
2568 Builder
.AddPlaceholderChunk("expression");
2569 Builder
.AddChunk(CodeCompletionString::CK_SemiColon
);
2570 Results
.AddResult(Result(Builder
.TakeString()));
2571 // "co_return expression ;" for coroutines(C++20).
2572 if (SemaRef
.getLangOpts().CPlusPlus20
) {
2573 Builder
.AddTypedTextChunk("co_return");
2574 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2575 Builder
.AddPlaceholderChunk("expression");
2576 Builder
.AddChunk(CodeCompletionString::CK_SemiColon
);
2577 Results
.AddResult(Result(Builder
.TakeString()));
2579 // When boolean, also add 'return true;' and 'return false;'.
2580 if (ReturnType
->isBooleanType()) {
2581 Builder
.AddTypedTextChunk("return true");
2582 Builder
.AddChunk(CodeCompletionString::CK_SemiColon
);
2583 Results
.AddResult(Result(Builder
.TakeString()));
2585 Builder
.AddTypedTextChunk("return false");
2586 Builder
.AddChunk(CodeCompletionString::CK_SemiColon
);
2587 Results
.AddResult(Result(Builder
.TakeString()));
2589 // For pointers, suggest 'return nullptr' in C++.
2590 if (SemaRef
.getLangOpts().CPlusPlus11
&&
2591 (ReturnType
->isPointerType() || ReturnType
->isMemberPointerType())) {
2592 Builder
.AddTypedTextChunk("return nullptr");
2593 Builder
.AddChunk(CodeCompletionString::CK_SemiColon
);
2594 Results
.AddResult(Result(Builder
.TakeString()));
2598 // goto identifier ;
2599 Builder
.AddTypedTextChunk("goto");
2600 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2601 Builder
.AddPlaceholderChunk("label");
2602 Builder
.AddChunk(CodeCompletionString::CK_SemiColon
);
2603 Results
.AddResult(Result(Builder
.TakeString()));
2606 Builder
.AddTypedTextChunk("using namespace");
2607 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2608 Builder
.AddPlaceholderChunk("identifier");
2609 Builder
.AddChunk(CodeCompletionString::CK_SemiColon
);
2610 Results
.AddResult(Result(Builder
.TakeString()));
2612 AddStaticAssertResult(Builder
, Results
, SemaRef
.getLangOpts());
2616 // Fall through (for statement expressions).
2617 case SemaCodeCompletion::PCC_ForInit
:
2618 case SemaCodeCompletion::PCC_Condition
:
2619 AddStorageSpecifiers(CCC
, SemaRef
.getLangOpts(), Results
);
2620 // Fall through: conditions and statements can have expressions.
2623 case SemaCodeCompletion::PCC_ParenthesizedExpression
:
2624 if (SemaRef
.getLangOpts().ObjCAutoRefCount
&&
2625 CCC
== SemaCodeCompletion::PCC_ParenthesizedExpression
) {
2626 // (__bridge <type>)<expression>
2627 Builder
.AddTypedTextChunk("__bridge");
2628 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2629 Builder
.AddPlaceholderChunk("type");
2630 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
2631 Builder
.AddPlaceholderChunk("expression");
2632 Results
.AddResult(Result(Builder
.TakeString()));
2634 // (__bridge_transfer <Objective-C type>)<expression>
2635 Builder
.AddTypedTextChunk("__bridge_transfer");
2636 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2637 Builder
.AddPlaceholderChunk("Objective-C type");
2638 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
2639 Builder
.AddPlaceholderChunk("expression");
2640 Results
.AddResult(Result(Builder
.TakeString()));
2642 // (__bridge_retained <CF type>)<expression>
2643 Builder
.AddTypedTextChunk("__bridge_retained");
2644 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2645 Builder
.AddPlaceholderChunk("CF type");
2646 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
2647 Builder
.AddPlaceholderChunk("expression");
2648 Results
.AddResult(Result(Builder
.TakeString()));
2653 case SemaCodeCompletion::PCC_Expression
: {
2654 if (SemaRef
.getLangOpts().CPlusPlus
) {
2655 // 'this', if we're in a non-static member function.
2656 addThisCompletion(SemaRef
, Results
);
2659 Builder
.AddResultTypeChunk("bool");
2660 Builder
.AddTypedTextChunk("true");
2661 Results
.AddResult(Result(Builder
.TakeString()));
2664 Builder
.AddResultTypeChunk("bool");
2665 Builder
.AddTypedTextChunk("false");
2666 Results
.AddResult(Result(Builder
.TakeString()));
2668 if (SemaRef
.getLangOpts().RTTI
) {
2669 // dynamic_cast < type-id > ( expression )
2670 Builder
.AddTypedTextChunk("dynamic_cast");
2671 Builder
.AddChunk(CodeCompletionString::CK_LeftAngle
);
2672 Builder
.AddPlaceholderChunk("type");
2673 Builder
.AddChunk(CodeCompletionString::CK_RightAngle
);
2674 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
2675 Builder
.AddPlaceholderChunk("expression");
2676 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
2677 Results
.AddResult(Result(Builder
.TakeString()));
2680 // static_cast < type-id > ( expression )
2681 Builder
.AddTypedTextChunk("static_cast");
2682 Builder
.AddChunk(CodeCompletionString::CK_LeftAngle
);
2683 Builder
.AddPlaceholderChunk("type");
2684 Builder
.AddChunk(CodeCompletionString::CK_RightAngle
);
2685 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
2686 Builder
.AddPlaceholderChunk("expression");
2687 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
2688 Results
.AddResult(Result(Builder
.TakeString()));
2690 // reinterpret_cast < type-id > ( expression )
2691 Builder
.AddTypedTextChunk("reinterpret_cast");
2692 Builder
.AddChunk(CodeCompletionString::CK_LeftAngle
);
2693 Builder
.AddPlaceholderChunk("type");
2694 Builder
.AddChunk(CodeCompletionString::CK_RightAngle
);
2695 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
2696 Builder
.AddPlaceholderChunk("expression");
2697 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
2698 Results
.AddResult(Result(Builder
.TakeString()));
2700 // const_cast < type-id > ( expression )
2701 Builder
.AddTypedTextChunk("const_cast");
2702 Builder
.AddChunk(CodeCompletionString::CK_LeftAngle
);
2703 Builder
.AddPlaceholderChunk("type");
2704 Builder
.AddChunk(CodeCompletionString::CK_RightAngle
);
2705 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
2706 Builder
.AddPlaceholderChunk("expression");
2707 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
2708 Results
.AddResult(Result(Builder
.TakeString()));
2710 if (SemaRef
.getLangOpts().RTTI
) {
2711 // typeid ( expression-or-type )
2712 Builder
.AddResultTypeChunk("std::type_info");
2713 Builder
.AddTypedTextChunk("typeid");
2714 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
2715 Builder
.AddPlaceholderChunk("expression-or-type");
2716 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
2717 Results
.AddResult(Result(Builder
.TakeString()));
2721 Builder
.AddTypedTextChunk("new");
2722 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2723 Builder
.AddPlaceholderChunk("type");
2724 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
2725 Builder
.AddPlaceholderChunk("expressions");
2726 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
2727 Results
.AddResult(Result(Builder
.TakeString()));
2729 // new T [ ] ( ... )
2730 Builder
.AddTypedTextChunk("new");
2731 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2732 Builder
.AddPlaceholderChunk("type");
2733 Builder
.AddChunk(CodeCompletionString::CK_LeftBracket
);
2734 Builder
.AddPlaceholderChunk("size");
2735 Builder
.AddChunk(CodeCompletionString::CK_RightBracket
);
2736 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
2737 Builder
.AddPlaceholderChunk("expressions");
2738 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
2739 Results
.AddResult(Result(Builder
.TakeString()));
2741 // delete expression
2742 Builder
.AddResultTypeChunk("void");
2743 Builder
.AddTypedTextChunk("delete");
2744 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2745 Builder
.AddPlaceholderChunk("expression");
2746 Results
.AddResult(Result(Builder
.TakeString()));
2748 // delete [] expression
2749 Builder
.AddResultTypeChunk("void");
2750 Builder
.AddTypedTextChunk("delete");
2751 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2752 Builder
.AddChunk(CodeCompletionString::CK_LeftBracket
);
2753 Builder
.AddChunk(CodeCompletionString::CK_RightBracket
);
2754 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2755 Builder
.AddPlaceholderChunk("expression");
2756 Results
.AddResult(Result(Builder
.TakeString()));
2758 if (SemaRef
.getLangOpts().CXXExceptions
) {
2760 Builder
.AddResultTypeChunk("void");
2761 Builder
.AddTypedTextChunk("throw");
2762 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2763 Builder
.AddPlaceholderChunk("expression");
2764 Results
.AddResult(Result(Builder
.TakeString()));
2769 if (SemaRef
.getLangOpts().CPlusPlus11
) {
2771 Builder
.AddResultTypeChunk("std::nullptr_t");
2772 Builder
.AddTypedTextChunk("nullptr");
2773 Results
.AddResult(Result(Builder
.TakeString()));
2776 Builder
.AddResultTypeChunk("size_t");
2777 Builder
.AddTypedTextChunk("alignof");
2778 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
2779 Builder
.AddPlaceholderChunk("type");
2780 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
2781 Results
.AddResult(Result(Builder
.TakeString()));
2784 Builder
.AddResultTypeChunk("bool");
2785 Builder
.AddTypedTextChunk("noexcept");
2786 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
2787 Builder
.AddPlaceholderChunk("expression");
2788 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
2789 Results
.AddResult(Result(Builder
.TakeString()));
2791 // sizeof... expression
2792 Builder
.AddResultTypeChunk("size_t");
2793 Builder
.AddTypedTextChunk("sizeof...");
2794 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
2795 Builder
.AddPlaceholderChunk("parameter-pack");
2796 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
2797 Results
.AddResult(Result(Builder
.TakeString()));
2800 if (SemaRef
.getLangOpts().CPlusPlus20
) {
2801 // co_await expression
2802 Builder
.AddTypedTextChunk("co_await");
2803 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2804 Builder
.AddPlaceholderChunk("expression");
2805 Results
.AddResult(Result(Builder
.TakeString()));
2807 // co_yield expression
2808 Builder
.AddTypedTextChunk("co_yield");
2809 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2810 Builder
.AddPlaceholderChunk("expression");
2811 Results
.AddResult(Result(Builder
.TakeString()));
2813 // requires (parameters) { requirements }
2814 Builder
.AddResultTypeChunk("bool");
2815 Builder
.AddTypedTextChunk("requires");
2816 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2817 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
2818 Builder
.AddPlaceholderChunk("parameters");
2819 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
2820 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2821 Builder
.AddChunk(CodeCompletionString::CK_LeftBrace
);
2822 Builder
.AddChunk(CodeCompletionString::CK_VerticalSpace
);
2823 Builder
.AddPlaceholderChunk("requirements");
2824 Builder
.AddChunk(CodeCompletionString::CK_VerticalSpace
);
2825 Builder
.AddChunk(CodeCompletionString::CK_RightBrace
);
2826 Results
.AddResult(Result(Builder
.TakeString()));
2828 if (SemaRef
.CurContext
->isRequiresExprBody()) {
2829 // requires expression ;
2830 Builder
.AddTypedTextChunk("requires");
2831 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2832 Builder
.AddPlaceholderChunk("expression");
2833 Builder
.AddChunk(CodeCompletionString::CK_SemiColon
);
2834 Results
.AddResult(Result(Builder
.TakeString()));
2839 if (SemaRef
.getLangOpts().ObjC
) {
2840 // Add "super", if we're in an Objective-C class with a superclass.
2841 if (ObjCMethodDecl
*Method
= SemaRef
.getCurMethodDecl()) {
2842 // The interface can be NULL.
2843 if (ObjCInterfaceDecl
*ID
= Method
->getClassInterface())
2844 if (ID
->getSuperClass()) {
2845 std::string SuperType
;
2846 SuperType
= ID
->getSuperClass()->getNameAsString();
2847 if (Method
->isInstanceMethod())
2850 Builder
.AddResultTypeChunk(Allocator
.CopyString(SuperType
));
2851 Builder
.AddTypedTextChunk("super");
2852 Results
.AddResult(Result(Builder
.TakeString()));
2856 AddObjCExpressionResults(Results
, true);
2859 if (SemaRef
.getLangOpts().C11
) {
2861 Builder
.AddResultTypeChunk("size_t");
2862 if (SemaRef
.PP
.isMacroDefined("alignof"))
2863 Builder
.AddTypedTextChunk("alignof");
2865 Builder
.AddTypedTextChunk("_Alignof");
2866 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
2867 Builder
.AddPlaceholderChunk("type");
2868 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
2869 Results
.AddResult(Result(Builder
.TakeString()));
2872 if (SemaRef
.getLangOpts().C23
) {
2874 Builder
.AddResultTypeChunk("nullptr_t");
2875 Builder
.AddTypedTextChunk("nullptr");
2876 Results
.AddResult(Result(Builder
.TakeString()));
2879 // sizeof expression
2880 Builder
.AddResultTypeChunk("size_t");
2881 Builder
.AddTypedTextChunk("sizeof");
2882 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
2883 Builder
.AddPlaceholderChunk("expression-or-type");
2884 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
2885 Results
.AddResult(Result(Builder
.TakeString()));
2889 case SemaCodeCompletion::PCC_Type
:
2890 case SemaCodeCompletion::PCC_LocalDeclarationSpecifiers
:
2894 if (WantTypesInContext(CCC
, SemaRef
.getLangOpts()))
2895 AddTypeSpecifierResults(SemaRef
.getLangOpts(), Results
);
2897 if (SemaRef
.getLangOpts().CPlusPlus
&& CCC
!= SemaCodeCompletion::PCC_Type
)
2898 Results
.AddResult(Result("operator"));
2901 /// If the given declaration has an associated type, add it as a result
2903 static void AddResultTypeChunk(ASTContext
&Context
,
2904 const PrintingPolicy
&Policy
,
2905 const NamedDecl
*ND
, QualType BaseType
,
2906 CodeCompletionBuilder
&Result
) {
2910 // Skip constructors and conversion functions, which have their return types
2911 // built into their names.
2912 if (isConstructor(ND
) || isa
<CXXConversionDecl
>(ND
))
2915 // Determine the type of the declaration (if it has a type).
2917 if (const FunctionDecl
*Function
= ND
->getAsFunction())
2918 T
= Function
->getReturnType();
2919 else if (const auto *Method
= dyn_cast
<ObjCMethodDecl
>(ND
)) {
2920 if (!BaseType
.isNull())
2921 T
= Method
->getSendResultType(BaseType
);
2923 T
= Method
->getReturnType();
2924 } else if (const auto *Enumerator
= dyn_cast
<EnumConstantDecl
>(ND
)) {
2925 T
= Context
.getTypeDeclType(cast
<TypeDecl
>(Enumerator
->getDeclContext()));
2926 T
= clang::TypeName::getFullyQualifiedType(T
, Context
);
2927 } else if (isa
<UnresolvedUsingValueDecl
>(ND
)) {
2928 /* Do nothing: ignore unresolved using declarations*/
2929 } else if (const auto *Ivar
= dyn_cast
<ObjCIvarDecl
>(ND
)) {
2930 if (!BaseType
.isNull())
2931 T
= Ivar
->getUsageType(BaseType
);
2933 T
= Ivar
->getType();
2934 } else if (const auto *Value
= dyn_cast
<ValueDecl
>(ND
)) {
2935 T
= Value
->getType();
2936 } else if (const auto *Property
= dyn_cast
<ObjCPropertyDecl
>(ND
)) {
2937 if (!BaseType
.isNull())
2938 T
= Property
->getUsageType(BaseType
);
2940 T
= Property
->getType();
2943 if (T
.isNull() || Context
.hasSameType(T
, Context
.DependentTy
))
2946 Result
.AddResultTypeChunk(
2947 GetCompletionTypeString(T
, Context
, Policy
, Result
.getAllocator()));
2950 static void MaybeAddSentinel(Preprocessor
&PP
,
2951 const NamedDecl
*FunctionOrMethod
,
2952 CodeCompletionBuilder
&Result
) {
2953 if (SentinelAttr
*Sentinel
= FunctionOrMethod
->getAttr
<SentinelAttr
>())
2954 if (Sentinel
->getSentinel() == 0) {
2955 if (PP
.getLangOpts().ObjC
&& PP
.isMacroDefined("nil"))
2956 Result
.AddTextChunk(", nil");
2957 else if (PP
.isMacroDefined("NULL"))
2958 Result
.AddTextChunk(", NULL");
2960 Result
.AddTextChunk(", (void*)0");
2964 static std::string
formatObjCParamQualifiers(unsigned ObjCQuals
,
2967 if (ObjCQuals
& Decl::OBJC_TQ_In
)
2969 else if (ObjCQuals
& Decl::OBJC_TQ_Inout
)
2971 else if (ObjCQuals
& Decl::OBJC_TQ_Out
)
2973 if (ObjCQuals
& Decl::OBJC_TQ_Bycopy
)
2974 Result
+= "bycopy ";
2975 else if (ObjCQuals
& Decl::OBJC_TQ_Byref
)
2977 if (ObjCQuals
& Decl::OBJC_TQ_Oneway
)
2978 Result
+= "oneway ";
2979 if (ObjCQuals
& Decl::OBJC_TQ_CSNullability
) {
2980 if (auto nullability
= AttributedType::stripOuterNullability(Type
)) {
2981 switch (*nullability
) {
2982 case NullabilityKind::NonNull
:
2983 Result
+= "nonnull ";
2986 case NullabilityKind::Nullable
:
2987 Result
+= "nullable ";
2990 case NullabilityKind::Unspecified
:
2991 Result
+= "null_unspecified ";
2994 case NullabilityKind::NullableResult
:
2995 llvm_unreachable("Not supported as a context-sensitive keyword!");
3003 /// Tries to find the most appropriate type location for an Objective-C
3004 /// block placeholder.
3006 /// This function ignores things like typedefs and qualifiers in order to
3007 /// present the most relevant and accurate block placeholders in code completion
3009 static void findTypeLocationForBlockDecl(const TypeSourceInfo
*TSInfo
,
3010 FunctionTypeLoc
&Block
,
3011 FunctionProtoTypeLoc
&BlockProto
,
3012 bool SuppressBlock
= false) {
3015 TypeLoc TL
= TSInfo
->getTypeLoc().getUnqualifiedLoc();
3017 // Look through typedefs.
3018 if (!SuppressBlock
) {
3019 if (TypedefTypeLoc TypedefTL
= TL
.getAsAdjusted
<TypedefTypeLoc
>()) {
3020 if (TypeSourceInfo
*InnerTSInfo
=
3021 TypedefTL
.getTypedefNameDecl()->getTypeSourceInfo()) {
3022 TL
= InnerTSInfo
->getTypeLoc().getUnqualifiedLoc();
3027 // Look through qualified types
3028 if (QualifiedTypeLoc QualifiedTL
= TL
.getAs
<QualifiedTypeLoc
>()) {
3029 TL
= QualifiedTL
.getUnqualifiedLoc();
3033 if (AttributedTypeLoc AttrTL
= TL
.getAs
<AttributedTypeLoc
>()) {
3034 TL
= AttrTL
.getModifiedLoc();
3039 // Try to get the function prototype behind the block pointer type,
3041 if (BlockPointerTypeLoc BlockPtr
= TL
.getAs
<BlockPointerTypeLoc
>()) {
3042 TL
= BlockPtr
.getPointeeLoc().IgnoreParens();
3043 Block
= TL
.getAs
<FunctionTypeLoc
>();
3044 BlockProto
= TL
.getAs
<FunctionProtoTypeLoc
>();
3050 static std::string
formatBlockPlaceholder(
3051 const PrintingPolicy
&Policy
, const NamedDecl
*BlockDecl
,
3052 FunctionTypeLoc
&Block
, FunctionProtoTypeLoc
&BlockProto
,
3053 bool SuppressBlockName
= false, bool SuppressBlock
= false,
3054 std::optional
<ArrayRef
<QualType
>> ObjCSubsts
= std::nullopt
);
3056 static std::string
FormatFunctionParameter(
3057 const PrintingPolicy
&Policy
, const DeclaratorDecl
*Param
,
3058 bool SuppressName
= false, bool SuppressBlock
= false,
3059 std::optional
<ArrayRef
<QualType
>> ObjCSubsts
= std::nullopt
) {
3060 // Params are unavailable in FunctionTypeLoc if the FunctionType is invalid.
3061 // It would be better to pass in the param Type, which is usually available.
3062 // But this case is rare, so just pretend we fell back to int as elsewhere.
3065 Decl::ObjCDeclQualifier ObjCQual
= Decl::OBJC_TQ_None
;
3066 if (const auto *PVD
= dyn_cast
<ParmVarDecl
>(Param
))
3067 ObjCQual
= PVD
->getObjCDeclQualifier();
3068 bool ObjCMethodParam
= isa
<ObjCMethodDecl
>(Param
->getDeclContext());
3069 if (Param
->getType()->isDependentType() ||
3070 !Param
->getType()->isBlockPointerType()) {
3071 // The argument for a dependent or non-block parameter is a placeholder
3072 // containing that parameter's type.
3075 if (Param
->getIdentifier() && !ObjCMethodParam
&& !SuppressName
)
3076 Result
= std::string(Param
->getIdentifier()->deuglifiedName());
3078 QualType Type
= Param
->getType();
3080 Type
= Type
.substObjCTypeArgs(Param
->getASTContext(), *ObjCSubsts
,
3081 ObjCSubstitutionContext::Parameter
);
3082 if (ObjCMethodParam
) {
3083 Result
= "(" + formatObjCParamQualifiers(ObjCQual
, Type
);
3084 Result
+= Type
.getAsString(Policy
) + ")";
3085 if (Param
->getIdentifier() && !SuppressName
)
3086 Result
+= Param
->getIdentifier()->deuglifiedName();
3088 Type
.getAsStringInternal(Result
, Policy
);
3093 // The argument for a block pointer parameter is a block literal with
3094 // the appropriate type.
3095 FunctionTypeLoc Block
;
3096 FunctionProtoTypeLoc BlockProto
;
3097 findTypeLocationForBlockDecl(Param
->getTypeSourceInfo(), Block
, BlockProto
,
3099 // Try to retrieve the block type information from the property if this is a
3100 // parameter in a setter.
3101 if (!Block
&& ObjCMethodParam
&&
3102 cast
<ObjCMethodDecl
>(Param
->getDeclContext())->isPropertyAccessor()) {
3103 if (const auto *PD
= cast
<ObjCMethodDecl
>(Param
->getDeclContext())
3104 ->findPropertyDecl(/*CheckOverrides=*/false))
3105 findTypeLocationForBlockDecl(PD
->getTypeSourceInfo(), Block
, BlockProto
,
3110 // We were unable to find a FunctionProtoTypeLoc with parameter names
3111 // for the block; just use the parameter type as a placeholder.
3113 if (!ObjCMethodParam
&& Param
->getIdentifier())
3114 Result
= std::string(Param
->getIdentifier()->deuglifiedName());
3116 QualType Type
= Param
->getType().getUnqualifiedType();
3118 if (ObjCMethodParam
) {
3119 Result
= Type
.getAsString(Policy
);
3120 std::string Quals
= formatObjCParamQualifiers(ObjCQual
, Type
);
3122 Result
= "(" + Quals
+ " " + Result
+ ")";
3123 if (Result
.back() != ')')
3125 if (Param
->getIdentifier())
3126 Result
+= Param
->getIdentifier()->deuglifiedName();
3128 Type
.getAsStringInternal(Result
, Policy
);
3134 // We have the function prototype behind the block pointer type, as it was
3135 // written in the source.
3136 return formatBlockPlaceholder(Policy
, Param
, Block
, BlockProto
,
3137 /*SuppressBlockName=*/false, SuppressBlock
,
3141 /// Returns a placeholder string that corresponds to an Objective-C block
3144 /// \param BlockDecl A declaration with an Objective-C block type.
3146 /// \param Block The most relevant type location for that block type.
3148 /// \param SuppressBlockName Determines whether or not the name of the block
3149 /// declaration is included in the resulting string.
3151 formatBlockPlaceholder(const PrintingPolicy
&Policy
, const NamedDecl
*BlockDecl
,
3152 FunctionTypeLoc
&Block
, FunctionProtoTypeLoc
&BlockProto
,
3153 bool SuppressBlockName
, bool SuppressBlock
,
3154 std::optional
<ArrayRef
<QualType
>> ObjCSubsts
) {
3156 QualType ResultType
= Block
.getTypePtr()->getReturnType();
3159 ResultType
.substObjCTypeArgs(BlockDecl
->getASTContext(), *ObjCSubsts
,
3160 ObjCSubstitutionContext::Result
);
3161 if (!ResultType
->isVoidType() || SuppressBlock
)
3162 ResultType
.getAsStringInternal(Result
, Policy
);
3164 // Format the parameter list.
3166 if (!BlockProto
|| Block
.getNumParams() == 0) {
3167 if (BlockProto
&& BlockProto
.getTypePtr()->isVariadic())
3173 for (unsigned I
= 0, N
= Block
.getNumParams(); I
!= N
; ++I
) {
3176 Params
+= FormatFunctionParameter(Policy
, Block
.getParam(I
),
3177 /*SuppressName=*/false,
3178 /*SuppressBlock=*/true, ObjCSubsts
);
3180 if (I
== N
- 1 && BlockProto
.getTypePtr()->isVariadic())
3186 if (SuppressBlock
) {
3187 // Format as a parameter.
3188 Result
= Result
+ " (^";
3189 if (!SuppressBlockName
&& BlockDecl
->getIdentifier())
3190 Result
+= BlockDecl
->getIdentifier()->getName();
3194 // Format as a block literal argument.
3195 Result
= '^' + Result
;
3198 if (!SuppressBlockName
&& BlockDecl
->getIdentifier())
3199 Result
+= BlockDecl
->getIdentifier()->getName();
3205 static std::string
GetDefaultValueString(const ParmVarDecl
*Param
,
3206 const SourceManager
&SM
,
3207 const LangOptions
&LangOpts
) {
3208 const SourceRange SrcRange
= Param
->getDefaultArgRange();
3209 CharSourceRange CharSrcRange
= CharSourceRange::getTokenRange(SrcRange
);
3210 bool Invalid
= CharSrcRange
.isInvalid();
3214 Lexer::getSourceText(CharSrcRange
, SM
, LangOpts
, &Invalid
);
3218 if (srcText
.empty() || srcText
== "=") {
3219 // Lexer can't determine the value.
3220 // This happens if the code is incorrect (for example class is forward
3224 std::string
DefValue(srcText
.str());
3225 // FIXME: remove this check if the Lexer::getSourceText value is fixed and
3226 // this value always has (or always does not have) '=' in front of it
3227 if (DefValue
.at(0) != '=') {
3228 // If we don't have '=' in front of value.
3229 // Lexer returns built-in types values without '=' and user-defined types
3231 return " = " + DefValue
;
3233 return " " + DefValue
;
3236 /// Add function parameter chunks to the given code completion string.
3237 static void AddFunctionParameterChunks(Preprocessor
&PP
,
3238 const PrintingPolicy
&Policy
,
3239 const FunctionDecl
*Function
,
3240 CodeCompletionBuilder
&Result
,
3242 bool InOptional
= false) {
3243 bool FirstParameter
= true;
3245 for (unsigned P
= Start
, N
= Function
->getNumParams(); P
!= N
; ++P
) {
3246 const ParmVarDecl
*Param
= Function
->getParamDecl(P
);
3248 if (Param
->hasDefaultArg() && !InOptional
) {
3249 // When we see an optional default argument, put that argument and
3250 // the remaining default arguments into a new, optional string.
3251 CodeCompletionBuilder
Opt(Result
.getAllocator(),
3252 Result
.getCodeCompletionTUInfo());
3253 if (!FirstParameter
)
3254 Opt
.AddChunk(CodeCompletionString::CK_Comma
);
3255 AddFunctionParameterChunks(PP
, Policy
, Function
, Opt
, P
, true);
3256 Result
.AddOptionalChunk(Opt
.TakeString());
3261 FirstParameter
= false;
3263 Result
.AddChunk(CodeCompletionString::CK_Comma
);
3267 // Format the placeholder string.
3268 std::string PlaceholderStr
= FormatFunctionParameter(Policy
, Param
);
3269 if (Param
->hasDefaultArg())
3271 GetDefaultValueString(Param
, PP
.getSourceManager(), PP
.getLangOpts());
3273 if (Function
->isVariadic() && P
== N
- 1)
3274 PlaceholderStr
+= ", ...";
3276 // Add the placeholder string.
3277 Result
.AddPlaceholderChunk(
3278 Result
.getAllocator().CopyString(PlaceholderStr
));
3281 if (const auto *Proto
= Function
->getType()->getAs
<FunctionProtoType
>())
3282 if (Proto
->isVariadic()) {
3283 if (Proto
->getNumParams() == 0)
3284 Result
.AddPlaceholderChunk("...");
3286 MaybeAddSentinel(PP
, Function
, Result
);
3290 /// Add template parameter chunks to the given code completion string.
3291 static void AddTemplateParameterChunks(
3292 ASTContext
&Context
, const PrintingPolicy
&Policy
,
3293 const TemplateDecl
*Template
, CodeCompletionBuilder
&Result
,
3294 unsigned MaxParameters
= 0, unsigned Start
= 0, bool InDefaultArg
= false) {
3295 bool FirstParameter
= true;
3297 // Prefer to take the template parameter names from the first declaration of
3299 Template
= cast
<TemplateDecl
>(Template
->getCanonicalDecl());
3301 TemplateParameterList
*Params
= Template
->getTemplateParameters();
3302 TemplateParameterList::iterator PEnd
= Params
->end();
3304 PEnd
= Params
->begin() + MaxParameters
;
3305 for (TemplateParameterList::iterator P
= Params
->begin() + Start
; P
!= PEnd
;
3307 bool HasDefaultArg
= false;
3308 std::string PlaceholderStr
;
3309 if (TemplateTypeParmDecl
*TTP
= dyn_cast
<TemplateTypeParmDecl
>(*P
)) {
3310 if (TTP
->wasDeclaredWithTypename())
3311 PlaceholderStr
= "typename";
3312 else if (const auto *TC
= TTP
->getTypeConstraint()) {
3313 llvm::raw_string_ostream
OS(PlaceholderStr
);
3314 TC
->print(OS
, Policy
);
3316 PlaceholderStr
= "class";
3318 if (TTP
->getIdentifier()) {
3319 PlaceholderStr
+= ' ';
3320 PlaceholderStr
+= TTP
->getIdentifier()->deuglifiedName();
3323 HasDefaultArg
= TTP
->hasDefaultArgument();
3324 } else if (NonTypeTemplateParmDecl
*NTTP
=
3325 dyn_cast
<NonTypeTemplateParmDecl
>(*P
)) {
3326 if (NTTP
->getIdentifier())
3327 PlaceholderStr
= std::string(NTTP
->getIdentifier()->deuglifiedName());
3328 NTTP
->getType().getAsStringInternal(PlaceholderStr
, Policy
);
3329 HasDefaultArg
= NTTP
->hasDefaultArgument();
3331 assert(isa
<TemplateTemplateParmDecl
>(*P
));
3332 TemplateTemplateParmDecl
*TTP
= cast
<TemplateTemplateParmDecl
>(*P
);
3334 // Since putting the template argument list into the placeholder would
3335 // be very, very long, we just use an abbreviation.
3336 PlaceholderStr
= "template<...> class";
3337 if (TTP
->getIdentifier()) {
3338 PlaceholderStr
+= ' ';
3339 PlaceholderStr
+= TTP
->getIdentifier()->deuglifiedName();
3342 HasDefaultArg
= TTP
->hasDefaultArgument();
3345 if (HasDefaultArg
&& !InDefaultArg
) {
3346 // When we see an optional default argument, put that argument and
3347 // the remaining default arguments into a new, optional string.
3348 CodeCompletionBuilder
Opt(Result
.getAllocator(),
3349 Result
.getCodeCompletionTUInfo());
3350 if (!FirstParameter
)
3351 Opt
.AddChunk(CodeCompletionString::CK_Comma
);
3352 AddTemplateParameterChunks(Context
, Policy
, Template
, Opt
, MaxParameters
,
3353 P
- Params
->begin(), true);
3354 Result
.AddOptionalChunk(Opt
.TakeString());
3358 InDefaultArg
= false;
3361 FirstParameter
= false;
3363 Result
.AddChunk(CodeCompletionString::CK_Comma
);
3365 // Add the placeholder string.
3366 Result
.AddPlaceholderChunk(
3367 Result
.getAllocator().CopyString(PlaceholderStr
));
3371 /// Add a qualifier to the given code-completion string, if the
3372 /// provided nested-name-specifier is non-NULL.
3373 static void AddQualifierToCompletionString(CodeCompletionBuilder
&Result
,
3374 NestedNameSpecifier
*Qualifier
,
3375 bool QualifierIsInformative
,
3376 ASTContext
&Context
,
3377 const PrintingPolicy
&Policy
) {
3381 std::string PrintedNNS
;
3383 llvm::raw_string_ostream
OS(PrintedNNS
);
3384 Qualifier
->print(OS
, Policy
);
3386 if (QualifierIsInformative
)
3387 Result
.AddInformativeChunk(Result
.getAllocator().CopyString(PrintedNNS
));
3389 Result
.AddTextChunk(Result
.getAllocator().CopyString(PrintedNNS
));
3393 AddFunctionTypeQualsToCompletionString(CodeCompletionBuilder
&Result
,
3394 const FunctionDecl
*Function
) {
3395 const auto *Proto
= Function
->getType()->getAs
<FunctionProtoType
>();
3396 if (!Proto
|| !Proto
->getMethodQuals())
3399 // FIXME: Add ref-qualifier!
3401 // Handle single qualifiers without copying
3402 if (Proto
->getMethodQuals().hasOnlyConst()) {
3403 Result
.AddInformativeChunk(" const");
3407 if (Proto
->getMethodQuals().hasOnlyVolatile()) {
3408 Result
.AddInformativeChunk(" volatile");
3412 if (Proto
->getMethodQuals().hasOnlyRestrict()) {
3413 Result
.AddInformativeChunk(" restrict");
3417 // Handle multiple qualifiers.
3418 std::string QualsStr
;
3419 if (Proto
->isConst())
3420 QualsStr
+= " const";
3421 if (Proto
->isVolatile())
3422 QualsStr
+= " volatile";
3423 if (Proto
->isRestrict())
3424 QualsStr
+= " restrict";
3425 Result
.AddInformativeChunk(Result
.getAllocator().CopyString(QualsStr
));
3428 /// Add the name of the given declaration
3429 static void AddTypedNameChunk(ASTContext
&Context
, const PrintingPolicy
&Policy
,
3430 const NamedDecl
*ND
,
3431 CodeCompletionBuilder
&Result
) {
3432 DeclarationName Name
= ND
->getDeclName();
3436 switch (Name
.getNameKind()) {
3437 case DeclarationName::CXXOperatorName
: {
3438 const char *OperatorName
= nullptr;
3439 switch (Name
.getCXXOverloadedOperator()) {
3441 case OO_Conditional
:
3442 case NUM_OVERLOADED_OPERATORS
:
3443 OperatorName
= "operator";
3446 #define OVERLOADED_OPERATOR(Name, Spelling, Token, Unary, Binary, MemberOnly) \
3448 OperatorName = "operator" Spelling; \
3450 #define OVERLOADED_OPERATOR_MULTI(Name, Spelling, Unary, Binary, MemberOnly)
3451 #include "clang/Basic/OperatorKinds.def"
3454 OperatorName
= "operator new";
3457 OperatorName
= "operator delete";
3460 OperatorName
= "operator new[]";
3462 case OO_Array_Delete
:
3463 OperatorName
= "operator delete[]";
3466 OperatorName
= "operator()";
3469 OperatorName
= "operator[]";
3472 Result
.AddTypedTextChunk(OperatorName
);
3476 case DeclarationName::Identifier
:
3477 case DeclarationName::CXXConversionFunctionName
:
3478 case DeclarationName::CXXDestructorName
:
3479 case DeclarationName::CXXLiteralOperatorName
:
3480 Result
.AddTypedTextChunk(
3481 Result
.getAllocator().CopyString(ND
->getNameAsString()));
3484 case DeclarationName::CXXDeductionGuideName
:
3485 case DeclarationName::CXXUsingDirective
:
3486 case DeclarationName::ObjCZeroArgSelector
:
3487 case DeclarationName::ObjCOneArgSelector
:
3488 case DeclarationName::ObjCMultiArgSelector
:
3491 case DeclarationName::CXXConstructorName
: {
3492 CXXRecordDecl
*Record
= nullptr;
3493 QualType Ty
= Name
.getCXXNameType();
3494 if (const auto *RecordTy
= Ty
->getAs
<RecordType
>())
3495 Record
= cast
<CXXRecordDecl
>(RecordTy
->getDecl());
3496 else if (const auto *InjectedTy
= Ty
->getAs
<InjectedClassNameType
>())
3497 Record
= InjectedTy
->getDecl();
3499 Result
.AddTypedTextChunk(
3500 Result
.getAllocator().CopyString(ND
->getNameAsString()));
3504 Result
.AddTypedTextChunk(
3505 Result
.getAllocator().CopyString(Record
->getNameAsString()));
3506 if (ClassTemplateDecl
*Template
= Record
->getDescribedClassTemplate()) {
3507 Result
.AddChunk(CodeCompletionString::CK_LeftAngle
);
3508 AddTemplateParameterChunks(Context
, Policy
, Template
, Result
);
3509 Result
.AddChunk(CodeCompletionString::CK_RightAngle
);
3516 CodeCompletionString
*CodeCompletionResult::CreateCodeCompletionString(
3517 Sema
&S
, const CodeCompletionContext
&CCContext
,
3518 CodeCompletionAllocator
&Allocator
, CodeCompletionTUInfo
&CCTUInfo
,
3519 bool IncludeBriefComments
) {
3520 return CreateCodeCompletionString(S
.Context
, S
.PP
, CCContext
, Allocator
,
3521 CCTUInfo
, IncludeBriefComments
);
3524 CodeCompletionString
*CodeCompletionResult::CreateCodeCompletionStringForMacro(
3525 Preprocessor
&PP
, CodeCompletionAllocator
&Allocator
,
3526 CodeCompletionTUInfo
&CCTUInfo
) {
3527 assert(Kind
== RK_Macro
);
3528 CodeCompletionBuilder
Result(Allocator
, CCTUInfo
, Priority
, Availability
);
3529 const MacroInfo
*MI
= PP
.getMacroInfo(Macro
);
3530 Result
.AddTypedTextChunk(Result
.getAllocator().CopyString(Macro
->getName()));
3532 if (!MI
|| !MI
->isFunctionLike())
3533 return Result
.TakeString();
3535 // Format a function-like macro with placeholders for the arguments.
3536 Result
.AddChunk(CodeCompletionString::CK_LeftParen
);
3537 MacroInfo::param_iterator A
= MI
->param_begin(), AEnd
= MI
->param_end();
3539 // C99 variadic macros add __VA_ARGS__ at the end. Skip it.
3540 if (MI
->isC99Varargs()) {
3544 Result
.AddPlaceholderChunk("...");
3548 for (MacroInfo::param_iterator A
= MI
->param_begin(); A
!= AEnd
; ++A
) {
3549 if (A
!= MI
->param_begin())
3550 Result
.AddChunk(CodeCompletionString::CK_Comma
);
3552 if (MI
->isVariadic() && (A
+ 1) == AEnd
) {
3553 SmallString
<32> Arg
= (*A
)->getName();
3554 if (MI
->isC99Varargs())
3558 Result
.AddPlaceholderChunk(Result
.getAllocator().CopyString(Arg
));
3562 // Non-variadic macros are simple.
3563 Result
.AddPlaceholderChunk(
3564 Result
.getAllocator().CopyString((*A
)->getName()));
3566 Result
.AddChunk(CodeCompletionString::CK_RightParen
);
3567 return Result
.TakeString();
3570 /// If possible, create a new code completion string for the given
3573 /// \returns Either a new, heap-allocated code completion string describing
3574 /// how to use this result, or NULL to indicate that the string or name of the
3575 /// result is all that is needed.
3576 CodeCompletionString
*CodeCompletionResult::CreateCodeCompletionString(
3577 ASTContext
&Ctx
, Preprocessor
&PP
, const CodeCompletionContext
&CCContext
,
3578 CodeCompletionAllocator
&Allocator
, CodeCompletionTUInfo
&CCTUInfo
,
3579 bool IncludeBriefComments
) {
3580 if (Kind
== RK_Macro
)
3581 return CreateCodeCompletionStringForMacro(PP
, Allocator
, CCTUInfo
);
3583 CodeCompletionBuilder
Result(Allocator
, CCTUInfo
, Priority
, Availability
);
3585 PrintingPolicy Policy
= getCompletionPrintingPolicy(Ctx
, PP
);
3586 if (Kind
== RK_Pattern
) {
3587 Pattern
->Priority
= Priority
;
3588 Pattern
->Availability
= Availability
;
3591 Result
.addParentContext(Declaration
->getDeclContext());
3592 Pattern
->ParentName
= Result
.getParentName();
3593 if (const RawComment
*RC
=
3594 getPatternCompletionComment(Ctx
, Declaration
)) {
3595 Result
.addBriefComment(RC
->getBriefText(Ctx
));
3596 Pattern
->BriefComment
= Result
.getBriefComment();
3603 if (Kind
== RK_Keyword
) {
3604 Result
.AddTypedTextChunk(Keyword
);
3605 return Result
.TakeString();
3607 assert(Kind
== RK_Declaration
&& "Missed a result kind?");
3608 return createCodeCompletionStringForDecl(
3609 PP
, Ctx
, Result
, IncludeBriefComments
, CCContext
, Policy
);
3612 static void printOverrideString(const CodeCompletionString
&CCS
,
3613 std::string
&BeforeName
,
3614 std::string
&NameAndSignature
) {
3615 bool SeenTypedChunk
= false;
3616 for (auto &Chunk
: CCS
) {
3617 if (Chunk
.Kind
== CodeCompletionString::CK_Optional
) {
3618 assert(SeenTypedChunk
&& "optional parameter before name");
3619 // Note that we put all chunks inside into NameAndSignature.
3620 printOverrideString(*Chunk
.Optional
, NameAndSignature
, NameAndSignature
);
3623 SeenTypedChunk
|= Chunk
.Kind
== CodeCompletionString::CK_TypedText
;
3625 NameAndSignature
+= Chunk
.Text
;
3627 BeforeName
+= Chunk
.Text
;
3631 CodeCompletionString
*
3632 CodeCompletionResult::createCodeCompletionStringForOverride(
3633 Preprocessor
&PP
, ASTContext
&Ctx
, CodeCompletionBuilder
&Result
,
3634 bool IncludeBriefComments
, const CodeCompletionContext
&CCContext
,
3635 PrintingPolicy
&Policy
) {
3636 auto *CCS
= createCodeCompletionStringForDecl(PP
, Ctx
, Result
,
3637 /*IncludeBriefComments=*/false,
3639 std::string BeforeName
;
3640 std::string NameAndSignature
;
3641 // For overrides all chunks go into the result, none are informative.
3642 printOverrideString(*CCS
, BeforeName
, NameAndSignature
);
3643 NameAndSignature
+= " override";
3645 Result
.AddTextChunk(Result
.getAllocator().CopyString(BeforeName
));
3646 Result
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
3647 Result
.AddTypedTextChunk(Result
.getAllocator().CopyString(NameAndSignature
));
3648 return Result
.TakeString();
3651 // FIXME: Right now this works well with lambdas. Add support for other functor
3652 // types like std::function.
3653 static const NamedDecl
*extractFunctorCallOperator(const NamedDecl
*ND
) {
3654 const auto *VD
= dyn_cast
<VarDecl
>(ND
);
3657 const auto *RecordDecl
= VD
->getType()->getAsCXXRecordDecl();
3658 if (!RecordDecl
|| !RecordDecl
->isLambda())
3660 return RecordDecl
->getLambdaCallOperator();
3663 CodeCompletionString
*CodeCompletionResult::createCodeCompletionStringForDecl(
3664 Preprocessor
&PP
, ASTContext
&Ctx
, CodeCompletionBuilder
&Result
,
3665 bool IncludeBriefComments
, const CodeCompletionContext
&CCContext
,
3666 PrintingPolicy
&Policy
) {
3667 const NamedDecl
*ND
= Declaration
;
3668 Result
.addParentContext(ND
->getDeclContext());
3670 if (IncludeBriefComments
) {
3671 // Add documentation comment, if it exists.
3672 if (const RawComment
*RC
= getCompletionComment(Ctx
, Declaration
)) {
3673 Result
.addBriefComment(RC
->getBriefText(Ctx
));
3677 if (StartsNestedNameSpecifier
) {
3678 Result
.AddTypedTextChunk(
3679 Result
.getAllocator().CopyString(ND
->getNameAsString()));
3680 Result
.AddTextChunk("::");
3681 return Result
.TakeString();
3684 for (const auto *I
: ND
->specific_attrs
<AnnotateAttr
>())
3685 Result
.AddAnnotation(Result
.getAllocator().CopyString(I
->getAnnotation()));
3687 auto AddFunctionTypeAndResult
= [&](const FunctionDecl
*Function
) {
3688 AddResultTypeChunk(Ctx
, Policy
, Function
, CCContext
.getBaseType(), Result
);
3689 AddQualifierToCompletionString(Result
, Qualifier
, QualifierIsInformative
,
3691 AddTypedNameChunk(Ctx
, Policy
, ND
, Result
);
3692 Result
.AddChunk(CodeCompletionString::CK_LeftParen
);
3693 AddFunctionParameterChunks(PP
, Policy
, Function
, Result
);
3694 Result
.AddChunk(CodeCompletionString::CK_RightParen
);
3695 AddFunctionTypeQualsToCompletionString(Result
, Function
);
3698 if (const auto *Function
= dyn_cast
<FunctionDecl
>(ND
)) {
3699 AddFunctionTypeAndResult(Function
);
3700 return Result
.TakeString();
3703 if (const auto *CallOperator
=
3704 dyn_cast_or_null
<FunctionDecl
>(extractFunctorCallOperator(ND
))) {
3705 AddFunctionTypeAndResult(CallOperator
);
3706 return Result
.TakeString();
3709 AddResultTypeChunk(Ctx
, Policy
, ND
, CCContext
.getBaseType(), Result
);
3711 if (const FunctionTemplateDecl
*FunTmpl
=
3712 dyn_cast
<FunctionTemplateDecl
>(ND
)) {
3713 AddQualifierToCompletionString(Result
, Qualifier
, QualifierIsInformative
,
3715 FunctionDecl
*Function
= FunTmpl
->getTemplatedDecl();
3716 AddTypedNameChunk(Ctx
, Policy
, Function
, Result
);
3718 // Figure out which template parameters are deduced (or have default
3720 // Note that we're creating a non-empty bit vector so that we can go
3721 // through the loop below to omit default template parameters for non-call
3723 llvm::SmallBitVector
Deduced(FunTmpl
->getTemplateParameters()->size());
3724 // Avoid running it if this is not a call: We should emit *all* template
3726 if (FunctionCanBeCall
)
3727 Sema::MarkDeducedTemplateParameters(Ctx
, FunTmpl
, Deduced
);
3728 unsigned LastDeducibleArgument
;
3729 for (LastDeducibleArgument
= Deduced
.size(); LastDeducibleArgument
> 0;
3730 --LastDeducibleArgument
) {
3731 if (!Deduced
[LastDeducibleArgument
- 1]) {
3732 // C++0x: Figure out if the template argument has a default. If so,
3733 // the user doesn't need to type this argument.
3734 // FIXME: We need to abstract template parameters better!
3735 bool HasDefaultArg
= false;
3736 NamedDecl
*Param
= FunTmpl
->getTemplateParameters()->getParam(
3737 LastDeducibleArgument
- 1);
3738 if (TemplateTypeParmDecl
*TTP
= dyn_cast
<TemplateTypeParmDecl
>(Param
))
3739 HasDefaultArg
= TTP
->hasDefaultArgument();
3740 else if (NonTypeTemplateParmDecl
*NTTP
=
3741 dyn_cast
<NonTypeTemplateParmDecl
>(Param
))
3742 HasDefaultArg
= NTTP
->hasDefaultArgument();
3744 assert(isa
<TemplateTemplateParmDecl
>(Param
));
3746 cast
<TemplateTemplateParmDecl
>(Param
)->hasDefaultArgument();
3754 if (LastDeducibleArgument
|| !FunctionCanBeCall
) {
3755 // Some of the function template arguments cannot be deduced from a
3756 // function call, so we introduce an explicit template argument list
3757 // containing all of the arguments up to the first deducible argument.
3759 // Or, if this isn't a call, emit all the template arguments
3760 // to disambiguate the (potential) overloads.
3762 // FIXME: Detect cases where the function parameters can be deduced from
3763 // the surrounding context, as per [temp.deduct.funcaddr].
3765 // template <class T> void foo(T);
3766 // void (*f)(int) = foo;
3767 Result
.AddChunk(CodeCompletionString::CK_LeftAngle
);
3768 AddTemplateParameterChunks(Ctx
, Policy
, FunTmpl
, Result
,
3769 LastDeducibleArgument
);
3770 Result
.AddChunk(CodeCompletionString::CK_RightAngle
);
3773 // Add the function parameters
3774 Result
.AddChunk(CodeCompletionString::CK_LeftParen
);
3775 AddFunctionParameterChunks(PP
, Policy
, Function
, Result
);
3776 Result
.AddChunk(CodeCompletionString::CK_RightParen
);
3777 AddFunctionTypeQualsToCompletionString(Result
, Function
);
3778 return Result
.TakeString();
3781 if (const auto *Template
= dyn_cast
<TemplateDecl
>(ND
)) {
3782 AddQualifierToCompletionString(Result
, Qualifier
, QualifierIsInformative
,
3784 Result
.AddTypedTextChunk(
3785 Result
.getAllocator().CopyString(Template
->getNameAsString()));
3786 Result
.AddChunk(CodeCompletionString::CK_LeftAngle
);
3787 AddTemplateParameterChunks(Ctx
, Policy
, Template
, Result
);
3788 Result
.AddChunk(CodeCompletionString::CK_RightAngle
);
3789 return Result
.TakeString();
3792 if (const auto *Method
= dyn_cast
<ObjCMethodDecl
>(ND
)) {
3793 Selector Sel
= Method
->getSelector();
3794 if (Sel
.isUnarySelector()) {
3795 Result
.AddTypedTextChunk(
3796 Result
.getAllocator().CopyString(Sel
.getNameForSlot(0)));
3797 return Result
.TakeString();
3800 std::string SelName
= Sel
.getNameForSlot(0).str();
3802 if (StartParameter
== 0)
3803 Result
.AddTypedTextChunk(Result
.getAllocator().CopyString(SelName
));
3805 Result
.AddInformativeChunk(Result
.getAllocator().CopyString(SelName
));
3807 // If there is only one parameter, and we're past it, add an empty
3808 // typed-text chunk since there is nothing to type.
3809 if (Method
->param_size() == 1)
3810 Result
.AddTypedTextChunk("");
3813 // The extra Idx < Sel.getNumArgs() check is needed due to legacy C-style
3814 // method parameters.
3815 for (ObjCMethodDecl::param_const_iterator P
= Method
->param_begin(),
3816 PEnd
= Method
->param_end();
3817 P
!= PEnd
&& Idx
< Sel
.getNumArgs(); (void)++P
, ++Idx
) {
3819 std::string Keyword
;
3820 if (Idx
> StartParameter
)
3821 Result
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
3822 if (const IdentifierInfo
*II
= Sel
.getIdentifierInfoForSlot(Idx
))
3823 Keyword
+= II
->getName();
3825 if (Idx
< StartParameter
|| AllParametersAreInformative
)
3826 Result
.AddInformativeChunk(Result
.getAllocator().CopyString(Keyword
));
3828 Result
.AddTypedTextChunk(Result
.getAllocator().CopyString(Keyword
));
3831 // If we're before the starting parameter, skip the placeholder.
3832 if (Idx
< StartParameter
)
3836 QualType ParamType
= (*P
)->getType();
3837 std::optional
<ArrayRef
<QualType
>> ObjCSubsts
;
3838 if (!CCContext
.getBaseType().isNull())
3839 ObjCSubsts
= CCContext
.getBaseType()->getObjCSubstitutions(Method
);
3841 if (ParamType
->isBlockPointerType() && !DeclaringEntity
)
3842 Arg
= FormatFunctionParameter(Policy
, *P
, true,
3843 /*SuppressBlock=*/false, ObjCSubsts
);
3846 ParamType
= ParamType
.substObjCTypeArgs(
3847 Ctx
, *ObjCSubsts
, ObjCSubstitutionContext::Parameter
);
3848 Arg
= "(" + formatObjCParamQualifiers((*P
)->getObjCDeclQualifier(),
3850 Arg
+= ParamType
.getAsString(Policy
) + ")";
3851 if (const IdentifierInfo
*II
= (*P
)->getIdentifier())
3852 if (DeclaringEntity
|| AllParametersAreInformative
)
3853 Arg
+= II
->getName();
3856 if (Method
->isVariadic() && (P
+ 1) == PEnd
)
3859 if (DeclaringEntity
)
3860 Result
.AddTextChunk(Result
.getAllocator().CopyString(Arg
));
3861 else if (AllParametersAreInformative
)
3862 Result
.AddInformativeChunk(Result
.getAllocator().CopyString(Arg
));
3864 Result
.AddPlaceholderChunk(Result
.getAllocator().CopyString(Arg
));
3867 if (Method
->isVariadic()) {
3868 if (Method
->param_size() == 0) {
3869 if (DeclaringEntity
)
3870 Result
.AddTextChunk(", ...");
3871 else if (AllParametersAreInformative
)
3872 Result
.AddInformativeChunk(", ...");
3874 Result
.AddPlaceholderChunk(", ...");
3877 MaybeAddSentinel(PP
, Method
, Result
);
3880 return Result
.TakeString();
3884 AddQualifierToCompletionString(Result
, Qualifier
, QualifierIsInformative
,
3887 Result
.AddTypedTextChunk(
3888 Result
.getAllocator().CopyString(ND
->getNameAsString()));
3889 return Result
.TakeString();
3892 const RawComment
*clang::getCompletionComment(const ASTContext
&Ctx
,
3893 const NamedDecl
*ND
) {
3896 if (auto *RC
= Ctx
.getRawCommentForAnyRedecl(ND
))
3899 // Try to find comment from a property for ObjC methods.
3900 const auto *M
= dyn_cast
<ObjCMethodDecl
>(ND
);
3903 const ObjCPropertyDecl
*PDecl
= M
->findPropertyDecl();
3907 return Ctx
.getRawCommentForAnyRedecl(PDecl
);
3910 const RawComment
*clang::getPatternCompletionComment(const ASTContext
&Ctx
,
3911 const NamedDecl
*ND
) {
3912 const auto *M
= dyn_cast_or_null
<ObjCMethodDecl
>(ND
);
3913 if (!M
|| !M
->isPropertyAccessor())
3916 // Provide code completion comment for self.GetterName where
3917 // GetterName is the getter method for a property with name
3918 // different from the property name (declared via a property
3919 // getter attribute.
3920 const ObjCPropertyDecl
*PDecl
= M
->findPropertyDecl();
3923 if (PDecl
->getGetterName() == M
->getSelector() &&
3924 PDecl
->getIdentifier() != M
->getIdentifier()) {
3925 if (auto *RC
= Ctx
.getRawCommentForAnyRedecl(M
))
3927 if (auto *RC
= Ctx
.getRawCommentForAnyRedecl(PDecl
))
3933 const RawComment
*clang::getParameterComment(
3934 const ASTContext
&Ctx
,
3935 const CodeCompleteConsumer::OverloadCandidate
&Result
, unsigned ArgIndex
) {
3936 auto FDecl
= Result
.getFunction();
3939 if (ArgIndex
< FDecl
->getNumParams())
3940 return Ctx
.getRawCommentForAnyRedecl(FDecl
->getParamDecl(ArgIndex
));
3944 static void AddOverloadAggregateChunks(const RecordDecl
*RD
,
3945 const PrintingPolicy
&Policy
,
3946 CodeCompletionBuilder
&Result
,
3947 unsigned CurrentArg
) {
3948 unsigned ChunkIndex
= 0;
3949 auto AddChunk
= [&](llvm::StringRef Placeholder
) {
3951 Result
.AddChunk(CodeCompletionString::CK_Comma
);
3952 const char *Copy
= Result
.getAllocator().CopyString(Placeholder
);
3953 if (ChunkIndex
== CurrentArg
)
3954 Result
.AddCurrentParameterChunk(Copy
);
3956 Result
.AddPlaceholderChunk(Copy
);
3959 // Aggregate initialization has all bases followed by all fields.
3960 // (Bases are not legal in C++11 but in that case we never get here).
3961 if (auto *CRD
= llvm::dyn_cast
<CXXRecordDecl
>(RD
)) {
3962 for (const auto &Base
: CRD
->bases())
3963 AddChunk(Base
.getType().getAsString(Policy
));
3965 for (const auto &Field
: RD
->fields())
3966 AddChunk(FormatFunctionParameter(Policy
, Field
));
3969 /// Add function overload parameter chunks to the given code completion
3971 static void AddOverloadParameterChunks(
3972 ASTContext
&Context
, const PrintingPolicy
&Policy
,
3973 const FunctionDecl
*Function
, const FunctionProtoType
*Prototype
,
3974 FunctionProtoTypeLoc PrototypeLoc
, CodeCompletionBuilder
&Result
,
3975 unsigned CurrentArg
, unsigned Start
= 0, bool InOptional
= false) {
3976 if (!Function
&& !Prototype
) {
3977 Result
.AddChunk(CodeCompletionString::CK_CurrentParameter
, "...");
3981 bool FirstParameter
= true;
3982 unsigned NumParams
=
3983 Function
? Function
->getNumParams() : Prototype
->getNumParams();
3985 for (unsigned P
= Start
; P
!= NumParams
; ++P
) {
3986 if (Function
&& Function
->getParamDecl(P
)->hasDefaultArg() && !InOptional
) {
3987 // When we see an optional default argument, put that argument and
3988 // the remaining default arguments into a new, optional string.
3989 CodeCompletionBuilder
Opt(Result
.getAllocator(),
3990 Result
.getCodeCompletionTUInfo());
3991 if (!FirstParameter
)
3992 Opt
.AddChunk(CodeCompletionString::CK_Comma
);
3993 // Optional sections are nested.
3994 AddOverloadParameterChunks(Context
, Policy
, Function
, Prototype
,
3995 PrototypeLoc
, Opt
, CurrentArg
, P
,
3996 /*InOptional=*/true);
3997 Result
.AddOptionalChunk(Opt
.TakeString());
4002 FirstParameter
= false;
4004 Result
.AddChunk(CodeCompletionString::CK_Comma
);
4008 // Format the placeholder string.
4009 std::string Placeholder
;
4010 assert(P
< Prototype
->getNumParams());
4011 if (Function
|| PrototypeLoc
) {
4012 const ParmVarDecl
*Param
=
4013 Function
? Function
->getParamDecl(P
) : PrototypeLoc
.getParam(P
);
4014 Placeholder
= FormatFunctionParameter(Policy
, Param
);
4015 if (Param
->hasDefaultArg())
4016 Placeholder
+= GetDefaultValueString(Param
, Context
.getSourceManager(),
4017 Context
.getLangOpts());
4019 Placeholder
= Prototype
->getParamType(P
).getAsString(Policy
);
4022 if (P
== CurrentArg
)
4023 Result
.AddCurrentParameterChunk(
4024 Result
.getAllocator().CopyString(Placeholder
));
4026 Result
.AddPlaceholderChunk(Result
.getAllocator().CopyString(Placeholder
));
4029 if (Prototype
&& Prototype
->isVariadic()) {
4030 CodeCompletionBuilder
Opt(Result
.getAllocator(),
4031 Result
.getCodeCompletionTUInfo());
4032 if (!FirstParameter
)
4033 Opt
.AddChunk(CodeCompletionString::CK_Comma
);
4035 if (CurrentArg
< NumParams
)
4036 Opt
.AddPlaceholderChunk("...");
4038 Opt
.AddCurrentParameterChunk("...");
4040 Result
.AddOptionalChunk(Opt
.TakeString());
4045 formatTemplateParameterPlaceholder(const NamedDecl
*Param
, bool &Optional
,
4046 const PrintingPolicy
&Policy
) {
4047 if (const auto *Type
= dyn_cast
<TemplateTypeParmDecl
>(Param
)) {
4048 Optional
= Type
->hasDefaultArgument();
4049 } else if (const auto *NonType
= dyn_cast
<NonTypeTemplateParmDecl
>(Param
)) {
4050 Optional
= NonType
->hasDefaultArgument();
4051 } else if (const auto *Template
= dyn_cast
<TemplateTemplateParmDecl
>(Param
)) {
4052 Optional
= Template
->hasDefaultArgument();
4055 llvm::raw_string_ostream
OS(Result
);
4056 Param
->print(OS
, Policy
);
4060 static std::string
templateResultType(const TemplateDecl
*TD
,
4061 const PrintingPolicy
&Policy
) {
4062 if (const auto *CTD
= dyn_cast
<ClassTemplateDecl
>(TD
))
4063 return CTD
->getTemplatedDecl()->getKindName().str();
4064 if (const auto *VTD
= dyn_cast
<VarTemplateDecl
>(TD
))
4065 return VTD
->getTemplatedDecl()->getType().getAsString(Policy
);
4066 if (const auto *FTD
= dyn_cast
<FunctionTemplateDecl
>(TD
))
4067 return FTD
->getTemplatedDecl()->getReturnType().getAsString(Policy
);
4068 if (isa
<TypeAliasTemplateDecl
>(TD
))
4070 if (isa
<TemplateTemplateParmDecl
>(TD
))
4072 if (isa
<ConceptDecl
>(TD
))
4077 static CodeCompletionString
*createTemplateSignatureString(
4078 const TemplateDecl
*TD
, CodeCompletionBuilder
&Builder
, unsigned CurrentArg
,
4079 const PrintingPolicy
&Policy
) {
4080 llvm::ArrayRef
<NamedDecl
*> Params
= TD
->getTemplateParameters()->asArray();
4081 CodeCompletionBuilder
OptionalBuilder(Builder
.getAllocator(),
4082 Builder
.getCodeCompletionTUInfo());
4083 std::string ResultType
= templateResultType(TD
, Policy
);
4084 if (!ResultType
.empty())
4085 Builder
.AddResultTypeChunk(Builder
.getAllocator().CopyString(ResultType
));
4086 Builder
.AddTextChunk(
4087 Builder
.getAllocator().CopyString(TD
->getNameAsString()));
4088 Builder
.AddChunk(CodeCompletionString::CK_LeftAngle
);
4089 // Initially we're writing into the main string. Once we see an optional arg
4090 // (with default), we're writing into the nested optional chunk.
4091 CodeCompletionBuilder
*Current
= &Builder
;
4092 for (unsigned I
= 0; I
< Params
.size(); ++I
) {
4093 bool Optional
= false;
4094 std::string Placeholder
=
4095 formatTemplateParameterPlaceholder(Params
[I
], Optional
, Policy
);
4097 Current
= &OptionalBuilder
;
4099 Current
->AddChunk(CodeCompletionString::CK_Comma
);
4100 Current
->AddChunk(I
== CurrentArg
4101 ? CodeCompletionString::CK_CurrentParameter
4102 : CodeCompletionString::CK_Placeholder
,
4103 Current
->getAllocator().CopyString(Placeholder
));
4105 // Add the optional chunk to the main string if we ever used it.
4106 if (Current
== &OptionalBuilder
)
4107 Builder
.AddOptionalChunk(OptionalBuilder
.TakeString());
4108 Builder
.AddChunk(CodeCompletionString::CK_RightAngle
);
4109 // For function templates, ResultType was the function's return type.
4110 // Give some clue this is a function. (Don't show the possibly-bulky params).
4111 if (isa
<FunctionTemplateDecl
>(TD
))
4112 Builder
.AddInformativeChunk("()");
4113 return Builder
.TakeString();
4116 CodeCompletionString
*
4117 CodeCompleteConsumer::OverloadCandidate::CreateSignatureString(
4118 unsigned CurrentArg
, Sema
&S
, CodeCompletionAllocator
&Allocator
,
4119 CodeCompletionTUInfo
&CCTUInfo
, bool IncludeBriefComments
,
4120 bool Braced
) const {
4121 PrintingPolicy Policy
= getCompletionPrintingPolicy(S
);
4122 // Show signatures of constructors as they are declared:
4123 // vector(int n) rather than vector<string>(int n)
4124 // This is less noisy without being less clear, and avoids tricky cases.
4125 Policy
.SuppressTemplateArgsInCXXConstructors
= true;
4127 // FIXME: Set priority, availability appropriately.
4128 CodeCompletionBuilder
Result(Allocator
, CCTUInfo
, 1,
4129 CXAvailability_Available
);
4131 if (getKind() == CK_Template
)
4132 return createTemplateSignatureString(getTemplate(), Result
, CurrentArg
,
4135 FunctionDecl
*FDecl
= getFunction();
4136 const FunctionProtoType
*Proto
=
4137 dyn_cast_or_null
<FunctionProtoType
>(getFunctionType());
4139 // First, the name/type of the callee.
4140 if (getKind() == CK_Aggregate
) {
4141 Result
.AddTextChunk(
4142 Result
.getAllocator().CopyString(getAggregate()->getName()));
4144 if (IncludeBriefComments
) {
4145 if (auto RC
= getParameterComment(S
.getASTContext(), *this, CurrentArg
))
4146 Result
.addBriefComment(RC
->getBriefText(S
.getASTContext()));
4148 AddResultTypeChunk(S
.Context
, Policy
, FDecl
, QualType(), Result
);
4151 llvm::raw_string_ostream
OS(Name
);
4152 FDecl
->getDeclName().print(OS
, Policy
);
4153 Result
.AddTextChunk(Result
.getAllocator().CopyString(Name
));
4155 // Function without a declaration. Just give the return type.
4156 Result
.AddResultTypeChunk(Result
.getAllocator().CopyString(
4157 getFunctionType()->getReturnType().getAsString(Policy
)));
4160 // Next, the brackets and parameters.
4161 Result
.AddChunk(Braced
? CodeCompletionString::CK_LeftBrace
4162 : CodeCompletionString::CK_LeftParen
);
4163 if (getKind() == CK_Aggregate
)
4164 AddOverloadAggregateChunks(getAggregate(), Policy
, Result
, CurrentArg
);
4166 AddOverloadParameterChunks(S
.getASTContext(), Policy
, FDecl
, Proto
,
4167 getFunctionProtoTypeLoc(), Result
, CurrentArg
);
4168 Result
.AddChunk(Braced
? CodeCompletionString::CK_RightBrace
4169 : CodeCompletionString::CK_RightParen
);
4171 return Result
.TakeString();
4174 unsigned clang::getMacroUsagePriority(StringRef MacroName
,
4175 const LangOptions
&LangOpts
,
4176 bool PreferredTypeIsPointer
) {
4177 unsigned Priority
= CCP_Macro
;
4179 // Treat the "nil", "Nil" and "NULL" macros as null pointer constants.
4180 if (MacroName
== "nil" || MacroName
== "NULL" || MacroName
== "Nil") {
4181 Priority
= CCP_Constant
;
4182 if (PreferredTypeIsPointer
)
4183 Priority
= Priority
/ CCF_SimilarTypeMatch
;
4185 // Treat "YES", "NO", "true", and "false" as constants.
4186 else if (MacroName
== "YES" || MacroName
== "NO" || MacroName
== "true" ||
4187 MacroName
== "false")
4188 Priority
= CCP_Constant
;
4189 // Treat "bool" as a type.
4190 else if (MacroName
== "bool")
4191 Priority
= CCP_Type
+ (LangOpts
.ObjC
? CCD_bool_in_ObjC
: 0);
4196 CXCursorKind
clang::getCursorKindForDecl(const Decl
*D
) {
4198 return CXCursor_UnexposedDecl
;
4200 switch (D
->getKind()) {
4202 return CXCursor_EnumDecl
;
4203 case Decl::EnumConstant
:
4204 return CXCursor_EnumConstantDecl
;
4206 return CXCursor_FieldDecl
;
4207 case Decl::Function
:
4208 return CXCursor_FunctionDecl
;
4209 case Decl::ObjCCategory
:
4210 return CXCursor_ObjCCategoryDecl
;
4211 case Decl::ObjCCategoryImpl
:
4212 return CXCursor_ObjCCategoryImplDecl
;
4213 case Decl::ObjCImplementation
:
4214 return CXCursor_ObjCImplementationDecl
;
4216 case Decl::ObjCInterface
:
4217 return CXCursor_ObjCInterfaceDecl
;
4218 case Decl::ObjCIvar
:
4219 return CXCursor_ObjCIvarDecl
;
4220 case Decl::ObjCMethod
:
4221 return cast
<ObjCMethodDecl
>(D
)->isInstanceMethod()
4222 ? CXCursor_ObjCInstanceMethodDecl
4223 : CXCursor_ObjCClassMethodDecl
;
4224 case Decl::CXXMethod
:
4225 return CXCursor_CXXMethod
;
4226 case Decl::CXXConstructor
:
4227 return CXCursor_Constructor
;
4228 case Decl::CXXDestructor
:
4229 return CXCursor_Destructor
;
4230 case Decl::CXXConversion
:
4231 return CXCursor_ConversionFunction
;
4232 case Decl::ObjCProperty
:
4233 return CXCursor_ObjCPropertyDecl
;
4234 case Decl::ObjCProtocol
:
4235 return CXCursor_ObjCProtocolDecl
;
4237 return CXCursor_ParmDecl
;
4239 return CXCursor_TypedefDecl
;
4240 case Decl::TypeAlias
:
4241 return CXCursor_TypeAliasDecl
;
4242 case Decl::TypeAliasTemplate
:
4243 return CXCursor_TypeAliasTemplateDecl
;
4245 return CXCursor_VarDecl
;
4246 case Decl::Namespace
:
4247 return CXCursor_Namespace
;
4248 case Decl::NamespaceAlias
:
4249 return CXCursor_NamespaceAlias
;
4250 case Decl::TemplateTypeParm
:
4251 return CXCursor_TemplateTypeParameter
;
4252 case Decl::NonTypeTemplateParm
:
4253 return CXCursor_NonTypeTemplateParameter
;
4254 case Decl::TemplateTemplateParm
:
4255 return CXCursor_TemplateTemplateParameter
;
4256 case Decl::FunctionTemplate
:
4257 return CXCursor_FunctionTemplate
;
4258 case Decl::ClassTemplate
:
4259 return CXCursor_ClassTemplate
;
4260 case Decl::AccessSpec
:
4261 return CXCursor_CXXAccessSpecifier
;
4262 case Decl::ClassTemplatePartialSpecialization
:
4263 return CXCursor_ClassTemplatePartialSpecialization
;
4264 case Decl::UsingDirective
:
4265 return CXCursor_UsingDirective
;
4266 case Decl::StaticAssert
:
4267 return CXCursor_StaticAssert
;
4269 return CXCursor_FriendDecl
;
4270 case Decl::TranslationUnit
:
4271 return CXCursor_TranslationUnit
;
4274 case Decl::UnresolvedUsingValue
:
4275 case Decl::UnresolvedUsingTypename
:
4276 return CXCursor_UsingDeclaration
;
4278 case Decl::UsingEnum
:
4279 return CXCursor_EnumDecl
;
4281 case Decl::ObjCPropertyImpl
:
4282 switch (cast
<ObjCPropertyImplDecl
>(D
)->getPropertyImplementation()) {
4283 case ObjCPropertyImplDecl::Dynamic
:
4284 return CXCursor_ObjCDynamicDecl
;
4286 case ObjCPropertyImplDecl::Synthesize
:
4287 return CXCursor_ObjCSynthesizeDecl
;
4289 llvm_unreachable("Unexpected Kind!");
4292 return CXCursor_ModuleImportDecl
;
4294 case Decl::ObjCTypeParam
:
4295 return CXCursor_TemplateTypeParameter
;
4298 return CXCursor_ConceptDecl
;
4300 case Decl::LinkageSpec
:
4301 return CXCursor_LinkageSpec
;
4304 if (const auto *TD
= dyn_cast
<TagDecl
>(D
)) {
4305 switch (TD
->getTagKind()) {
4306 case TagTypeKind::Interface
: // fall through
4307 case TagTypeKind::Struct
:
4308 return CXCursor_StructDecl
;
4309 case TagTypeKind::Class
:
4310 return CXCursor_ClassDecl
;
4311 case TagTypeKind::Union
:
4312 return CXCursor_UnionDecl
;
4313 case TagTypeKind::Enum
:
4314 return CXCursor_EnumDecl
;
4319 return CXCursor_UnexposedDecl
;
4322 static void AddMacroResults(Preprocessor
&PP
, ResultBuilder
&Results
,
4323 bool LoadExternal
, bool IncludeUndefined
,
4324 bool TargetTypeIsPointer
= false) {
4325 typedef CodeCompletionResult Result
;
4327 Results
.EnterNewScope();
4329 for (Preprocessor::macro_iterator M
= PP
.macro_begin(LoadExternal
),
4330 MEnd
= PP
.macro_end(LoadExternal
);
4332 auto MD
= PP
.getMacroDefinition(M
->first
);
4333 if (IncludeUndefined
|| MD
) {
4334 MacroInfo
*MI
= MD
.getMacroInfo();
4335 if (MI
&& MI
->isUsedForHeaderGuard())
4339 Result(M
->first
, MI
,
4340 getMacroUsagePriority(M
->first
->getName(), PP
.getLangOpts(),
4341 TargetTypeIsPointer
)));
4345 Results
.ExitScope();
4348 static void AddPrettyFunctionResults(const LangOptions
&LangOpts
,
4349 ResultBuilder
&Results
) {
4350 typedef CodeCompletionResult Result
;
4352 Results
.EnterNewScope();
4354 Results
.AddResult(Result("__PRETTY_FUNCTION__", CCP_Constant
));
4355 Results
.AddResult(Result("__FUNCTION__", CCP_Constant
));
4356 if (LangOpts
.C99
|| LangOpts
.CPlusPlus11
)
4357 Results
.AddResult(Result("__func__", CCP_Constant
));
4358 Results
.ExitScope();
4361 static void HandleCodeCompleteResults(Sema
*S
,
4362 CodeCompleteConsumer
*CodeCompleter
,
4363 const CodeCompletionContext
&Context
,
4364 CodeCompletionResult
*Results
,
4365 unsigned NumResults
) {
4367 CodeCompleter
->ProcessCodeCompleteResults(*S
, Context
, Results
, NumResults
);
4370 static CodeCompletionContext
4371 mapCodeCompletionContext(Sema
&S
,
4372 SemaCodeCompletion::ParserCompletionContext PCC
) {
4374 case SemaCodeCompletion::PCC_Namespace
:
4375 return CodeCompletionContext::CCC_TopLevel
;
4377 case SemaCodeCompletion::PCC_Class
:
4378 return CodeCompletionContext::CCC_ClassStructUnion
;
4380 case SemaCodeCompletion::PCC_ObjCInterface
:
4381 return CodeCompletionContext::CCC_ObjCInterface
;
4383 case SemaCodeCompletion::PCC_ObjCImplementation
:
4384 return CodeCompletionContext::CCC_ObjCImplementation
;
4386 case SemaCodeCompletion::PCC_ObjCInstanceVariableList
:
4387 return CodeCompletionContext::CCC_ObjCIvarList
;
4389 case SemaCodeCompletion::PCC_Template
:
4390 case SemaCodeCompletion::PCC_MemberTemplate
:
4391 if (S
.CurContext
->isFileContext())
4392 return CodeCompletionContext::CCC_TopLevel
;
4393 if (S
.CurContext
->isRecord())
4394 return CodeCompletionContext::CCC_ClassStructUnion
;
4395 return CodeCompletionContext::CCC_Other
;
4397 case SemaCodeCompletion::PCC_RecoveryInFunction
:
4398 return CodeCompletionContext::CCC_Recovery
;
4400 case SemaCodeCompletion::PCC_ForInit
:
4401 if (S
.getLangOpts().CPlusPlus
|| S
.getLangOpts().C99
||
4402 S
.getLangOpts().ObjC
)
4403 return CodeCompletionContext::CCC_ParenthesizedExpression
;
4405 return CodeCompletionContext::CCC_Expression
;
4407 case SemaCodeCompletion::PCC_Expression
:
4408 return CodeCompletionContext::CCC_Expression
;
4409 case SemaCodeCompletion::PCC_Condition
:
4410 return CodeCompletionContext(CodeCompletionContext::CCC_Expression
,
4411 S
.getASTContext().BoolTy
);
4413 case SemaCodeCompletion::PCC_Statement
:
4414 return CodeCompletionContext::CCC_Statement
;
4416 case SemaCodeCompletion::PCC_Type
:
4417 return CodeCompletionContext::CCC_Type
;
4419 case SemaCodeCompletion::PCC_ParenthesizedExpression
:
4420 return CodeCompletionContext::CCC_ParenthesizedExpression
;
4422 case SemaCodeCompletion::PCC_LocalDeclarationSpecifiers
:
4423 return CodeCompletionContext::CCC_Type
;
4424 case SemaCodeCompletion::PCC_TopLevelOrExpression
:
4425 return CodeCompletionContext::CCC_TopLevelOrExpression
;
4428 llvm_unreachable("Invalid ParserCompletionContext!");
4431 /// If we're in a C++ virtual member function, add completion results
4432 /// that invoke the functions we override, since it's common to invoke the
4433 /// overridden function as well as adding new functionality.
4435 /// \param S The semantic analysis object for which we are generating results.
4437 /// \param InContext This context in which the nested-name-specifier preceding
4438 /// the code-completion point
4439 static void MaybeAddOverrideCalls(Sema
&S
, DeclContext
*InContext
,
4440 ResultBuilder
&Results
) {
4441 // Look through blocks.
4442 DeclContext
*CurContext
= S
.CurContext
;
4443 while (isa
<BlockDecl
>(CurContext
))
4444 CurContext
= CurContext
->getParent();
4446 CXXMethodDecl
*Method
= dyn_cast
<CXXMethodDecl
>(CurContext
);
4447 if (!Method
|| !Method
->isVirtual())
4450 // We need to have names for all of the parameters, if we're going to
4451 // generate a forwarding call.
4452 for (auto *P
: Method
->parameters())
4453 if (!P
->getDeclName())
4456 PrintingPolicy Policy
= getCompletionPrintingPolicy(S
);
4457 for (const CXXMethodDecl
*Overridden
: Method
->overridden_methods()) {
4458 CodeCompletionBuilder
Builder(Results
.getAllocator(),
4459 Results
.getCodeCompletionTUInfo());
4460 if (Overridden
->getCanonicalDecl() == Method
->getCanonicalDecl())
4463 // If we need a nested-name-specifier, add one now.
4465 NestedNameSpecifier
*NNS
= getRequiredQualification(
4466 S
.Context
, CurContext
, Overridden
->getDeclContext());
4469 llvm::raw_string_ostream
OS(Str
);
4470 NNS
->print(OS
, Policy
);
4471 Builder
.AddTextChunk(Results
.getAllocator().CopyString(Str
));
4473 } else if (!InContext
->Equals(Overridden
->getDeclContext()))
4476 Builder
.AddTypedTextChunk(
4477 Results
.getAllocator().CopyString(Overridden
->getNameAsString()));
4478 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
4479 bool FirstParam
= true;
4480 for (auto *P
: Method
->parameters()) {
4484 Builder
.AddChunk(CodeCompletionString::CK_Comma
);
4486 Builder
.AddPlaceholderChunk(
4487 Results
.getAllocator().CopyString(P
->getIdentifier()->getName()));
4489 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
4490 Results
.AddResult(CodeCompletionResult(
4491 Builder
.TakeString(), CCP_SuperCompletion
, CXCursor_CXXMethod
,
4492 CXAvailability_Available
, Overridden
));
4493 Results
.Ignore(Overridden
);
4497 void SemaCodeCompletion::CodeCompleteModuleImport(SourceLocation ImportLoc
,
4498 ModuleIdPath Path
) {
4499 typedef CodeCompletionResult Result
;
4500 ResultBuilder
Results(SemaRef
, CodeCompleter
->getAllocator(),
4501 CodeCompleter
->getCodeCompletionTUInfo(),
4502 CodeCompletionContext::CCC_Other
);
4503 Results
.EnterNewScope();
4505 CodeCompletionAllocator
&Allocator
= Results
.getAllocator();
4506 CodeCompletionBuilder
Builder(Allocator
, Results
.getCodeCompletionTUInfo());
4507 typedef CodeCompletionResult Result
;
4509 // Enumerate all top-level modules.
4510 SmallVector
<Module
*, 8> Modules
;
4511 SemaRef
.PP
.getHeaderSearchInfo().collectAllModules(Modules
);
4512 for (unsigned I
= 0, N
= Modules
.size(); I
!= N
; ++I
) {
4513 Builder
.AddTypedTextChunk(
4514 Builder
.getAllocator().CopyString(Modules
[I
]->Name
));
4515 Results
.AddResult(Result(
4516 Builder
.TakeString(), CCP_Declaration
, CXCursor_ModuleImportDecl
,
4517 Modules
[I
]->isAvailable() ? CXAvailability_Available
4518 : CXAvailability_NotAvailable
));
4520 } else if (getLangOpts().Modules
) {
4521 // Load the named module.
4522 Module
*Mod
= SemaRef
.PP
.getModuleLoader().loadModule(
4523 ImportLoc
, Path
, Module::AllVisible
,
4524 /*IsInclusionDirective=*/false);
4525 // Enumerate submodules.
4527 for (auto *Submodule
: Mod
->submodules()) {
4528 Builder
.AddTypedTextChunk(
4529 Builder
.getAllocator().CopyString(Submodule
->Name
));
4530 Results
.AddResult(Result(
4531 Builder
.TakeString(), CCP_Declaration
, CXCursor_ModuleImportDecl
,
4532 Submodule
->isAvailable() ? CXAvailability_Available
4533 : CXAvailability_NotAvailable
));
4537 Results
.ExitScope();
4538 HandleCodeCompleteResults(&SemaRef
, CodeCompleter
,
4539 Results
.getCompletionContext(), Results
.data(),
4543 void SemaCodeCompletion::CodeCompleteOrdinaryName(
4544 Scope
*S
, SemaCodeCompletion::ParserCompletionContext CompletionContext
) {
4545 ResultBuilder
Results(SemaRef
, CodeCompleter
->getAllocator(),
4546 CodeCompleter
->getCodeCompletionTUInfo(),
4547 mapCodeCompletionContext(SemaRef
, CompletionContext
));
4548 Results
.EnterNewScope();
4550 // Determine how to filter results, e.g., so that the names of
4551 // values (functions, enumerators, function templates, etc.) are
4552 // only allowed where we can have an expression.
4553 switch (CompletionContext
) {
4556 case PCC_ObjCInterface
:
4557 case PCC_ObjCImplementation
:
4558 case PCC_ObjCInstanceVariableList
:
4560 case PCC_MemberTemplate
:
4562 case PCC_LocalDeclarationSpecifiers
:
4563 Results
.setFilter(&ResultBuilder::IsOrdinaryNonValueName
);
4567 case PCC_TopLevelOrExpression
:
4568 case PCC_ParenthesizedExpression
:
4569 case PCC_Expression
:
4572 if (WantTypesInContext(CompletionContext
, getLangOpts()))
4573 Results
.setFilter(&ResultBuilder::IsOrdinaryName
);
4575 Results
.setFilter(&ResultBuilder::IsOrdinaryNonTypeName
);
4577 if (getLangOpts().CPlusPlus
)
4578 MaybeAddOverrideCalls(SemaRef
, /*InContext=*/nullptr, Results
);
4581 case PCC_RecoveryInFunction
:
4586 // If we are in a C++ non-static member function, check the qualifiers on
4587 // the member function to filter/prioritize the results list.
4588 auto ThisType
= SemaRef
.getCurrentThisType();
4589 if (!ThisType
.isNull())
4590 Results
.setObjectTypeQualifiers(ThisType
->getPointeeType().getQualifiers(),
4593 CodeCompletionDeclConsumer
Consumer(Results
, SemaRef
.CurContext
);
4594 SemaRef
.LookupVisibleDecls(S
, SemaRef
.LookupOrdinaryName
, Consumer
,
4595 CodeCompleter
->includeGlobals(),
4596 CodeCompleter
->loadExternal());
4598 AddOrdinaryNameResults(CompletionContext
, S
, SemaRef
, Results
);
4599 Results
.ExitScope();
4601 switch (CompletionContext
) {
4602 case PCC_ParenthesizedExpression
:
4603 case PCC_Expression
:
4605 case PCC_TopLevelOrExpression
:
4606 case PCC_RecoveryInFunction
:
4607 if (S
->getFnParent())
4608 AddPrettyFunctionResults(getLangOpts(), Results
);
4613 case PCC_ObjCInterface
:
4614 case PCC_ObjCImplementation
:
4615 case PCC_ObjCInstanceVariableList
:
4617 case PCC_MemberTemplate
:
4621 case PCC_LocalDeclarationSpecifiers
:
4625 if (CodeCompleter
->includeMacros())
4626 AddMacroResults(SemaRef
.PP
, Results
, CodeCompleter
->loadExternal(), false);
4628 HandleCodeCompleteResults(&SemaRef
, CodeCompleter
,
4629 Results
.getCompletionContext(), Results
.data(),
4634 AddClassMessageCompletions(Sema
&SemaRef
, Scope
*S
, ParsedType Receiver
,
4635 ArrayRef
<const IdentifierInfo
*> SelIdents
,
4636 bool AtArgumentExpression
, bool IsSuper
,
4637 ResultBuilder
&Results
);
4639 void SemaCodeCompletion::CodeCompleteDeclSpec(Scope
*S
, DeclSpec
&DS
,
4640 bool AllowNonIdentifiers
,
4641 bool AllowNestedNameSpecifiers
) {
4642 typedef CodeCompletionResult Result
;
4643 ResultBuilder
Results(
4644 SemaRef
, CodeCompleter
->getAllocator(),
4645 CodeCompleter
->getCodeCompletionTUInfo(),
4646 AllowNestedNameSpecifiers
4647 // FIXME: Try to separate codepath leading here to deduce whether we
4648 // need an existing symbol or a new one.
4649 ? CodeCompletionContext::CCC_SymbolOrNewName
4650 : CodeCompletionContext::CCC_NewName
);
4651 Results
.EnterNewScope();
4653 // Type qualifiers can come after names.
4654 Results
.AddResult(Result("const"));
4655 Results
.AddResult(Result("volatile"));
4656 if (getLangOpts().C99
)
4657 Results
.AddResult(Result("restrict"));
4659 if (getLangOpts().CPlusPlus
) {
4660 if (getLangOpts().CPlusPlus11
&&
4661 (DS
.getTypeSpecType() == DeclSpec::TST_class
||
4662 DS
.getTypeSpecType() == DeclSpec::TST_struct
))
4663 Results
.AddResult("final");
4665 if (AllowNonIdentifiers
) {
4666 Results
.AddResult(Result("operator"));
4669 // Add nested-name-specifiers.
4670 if (AllowNestedNameSpecifiers
) {
4671 Results
.allowNestedNameSpecifiers();
4672 Results
.setFilter(&ResultBuilder::IsImpossibleToSatisfy
);
4673 CodeCompletionDeclConsumer
Consumer(Results
, SemaRef
.CurContext
);
4674 SemaRef
.LookupVisibleDecls(S
, Sema::LookupNestedNameSpecifierName
,
4675 Consumer
, CodeCompleter
->includeGlobals(),
4676 CodeCompleter
->loadExternal());
4677 Results
.setFilter(nullptr);
4680 Results
.ExitScope();
4682 // If we're in a context where we might have an expression (rather than a
4683 // declaration), and what we've seen so far is an Objective-C type that could
4684 // be a receiver of a class message, this may be a class message send with
4685 // the initial opening bracket '[' missing. Add appropriate completions.
4686 if (AllowNonIdentifiers
&& !AllowNestedNameSpecifiers
&&
4687 DS
.getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier
&&
4688 DS
.getTypeSpecType() == DeclSpec::TST_typename
&&
4689 DS
.getTypeSpecComplex() == DeclSpec::TSC_unspecified
&&
4690 DS
.getTypeSpecSign() == TypeSpecifierSign::Unspecified
&&
4691 !DS
.isTypeAltiVecVector() && S
&&
4692 (S
->getFlags() & Scope::DeclScope
) != 0 &&
4693 (S
->getFlags() & (Scope::ClassScope
| Scope::TemplateParamScope
|
4694 Scope::FunctionPrototypeScope
| Scope::AtCatchScope
)) ==
4696 ParsedType T
= DS
.getRepAsType();
4697 if (!T
.get().isNull() && T
.get()->isObjCObjectOrInterfaceType())
4698 AddClassMessageCompletions(SemaRef
, S
, T
, {}, false, false, Results
);
4701 // Note that we intentionally suppress macro results here, since we do not
4702 // encourage using macros to produce the names of entities.
4704 HandleCodeCompleteResults(&SemaRef
, CodeCompleter
,
4705 Results
.getCompletionContext(), Results
.data(),
4709 static const char *underscoreAttrScope(llvm::StringRef Scope
) {
4710 if (Scope
== "clang")
4717 static const char *noUnderscoreAttrScope(llvm::StringRef Scope
) {
4718 if (Scope
== "_Clang")
4720 if (Scope
== "__gnu__")
4725 void SemaCodeCompletion::CodeCompleteAttribute(
4726 AttributeCommonInfo::Syntax Syntax
, AttributeCompletion Completion
,
4727 const IdentifierInfo
*InScope
) {
4728 if (Completion
== AttributeCompletion::None
)
4730 ResultBuilder
Results(SemaRef
, CodeCompleter
->getAllocator(),
4731 CodeCompleter
->getCodeCompletionTUInfo(),
4732 CodeCompletionContext::CCC_Attribute
);
4734 // We're going to iterate over the normalized spellings of the attribute.
4735 // These don't include "underscore guarding": the normalized spelling is
4736 // clang::foo but you can also write _Clang::__foo__.
4738 // (Clang supports a mix like clang::__foo__ but we won't suggest it: either
4739 // you care about clashing with macros or you don't).
4741 // So if we're already in a scope, we determine its canonical spellings
4742 // (for comparison with normalized attr spelling) and remember whether it was
4743 // underscore-guarded (so we know how to spell contained attributes).
4744 llvm::StringRef InScopeName
;
4745 bool InScopeUnderscore
= false;
4747 InScopeName
= InScope
->getName();
4748 if (const char *NoUnderscore
= noUnderscoreAttrScope(InScopeName
)) {
4749 InScopeName
= NoUnderscore
;
4750 InScopeUnderscore
= true;
4753 bool SyntaxSupportsGuards
= Syntax
== AttributeCommonInfo::AS_GNU
||
4754 Syntax
== AttributeCommonInfo::AS_CXX11
||
4755 Syntax
== AttributeCommonInfo::AS_C23
;
4757 llvm::DenseSet
<llvm::StringRef
> FoundScopes
;
4758 auto AddCompletions
= [&](const ParsedAttrInfo
&A
) {
4759 if (A
.IsTargetSpecific
&&
4760 !A
.existsInTarget(getASTContext().getTargetInfo()))
4762 if (!A
.acceptsLangOpts(getLangOpts()))
4764 for (const auto &S
: A
.Spellings
) {
4765 if (S
.Syntax
!= Syntax
)
4767 llvm::StringRef Name
= S
.NormalizedFullName
;
4768 llvm::StringRef Scope
;
4769 if ((Syntax
== AttributeCommonInfo::AS_CXX11
||
4770 Syntax
== AttributeCommonInfo::AS_C23
)) {
4771 std::tie(Scope
, Name
) = Name
.split("::");
4772 if (Name
.empty()) // oops, unscoped
4773 std::swap(Name
, Scope
);
4776 // Do we just want a list of scopes rather than attributes?
4777 if (Completion
== AttributeCompletion::Scope
) {
4778 // Make sure to emit each scope only once.
4779 if (!Scope
.empty() && FoundScopes
.insert(Scope
).second
) {
4781 CodeCompletionResult(Results
.getAllocator().CopyString(Scope
)));
4782 // Include alternate form (__gnu__ instead of gnu).
4783 if (const char *Scope2
= underscoreAttrScope(Scope
))
4784 Results
.AddResult(CodeCompletionResult(Scope2
));
4789 // If a scope was specified, it must match but we don't need to print it.
4790 if (!InScopeName
.empty()) {
4791 if (Scope
!= InScopeName
)
4796 auto Add
= [&](llvm::StringRef Scope
, llvm::StringRef Name
,
4798 CodeCompletionBuilder
Builder(Results
.getAllocator(),
4799 Results
.getCodeCompletionTUInfo());
4800 llvm::SmallString
<32> Text
;
4801 if (!Scope
.empty()) {
4810 Builder
.AddTypedTextChunk(Results
.getAllocator().CopyString(Text
));
4812 if (!A
.ArgNames
.empty()) {
4813 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
, "(");
4815 for (const char *Arg
: A
.ArgNames
) {
4817 Builder
.AddChunk(CodeCompletionString::CK_Comma
, ", ");
4819 Builder
.AddPlaceholderChunk(Arg
);
4821 Builder
.AddChunk(CodeCompletionString::CK_RightParen
, ")");
4824 Results
.AddResult(Builder
.TakeString());
4827 // Generate the non-underscore-guarded result.
4828 // Note this is (a suffix of) the NormalizedFullName, no need to copy.
4829 // If an underscore-guarded scope was specified, only the
4830 // underscore-guarded attribute name is relevant.
4831 if (!InScopeUnderscore
)
4832 Add(Scope
, Name
, /*Underscores=*/false);
4834 // Generate the underscore-guarded version, for syntaxes that support it.
4835 // We skip this if the scope was already spelled and not guarded, or
4836 // we must spell it and can't guard it.
4837 if (!(InScope
&& !InScopeUnderscore
) && SyntaxSupportsGuards
) {
4838 llvm::SmallString
<32> Guarded
;
4839 if (Scope
.empty()) {
4840 Add(Scope
, Name
, /*Underscores=*/true);
4842 const char *GuardedScope
= underscoreAttrScope(Scope
);
4845 Add(GuardedScope
, Name
, /*Underscores=*/true);
4849 // It may be nice to include the Kind so we can look up the docs later.
4853 for (const auto *A
: ParsedAttrInfo::getAllBuiltin())
4855 for (const auto &Entry
: ParsedAttrInfoRegistry::entries())
4856 AddCompletions(*Entry
.instantiate());
4858 HandleCodeCompleteResults(&SemaRef
, CodeCompleter
,
4859 Results
.getCompletionContext(), Results
.data(),
4863 struct SemaCodeCompletion::CodeCompleteExpressionData
{
4864 CodeCompleteExpressionData(QualType PreferredType
= QualType(),
4865 bool IsParenthesized
= false)
4866 : PreferredType(PreferredType
), IntegralConstantExpression(false),
4867 ObjCCollection(false), IsParenthesized(IsParenthesized
) {}
4869 QualType PreferredType
;
4870 bool IntegralConstantExpression
;
4871 bool ObjCCollection
;
4872 bool IsParenthesized
;
4873 SmallVector
<Decl
*, 4> IgnoreDecls
;
4877 /// Information that allows to avoid completing redundant enumerators.
4878 struct CoveredEnumerators
{
4879 llvm::SmallPtrSet
<EnumConstantDecl
*, 8> Seen
;
4880 NestedNameSpecifier
*SuggestedQualifier
= nullptr;
4884 static void AddEnumerators(ResultBuilder
&Results
, ASTContext
&Context
,
4885 EnumDecl
*Enum
, DeclContext
*CurContext
,
4886 const CoveredEnumerators
&Enumerators
) {
4887 NestedNameSpecifier
*Qualifier
= Enumerators
.SuggestedQualifier
;
4888 if (Context
.getLangOpts().CPlusPlus
&& !Qualifier
&& Enumerators
.Seen
.empty()) {
4889 // If there are no prior enumerators in C++, check whether we have to
4890 // qualify the names of the enumerators that we suggest, because they
4891 // may not be visible in this scope.
4892 Qualifier
= getRequiredQualification(Context
, CurContext
, Enum
);
4895 Results
.EnterNewScope();
4896 for (auto *E
: Enum
->enumerators()) {
4897 if (Enumerators
.Seen
.count(E
))
4900 CodeCompletionResult
R(E
, CCP_EnumInCase
, Qualifier
);
4901 Results
.AddResult(R
, CurContext
, nullptr, false);
4903 Results
.ExitScope();
4906 /// Try to find a corresponding FunctionProtoType for function-like types (e.g.
4907 /// function pointers, std::function, etc).
4908 static const FunctionProtoType
*TryDeconstructFunctionLike(QualType T
) {
4909 assert(!T
.isNull());
4910 // Try to extract first template argument from std::function<> and similar.
4911 // Note we only handle the sugared types, they closely match what users wrote.
4912 // We explicitly choose to not handle ClassTemplateSpecializationDecl.
4913 if (auto *Specialization
= T
->getAs
<TemplateSpecializationType
>()) {
4914 if (Specialization
->template_arguments().size() != 1)
4916 const TemplateArgument
&Argument
= Specialization
->template_arguments()[0];
4917 if (Argument
.getKind() != TemplateArgument::Type
)
4919 return Argument
.getAsType()->getAs
<FunctionProtoType
>();
4921 // Handle other cases.
4922 if (T
->isPointerType())
4923 T
= T
->getPointeeType();
4924 return T
->getAs
<FunctionProtoType
>();
4927 /// Adds a pattern completion for a lambda expression with the specified
4928 /// parameter types and placeholders for parameter names.
4929 static void AddLambdaCompletion(ResultBuilder
&Results
,
4930 llvm::ArrayRef
<QualType
> Parameters
,
4931 const LangOptions
&LangOpts
) {
4932 if (!Results
.includeCodePatterns())
4934 CodeCompletionBuilder
Completion(Results
.getAllocator(),
4935 Results
.getCodeCompletionTUInfo());
4936 // [](<parameters>) {}
4937 Completion
.AddChunk(CodeCompletionString::CK_LeftBracket
);
4938 Completion
.AddPlaceholderChunk("=");
4939 Completion
.AddChunk(CodeCompletionString::CK_RightBracket
);
4940 if (!Parameters
.empty()) {
4941 Completion
.AddChunk(CodeCompletionString::CK_LeftParen
);
4943 for (auto Parameter
: Parameters
) {
4945 Completion
.AddChunk(CodeCompletionString::ChunkKind::CK_Comma
);
4949 constexpr llvm::StringLiteral NamePlaceholder
= "!#!NAME_GOES_HERE!#!";
4950 std::string Type
= std::string(NamePlaceholder
);
4951 Parameter
.getAsStringInternal(Type
, PrintingPolicy(LangOpts
));
4952 llvm::StringRef Prefix
, Suffix
;
4953 std::tie(Prefix
, Suffix
) = llvm::StringRef(Type
).split(NamePlaceholder
);
4954 Prefix
= Prefix
.rtrim();
4955 Suffix
= Suffix
.ltrim();
4957 Completion
.AddTextChunk(Completion
.getAllocator().CopyString(Prefix
));
4958 Completion
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
4959 Completion
.AddPlaceholderChunk("parameter");
4960 Completion
.AddTextChunk(Completion
.getAllocator().CopyString(Suffix
));
4962 Completion
.AddChunk(CodeCompletionString::CK_RightParen
);
4964 Completion
.AddChunk(clang::CodeCompletionString::CK_HorizontalSpace
);
4965 Completion
.AddChunk(CodeCompletionString::CK_LeftBrace
);
4966 Completion
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
4967 Completion
.AddPlaceholderChunk("body");
4968 Completion
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
4969 Completion
.AddChunk(CodeCompletionString::CK_RightBrace
);
4971 Results
.AddResult(Completion
.TakeString());
4974 /// Perform code-completion in an expression context when we know what
4975 /// type we're looking for.
4976 void SemaCodeCompletion::CodeCompleteExpression(
4977 Scope
*S
, const CodeCompleteExpressionData
&Data
) {
4978 ResultBuilder
Results(
4979 SemaRef
, CodeCompleter
->getAllocator(),
4980 CodeCompleter
->getCodeCompletionTUInfo(),
4981 CodeCompletionContext(
4982 Data
.IsParenthesized
4983 ? CodeCompletionContext::CCC_ParenthesizedExpression
4984 : CodeCompletionContext::CCC_Expression
,
4985 Data
.PreferredType
));
4987 Data
.IsParenthesized
? PCC_ParenthesizedExpression
: PCC_Expression
;
4988 if (Data
.ObjCCollection
)
4989 Results
.setFilter(&ResultBuilder::IsObjCCollection
);
4990 else if (Data
.IntegralConstantExpression
)
4991 Results
.setFilter(&ResultBuilder::IsIntegralConstantValue
);
4992 else if (WantTypesInContext(PCC
, getLangOpts()))
4993 Results
.setFilter(&ResultBuilder::IsOrdinaryName
);
4995 Results
.setFilter(&ResultBuilder::IsOrdinaryNonTypeName
);
4997 if (!Data
.PreferredType
.isNull())
4998 Results
.setPreferredType(Data
.PreferredType
.getNonReferenceType());
5000 // Ignore any declarations that we were told that we don't care about.
5001 for (unsigned I
= 0, N
= Data
.IgnoreDecls
.size(); I
!= N
; ++I
)
5002 Results
.Ignore(Data
.IgnoreDecls
[I
]);
5004 CodeCompletionDeclConsumer
Consumer(Results
, SemaRef
.CurContext
);
5005 SemaRef
.LookupVisibleDecls(S
, Sema::LookupOrdinaryName
, Consumer
,
5006 CodeCompleter
->includeGlobals(),
5007 CodeCompleter
->loadExternal());
5009 Results
.EnterNewScope();
5010 AddOrdinaryNameResults(PCC
, S
, SemaRef
, Results
);
5011 Results
.ExitScope();
5013 bool PreferredTypeIsPointer
= false;
5014 if (!Data
.PreferredType
.isNull()) {
5015 PreferredTypeIsPointer
= Data
.PreferredType
->isAnyPointerType() ||
5016 Data
.PreferredType
->isMemberPointerType() ||
5017 Data
.PreferredType
->isBlockPointerType();
5018 if (Data
.PreferredType
->isEnumeralType()) {
5019 EnumDecl
*Enum
= Data
.PreferredType
->castAs
<EnumType
>()->getDecl();
5020 if (auto *Def
= Enum
->getDefinition())
5022 // FIXME: collect covered enumerators in cases like:
5023 // if (x == my_enum::one) { ... } else if (x == ^) {}
5024 AddEnumerators(Results
, getASTContext(), Enum
, SemaRef
.CurContext
,
5025 CoveredEnumerators());
5029 if (S
->getFnParent() && !Data
.ObjCCollection
&&
5030 !Data
.IntegralConstantExpression
)
5031 AddPrettyFunctionResults(getLangOpts(), Results
);
5033 if (CodeCompleter
->includeMacros())
5034 AddMacroResults(SemaRef
.PP
, Results
, CodeCompleter
->loadExternal(), false,
5035 PreferredTypeIsPointer
);
5037 // Complete a lambda expression when preferred type is a function.
5038 if (!Data
.PreferredType
.isNull() && getLangOpts().CPlusPlus11
) {
5039 if (const FunctionProtoType
*F
=
5040 TryDeconstructFunctionLike(Data
.PreferredType
))
5041 AddLambdaCompletion(Results
, F
->getParamTypes(), getLangOpts());
5044 HandleCodeCompleteResults(&SemaRef
, CodeCompleter
,
5045 Results
.getCompletionContext(), Results
.data(),
5049 void SemaCodeCompletion::CodeCompleteExpression(Scope
*S
,
5050 QualType PreferredType
,
5051 bool IsParenthesized
) {
5052 return CodeCompleteExpression(
5053 S
, CodeCompleteExpressionData(PreferredType
, IsParenthesized
));
5056 void SemaCodeCompletion::CodeCompletePostfixExpression(Scope
*S
, ExprResult E
,
5057 QualType PreferredType
) {
5059 CodeCompleteExpression(S
, PreferredType
);
5060 else if (getLangOpts().ObjC
)
5061 CodeCompleteObjCInstanceMessage(S
, E
.get(), {}, false);
5064 /// The set of properties that have already been added, referenced by
5066 typedef llvm::SmallPtrSet
<const IdentifierInfo
*, 16> AddedPropertiesSet
;
5068 /// Retrieve the container definition, if any?
5069 static ObjCContainerDecl
*getContainerDef(ObjCContainerDecl
*Container
) {
5070 if (ObjCInterfaceDecl
*Interface
= dyn_cast
<ObjCInterfaceDecl
>(Container
)) {
5071 if (Interface
->hasDefinition())
5072 return Interface
->getDefinition();
5077 if (ObjCProtocolDecl
*Protocol
= dyn_cast
<ObjCProtocolDecl
>(Container
)) {
5078 if (Protocol
->hasDefinition())
5079 return Protocol
->getDefinition();
5086 /// Adds a block invocation code completion result for the given block
5087 /// declaration \p BD.
5088 static void AddObjCBlockCall(ASTContext
&Context
, const PrintingPolicy
&Policy
,
5089 CodeCompletionBuilder
&Builder
,
5090 const NamedDecl
*BD
,
5091 const FunctionTypeLoc
&BlockLoc
,
5092 const FunctionProtoTypeLoc
&BlockProtoLoc
) {
5093 Builder
.AddResultTypeChunk(
5094 GetCompletionTypeString(BlockLoc
.getReturnLoc().getType(), Context
,
5095 Policy
, Builder
.getAllocator()));
5097 AddTypedNameChunk(Context
, Policy
, BD
, Builder
);
5098 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
5100 if (BlockProtoLoc
&& BlockProtoLoc
.getTypePtr()->isVariadic()) {
5101 Builder
.AddPlaceholderChunk("...");
5103 for (unsigned I
= 0, N
= BlockLoc
.getNumParams(); I
!= N
; ++I
) {
5105 Builder
.AddChunk(CodeCompletionString::CK_Comma
);
5107 // Format the placeholder string.
5108 std::string PlaceholderStr
=
5109 FormatFunctionParameter(Policy
, BlockLoc
.getParam(I
));
5111 if (I
== N
- 1 && BlockProtoLoc
&&
5112 BlockProtoLoc
.getTypePtr()->isVariadic())
5113 PlaceholderStr
+= ", ...";
5115 // Add the placeholder string.
5116 Builder
.AddPlaceholderChunk(
5117 Builder
.getAllocator().CopyString(PlaceholderStr
));
5121 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
5125 AddObjCProperties(const CodeCompletionContext
&CCContext
,
5126 ObjCContainerDecl
*Container
, bool AllowCategories
,
5127 bool AllowNullaryMethods
, DeclContext
*CurContext
,
5128 AddedPropertiesSet
&AddedProperties
, ResultBuilder
&Results
,
5129 bool IsBaseExprStatement
= false,
5130 bool IsClassProperty
= false, bool InOriginalClass
= true) {
5131 typedef CodeCompletionResult Result
;
5133 // Retrieve the definition.
5134 Container
= getContainerDef(Container
);
5136 // Add properties in this container.
5137 const auto AddProperty
= [&](const ObjCPropertyDecl
*P
) {
5138 if (!AddedProperties
.insert(P
->getIdentifier()).second
)
5141 // FIXME: Provide block invocation completion for non-statement
5143 if (!P
->getType().getTypePtr()->isBlockPointerType() ||
5144 !IsBaseExprStatement
) {
5145 Result R
= Result(P
, Results
.getBasePriority(P
), nullptr);
5146 if (!InOriginalClass
)
5148 Results
.MaybeAddResult(R
, CurContext
);
5152 // Block setter and invocation completion is provided only when we are able
5153 // to find the FunctionProtoTypeLoc with parameter names for the block.
5154 FunctionTypeLoc BlockLoc
;
5155 FunctionProtoTypeLoc BlockProtoLoc
;
5156 findTypeLocationForBlockDecl(P
->getTypeSourceInfo(), BlockLoc
,
5159 Result R
= Result(P
, Results
.getBasePriority(P
), nullptr);
5160 if (!InOriginalClass
)
5162 Results
.MaybeAddResult(R
, CurContext
);
5166 // The default completion result for block properties should be the block
5167 // invocation completion when the base expression is a statement.
5168 CodeCompletionBuilder
Builder(Results
.getAllocator(),
5169 Results
.getCodeCompletionTUInfo());
5170 AddObjCBlockCall(Container
->getASTContext(),
5171 getCompletionPrintingPolicy(Results
.getSema()), Builder
, P
,
5172 BlockLoc
, BlockProtoLoc
);
5173 Result R
= Result(Builder
.TakeString(), P
, Results
.getBasePriority(P
));
5174 if (!InOriginalClass
)
5176 Results
.MaybeAddResult(R
, CurContext
);
5178 // Provide additional block setter completion iff the base expression is a
5179 // statement and the block property is mutable.
5180 if (!P
->isReadOnly()) {
5181 CodeCompletionBuilder
Builder(Results
.getAllocator(),
5182 Results
.getCodeCompletionTUInfo());
5183 AddResultTypeChunk(Container
->getASTContext(),
5184 getCompletionPrintingPolicy(Results
.getSema()), P
,
5185 CCContext
.getBaseType(), Builder
);
5186 Builder
.AddTypedTextChunk(
5187 Results
.getAllocator().CopyString(P
->getName()));
5188 Builder
.AddChunk(CodeCompletionString::CK_Equal
);
5190 std::string PlaceholderStr
= formatBlockPlaceholder(
5191 getCompletionPrintingPolicy(Results
.getSema()), P
, BlockLoc
,
5192 BlockProtoLoc
, /*SuppressBlockName=*/true);
5193 // Add the placeholder string.
5194 Builder
.AddPlaceholderChunk(
5195 Builder
.getAllocator().CopyString(PlaceholderStr
));
5197 // When completing blocks properties that return void the default
5198 // property completion result should show up before the setter,
5199 // otherwise the setter completion should show up before the default
5200 // property completion, as we normally want to use the result of the
5203 Result(Builder
.TakeString(), P
,
5204 Results
.getBasePriority(P
) +
5205 (BlockLoc
.getTypePtr()->getReturnType()->isVoidType()
5206 ? CCD_BlockPropertySetter
5207 : -CCD_BlockPropertySetter
));
5208 if (!InOriginalClass
)
5210 Results
.MaybeAddResult(R
, CurContext
);
5214 if (IsClassProperty
) {
5215 for (const auto *P
: Container
->class_properties())
5218 for (const auto *P
: Container
->instance_properties())
5222 // Add nullary methods or implicit class properties
5223 if (AllowNullaryMethods
) {
5224 ASTContext
&Context
= Container
->getASTContext();
5225 PrintingPolicy Policy
= getCompletionPrintingPolicy(Results
.getSema());
5226 // Adds a method result
5227 const auto AddMethod
= [&](const ObjCMethodDecl
*M
) {
5228 const IdentifierInfo
*Name
= M
->getSelector().getIdentifierInfoForSlot(0);
5231 if (!AddedProperties
.insert(Name
).second
)
5233 CodeCompletionBuilder
Builder(Results
.getAllocator(),
5234 Results
.getCodeCompletionTUInfo());
5235 AddResultTypeChunk(Context
, Policy
, M
, CCContext
.getBaseType(), Builder
);
5236 Builder
.AddTypedTextChunk(
5237 Results
.getAllocator().CopyString(Name
->getName()));
5238 Result R
= Result(Builder
.TakeString(), M
,
5239 CCP_MemberDeclaration
+ CCD_MethodAsProperty
);
5240 if (!InOriginalClass
)
5242 Results
.MaybeAddResult(R
, CurContext
);
5245 if (IsClassProperty
) {
5246 for (const auto *M
: Container
->methods()) {
5247 // Gather the class method that can be used as implicit property
5248 // getters. Methods with arguments or methods that return void aren't
5249 // added to the results as they can't be used as a getter.
5250 if (!M
->getSelector().isUnarySelector() ||
5251 M
->getReturnType()->isVoidType() || M
->isInstanceMethod())
5256 for (auto *M
: Container
->methods()) {
5257 if (M
->getSelector().isUnarySelector())
5263 // Add properties in referenced protocols.
5264 if (ObjCProtocolDecl
*Protocol
= dyn_cast
<ObjCProtocolDecl
>(Container
)) {
5265 for (auto *P
: Protocol
->protocols())
5266 AddObjCProperties(CCContext
, P
, AllowCategories
, AllowNullaryMethods
,
5267 CurContext
, AddedProperties
, Results
,
5268 IsBaseExprStatement
, IsClassProperty
,
5269 /*InOriginalClass*/ false);
5270 } else if (ObjCInterfaceDecl
*IFace
=
5271 dyn_cast
<ObjCInterfaceDecl
>(Container
)) {
5272 if (AllowCategories
) {
5273 // Look through categories.
5274 for (auto *Cat
: IFace
->known_categories())
5275 AddObjCProperties(CCContext
, Cat
, AllowCategories
, AllowNullaryMethods
,
5276 CurContext
, AddedProperties
, Results
,
5277 IsBaseExprStatement
, IsClassProperty
,
5281 // Look through protocols.
5282 for (auto *I
: IFace
->all_referenced_protocols())
5283 AddObjCProperties(CCContext
, I
, AllowCategories
, AllowNullaryMethods
,
5284 CurContext
, AddedProperties
, Results
,
5285 IsBaseExprStatement
, IsClassProperty
,
5286 /*InOriginalClass*/ false);
5288 // Look in the superclass.
5289 if (IFace
->getSuperClass())
5290 AddObjCProperties(CCContext
, IFace
->getSuperClass(), AllowCategories
,
5291 AllowNullaryMethods
, CurContext
, AddedProperties
,
5292 Results
, IsBaseExprStatement
, IsClassProperty
,
5293 /*InOriginalClass*/ false);
5294 } else if (const auto *Category
=
5295 dyn_cast
<ObjCCategoryDecl
>(Container
)) {
5296 // Look through protocols.
5297 for (auto *P
: Category
->protocols())
5298 AddObjCProperties(CCContext
, P
, AllowCategories
, AllowNullaryMethods
,
5299 CurContext
, AddedProperties
, Results
,
5300 IsBaseExprStatement
, IsClassProperty
,
5301 /*InOriginalClass*/ false);
5306 AddRecordMembersCompletionResults(Sema
&SemaRef
, ResultBuilder
&Results
,
5307 Scope
*S
, QualType BaseType
,
5308 ExprValueKind BaseKind
, RecordDecl
*RD
,
5309 std::optional
<FixItHint
> AccessOpFixIt
) {
5310 // Indicate that we are performing a member access, and the cv-qualifiers
5311 // for the base object type.
5312 Results
.setObjectTypeQualifiers(BaseType
.getQualifiers(), BaseKind
);
5314 // Access to a C/C++ class, struct, or union.
5315 Results
.allowNestedNameSpecifiers();
5316 std::vector
<FixItHint
> FixIts
;
5318 FixIts
.emplace_back(*AccessOpFixIt
);
5319 CodeCompletionDeclConsumer
Consumer(Results
, RD
, BaseType
, std::move(FixIts
));
5320 SemaRef
.LookupVisibleDecls(
5321 RD
, Sema::LookupMemberName
, Consumer
,
5322 SemaRef
.CodeCompletion().CodeCompleter
->includeGlobals(),
5323 /*IncludeDependentBases=*/true,
5324 SemaRef
.CodeCompletion().CodeCompleter
->loadExternal());
5326 if (SemaRef
.getLangOpts().CPlusPlus
) {
5327 if (!Results
.empty()) {
5328 // The "template" keyword can follow "->" or "." in the grammar.
5329 // However, we only want to suggest the template keyword if something
5331 bool IsDependent
= BaseType
->isDependentType();
5333 for (Scope
*DepScope
= S
; DepScope
; DepScope
= DepScope
->getParent())
5334 if (DeclContext
*Ctx
= DepScope
->getEntity()) {
5335 IsDependent
= Ctx
->isDependentContext();
5341 Results
.AddResult(CodeCompletionResult("template"));
5346 // Returns the RecordDecl inside the BaseType, falling back to primary template
5347 // in case of specializations. Since we might not have a decl for the
5348 // instantiation/specialization yet, e.g. dependent code.
5349 static RecordDecl
*getAsRecordDecl(QualType BaseType
) {
5350 BaseType
= BaseType
.getNonReferenceType();
5351 if (auto *RD
= BaseType
->getAsRecordDecl()) {
5352 if (const auto *CTSD
=
5353 llvm::dyn_cast
<ClassTemplateSpecializationDecl
>(RD
)) {
5354 // Template might not be instantiated yet, fall back to primary template
5356 if (CTSD
->getTemplateSpecializationKind() == TSK_Undeclared
)
5357 RD
= CTSD
->getSpecializedTemplate()->getTemplatedDecl();
5362 if (const auto *TST
= BaseType
->getAs
<TemplateSpecializationType
>()) {
5363 if (const auto *TD
= dyn_cast_or_null
<ClassTemplateDecl
>(
5364 TST
->getTemplateName().getAsTemplateDecl())) {
5365 return TD
->getTemplatedDecl();
5373 // Collects completion-relevant information about a concept-constrainted type T.
5374 // In particular, examines the constraint expressions to find members of T.
5376 // The design is very simple: we walk down each constraint looking for
5377 // expressions of the form T.foo().
5378 // If we're extra lucky, the return type is specified.
5379 // We don't do any clever handling of && or || in constraint expressions, we
5380 // take members from both branches.
5382 // For example, given:
5383 // template <class T> concept X = requires (T t, string& s) { t.print(s); };
5384 // template <X U> void foo(U u) { u.^ }
5385 // We want to suggest the inferred member function 'print(string)'.
5386 // We see that u has type U, so X<U> holds.
5387 // X<U> requires t.print(s) to be valid, where t has type U (substituted for T).
5388 // By looking at the CallExpr we find the signature of print().
5390 // While we tend to know in advance which kind of members (access via . -> ::)
5391 // we want, it's simpler just to gather them all and post-filter.
5393 // FIXME: some of this machinery could be used for non-concept type-parms too,
5394 // enabling completion for type parameters based on other uses of that param.
5396 // FIXME: there are other cases where a type can be constrained by a concept,
5397 // e.g. inside `if constexpr(ConceptSpecializationExpr) { ... }`
5400 // Describes a likely member of a type, inferred by concept constraints.
5401 // Offered as a code completion for T. T-> and T:: contexts.
5403 // Always non-null: we only handle members with ordinary identifier names.
5404 const IdentifierInfo
*Name
= nullptr;
5405 // Set for functions we've seen called.
5406 // We don't have the declared parameter types, only the actual types of
5407 // arguments we've seen. These are still valuable, as it's hard to render
5408 // a useful function completion with neither parameter types nor names!
5409 std::optional
<SmallVector
<QualType
, 1>> ArgTypes
;
5410 // Whether this is accessed as T.member, T->member, or T::member.
5411 enum AccessOperator
{
5416 // What's known about the type of a variable or return type of a function.
5417 const TypeConstraint
*ResultType
= nullptr;
5418 // FIXME: also track:
5419 // - kind of entity (function/variable/type), to expose structured results
5420 // - template args kinds/types, as a proxy for template params
5422 // For now we simply return these results as "pattern" strings.
5423 CodeCompletionString
*render(Sema
&S
, CodeCompletionAllocator
&Alloc
,
5424 CodeCompletionTUInfo
&Info
) const {
5425 CodeCompletionBuilder
B(Alloc
, Info
);
5428 std::string AsString
;
5430 llvm::raw_string_ostream
OS(AsString
);
5431 QualType ExactType
= deduceType(*ResultType
);
5432 if (!ExactType
.isNull())
5433 ExactType
.print(OS
, getCompletionPrintingPolicy(S
));
5435 ResultType
->print(OS
, getCompletionPrintingPolicy(S
));
5437 B
.AddResultTypeChunk(Alloc
.CopyString(AsString
));
5440 B
.AddTypedTextChunk(Alloc
.CopyString(Name
->getName()));
5441 // Function argument list
5443 B
.AddChunk(clang::CodeCompletionString::CK_LeftParen
);
5445 for (QualType Arg
: *ArgTypes
) {
5449 B
.AddChunk(clang::CodeCompletionString::CK_Comma
);
5450 B
.AddChunk(clang::CodeCompletionString::CK_HorizontalSpace
);
5452 B
.AddPlaceholderChunk(Alloc
.CopyString(
5453 Arg
.getAsString(getCompletionPrintingPolicy(S
))));
5455 B
.AddChunk(clang::CodeCompletionString::CK_RightParen
);
5457 return B
.TakeString();
5461 // BaseType is the type parameter T to infer members from.
5462 // T must be accessible within S, as we use it to find the template entity
5463 // that T is attached to in order to gather the relevant constraints.
5464 ConceptInfo(const TemplateTypeParmType
&BaseType
, Scope
*S
) {
5465 auto *TemplatedEntity
= getTemplatedEntity(BaseType
.getDecl(), S
);
5466 for (const Expr
*E
: constraintsForTemplatedEntity(TemplatedEntity
))
5467 believe(E
, &BaseType
);
5470 std::vector
<Member
> members() {
5471 std::vector
<Member
> Results
;
5472 for (const auto &E
: this->Results
)
5473 Results
.push_back(E
.second
);
5474 llvm::sort(Results
, [](const Member
&L
, const Member
&R
) {
5475 return L
.Name
->getName() < R
.Name
->getName();
5481 // Infer members of T, given that the expression E (dependent on T) is true.
5482 void believe(const Expr
*E
, const TemplateTypeParmType
*T
) {
5485 if (auto *CSE
= dyn_cast
<ConceptSpecializationExpr
>(E
)) {
5486 // If the concept is
5487 // template <class A, class B> concept CD = f<A, B>();
5488 // And the concept specialization is
5490 // Then we're substituting T for B, so we want to make f<A, B>() true
5491 // by adding members to B - i.e. believe(f<A, B>(), B);
5494 // - we don't attempt to substitute int for A
5495 // - when T is used in other ways (like CD<T*>) we ignore it
5496 ConceptDecl
*CD
= CSE
->getNamedConcept();
5497 TemplateParameterList
*Params
= CD
->getTemplateParameters();
5499 for (const auto &Arg
: CSE
->getTemplateArguments()) {
5500 if (Index
>= Params
->size())
5501 break; // Won't happen in valid code.
5502 if (isApprox(Arg
, T
)) {
5503 auto *TTPD
= dyn_cast
<TemplateTypeParmDecl
>(Params
->getParam(Index
));
5506 // T was used as an argument, and bound to the parameter TT.
5507 auto *TT
= cast
<TemplateTypeParmType
>(TTPD
->getTypeForDecl());
5508 // So now we know the constraint as a function of TT is true.
5509 believe(CD
->getConstraintExpr(), TT
);
5510 // (concepts themselves have no associated constraints to require)
5515 } else if (auto *BO
= dyn_cast
<BinaryOperator
>(E
)) {
5516 // For A && B, we can infer members from both branches.
5517 // For A || B, the union is still more useful than the intersection.
5518 if (BO
->getOpcode() == BO_LAnd
|| BO
->getOpcode() == BO_LOr
) {
5519 believe(BO
->getLHS(), T
);
5520 believe(BO
->getRHS(), T
);
5522 } else if (auto *RE
= dyn_cast
<RequiresExpr
>(E
)) {
5523 // A requires(){...} lets us infer members from each requirement.
5524 for (const concepts::Requirement
*Req
: RE
->getRequirements()) {
5525 if (!Req
->isDependent())
5526 continue; // Can't tell us anything about T.
5527 // Now Req cannot a substitution-error: those aren't dependent.
5529 if (auto *TR
= dyn_cast
<concepts::TypeRequirement
>(Req
)) {
5530 // Do a full traversal so we get `foo` from `typename T::foo::bar`.
5531 QualType AssertedType
= TR
->getType()->getType();
5532 ValidVisitor(this, T
).TraverseType(AssertedType
);
5533 } else if (auto *ER
= dyn_cast
<concepts::ExprRequirement
>(Req
)) {
5534 ValidVisitor
Visitor(this, T
);
5535 // If we have a type constraint on the value of the expression,
5536 // AND the whole outer expression describes a member, then we'll
5537 // be able to use the constraint to provide the return type.
5538 if (ER
->getReturnTypeRequirement().isTypeConstraint()) {
5540 ER
->getReturnTypeRequirement().getTypeConstraint();
5541 Visitor
.OuterExpr
= ER
->getExpr();
5543 Visitor
.TraverseStmt(ER
->getExpr());
5544 } else if (auto *NR
= dyn_cast
<concepts::NestedRequirement
>(Req
)) {
5545 believe(NR
->getConstraintExpr(), T
);
5551 // This visitor infers members of T based on traversing expressions/types
5552 // that involve T. It is invoked with code known to be valid for T.
5553 class ValidVisitor
: public DynamicRecursiveASTVisitor
{
5555 const TemplateTypeParmType
*T
;
5557 CallExpr
*Caller
= nullptr;
5558 Expr
*Callee
= nullptr;
5561 // If set, OuterExpr is constrained by OuterType.
5562 Expr
*OuterExpr
= nullptr;
5563 const TypeConstraint
*OuterType
= nullptr;
5565 ValidVisitor(ConceptInfo
*Outer
, const TemplateTypeParmType
*T
)
5566 : Outer(Outer
), T(T
) {
5570 // In T.foo or T->foo, `foo` is a member function/variable.
5572 VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr
*E
) override
{
5573 const Type
*Base
= E
->getBaseType().getTypePtr();
5574 bool IsArrow
= E
->isArrow();
5575 if (Base
->isPointerType() && IsArrow
) {
5577 Base
= Base
->getPointeeType().getTypePtr();
5579 if (isApprox(Base
, T
))
5580 addValue(E
, E
->getMember(), IsArrow
? Member::Arrow
: Member::Dot
);
5584 // In T::foo, `foo` is a static member function/variable.
5585 bool VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr
*E
) override
{
5586 if (E
->getQualifier() && isApprox(E
->getQualifier()->getAsType(), T
))
5587 addValue(E
, E
->getDeclName(), Member::Colons
);
5591 // In T::typename foo, `foo` is a type.
5592 bool VisitDependentNameType(DependentNameType
*DNT
) override
{
5593 const auto *Q
= DNT
->getQualifier();
5594 if (Q
&& isApprox(Q
->getAsType(), T
))
5595 addType(DNT
->getIdentifier());
5599 // In T::foo::bar, `foo` must be a type.
5600 // VisitNNS() doesn't exist, and TraverseNNS isn't always called :-(
5601 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNSL
) override
{
5603 NestedNameSpecifier
*NNS
= NNSL
.getNestedNameSpecifier();
5604 const auto *Q
= NNS
->getPrefix();
5605 if (Q
&& isApprox(Q
->getAsType(), T
))
5606 addType(NNS
->getAsIdentifier());
5608 // FIXME: also handle T::foo<X>::bar
5609 return DynamicRecursiveASTVisitor::TraverseNestedNameSpecifierLoc(NNSL
);
5612 // FIXME also handle T::foo<X>
5614 // Track the innermost caller/callee relationship so we can tell if a
5615 // nested expr is being called as a function.
5616 bool VisitCallExpr(CallExpr
*CE
) override
{
5618 Callee
= CE
->getCallee();
5623 void addResult(Member
&&M
) {
5624 auto R
= Outer
->Results
.try_emplace(M
.Name
);
5625 Member
&O
= R
.first
->second
;
5626 // Overwrite existing if the new member has more info.
5627 // The preference of . vs :: vs -> is fairly arbitrary.
5628 if (/*Inserted*/ R
.second
||
5629 std::make_tuple(M
.ArgTypes
.has_value(), M
.ResultType
!= nullptr,
5630 M
.Operator
) > std::make_tuple(O
.ArgTypes
.has_value(),
5631 O
.ResultType
!= nullptr,
5636 void addType(const IdentifierInfo
*Name
) {
5641 M
.Operator
= Member::Colons
;
5642 addResult(std::move(M
));
5645 void addValue(Expr
*E
, DeclarationName Name
,
5646 Member::AccessOperator Operator
) {
5647 if (!Name
.isIdentifier())
5650 Result
.Name
= Name
.getAsIdentifierInfo();
5651 Result
.Operator
= Operator
;
5652 // If this is the callee of an immediately-enclosing CallExpr, then
5653 // treat it as a method, otherwise it's a variable.
5654 if (Caller
!= nullptr && Callee
== E
) {
5655 Result
.ArgTypes
.emplace();
5656 for (const auto *Arg
: Caller
->arguments())
5657 Result
.ArgTypes
->push_back(Arg
->getType());
5658 if (Caller
== OuterExpr
) {
5659 Result
.ResultType
= OuterType
;
5663 Result
.ResultType
= OuterType
;
5665 addResult(std::move(Result
));
5669 static bool isApprox(const TemplateArgument
&Arg
, const Type
*T
) {
5670 return Arg
.getKind() == TemplateArgument::Type
&&
5671 isApprox(Arg
.getAsType().getTypePtr(), T
);
5674 static bool isApprox(const Type
*T1
, const Type
*T2
) {
5676 T1
->getCanonicalTypeUnqualified() ==
5677 T2
->getCanonicalTypeUnqualified();
5680 // Returns the DeclContext immediately enclosed by the template parameter
5681 // scope. For primary templates, this is the templated (e.g.) CXXRecordDecl.
5682 // For specializations, this is e.g. ClassTemplatePartialSpecializationDecl.
5683 static DeclContext
*getTemplatedEntity(const TemplateTypeParmDecl
*D
,
5687 Scope
*Inner
= nullptr;
5689 if (S
->isTemplateParamScope() && S
->isDeclScope(D
))
5690 return Inner
? Inner
->getEntity() : nullptr;
5697 // Gets all the type constraint expressions that might apply to the type
5698 // variables associated with DC (as returned by getTemplatedEntity()).
5699 static SmallVector
<const Expr
*, 1>
5700 constraintsForTemplatedEntity(DeclContext
*DC
) {
5701 SmallVector
<const Expr
*, 1> Result
;
5704 // Primary templates can have constraints.
5705 if (const auto *TD
= cast
<Decl
>(DC
)->getDescribedTemplate())
5706 TD
->getAssociatedConstraints(Result
);
5707 // Partial specializations may have constraints.
5708 if (const auto *CTPSD
=
5709 dyn_cast
<ClassTemplatePartialSpecializationDecl
>(DC
))
5710 CTPSD
->getAssociatedConstraints(Result
);
5711 if (const auto *VTPSD
= dyn_cast
<VarTemplatePartialSpecializationDecl
>(DC
))
5712 VTPSD
->getAssociatedConstraints(Result
);
5716 // Attempt to find the unique type satisfying a constraint.
5717 // This lets us show e.g. `int` instead of `std::same_as<int>`.
5718 static QualType
deduceType(const TypeConstraint
&T
) {
5719 // Assume a same_as<T> return type constraint is std::same_as or equivalent.
5720 // In this case the return type is T.
5721 DeclarationName DN
= T
.getNamedConcept()->getDeclName();
5722 if (DN
.isIdentifier() && DN
.getAsIdentifierInfo()->isStr("same_as"))
5723 if (const auto *Args
= T
.getTemplateArgsAsWritten())
5724 if (Args
->getNumTemplateArgs() == 1) {
5725 const auto &Arg
= Args
->arguments().front().getArgument();
5726 if (Arg
.getKind() == TemplateArgument::Type
)
5727 return Arg
.getAsType();
5732 llvm::DenseMap
<const IdentifierInfo
*, Member
> Results
;
5735 // Returns a type for E that yields acceptable member completions.
5736 // In particular, when E->getType() is DependentTy, try to guess a likely type.
5737 // We accept some lossiness (like dropping parameters).
5738 // We only try to handle common expressions on the LHS of MemberExpr.
5739 QualType
getApproximateType(const Expr
*E
) {
5740 if (E
->getType().isNull())
5742 E
= E
->IgnoreParenImpCasts();
5743 QualType Unresolved
= E
->getType();
5744 // We only resolve DependentTy, or undeduced autos (including auto* etc).
5745 if (!Unresolved
->isSpecificBuiltinType(BuiltinType::Dependent
)) {
5746 AutoType
*Auto
= Unresolved
->getContainedAutoType();
5747 if (!Auto
|| !Auto
->isUndeducedAutoType())
5750 // A call: approximate-resolve callee to a function type, get its return type
5751 if (const CallExpr
*CE
= llvm::dyn_cast
<CallExpr
>(E
)) {
5752 QualType Callee
= getApproximateType(CE
->getCallee());
5753 if (Callee
.isNull() ||
5754 Callee
->isSpecificPlaceholderType(BuiltinType::BoundMember
))
5755 Callee
= Expr::findBoundMemberType(CE
->getCallee());
5756 if (Callee
.isNull())
5759 if (const auto *FnTypePtr
= Callee
->getAs
<PointerType
>()) {
5760 Callee
= FnTypePtr
->getPointeeType();
5761 } else if (const auto *BPT
= Callee
->getAs
<BlockPointerType
>()) {
5762 Callee
= BPT
->getPointeeType();
5764 if (const FunctionType
*FnType
= Callee
->getAs
<FunctionType
>())
5765 return FnType
->getReturnType().getNonReferenceType();
5767 // Unresolved call: try to guess the return type.
5768 if (const auto *OE
= llvm::dyn_cast
<OverloadExpr
>(CE
->getCallee())) {
5769 // If all candidates have the same approximate return type, use it.
5770 // Discard references and const to allow more to be "the same".
5771 // (In particular, if there's one candidate + ADL, resolve it).
5772 const Type
*Common
= nullptr;
5773 for (const auto *D
: OE
->decls()) {
5774 QualType ReturnType
;
5775 if (const auto *FD
= llvm::dyn_cast
<FunctionDecl
>(D
))
5776 ReturnType
= FD
->getReturnType();
5777 else if (const auto *FTD
= llvm::dyn_cast
<FunctionTemplateDecl
>(D
))
5778 ReturnType
= FTD
->getTemplatedDecl()->getReturnType();
5779 if (ReturnType
.isNull())
5781 const Type
*Candidate
=
5782 ReturnType
.getNonReferenceType().getCanonicalType().getTypePtr();
5783 if (Common
&& Common
!= Candidate
)
5784 return Unresolved
; // Multiple candidates.
5787 if (Common
!= nullptr)
5788 return QualType(Common
, 0);
5791 // A dependent member: approximate-resolve the base, then lookup.
5792 if (const auto *CDSME
= llvm::dyn_cast
<CXXDependentScopeMemberExpr
>(E
)) {
5793 QualType Base
= CDSME
->isImplicitAccess()
5794 ? CDSME
->getBaseType()
5795 : getApproximateType(CDSME
->getBase());
5796 if (CDSME
->isArrow() && !Base
.isNull())
5797 Base
= Base
->getPointeeType(); // could handle unique_ptr etc here?
5801 : llvm::dyn_cast_or_null
<CXXRecordDecl
>(getAsRecordDecl(Base
));
5802 if (RD
&& RD
->isCompleteDefinition()) {
5803 // Look up member heuristically, including in bases.
5804 for (const auto *Member
: RD
->lookupDependentName(
5805 CDSME
->getMember(), [](const NamedDecl
*Member
) {
5806 return llvm::isa
<ValueDecl
>(Member
);
5808 return llvm::cast
<ValueDecl
>(Member
)->getType().getNonReferenceType();
5812 // A reference to an `auto` variable: approximate-resolve its initializer.
5813 if (const auto *DRE
= llvm::dyn_cast
<DeclRefExpr
>(E
)) {
5814 if (const auto *VD
= llvm::dyn_cast
<VarDecl
>(DRE
->getDecl())) {
5816 return getApproximateType(VD
->getInit());
5819 if (const auto *UO
= llvm::dyn_cast
<UnaryOperator
>(E
)) {
5820 if (UO
->getOpcode() == UnaryOperatorKind::UO_Deref
) {
5821 // We recurse into the subexpression because it could be of dependent
5823 if (auto Pointee
= getApproximateType(UO
->getSubExpr())->getPointeeType();
5826 // Our caller expects a non-null result, even though the SubType is
5827 // supposed to have a pointee. Fall through to Unresolved anyway.
5833 // If \p Base is ParenListExpr, assume a chain of comma operators and pick the
5834 // last expr. We expect other ParenListExprs to be resolved to e.g. constructor
5835 // calls before here. (So the ParenListExpr should be nonempty, but check just
5837 Expr
*unwrapParenList(Expr
*Base
) {
5838 if (auto *PLE
= llvm::dyn_cast_or_null
<ParenListExpr
>(Base
)) {
5839 if (PLE
->getNumExprs() == 0)
5841 Base
= PLE
->getExpr(PLE
->getNumExprs() - 1);
5848 void SemaCodeCompletion::CodeCompleteMemberReferenceExpr(
5849 Scope
*S
, Expr
*Base
, Expr
*OtherOpBase
, SourceLocation OpLoc
, bool IsArrow
,
5850 bool IsBaseExprStatement
, QualType PreferredType
) {
5851 Base
= unwrapParenList(Base
);
5852 OtherOpBase
= unwrapParenList(OtherOpBase
);
5853 if (!Base
|| !CodeCompleter
)
5856 ExprResult ConvertedBase
=
5857 SemaRef
.PerformMemberExprBaseConversion(Base
, IsArrow
);
5858 if (ConvertedBase
.isInvalid())
5860 QualType ConvertedBaseType
= getApproximateType(ConvertedBase
.get());
5862 enum CodeCompletionContext::Kind contextKind
;
5865 if (const auto *Ptr
= ConvertedBaseType
->getAs
<PointerType
>())
5866 ConvertedBaseType
= Ptr
->getPointeeType();
5870 contextKind
= CodeCompletionContext::CCC_ArrowMemberAccess
;
5872 if (ConvertedBaseType
->isObjCObjectPointerType() ||
5873 ConvertedBaseType
->isObjCObjectOrInterfaceType()) {
5874 contextKind
= CodeCompletionContext::CCC_ObjCPropertyAccess
;
5876 contextKind
= CodeCompletionContext::CCC_DotMemberAccess
;
5880 CodeCompletionContext
CCContext(contextKind
, ConvertedBaseType
);
5881 CCContext
.setPreferredType(PreferredType
);
5882 ResultBuilder
Results(SemaRef
, CodeCompleter
->getAllocator(),
5883 CodeCompleter
->getCodeCompletionTUInfo(), CCContext
,
5884 &ResultBuilder::IsMember
);
5886 auto DoCompletion
= [&](Expr
*Base
, bool IsArrow
,
5887 std::optional
<FixItHint
> AccessOpFixIt
) -> bool {
5891 ExprResult ConvertedBase
=
5892 SemaRef
.PerformMemberExprBaseConversion(Base
, IsArrow
);
5893 if (ConvertedBase
.isInvalid())
5895 Base
= ConvertedBase
.get();
5897 QualType BaseType
= getApproximateType(Base
);
5898 if (BaseType
.isNull())
5900 ExprValueKind BaseKind
= Base
->getValueKind();
5903 if (const PointerType
*Ptr
= BaseType
->getAs
<PointerType
>()) {
5904 BaseType
= Ptr
->getPointeeType();
5905 BaseKind
= VK_LValue
;
5906 } else if (BaseType
->isObjCObjectPointerType() ||
5907 BaseType
->isTemplateTypeParmType()) {
5908 // Both cases (dot/arrow) handled below.
5914 if (RecordDecl
*RD
= getAsRecordDecl(BaseType
)) {
5915 AddRecordMembersCompletionResults(SemaRef
, Results
, S
, BaseType
, BaseKind
,
5916 RD
, std::move(AccessOpFixIt
));
5917 } else if (const auto *TTPT
=
5918 dyn_cast
<TemplateTypeParmType
>(BaseType
.getTypePtr())) {
5920 IsArrow
? ConceptInfo::Member::Arrow
: ConceptInfo::Member::Dot
;
5921 for (const auto &R
: ConceptInfo(*TTPT
, S
).members()) {
5922 if (R
.Operator
!= Operator
)
5924 CodeCompletionResult
Result(
5925 R
.render(SemaRef
, CodeCompleter
->getAllocator(),
5926 CodeCompleter
->getCodeCompletionTUInfo()));
5928 Result
.FixIts
.push_back(*AccessOpFixIt
);
5929 Results
.AddResult(std::move(Result
));
5931 } else if (!IsArrow
&& BaseType
->isObjCObjectPointerType()) {
5932 // Objective-C property reference. Bail if we're performing fix-it code
5933 // completion since Objective-C properties are normally backed by ivars,
5934 // most Objective-C fix-its here would have little value.
5935 if (AccessOpFixIt
) {
5938 AddedPropertiesSet AddedProperties
;
5940 if (const ObjCObjectPointerType
*ObjCPtr
=
5941 BaseType
->getAsObjCInterfacePointerType()) {
5942 // Add property results based on our interface.
5943 assert(ObjCPtr
&& "Non-NULL pointer guaranteed above!");
5944 AddObjCProperties(CCContext
, ObjCPtr
->getInterfaceDecl(), true,
5945 /*AllowNullaryMethods=*/true, SemaRef
.CurContext
,
5946 AddedProperties
, Results
, IsBaseExprStatement
);
5949 // Add properties from the protocols in a qualified interface.
5950 for (auto *I
: BaseType
->castAs
<ObjCObjectPointerType
>()->quals())
5951 AddObjCProperties(CCContext
, I
, true, /*AllowNullaryMethods=*/true,
5952 SemaRef
.CurContext
, AddedProperties
, Results
,
5953 IsBaseExprStatement
, /*IsClassProperty*/ false,
5954 /*InOriginalClass*/ false);
5955 } else if ((IsArrow
&& BaseType
->isObjCObjectPointerType()) ||
5956 (!IsArrow
&& BaseType
->isObjCObjectType())) {
5957 // Objective-C instance variable access. Bail if we're performing fix-it
5958 // code completion since Objective-C properties are normally backed by
5959 // ivars, most Objective-C fix-its here would have little value.
5960 if (AccessOpFixIt
) {
5963 ObjCInterfaceDecl
*Class
= nullptr;
5964 if (const ObjCObjectPointerType
*ObjCPtr
=
5965 BaseType
->getAs
<ObjCObjectPointerType
>())
5966 Class
= ObjCPtr
->getInterfaceDecl();
5968 Class
= BaseType
->castAs
<ObjCObjectType
>()->getInterface();
5970 // Add all ivars from this class and its superclasses.
5972 CodeCompletionDeclConsumer
Consumer(Results
, Class
, BaseType
);
5973 Results
.setFilter(&ResultBuilder::IsObjCIvar
);
5974 SemaRef
.LookupVisibleDecls(Class
, Sema::LookupMemberName
, Consumer
,
5975 CodeCompleter
->includeGlobals(),
5976 /*IncludeDependentBases=*/false,
5977 CodeCompleter
->loadExternal());
5981 // FIXME: How do we cope with isa?
5985 Results
.EnterNewScope();
5987 bool CompletionSucceded
= DoCompletion(Base
, IsArrow
, std::nullopt
);
5988 if (CodeCompleter
->includeFixIts()) {
5989 const CharSourceRange OpRange
=
5990 CharSourceRange::getTokenRange(OpLoc
, OpLoc
);
5991 CompletionSucceded
|= DoCompletion(
5992 OtherOpBase
, !IsArrow
,
5993 FixItHint::CreateReplacement(OpRange
, IsArrow
? "." : "->"));
5996 Results
.ExitScope();
5998 if (!CompletionSucceded
)
6001 // Hand off the results found for code completion.
6002 HandleCodeCompleteResults(&SemaRef
, CodeCompleter
,
6003 Results
.getCompletionContext(), Results
.data(),
6007 void SemaCodeCompletion::CodeCompleteObjCClassPropertyRefExpr(
6008 Scope
*S
, const IdentifierInfo
&ClassName
, SourceLocation ClassNameLoc
,
6009 bool IsBaseExprStatement
) {
6010 const IdentifierInfo
*ClassNamePtr
= &ClassName
;
6011 ObjCInterfaceDecl
*IFace
=
6012 SemaRef
.ObjC().getObjCInterfaceDecl(ClassNamePtr
, ClassNameLoc
);
6015 CodeCompletionContext
CCContext(
6016 CodeCompletionContext::CCC_ObjCPropertyAccess
);
6017 ResultBuilder
Results(SemaRef
, CodeCompleter
->getAllocator(),
6018 CodeCompleter
->getCodeCompletionTUInfo(), CCContext
,
6019 &ResultBuilder::IsMember
);
6020 Results
.EnterNewScope();
6021 AddedPropertiesSet AddedProperties
;
6022 AddObjCProperties(CCContext
, IFace
, true,
6023 /*AllowNullaryMethods=*/true, SemaRef
.CurContext
,
6024 AddedProperties
, Results
, IsBaseExprStatement
,
6025 /*IsClassProperty=*/true);
6026 Results
.ExitScope();
6027 HandleCodeCompleteResults(&SemaRef
, CodeCompleter
,
6028 Results
.getCompletionContext(), Results
.data(),
6032 void SemaCodeCompletion::CodeCompleteTag(Scope
*S
, unsigned TagSpec
) {
6036 ResultBuilder::LookupFilter Filter
= nullptr;
6037 enum CodeCompletionContext::Kind ContextKind
=
6038 CodeCompletionContext::CCC_Other
;
6039 switch ((DeclSpec::TST
)TagSpec
) {
6040 case DeclSpec::TST_enum
:
6041 Filter
= &ResultBuilder::IsEnum
;
6042 ContextKind
= CodeCompletionContext::CCC_EnumTag
;
6045 case DeclSpec::TST_union
:
6046 Filter
= &ResultBuilder::IsUnion
;
6047 ContextKind
= CodeCompletionContext::CCC_UnionTag
;
6050 case DeclSpec::TST_struct
:
6051 case DeclSpec::TST_class
:
6052 case DeclSpec::TST_interface
:
6053 Filter
= &ResultBuilder::IsClassOrStruct
;
6054 ContextKind
= CodeCompletionContext::CCC_ClassOrStructTag
;
6058 llvm_unreachable("Unknown type specifier kind in CodeCompleteTag");
6061 ResultBuilder
Results(SemaRef
, CodeCompleter
->getAllocator(),
6062 CodeCompleter
->getCodeCompletionTUInfo(), ContextKind
);
6063 CodeCompletionDeclConsumer
Consumer(Results
, SemaRef
.CurContext
);
6065 // First pass: look for tags.
6066 Results
.setFilter(Filter
);
6067 SemaRef
.LookupVisibleDecls(S
, Sema::LookupTagName
, Consumer
,
6068 CodeCompleter
->includeGlobals(),
6069 CodeCompleter
->loadExternal());
6071 if (CodeCompleter
->includeGlobals()) {
6072 // Second pass: look for nested name specifiers.
6073 Results
.setFilter(&ResultBuilder::IsNestedNameSpecifier
);
6074 SemaRef
.LookupVisibleDecls(S
, Sema::LookupNestedNameSpecifierName
, Consumer
,
6075 CodeCompleter
->includeGlobals(),
6076 CodeCompleter
->loadExternal());
6079 HandleCodeCompleteResults(&SemaRef
, CodeCompleter
,
6080 Results
.getCompletionContext(), Results
.data(),
6084 static void AddTypeQualifierResults(DeclSpec
&DS
, ResultBuilder
&Results
,
6085 const LangOptions
&LangOpts
) {
6086 if (!(DS
.getTypeQualifiers() & DeclSpec::TQ_const
))
6087 Results
.AddResult("const");
6088 if (!(DS
.getTypeQualifiers() & DeclSpec::TQ_volatile
))
6089 Results
.AddResult("volatile");
6090 if (LangOpts
.C99
&& !(DS
.getTypeQualifiers() & DeclSpec::TQ_restrict
))
6091 Results
.AddResult("restrict");
6092 if (LangOpts
.C11
&& !(DS
.getTypeQualifiers() & DeclSpec::TQ_atomic
))
6093 Results
.AddResult("_Atomic");
6094 if (LangOpts
.MSVCCompat
&& !(DS
.getTypeQualifiers() & DeclSpec::TQ_unaligned
))
6095 Results
.AddResult("__unaligned");
6098 void SemaCodeCompletion::CodeCompleteTypeQualifiers(DeclSpec
&DS
) {
6099 ResultBuilder
Results(SemaRef
, CodeCompleter
->getAllocator(),
6100 CodeCompleter
->getCodeCompletionTUInfo(),
6101 CodeCompletionContext::CCC_TypeQualifiers
);
6102 Results
.EnterNewScope();
6103 AddTypeQualifierResults(DS
, Results
, getLangOpts());
6104 Results
.ExitScope();
6105 HandleCodeCompleteResults(&SemaRef
, CodeCompleter
,
6106 Results
.getCompletionContext(), Results
.data(),
6110 void SemaCodeCompletion::CodeCompleteFunctionQualifiers(
6111 DeclSpec
&DS
, Declarator
&D
, const VirtSpecifiers
*VS
) {
6112 ResultBuilder
Results(SemaRef
, CodeCompleter
->getAllocator(),
6113 CodeCompleter
->getCodeCompletionTUInfo(),
6114 CodeCompletionContext::CCC_TypeQualifiers
);
6115 Results
.EnterNewScope();
6116 AddTypeQualifierResults(DS
, Results
, getLangOpts());
6117 if (getLangOpts().CPlusPlus11
) {
6118 Results
.AddResult("noexcept");
6119 if (D
.getContext() == DeclaratorContext::Member
&& !D
.isCtorOrDtor() &&
6120 !D
.isStaticMember()) {
6121 if (!VS
|| !VS
->isFinalSpecified())
6122 Results
.AddResult("final");
6123 if (!VS
|| !VS
->isOverrideSpecified())
6124 Results
.AddResult("override");
6127 Results
.ExitScope();
6128 HandleCodeCompleteResults(&SemaRef
, CodeCompleter
,
6129 Results
.getCompletionContext(), Results
.data(),
6133 void SemaCodeCompletion::CodeCompleteBracketDeclarator(Scope
*S
) {
6134 CodeCompleteExpression(S
, QualType(getASTContext().getSizeType()));
6137 void SemaCodeCompletion::CodeCompleteCase(Scope
*S
) {
6138 if (SemaRef
.getCurFunction()->SwitchStack
.empty() || !CodeCompleter
)
6141 SwitchStmt
*Switch
=
6142 SemaRef
.getCurFunction()->SwitchStack
.back().getPointer();
6143 // Condition expression might be invalid, do not continue in this case.
6144 if (!Switch
->getCond())
6146 QualType type
= Switch
->getCond()->IgnoreImplicit()->getType();
6147 if (!type
->isEnumeralType()) {
6148 CodeCompleteExpressionData
Data(type
);
6149 Data
.IntegralConstantExpression
= true;
6150 CodeCompleteExpression(S
, Data
);
6154 // Code-complete the cases of a switch statement over an enumeration type
6155 // by providing the list of
6156 EnumDecl
*Enum
= type
->castAs
<EnumType
>()->getDecl();
6157 if (EnumDecl
*Def
= Enum
->getDefinition())
6160 // Determine which enumerators we have already seen in the switch statement.
6161 // FIXME: Ideally, we would also be able to look *past* the code-completion
6162 // token, in case we are code-completing in the middle of the switch and not
6163 // at the end. However, we aren't able to do so at the moment.
6164 CoveredEnumerators Enumerators
;
6165 for (SwitchCase
*SC
= Switch
->getSwitchCaseList(); SC
;
6166 SC
= SC
->getNextSwitchCase()) {
6167 CaseStmt
*Case
= dyn_cast
<CaseStmt
>(SC
);
6171 Expr
*CaseVal
= Case
->getLHS()->IgnoreParenCasts();
6172 if (auto *DRE
= dyn_cast
<DeclRefExpr
>(CaseVal
))
6173 if (auto *Enumerator
=
6174 dyn_cast
<EnumConstantDecl
>(DRE
->getDecl())) {
6175 // We look into the AST of the case statement to determine which
6176 // enumerator was named. Alternatively, we could compute the value of
6177 // the integral constant expression, then compare it against the
6178 // values of each enumerator. However, value-based approach would not
6179 // work as well with C++ templates where enumerators declared within a
6180 // template are type- and value-dependent.
6181 Enumerators
.Seen
.insert(Enumerator
);
6183 // If this is a qualified-id, keep track of the nested-name-specifier
6184 // so that we can reproduce it as part of code completion, e.g.,
6186 // switch (TagD.getKind()) {
6187 // case TagDecl::TK_enum:
6191 // At the XXX, our completions are TagDecl::TK_union,
6192 // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
6193 // TK_struct, and TK_class.
6194 Enumerators
.SuggestedQualifier
= DRE
->getQualifier();
6198 // Add any enumerators that have not yet been mentioned.
6199 ResultBuilder
Results(SemaRef
, CodeCompleter
->getAllocator(),
6200 CodeCompleter
->getCodeCompletionTUInfo(),
6201 CodeCompletionContext::CCC_Expression
);
6202 AddEnumerators(Results
, getASTContext(), Enum
, SemaRef
.CurContext
,
6205 if (CodeCompleter
->includeMacros()) {
6206 AddMacroResults(SemaRef
.PP
, Results
, CodeCompleter
->loadExternal(), false);
6208 HandleCodeCompleteResults(&SemaRef
, CodeCompleter
,
6209 Results
.getCompletionContext(), Results
.data(),
6213 static bool anyNullArguments(ArrayRef
<Expr
*> Args
) {
6214 if (Args
.size() && !Args
.data())
6217 for (unsigned I
= 0; I
!= Args
.size(); ++I
)
6224 typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate
;
6226 static void mergeCandidatesWithResults(
6227 Sema
&SemaRef
, SmallVectorImpl
<ResultCandidate
> &Results
,
6228 OverloadCandidateSet
&CandidateSet
, SourceLocation Loc
, size_t ArgSize
) {
6229 // Sort the overload candidate set by placing the best overloads first.
6230 llvm::stable_sort(CandidateSet
, [&](const OverloadCandidate
&X
,
6231 const OverloadCandidate
&Y
) {
6232 return isBetterOverloadCandidate(SemaRef
, X
, Y
, Loc
,
6233 CandidateSet
.getKind());
6236 // Add the remaining viable overload candidates as code-completion results.
6237 for (OverloadCandidate
&Candidate
: CandidateSet
) {
6238 if (Candidate
.Function
) {
6239 if (Candidate
.Function
->isDeleted())
6241 if (shouldEnforceArgLimit(/*PartialOverloading=*/true,
6242 Candidate
.Function
) &&
6243 Candidate
.Function
->getNumParams() <= ArgSize
&&
6244 // Having zero args is annoying, normally we don't surface a function
6245 // with 2 params, if you already have 2 params, because you are
6246 // inserting the 3rd now. But with zero, it helps the user to figure
6247 // out there are no overloads that take any arguments. Hence we are
6248 // keeping the overload.
6252 if (Candidate
.Viable
)
6253 Results
.push_back(ResultCandidate(Candidate
.Function
));
6257 /// Get the type of the Nth parameter from a given set of overload
6259 static QualType
getParamType(Sema
&SemaRef
,
6260 ArrayRef
<ResultCandidate
> Candidates
, unsigned N
) {
6262 // Given the overloads 'Candidates' for a function call matching all arguments
6263 // up to N, return the type of the Nth parameter if it is the same for all
6264 // overload candidates.
6266 for (auto &Candidate
: Candidates
) {
6267 QualType CandidateParamType
= Candidate
.getParamType(N
);
6268 if (CandidateParamType
.isNull())
6270 if (ParamType
.isNull()) {
6271 ParamType
= CandidateParamType
;
6274 if (!SemaRef
.Context
.hasSameUnqualifiedType(
6275 ParamType
.getNonReferenceType(),
6276 CandidateParamType
.getNonReferenceType()))
6277 // Two conflicting types, give up.
6285 ProduceSignatureHelp(Sema
&SemaRef
, MutableArrayRef
<ResultCandidate
> Candidates
,
6286 unsigned CurrentArg
, SourceLocation OpenParLoc
,
6288 if (Candidates
.empty())
6290 if (SemaRef
.getPreprocessor().isCodeCompletionReached())
6291 SemaRef
.CodeCompletion().CodeCompleter
->ProcessOverloadCandidates(
6292 SemaRef
, CurrentArg
, Candidates
.data(), Candidates
.size(), OpenParLoc
,
6294 return getParamType(SemaRef
, Candidates
, CurrentArg
);
6297 // Given a callee expression `Fn`, if the call is through a function pointer,
6298 // try to find the declaration of the corresponding function pointer type,
6299 // so that we can recover argument names from it.
6300 static FunctionProtoTypeLoc
GetPrototypeLoc(Expr
*Fn
) {
6303 if (const auto *T
= Fn
->getType().getTypePtr()->getAs
<TypedefType
>()) {
6304 Target
= T
->getDecl()->getTypeSourceInfo()->getTypeLoc();
6306 } else if (const auto *DR
= dyn_cast
<DeclRefExpr
>(Fn
)) {
6307 const auto *D
= DR
->getDecl();
6308 if (const auto *const VD
= dyn_cast
<VarDecl
>(D
)) {
6309 Target
= VD
->getTypeSourceInfo()->getTypeLoc();
6311 } else if (const auto *ME
= dyn_cast
<MemberExpr
>(Fn
)) {
6312 const auto *MD
= ME
->getMemberDecl();
6313 if (const auto *FD
= dyn_cast
<FieldDecl
>(MD
)) {
6314 Target
= FD
->getTypeSourceInfo()->getTypeLoc();
6321 // Unwrap types that may be wrapping the function type
6323 if (auto P
= Target
.getAs
<PointerTypeLoc
>()) {
6324 Target
= P
.getPointeeLoc();
6327 if (auto A
= Target
.getAs
<AttributedTypeLoc
>()) {
6328 Target
= A
.getModifiedLoc();
6331 if (auto P
= Target
.getAs
<ParenTypeLoc
>()) {
6332 Target
= P
.getInnerLoc();
6338 if (auto F
= Target
.getAs
<FunctionProtoTypeLoc
>()) {
6346 SemaCodeCompletion::ProduceCallSignatureHelp(Expr
*Fn
, ArrayRef
<Expr
*> Args
,
6347 SourceLocation OpenParLoc
) {
6348 Fn
= unwrapParenList(Fn
);
6349 if (!CodeCompleter
|| !Fn
)
6352 // FIXME: Provide support for variadic template functions.
6353 // Ignore type-dependent call expressions entirely.
6354 if (Fn
->isTypeDependent() || anyNullArguments(Args
))
6356 // In presence of dependent args we surface all possible signatures using the
6357 // non-dependent args in the prefix. Afterwards we do a post filtering to make
6358 // sure provided candidates satisfy parameter count restrictions.
6359 auto ArgsWithoutDependentTypes
=
6360 Args
.take_while([](Expr
*Arg
) { return !Arg
->isTypeDependent(); });
6362 SmallVector
<ResultCandidate
, 8> Results
;
6364 Expr
*NakedFn
= Fn
->IgnoreParenCasts();
6365 // Build an overload candidate set based on the functions we find.
6366 SourceLocation Loc
= Fn
->getExprLoc();
6367 OverloadCandidateSet
CandidateSet(Loc
, OverloadCandidateSet::CSK_Normal
);
6369 if (auto ULE
= dyn_cast
<UnresolvedLookupExpr
>(NakedFn
)) {
6370 SemaRef
.AddOverloadedCallCandidates(ULE
, ArgsWithoutDependentTypes
,
6372 /*PartialOverloading=*/true);
6373 } else if (auto UME
= dyn_cast
<UnresolvedMemberExpr
>(NakedFn
)) {
6374 TemplateArgumentListInfo TemplateArgsBuffer
, *TemplateArgs
= nullptr;
6375 if (UME
->hasExplicitTemplateArgs()) {
6376 UME
->copyTemplateArgumentsInto(TemplateArgsBuffer
);
6377 TemplateArgs
= &TemplateArgsBuffer
;
6380 // Add the base as first argument (use a nullptr if the base is implicit).
6381 SmallVector
<Expr
*, 12> ArgExprs(
6382 1, UME
->isImplicitAccess() ? nullptr : UME
->getBase());
6383 ArgExprs
.append(ArgsWithoutDependentTypes
.begin(),
6384 ArgsWithoutDependentTypes
.end());
6385 UnresolvedSet
<8> Decls
;
6386 Decls
.append(UME
->decls_begin(), UME
->decls_end());
6387 const bool FirstArgumentIsBase
= !UME
->isImplicitAccess() && UME
->getBase();
6388 SemaRef
.AddFunctionCandidates(Decls
, ArgExprs
, CandidateSet
, TemplateArgs
,
6389 /*SuppressUserConversions=*/false,
6390 /*PartialOverloading=*/true,
6391 FirstArgumentIsBase
);
6393 FunctionDecl
*FD
= nullptr;
6394 if (auto *MCE
= dyn_cast
<MemberExpr
>(NakedFn
))
6395 FD
= dyn_cast
<FunctionDecl
>(MCE
->getMemberDecl());
6396 else if (auto *DRE
= dyn_cast
<DeclRefExpr
>(NakedFn
))
6397 FD
= dyn_cast
<FunctionDecl
>(DRE
->getDecl());
6398 if (FD
) { // We check whether it's a resolved function declaration.
6399 if (!getLangOpts().CPlusPlus
||
6400 !FD
->getType()->getAs
<FunctionProtoType
>())
6401 Results
.push_back(ResultCandidate(FD
));
6403 SemaRef
.AddOverloadCandidate(FD
,
6404 DeclAccessPair::make(FD
, FD
->getAccess()),
6405 ArgsWithoutDependentTypes
, CandidateSet
,
6406 /*SuppressUserConversions=*/false,
6407 /*PartialOverloading=*/true);
6409 } else if (auto DC
= NakedFn
->getType()->getAsCXXRecordDecl()) {
6410 // If expression's type is CXXRecordDecl, it may overload the function
6411 // call operator, so we check if it does and add them as candidates.
6412 // A complete type is needed to lookup for member function call operators.
6413 if (SemaRef
.isCompleteType(Loc
, NakedFn
->getType())) {
6414 DeclarationName OpName
=
6415 getASTContext().DeclarationNames
.getCXXOperatorName(OO_Call
);
6416 LookupResult
R(SemaRef
, OpName
, Loc
, Sema::LookupOrdinaryName
);
6417 SemaRef
.LookupQualifiedName(R
, DC
);
6418 R
.suppressDiagnostics();
6419 SmallVector
<Expr
*, 12> ArgExprs(1, NakedFn
);
6420 ArgExprs
.append(ArgsWithoutDependentTypes
.begin(),
6421 ArgsWithoutDependentTypes
.end());
6422 SemaRef
.AddFunctionCandidates(R
.asUnresolvedSet(), ArgExprs
,
6424 /*ExplicitArgs=*/nullptr,
6425 /*SuppressUserConversions=*/false,
6426 /*PartialOverloading=*/true);
6429 // Lastly we check whether expression's type is function pointer or
6432 FunctionProtoTypeLoc P
= GetPrototypeLoc(NakedFn
);
6433 QualType T
= NakedFn
->getType();
6434 if (!T
->getPointeeType().isNull())
6435 T
= T
->getPointeeType();
6437 if (auto FP
= T
->getAs
<FunctionProtoType
>()) {
6438 if (!SemaRef
.TooManyArguments(FP
->getNumParams(),
6439 ArgsWithoutDependentTypes
.size(),
6440 /*PartialOverloading=*/true) ||
6443 Results
.push_back(ResultCandidate(P
));
6445 Results
.push_back(ResultCandidate(FP
));
6448 } else if (auto FT
= T
->getAs
<FunctionType
>())
6449 // No prototype and declaration, it may be a K & R style function.
6450 Results
.push_back(ResultCandidate(FT
));
6453 mergeCandidatesWithResults(SemaRef
, Results
, CandidateSet
, Loc
, Args
.size());
6454 QualType ParamType
= ProduceSignatureHelp(SemaRef
, Results
, Args
.size(),
6455 OpenParLoc
, /*Braced=*/false);
6456 return !CandidateSet
.empty() ? ParamType
: QualType();
6459 // Determine which param to continue aggregate initialization from after
6460 // a designated initializer.
6462 // Given struct S { int a,b,c,d,e; }:
6463 // after `S{.b=1,` we want to suggest c to continue
6464 // after `S{.b=1, 2,` we continue with d (this is legal C and ext in C++)
6465 // after `S{.b=1, .a=2,` we continue with b (this is legal C and ext in C++)
6467 // Possible outcomes:
6468 // - we saw a designator for a field, and continue from the returned index.
6469 // Only aggregate initialization is allowed.
6470 // - we saw a designator, but it was complex or we couldn't find the field.
6471 // Only aggregate initialization is possible, but we can't assist with it.
6472 // Returns an out-of-range index.
6473 // - we saw no designators, just positional arguments.
6474 // Returns std::nullopt.
6475 static std::optional
<unsigned>
6476 getNextAggregateIndexAfterDesignatedInit(const ResultCandidate
&Aggregate
,
6477 ArrayRef
<Expr
*> Args
) {
6478 static constexpr unsigned Invalid
= std::numeric_limits
<unsigned>::max();
6479 assert(Aggregate
.getKind() == ResultCandidate::CK_Aggregate
);
6481 // Look for designated initializers.
6482 // They're in their syntactic form, not yet resolved to fields.
6483 const IdentifierInfo
*DesignatedFieldName
= nullptr;
6484 unsigned ArgsAfterDesignator
= 0;
6485 for (const Expr
*Arg
: Args
) {
6486 if (const auto *DIE
= dyn_cast
<DesignatedInitExpr
>(Arg
)) {
6487 if (DIE
->size() == 1 && DIE
->getDesignator(0)->isFieldDesignator()) {
6488 DesignatedFieldName
= DIE
->getDesignator(0)->getFieldName();
6489 ArgsAfterDesignator
= 0;
6491 return Invalid
; // Complicated designator.
6493 } else if (isa
<DesignatedInitUpdateExpr
>(Arg
)) {
6494 return Invalid
; // Unsupported.
6496 ++ArgsAfterDesignator
;
6499 if (!DesignatedFieldName
)
6500 return std::nullopt
;
6502 // Find the index within the class's fields.
6503 // (Probing getParamDecl() directly would be quadratic in number of fields).
6504 unsigned DesignatedIndex
= 0;
6505 const FieldDecl
*DesignatedField
= nullptr;
6506 for (const auto *Field
: Aggregate
.getAggregate()->fields()) {
6507 if (Field
->getIdentifier() == DesignatedFieldName
) {
6508 DesignatedField
= Field
;
6513 if (!DesignatedField
)
6514 return Invalid
; // Designator referred to a missing field, give up.
6516 // Find the index within the aggregate (which may have leading bases).
6517 unsigned AggregateSize
= Aggregate
.getNumParams();
6518 while (DesignatedIndex
< AggregateSize
&&
6519 Aggregate
.getParamDecl(DesignatedIndex
) != DesignatedField
)
6522 // Continue from the index after the last named field.
6523 return DesignatedIndex
+ ArgsAfterDesignator
+ 1;
6526 QualType
SemaCodeCompletion::ProduceConstructorSignatureHelp(
6527 QualType Type
, SourceLocation Loc
, ArrayRef
<Expr
*> Args
,
6528 SourceLocation OpenParLoc
, bool Braced
) {
6531 SmallVector
<ResultCandidate
, 8> Results
;
6533 // A complete type is needed to lookup for constructors.
6535 SemaRef
.isCompleteType(Loc
, Type
) ? Type
->getAsRecordDecl() : nullptr;
6538 CXXRecordDecl
*CRD
= dyn_cast
<CXXRecordDecl
>(RD
);
6540 // Consider aggregate initialization.
6541 // We don't check that types so far are correct.
6542 // We also don't handle C99/C++17 brace-elision, we assume init-list elements
6543 // are 1:1 with fields.
6544 // FIXME: it would be nice to support "unwrapping" aggregates that contain
6545 // a single subaggregate, like std::array<T, N> -> T __elements[N].
6546 if (Braced
&& !RD
->isUnion() &&
6547 (!getLangOpts().CPlusPlus
|| (CRD
&& CRD
->isAggregate()))) {
6548 ResultCandidate
AggregateSig(RD
);
6549 unsigned AggregateSize
= AggregateSig
.getNumParams();
6551 if (auto NextIndex
=
6552 getNextAggregateIndexAfterDesignatedInit(AggregateSig
, Args
)) {
6553 // A designator was used, only aggregate init is possible.
6554 if (*NextIndex
>= AggregateSize
)
6556 Results
.push_back(AggregateSig
);
6557 return ProduceSignatureHelp(SemaRef
, Results
, *NextIndex
, OpenParLoc
,
6561 // Describe aggregate initialization, but also constructors below.
6562 if (Args
.size() < AggregateSize
)
6563 Results
.push_back(AggregateSig
);
6566 // FIXME: Provide support for member initializers.
6567 // FIXME: Provide support for variadic template constructors.
6570 OverloadCandidateSet
CandidateSet(Loc
, OverloadCandidateSet::CSK_Normal
);
6571 for (NamedDecl
*C
: SemaRef
.LookupConstructors(CRD
)) {
6572 if (auto *FD
= dyn_cast
<FunctionDecl
>(C
)) {
6573 // FIXME: we can't yet provide correct signature help for initializer
6574 // list constructors, so skip them entirely.
6575 if (Braced
&& getLangOpts().CPlusPlus
&&
6576 SemaRef
.isInitListConstructor(FD
))
6578 SemaRef
.AddOverloadCandidate(
6579 FD
, DeclAccessPair::make(FD
, C
->getAccess()), Args
, CandidateSet
,
6580 /*SuppressUserConversions=*/false,
6581 /*PartialOverloading=*/true,
6582 /*AllowExplicit*/ true);
6583 } else if (auto *FTD
= dyn_cast
<FunctionTemplateDecl
>(C
)) {
6584 if (Braced
&& getLangOpts().CPlusPlus
&&
6585 SemaRef
.isInitListConstructor(FTD
->getTemplatedDecl()))
6588 SemaRef
.AddTemplateOverloadCandidate(
6589 FTD
, DeclAccessPair::make(FTD
, C
->getAccess()),
6590 /*ExplicitTemplateArgs=*/nullptr, Args
, CandidateSet
,
6591 /*SuppressUserConversions=*/false,
6592 /*PartialOverloading=*/true);
6595 mergeCandidatesWithResults(SemaRef
, Results
, CandidateSet
, Loc
,
6599 return ProduceSignatureHelp(SemaRef
, Results
, Args
.size(), OpenParLoc
,
6603 QualType
SemaCodeCompletion::ProduceCtorInitMemberSignatureHelp(
6604 Decl
*ConstructorDecl
, CXXScopeSpec SS
, ParsedType TemplateTypeTy
,
6605 ArrayRef
<Expr
*> ArgExprs
, IdentifierInfo
*II
, SourceLocation OpenParLoc
,
6610 CXXConstructorDecl
*Constructor
=
6611 dyn_cast
<CXXConstructorDecl
>(ConstructorDecl
);
6614 // FIXME: Add support for Base class constructors as well.
6615 if (ValueDecl
*MemberDecl
= SemaRef
.tryLookupCtorInitMemberDecl(
6616 Constructor
->getParent(), SS
, TemplateTypeTy
, II
))
6617 return ProduceConstructorSignatureHelp(MemberDecl
->getType(),
6618 MemberDecl
->getLocation(), ArgExprs
,
6619 OpenParLoc
, Braced
);
6623 static bool argMatchesTemplateParams(const ParsedTemplateArgument
&Arg
,
6625 const TemplateParameterList
&Params
) {
6626 const NamedDecl
*Param
;
6627 if (Index
< Params
.size())
6628 Param
= Params
.getParam(Index
);
6629 else if (Params
.hasParameterPack())
6630 Param
= Params
.asArray().back();
6632 return false; // too many args
6634 switch (Arg
.getKind()) {
6635 case ParsedTemplateArgument::Type
:
6636 return llvm::isa
<TemplateTypeParmDecl
>(Param
); // constraints not checked
6637 case ParsedTemplateArgument::NonType
:
6638 return llvm::isa
<NonTypeTemplateParmDecl
>(Param
); // type not checked
6639 case ParsedTemplateArgument::Template
:
6640 return llvm::isa
<TemplateTemplateParmDecl
>(Param
); // signature not checked
6642 llvm_unreachable("Unhandled switch case");
6645 QualType
SemaCodeCompletion::ProduceTemplateArgumentSignatureHelp(
6646 TemplateTy ParsedTemplate
, ArrayRef
<ParsedTemplateArgument
> Args
,
6647 SourceLocation LAngleLoc
) {
6648 if (!CodeCompleter
|| !ParsedTemplate
)
6651 SmallVector
<ResultCandidate
, 8> Results
;
6652 auto Consider
= [&](const TemplateDecl
*TD
) {
6653 // Only add if the existing args are compatible with the template.
6654 bool Matches
= true;
6655 for (unsigned I
= 0; I
< Args
.size(); ++I
) {
6656 if (!argMatchesTemplateParams(Args
[I
], I
, *TD
->getTemplateParameters())) {
6662 Results
.emplace_back(TD
);
6665 TemplateName Template
= ParsedTemplate
.get();
6666 if (const auto *TD
= Template
.getAsTemplateDecl()) {
6668 } else if (const auto *OTS
= Template
.getAsOverloadedTemplate()) {
6669 for (const NamedDecl
*ND
: *OTS
)
6670 if (const auto *TD
= llvm::dyn_cast
<TemplateDecl
>(ND
))
6673 return ProduceSignatureHelp(SemaRef
, Results
, Args
.size(), LAngleLoc
,
6677 static QualType
getDesignatedType(QualType BaseType
, const Designation
&Desig
) {
6678 for (unsigned I
= 0; I
< Desig
.getNumDesignators(); ++I
) {
6679 if (BaseType
.isNull())
6682 const auto &D
= Desig
.getDesignator(I
);
6683 if (D
.isArrayDesignator() || D
.isArrayRangeDesignator()) {
6684 if (BaseType
->isArrayType())
6685 NextType
= BaseType
->getAsArrayTypeUnsafe()->getElementType();
6687 assert(D
.isFieldDesignator());
6688 auto *RD
= getAsRecordDecl(BaseType
);
6689 if (RD
&& RD
->isCompleteDefinition()) {
6690 for (const auto *Member
: RD
->lookup(D
.getFieldDecl()))
6691 if (const FieldDecl
*FD
= llvm::dyn_cast
<FieldDecl
>(Member
)) {
6692 NextType
= FD
->getType();
6697 BaseType
= NextType
;
6702 void SemaCodeCompletion::CodeCompleteDesignator(
6703 QualType BaseType
, llvm::ArrayRef
<Expr
*> InitExprs
, const Designation
&D
) {
6704 BaseType
= getDesignatedType(BaseType
, D
);
6705 if (BaseType
.isNull())
6707 const auto *RD
= getAsRecordDecl(BaseType
);
6708 if (!RD
|| RD
->fields().empty())
6711 CodeCompletionContext
CCC(CodeCompletionContext::CCC_DotMemberAccess
,
6713 ResultBuilder
Results(SemaRef
, CodeCompleter
->getAllocator(),
6714 CodeCompleter
->getCodeCompletionTUInfo(), CCC
);
6716 Results
.EnterNewScope();
6717 for (const Decl
*D
: RD
->decls()) {
6718 const FieldDecl
*FD
;
6719 if (auto *IFD
= dyn_cast
<IndirectFieldDecl
>(D
))
6720 FD
= IFD
->getAnonField();
6721 else if (auto *DFD
= dyn_cast
<FieldDecl
>(D
))
6726 // FIXME: Make use of previous designators to mark any fields before those
6727 // inaccessible, and also compute the next initializer priority.
6728 ResultBuilder::Result
Result(FD
, Results
.getBasePriority(FD
));
6729 Results
.AddResult(Result
, SemaRef
.CurContext
, /*Hiding=*/nullptr);
6731 Results
.ExitScope();
6732 HandleCodeCompleteResults(&SemaRef
, CodeCompleter
,
6733 Results
.getCompletionContext(), Results
.data(),
6737 void SemaCodeCompletion::CodeCompleteInitializer(Scope
*S
, Decl
*D
) {
6738 ValueDecl
*VD
= dyn_cast_or_null
<ValueDecl
>(D
);
6740 CodeCompleteOrdinaryName(S
, PCC_Expression
);
6744 CodeCompleteExpressionData Data
;
6745 Data
.PreferredType
= VD
->getType();
6746 // Ignore VD to avoid completing the variable itself, e.g. in 'int foo = ^'.
6747 Data
.IgnoreDecls
.push_back(VD
);
6749 CodeCompleteExpression(S
, Data
);
6752 void SemaCodeCompletion::CodeCompleteAfterIf(Scope
*S
, bool IsBracedThen
) {
6753 ResultBuilder
Results(SemaRef
, CodeCompleter
->getAllocator(),
6754 CodeCompleter
->getCodeCompletionTUInfo(),
6755 mapCodeCompletionContext(SemaRef
, PCC_Statement
));
6756 Results
.setFilter(&ResultBuilder::IsOrdinaryName
);
6757 Results
.EnterNewScope();
6759 CodeCompletionDeclConsumer
Consumer(Results
, SemaRef
.CurContext
);
6760 SemaRef
.LookupVisibleDecls(S
, Sema::LookupOrdinaryName
, Consumer
,
6761 CodeCompleter
->includeGlobals(),
6762 CodeCompleter
->loadExternal());
6764 AddOrdinaryNameResults(PCC_Statement
, S
, SemaRef
, Results
);
6767 CodeCompletionBuilder
Builder(Results
.getAllocator(),
6768 Results
.getCodeCompletionTUInfo());
6770 auto AddElseBodyPattern
= [&] {
6772 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
6773 Builder
.AddChunk(CodeCompletionString::CK_LeftBrace
);
6774 Builder
.AddChunk(CodeCompletionString::CK_VerticalSpace
);
6775 Builder
.AddPlaceholderChunk("statements");
6776 Builder
.AddChunk(CodeCompletionString::CK_VerticalSpace
);
6777 Builder
.AddChunk(CodeCompletionString::CK_RightBrace
);
6779 Builder
.AddChunk(CodeCompletionString::CK_VerticalSpace
);
6780 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
6781 Builder
.AddPlaceholderChunk("statement");
6782 Builder
.AddChunk(CodeCompletionString::CK_SemiColon
);
6785 Builder
.AddTypedTextChunk("else");
6786 if (Results
.includeCodePatterns())
6787 AddElseBodyPattern();
6788 Results
.AddResult(Builder
.TakeString());
6791 Builder
.AddTypedTextChunk("else if");
6792 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
6793 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
6794 if (getLangOpts().CPlusPlus
)
6795 Builder
.AddPlaceholderChunk("condition");
6797 Builder
.AddPlaceholderChunk("expression");
6798 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
6799 if (Results
.includeCodePatterns()) {
6800 AddElseBodyPattern();
6802 Results
.AddResult(Builder
.TakeString());
6804 Results
.ExitScope();
6806 if (S
->getFnParent())
6807 AddPrettyFunctionResults(getLangOpts(), Results
);
6809 if (CodeCompleter
->includeMacros())
6810 AddMacroResults(SemaRef
.PP
, Results
, CodeCompleter
->loadExternal(), false);
6812 HandleCodeCompleteResults(&SemaRef
, CodeCompleter
,
6813 Results
.getCompletionContext(), Results
.data(),
6817 void SemaCodeCompletion::CodeCompleteQualifiedId(Scope
*S
, CXXScopeSpec
&SS
,
6818 bool EnteringContext
,
6819 bool IsUsingDeclaration
,
6821 QualType PreferredType
) {
6822 if (SS
.isEmpty() || !CodeCompleter
)
6825 CodeCompletionContext
CC(CodeCompletionContext::CCC_Symbol
, PreferredType
);
6826 CC
.setIsUsingDeclaration(IsUsingDeclaration
);
6827 CC
.setCXXScopeSpecifier(SS
);
6829 // We want to keep the scope specifier even if it's invalid (e.g. the scope
6830 // "a::b::" is not corresponding to any context/namespace in the AST), since
6831 // it can be useful for global code completion which have information about
6832 // contexts/symbols that are not in the AST.
6833 if (SS
.isInvalid()) {
6834 // As SS is invalid, we try to collect accessible contexts from the current
6835 // scope with a dummy lookup so that the completion consumer can try to
6836 // guess what the specified scope is.
6837 ResultBuilder
DummyResults(SemaRef
, CodeCompleter
->getAllocator(),
6838 CodeCompleter
->getCodeCompletionTUInfo(), CC
);
6839 if (!PreferredType
.isNull())
6840 DummyResults
.setPreferredType(PreferredType
);
6841 if (S
->getEntity()) {
6842 CodeCompletionDeclConsumer
Consumer(DummyResults
, S
->getEntity(),
6844 SemaRef
.LookupVisibleDecls(S
, Sema::LookupOrdinaryName
, Consumer
,
6845 /*IncludeGlobalScope=*/false,
6846 /*LoadExternal=*/false);
6848 HandleCodeCompleteResults(&SemaRef
, CodeCompleter
,
6849 DummyResults
.getCompletionContext(), nullptr, 0);
6852 // Always pretend to enter a context to ensure that a dependent type
6853 // resolves to a dependent record.
6854 DeclContext
*Ctx
= SemaRef
.computeDeclContext(SS
, /*EnteringContext=*/true);
6856 // Try to instantiate any non-dependent declaration contexts before
6857 // we look in them. Bail out if we fail.
6858 NestedNameSpecifier
*NNS
= SS
.getScopeRep();
6859 if (NNS
!= nullptr && SS
.isValid() && !NNS
->isDependent()) {
6860 if (Ctx
== nullptr || SemaRef
.RequireCompleteDeclContext(SS
, Ctx
))
6864 ResultBuilder
Results(SemaRef
, CodeCompleter
->getAllocator(),
6865 CodeCompleter
->getCodeCompletionTUInfo(), CC
);
6866 if (!PreferredType
.isNull())
6867 Results
.setPreferredType(PreferredType
);
6868 Results
.EnterNewScope();
6870 // The "template" keyword can follow "::" in the grammar, but only
6871 // put it into the grammar if the nested-name-specifier is dependent.
6872 // FIXME: results is always empty, this appears to be dead.
6873 if (!Results
.empty() && NNS
&& NNS
->isDependent())
6874 Results
.AddResult("template");
6876 // If the scope is a concept-constrained type parameter, infer nested
6877 // members based on the constraints.
6879 if (const auto *TTPT
=
6880 dyn_cast_or_null
<TemplateTypeParmType
>(NNS
->getAsType())) {
6881 for (const auto &R
: ConceptInfo(*TTPT
, S
).members()) {
6882 if (R
.Operator
!= ConceptInfo::Member::Colons
)
6884 Results
.AddResult(CodeCompletionResult(
6885 R
.render(SemaRef
, CodeCompleter
->getAllocator(),
6886 CodeCompleter
->getCodeCompletionTUInfo())));
6891 // Add calls to overridden virtual functions, if there are any.
6893 // FIXME: This isn't wonderful, because we don't know whether we're actually
6894 // in a context that permits expressions. This is a general issue with
6895 // qualified-id completions.
6896 if (Ctx
&& !EnteringContext
)
6897 MaybeAddOverrideCalls(SemaRef
, Ctx
, Results
);
6898 Results
.ExitScope();
6901 (CodeCompleter
->includeNamespaceLevelDecls() || !Ctx
->isFileContext())) {
6902 CodeCompletionDeclConsumer
Consumer(Results
, Ctx
, BaseType
);
6903 SemaRef
.LookupVisibleDecls(Ctx
, Sema::LookupOrdinaryName
, Consumer
,
6904 /*IncludeGlobalScope=*/true,
6905 /*IncludeDependentBases=*/true,
6906 CodeCompleter
->loadExternal());
6909 HandleCodeCompleteResults(&SemaRef
, CodeCompleter
,
6910 Results
.getCompletionContext(), Results
.data(),
6914 void SemaCodeCompletion::CodeCompleteUsing(Scope
*S
) {
6918 // This can be both a using alias or using declaration, in the former we
6919 // expect a new name and a symbol in the latter case.
6920 CodeCompletionContext
Context(CodeCompletionContext::CCC_SymbolOrNewName
);
6921 Context
.setIsUsingDeclaration(true);
6923 ResultBuilder
Results(SemaRef
, CodeCompleter
->getAllocator(),
6924 CodeCompleter
->getCodeCompletionTUInfo(), Context
,
6925 &ResultBuilder::IsNestedNameSpecifier
);
6926 Results
.EnterNewScope();
6928 // If we aren't in class scope, we could see the "namespace" keyword.
6929 if (!S
->isClassScope())
6930 Results
.AddResult(CodeCompletionResult("namespace"));
6932 // After "using", we can see anything that would start a
6933 // nested-name-specifier.
6934 CodeCompletionDeclConsumer
Consumer(Results
, SemaRef
.CurContext
);
6935 SemaRef
.LookupVisibleDecls(S
, Sema::LookupOrdinaryName
, Consumer
,
6936 CodeCompleter
->includeGlobals(),
6937 CodeCompleter
->loadExternal());
6938 Results
.ExitScope();
6940 HandleCodeCompleteResults(&SemaRef
, CodeCompleter
,
6941 Results
.getCompletionContext(), Results
.data(),
6945 void SemaCodeCompletion::CodeCompleteUsingDirective(Scope
*S
) {
6949 // After "using namespace", we expect to see a namespace name or namespace
6951 ResultBuilder
Results(SemaRef
, CodeCompleter
->getAllocator(),
6952 CodeCompleter
->getCodeCompletionTUInfo(),
6953 CodeCompletionContext::CCC_Namespace
,
6954 &ResultBuilder::IsNamespaceOrAlias
);
6955 Results
.EnterNewScope();
6956 CodeCompletionDeclConsumer
Consumer(Results
, SemaRef
.CurContext
);
6957 SemaRef
.LookupVisibleDecls(S
, Sema::LookupOrdinaryName
, Consumer
,
6958 CodeCompleter
->includeGlobals(),
6959 CodeCompleter
->loadExternal());
6960 Results
.ExitScope();
6961 HandleCodeCompleteResults(&SemaRef
, CodeCompleter
,
6962 Results
.getCompletionContext(), Results
.data(),
6966 void SemaCodeCompletion::CodeCompleteNamespaceDecl(Scope
*S
) {
6970 DeclContext
*Ctx
= S
->getEntity();
6971 if (!S
->getParent())
6972 Ctx
= getASTContext().getTranslationUnitDecl();
6974 bool SuppressedGlobalResults
=
6975 Ctx
&& !CodeCompleter
->includeGlobals() && isa
<TranslationUnitDecl
>(Ctx
);
6977 ResultBuilder
Results(SemaRef
, CodeCompleter
->getAllocator(),
6978 CodeCompleter
->getCodeCompletionTUInfo(),
6979 SuppressedGlobalResults
6980 ? CodeCompletionContext::CCC_Namespace
6981 : CodeCompletionContext::CCC_Other
,
6982 &ResultBuilder::IsNamespace
);
6984 if (Ctx
&& Ctx
->isFileContext() && !SuppressedGlobalResults
) {
6985 // We only want to see those namespaces that have already been defined
6986 // within this scope, because its likely that the user is creating an
6987 // extended namespace declaration. Keep track of the most recent
6988 // definition of each namespace.
6989 std::map
<NamespaceDecl
*, NamespaceDecl
*> OrigToLatest
;
6990 for (DeclContext::specific_decl_iterator
<NamespaceDecl
>
6991 NS(Ctx
->decls_begin()),
6992 NSEnd(Ctx
->decls_end());
6994 OrigToLatest
[NS
->getFirstDecl()] = *NS
;
6996 // Add the most recent definition (or extended definition) of each
6997 // namespace to the list of results.
6998 Results
.EnterNewScope();
6999 for (std::map
<NamespaceDecl
*, NamespaceDecl
*>::iterator
7000 NS
= OrigToLatest
.begin(),
7001 NSEnd
= OrigToLatest
.end();
7004 CodeCompletionResult(NS
->second
, Results
.getBasePriority(NS
->second
),
7006 SemaRef
.CurContext
, nullptr, false);
7007 Results
.ExitScope();
7010 HandleCodeCompleteResults(&SemaRef
, CodeCompleter
,
7011 Results
.getCompletionContext(), Results
.data(),
7015 void SemaCodeCompletion::CodeCompleteNamespaceAliasDecl(Scope
*S
) {
7019 // After "namespace", we expect to see a namespace or alias.
7020 ResultBuilder
Results(SemaRef
, CodeCompleter
->getAllocator(),
7021 CodeCompleter
->getCodeCompletionTUInfo(),
7022 CodeCompletionContext::CCC_Namespace
,
7023 &ResultBuilder::IsNamespaceOrAlias
);
7024 CodeCompletionDeclConsumer
Consumer(Results
, SemaRef
.CurContext
);
7025 SemaRef
.LookupVisibleDecls(S
, Sema::LookupOrdinaryName
, Consumer
,
7026 CodeCompleter
->includeGlobals(),
7027 CodeCompleter
->loadExternal());
7028 HandleCodeCompleteResults(&SemaRef
, CodeCompleter
,
7029 Results
.getCompletionContext(), Results
.data(),
7033 void SemaCodeCompletion::CodeCompleteOperatorName(Scope
*S
) {
7037 typedef CodeCompletionResult Result
;
7038 ResultBuilder
Results(SemaRef
, CodeCompleter
->getAllocator(),
7039 CodeCompleter
->getCodeCompletionTUInfo(),
7040 CodeCompletionContext::CCC_Type
,
7041 &ResultBuilder::IsType
);
7042 Results
.EnterNewScope();
7044 // Add the names of overloadable operators. Note that OO_Conditional is not
7045 // actually overloadable.
7046 #define OVERLOADED_OPERATOR(Name, Spelling, Token, Unary, Binary, MemberOnly) \
7047 if (OO_##Name != OO_Conditional) \
7048 Results.AddResult(Result(Spelling));
7049 #include "clang/Basic/OperatorKinds.def"
7051 // Add any type names visible from the current scope
7052 Results
.allowNestedNameSpecifiers();
7053 CodeCompletionDeclConsumer
Consumer(Results
, SemaRef
.CurContext
);
7054 SemaRef
.LookupVisibleDecls(S
, Sema::LookupOrdinaryName
, Consumer
,
7055 CodeCompleter
->includeGlobals(),
7056 CodeCompleter
->loadExternal());
7058 // Add any type specifiers
7059 AddTypeSpecifierResults(getLangOpts(), Results
);
7060 Results
.ExitScope();
7062 HandleCodeCompleteResults(&SemaRef
, CodeCompleter
,
7063 Results
.getCompletionContext(), Results
.data(),
7067 void SemaCodeCompletion::CodeCompleteConstructorInitializer(
7068 Decl
*ConstructorD
, ArrayRef
<CXXCtorInitializer
*> Initializers
) {
7072 SemaRef
.AdjustDeclIfTemplate(ConstructorD
);
7074 auto *Constructor
= dyn_cast
<CXXConstructorDecl
>(ConstructorD
);
7078 ResultBuilder
Results(SemaRef
, CodeCompleter
->getAllocator(),
7079 CodeCompleter
->getCodeCompletionTUInfo(),
7080 CodeCompletionContext::CCC_Symbol
);
7081 Results
.EnterNewScope();
7083 // Fill in any already-initialized fields or base classes.
7084 llvm::SmallPtrSet
<FieldDecl
*, 4> InitializedFields
;
7085 llvm::SmallPtrSet
<CanQualType
, 4> InitializedBases
;
7086 for (unsigned I
= 0, E
= Initializers
.size(); I
!= E
; ++I
) {
7087 if (Initializers
[I
]->isBaseInitializer())
7088 InitializedBases
.insert(getASTContext().getCanonicalType(
7089 QualType(Initializers
[I
]->getBaseClass(), 0)));
7091 InitializedFields
.insert(
7092 cast
<FieldDecl
>(Initializers
[I
]->getAnyMember()));
7095 // Add completions for base classes.
7096 PrintingPolicy Policy
= getCompletionPrintingPolicy(SemaRef
);
7097 bool SawLastInitializer
= Initializers
.empty();
7098 CXXRecordDecl
*ClassDecl
= Constructor
->getParent();
7100 auto GenerateCCS
= [&](const NamedDecl
*ND
, const char *Name
) {
7101 CodeCompletionBuilder
Builder(Results
.getAllocator(),
7102 Results
.getCodeCompletionTUInfo());
7103 Builder
.AddTypedTextChunk(Name
);
7104 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
7105 if (const auto *Function
= dyn_cast
<FunctionDecl
>(ND
))
7106 AddFunctionParameterChunks(SemaRef
.PP
, Policy
, Function
, Builder
);
7107 else if (const auto *FunTemplDecl
= dyn_cast
<FunctionTemplateDecl
>(ND
))
7108 AddFunctionParameterChunks(SemaRef
.PP
, Policy
,
7109 FunTemplDecl
->getTemplatedDecl(), Builder
);
7110 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
7111 return Builder
.TakeString();
7113 auto AddDefaultCtorInit
= [&](const char *Name
, const char *Type
,
7114 const NamedDecl
*ND
) {
7115 CodeCompletionBuilder
Builder(Results
.getAllocator(),
7116 Results
.getCodeCompletionTUInfo());
7117 Builder
.AddTypedTextChunk(Name
);
7118 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
7119 Builder
.AddPlaceholderChunk(Type
);
7120 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
7122 auto CCR
= CodeCompletionResult(
7123 Builder
.TakeString(), ND
,
7124 SawLastInitializer
? CCP_NextInitializer
: CCP_MemberDeclaration
);
7125 if (isa
<FieldDecl
>(ND
))
7126 CCR
.CursorKind
= CXCursor_MemberRef
;
7127 return Results
.AddResult(CCR
);
7129 return Results
.AddResult(CodeCompletionResult(
7130 Builder
.TakeString(),
7131 SawLastInitializer
? CCP_NextInitializer
: CCP_MemberDeclaration
));
7133 auto AddCtorsWithName
= [&](const CXXRecordDecl
*RD
, unsigned int Priority
,
7134 const char *Name
, const FieldDecl
*FD
) {
7136 return AddDefaultCtorInit(Name
,
7137 FD
? Results
.getAllocator().CopyString(
7138 FD
->getType().getAsString(Policy
))
7141 auto Ctors
= getConstructors(getASTContext(), RD
);
7142 if (Ctors
.begin() == Ctors
.end())
7143 return AddDefaultCtorInit(Name
, Name
, RD
);
7144 for (const NamedDecl
*Ctor
: Ctors
) {
7145 auto CCR
= CodeCompletionResult(GenerateCCS(Ctor
, Name
), RD
, Priority
);
7146 CCR
.CursorKind
= getCursorKindForDecl(Ctor
);
7147 Results
.AddResult(CCR
);
7150 auto AddBase
= [&](const CXXBaseSpecifier
&Base
) {
7151 const char *BaseName
=
7152 Results
.getAllocator().CopyString(Base
.getType().getAsString(Policy
));
7153 const auto *RD
= Base
.getType()->getAsCXXRecordDecl();
7155 RD
, SawLastInitializer
? CCP_NextInitializer
: CCP_MemberDeclaration
,
7158 auto AddField
= [&](const FieldDecl
*FD
) {
7159 const char *FieldName
=
7160 Results
.getAllocator().CopyString(FD
->getIdentifier()->getName());
7161 const CXXRecordDecl
*RD
= FD
->getType()->getAsCXXRecordDecl();
7163 RD
, SawLastInitializer
? CCP_NextInitializer
: CCP_MemberDeclaration
,
7167 for (const auto &Base
: ClassDecl
->bases()) {
7168 if (!InitializedBases
7169 .insert(getASTContext().getCanonicalType(Base
.getType()))
7171 SawLastInitializer
=
7172 !Initializers
.empty() && Initializers
.back()->isBaseInitializer() &&
7173 getASTContext().hasSameUnqualifiedType(
7174 Base
.getType(), QualType(Initializers
.back()->getBaseClass(), 0));
7179 SawLastInitializer
= false;
7182 // Add completions for virtual base classes.
7183 for (const auto &Base
: ClassDecl
->vbases()) {
7184 if (!InitializedBases
7185 .insert(getASTContext().getCanonicalType(Base
.getType()))
7187 SawLastInitializer
=
7188 !Initializers
.empty() && Initializers
.back()->isBaseInitializer() &&
7189 getASTContext().hasSameUnqualifiedType(
7190 Base
.getType(), QualType(Initializers
.back()->getBaseClass(), 0));
7195 SawLastInitializer
= false;
7198 // Add completions for members.
7199 for (auto *Field
: ClassDecl
->fields()) {
7200 if (!InitializedFields
.insert(cast
<FieldDecl
>(Field
->getCanonicalDecl()))
7202 SawLastInitializer
= !Initializers
.empty() &&
7203 Initializers
.back()->isAnyMemberInitializer() &&
7204 Initializers
.back()->getAnyMember() == Field
;
7208 if (!Field
->getDeclName())
7212 SawLastInitializer
= false;
7214 Results
.ExitScope();
7216 HandleCodeCompleteResults(&SemaRef
, CodeCompleter
,
7217 Results
.getCompletionContext(), Results
.data(),
7221 /// Determine whether this scope denotes a namespace.
7222 static bool isNamespaceScope(Scope
*S
) {
7223 DeclContext
*DC
= S
->getEntity();
7227 return DC
->isFileContext();
7230 void SemaCodeCompletion::CodeCompleteLambdaIntroducer(Scope
*S
,
7231 LambdaIntroducer
&Intro
,
7232 bool AfterAmpersand
) {
7233 ResultBuilder
Results(SemaRef
, CodeCompleter
->getAllocator(),
7234 CodeCompleter
->getCodeCompletionTUInfo(),
7235 CodeCompletionContext::CCC_Other
);
7236 Results
.EnterNewScope();
7238 // Note what has already been captured.
7239 llvm::SmallPtrSet
<IdentifierInfo
*, 4> Known
;
7240 bool IncludedThis
= false;
7241 for (const auto &C
: Intro
.Captures
) {
7242 if (C
.Kind
== LCK_This
) {
7243 IncludedThis
= true;
7250 // Look for other capturable variables.
7251 for (; S
&& !isNamespaceScope(S
); S
= S
->getParent()) {
7252 for (const auto *D
: S
->decls()) {
7253 const auto *Var
= dyn_cast
<VarDecl
>(D
);
7254 if (!Var
|| !Var
->hasLocalStorage() || Var
->hasAttr
<BlocksAttr
>())
7257 if (Known
.insert(Var
->getIdentifier()).second
)
7258 Results
.AddResult(CodeCompletionResult(Var
, CCP_LocalDeclaration
),
7259 SemaRef
.CurContext
, nullptr, false);
7263 // Add 'this', if it would be valid.
7264 if (!IncludedThis
&& !AfterAmpersand
&& Intro
.Default
!= LCD_ByCopy
)
7265 addThisCompletion(SemaRef
, Results
);
7267 Results
.ExitScope();
7269 HandleCodeCompleteResults(&SemaRef
, CodeCompleter
,
7270 Results
.getCompletionContext(), Results
.data(),
7274 void SemaCodeCompletion::CodeCompleteAfterFunctionEquals(Declarator
&D
) {
7275 if (!getLangOpts().CPlusPlus11
)
7277 ResultBuilder
Results(SemaRef
, CodeCompleter
->getAllocator(),
7278 CodeCompleter
->getCodeCompletionTUInfo(),
7279 CodeCompletionContext::CCC_Other
);
7280 auto ShouldAddDefault
= [&D
, this]() {
7281 if (!D
.isFunctionDeclarator())
7283 auto &Id
= D
.getName();
7284 if (Id
.getKind() == UnqualifiedIdKind::IK_DestructorName
)
7286 // FIXME(liuhui): Ideally, we should check the constructor parameter list to
7287 // verify that it is the default, copy or move constructor?
7288 if (Id
.getKind() == UnqualifiedIdKind::IK_ConstructorName
&&
7289 D
.getFunctionTypeInfo().NumParams
<= 1)
7291 if (Id
.getKind() == UnqualifiedIdKind::IK_OperatorFunctionId
) {
7292 auto Op
= Id
.OperatorFunctionId
.Operator
;
7293 // FIXME(liuhui): Ideally, we should check the function parameter list to
7294 // verify that it is the copy or move assignment?
7295 if (Op
== OverloadedOperatorKind::OO_Equal
)
7297 if (getLangOpts().CPlusPlus20
&&
7298 (Op
== OverloadedOperatorKind::OO_EqualEqual
||
7299 Op
== OverloadedOperatorKind::OO_ExclaimEqual
||
7300 Op
== OverloadedOperatorKind::OO_Less
||
7301 Op
== OverloadedOperatorKind::OO_LessEqual
||
7302 Op
== OverloadedOperatorKind::OO_Greater
||
7303 Op
== OverloadedOperatorKind::OO_GreaterEqual
||
7304 Op
== OverloadedOperatorKind::OO_Spaceship
))
7310 Results
.EnterNewScope();
7311 if (ShouldAddDefault())
7312 Results
.AddResult("default");
7313 // FIXME(liuhui): Ideally, we should only provide `delete` completion for the
7314 // first function declaration.
7315 Results
.AddResult("delete");
7316 Results
.ExitScope();
7317 HandleCodeCompleteResults(&SemaRef
, CodeCompleter
,
7318 Results
.getCompletionContext(), Results
.data(),
7322 /// Macro that optionally prepends an "@" to the string literal passed in via
7323 /// Keyword, depending on whether NeedAt is true or false.
7324 #define OBJC_AT_KEYWORD_NAME(NeedAt, Keyword) ((NeedAt) ? "@" Keyword : Keyword)
7326 static void AddObjCImplementationResults(const LangOptions
&LangOpts
,
7327 ResultBuilder
&Results
, bool NeedAt
) {
7328 typedef CodeCompletionResult Result
;
7329 // Since we have an implementation, we can end it.
7330 Results
.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt
, "end")));
7332 CodeCompletionBuilder
Builder(Results
.getAllocator(),
7333 Results
.getCodeCompletionTUInfo());
7334 if (LangOpts
.ObjC
) {
7336 Builder
.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt
, "dynamic"));
7337 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
7338 Builder
.AddPlaceholderChunk("property");
7339 Results
.AddResult(Result(Builder
.TakeString()));
7342 Builder
.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt
, "synthesize"));
7343 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
7344 Builder
.AddPlaceholderChunk("property");
7345 Results
.AddResult(Result(Builder
.TakeString()));
7349 static void AddObjCInterfaceResults(const LangOptions
&LangOpts
,
7350 ResultBuilder
&Results
, bool NeedAt
) {
7351 typedef CodeCompletionResult Result
;
7353 // Since we have an interface or protocol, we can end it.
7354 Results
.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt
, "end")));
7356 if (LangOpts
.ObjC
) {
7358 Results
.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt
, "property")));
7361 Results
.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt
, "required")));
7364 Results
.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt
, "optional")));
7368 static void AddObjCTopLevelResults(ResultBuilder
&Results
, bool NeedAt
) {
7369 typedef CodeCompletionResult Result
;
7370 CodeCompletionBuilder
Builder(Results
.getAllocator(),
7371 Results
.getCodeCompletionTUInfo());
7374 Builder
.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt
, "class"));
7375 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
7376 Builder
.AddPlaceholderChunk("name");
7377 Results
.AddResult(Result(Builder
.TakeString()));
7379 if (Results
.includeCodePatterns()) {
7381 // FIXME: Could introduce the whole pattern, including superclasses and
7383 Builder
.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt
, "interface"));
7384 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
7385 Builder
.AddPlaceholderChunk("class");
7386 Results
.AddResult(Result(Builder
.TakeString()));
7389 Builder
.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt
, "protocol"));
7390 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
7391 Builder
.AddPlaceholderChunk("protocol");
7392 Results
.AddResult(Result(Builder
.TakeString()));
7394 // @implementation name
7395 Builder
.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt
, "implementation"));
7396 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
7397 Builder
.AddPlaceholderChunk("class");
7398 Results
.AddResult(Result(Builder
.TakeString()));
7401 // @compatibility_alias name
7402 Builder
.AddTypedTextChunk(
7403 OBJC_AT_KEYWORD_NAME(NeedAt
, "compatibility_alias"));
7404 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
7405 Builder
.AddPlaceholderChunk("alias");
7406 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
7407 Builder
.AddPlaceholderChunk("class");
7408 Results
.AddResult(Result(Builder
.TakeString()));
7410 if (Results
.getSema().getLangOpts().Modules
) {
7412 Builder
.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt
, "import"));
7413 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
7414 Builder
.AddPlaceholderChunk("module");
7415 Results
.AddResult(Result(Builder
.TakeString()));
7419 void SemaCodeCompletion::CodeCompleteObjCAtDirective(Scope
*S
) {
7420 ResultBuilder
Results(SemaRef
, CodeCompleter
->getAllocator(),
7421 CodeCompleter
->getCodeCompletionTUInfo(),
7422 CodeCompletionContext::CCC_Other
);
7423 Results
.EnterNewScope();
7424 if (isa
<ObjCImplDecl
>(SemaRef
.CurContext
))
7425 AddObjCImplementationResults(getLangOpts(), Results
, false);
7426 else if (SemaRef
.CurContext
->isObjCContainer())
7427 AddObjCInterfaceResults(getLangOpts(), Results
, false);
7429 AddObjCTopLevelResults(Results
, false);
7430 Results
.ExitScope();
7431 HandleCodeCompleteResults(&SemaRef
, CodeCompleter
,
7432 Results
.getCompletionContext(), Results
.data(),
7436 static void AddObjCExpressionResults(ResultBuilder
&Results
, bool NeedAt
) {
7437 typedef CodeCompletionResult Result
;
7438 CodeCompletionBuilder
Builder(Results
.getAllocator(),
7439 Results
.getCodeCompletionTUInfo());
7441 // @encode ( type-name )
7442 const char *EncodeType
= "char[]";
7443 if (Results
.getSema().getLangOpts().CPlusPlus
||
7444 Results
.getSema().getLangOpts().ConstStrings
)
7445 EncodeType
= "const char[]";
7446 Builder
.AddResultTypeChunk(EncodeType
);
7447 Builder
.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt
, "encode"));
7448 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
7449 Builder
.AddPlaceholderChunk("type-name");
7450 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
7451 Results
.AddResult(Result(Builder
.TakeString()));
7453 // @protocol ( protocol-name )
7454 Builder
.AddResultTypeChunk("Protocol *");
7455 Builder
.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt
, "protocol"));
7456 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
7457 Builder
.AddPlaceholderChunk("protocol-name");
7458 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
7459 Results
.AddResult(Result(Builder
.TakeString()));
7461 // @selector ( selector )
7462 Builder
.AddResultTypeChunk("SEL");
7463 Builder
.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt
, "selector"));
7464 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
7465 Builder
.AddPlaceholderChunk("selector");
7466 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
7467 Results
.AddResult(Result(Builder
.TakeString()));
7470 Builder
.AddResultTypeChunk("NSString *");
7471 Builder
.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt
, "\""));
7472 Builder
.AddPlaceholderChunk("string");
7473 Builder
.AddTextChunk("\"");
7474 Results
.AddResult(Result(Builder
.TakeString()));
7477 Builder
.AddResultTypeChunk("NSArray *");
7478 Builder
.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt
, "["));
7479 Builder
.AddPlaceholderChunk("objects, ...");
7480 Builder
.AddChunk(CodeCompletionString::CK_RightBracket
);
7481 Results
.AddResult(Result(Builder
.TakeString()));
7483 // @{key : object, ...}
7484 Builder
.AddResultTypeChunk("NSDictionary *");
7485 Builder
.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt
, "{"));
7486 Builder
.AddPlaceholderChunk("key");
7487 Builder
.AddChunk(CodeCompletionString::CK_Colon
);
7488 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
7489 Builder
.AddPlaceholderChunk("object, ...");
7490 Builder
.AddChunk(CodeCompletionString::CK_RightBrace
);
7491 Results
.AddResult(Result(Builder
.TakeString()));
7494 Builder
.AddResultTypeChunk("id");
7495 Builder
.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt
, "("));
7496 Builder
.AddPlaceholderChunk("expression");
7497 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
7498 Results
.AddResult(Result(Builder
.TakeString()));
7501 static void AddObjCStatementResults(ResultBuilder
&Results
, bool NeedAt
) {
7502 typedef CodeCompletionResult Result
;
7503 CodeCompletionBuilder
Builder(Results
.getAllocator(),
7504 Results
.getCodeCompletionTUInfo());
7506 if (Results
.includeCodePatterns()) {
7507 // @try { statements } @catch ( declaration ) { statements } @finally
7509 Builder
.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt
, "try"));
7510 Builder
.AddChunk(CodeCompletionString::CK_LeftBrace
);
7511 Builder
.AddPlaceholderChunk("statements");
7512 Builder
.AddChunk(CodeCompletionString::CK_RightBrace
);
7513 Builder
.AddTextChunk("@catch");
7514 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
7515 Builder
.AddPlaceholderChunk("parameter");
7516 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
7517 Builder
.AddChunk(CodeCompletionString::CK_LeftBrace
);
7518 Builder
.AddPlaceholderChunk("statements");
7519 Builder
.AddChunk(CodeCompletionString::CK_RightBrace
);
7520 Builder
.AddTextChunk("@finally");
7521 Builder
.AddChunk(CodeCompletionString::CK_LeftBrace
);
7522 Builder
.AddPlaceholderChunk("statements");
7523 Builder
.AddChunk(CodeCompletionString::CK_RightBrace
);
7524 Results
.AddResult(Result(Builder
.TakeString()));
7528 Builder
.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt
, "throw"));
7529 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
7530 Builder
.AddPlaceholderChunk("expression");
7531 Results
.AddResult(Result(Builder
.TakeString()));
7533 if (Results
.includeCodePatterns()) {
7534 // @synchronized ( expression ) { statements }
7535 Builder
.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt
, "synchronized"));
7536 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
7537 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
7538 Builder
.AddPlaceholderChunk("expression");
7539 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
7540 Builder
.AddChunk(CodeCompletionString::CK_LeftBrace
);
7541 Builder
.AddPlaceholderChunk("statements");
7542 Builder
.AddChunk(CodeCompletionString::CK_RightBrace
);
7543 Results
.AddResult(Result(Builder
.TakeString()));
7547 static void AddObjCVisibilityResults(const LangOptions
&LangOpts
,
7548 ResultBuilder
&Results
, bool NeedAt
) {
7549 typedef CodeCompletionResult Result
;
7550 Results
.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt
, "private")));
7551 Results
.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt
, "protected")));
7552 Results
.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt
, "public")));
7554 Results
.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt
, "package")));
7557 void SemaCodeCompletion::CodeCompleteObjCAtVisibility(Scope
*S
) {
7558 ResultBuilder
Results(SemaRef
, CodeCompleter
->getAllocator(),
7559 CodeCompleter
->getCodeCompletionTUInfo(),
7560 CodeCompletionContext::CCC_Other
);
7561 Results
.EnterNewScope();
7562 AddObjCVisibilityResults(getLangOpts(), Results
, false);
7563 Results
.ExitScope();
7564 HandleCodeCompleteResults(&SemaRef
, CodeCompleter
,
7565 Results
.getCompletionContext(), Results
.data(),
7569 void SemaCodeCompletion::CodeCompleteObjCAtStatement(Scope
*S
) {
7570 ResultBuilder
Results(SemaRef
, CodeCompleter
->getAllocator(),
7571 CodeCompleter
->getCodeCompletionTUInfo(),
7572 CodeCompletionContext::CCC_Other
);
7573 Results
.EnterNewScope();
7574 AddObjCStatementResults(Results
, false);
7575 AddObjCExpressionResults(Results
, false);
7576 Results
.ExitScope();
7577 HandleCodeCompleteResults(&SemaRef
, CodeCompleter
,
7578 Results
.getCompletionContext(), Results
.data(),
7582 void SemaCodeCompletion::CodeCompleteObjCAtExpression(Scope
*S
) {
7583 ResultBuilder
Results(SemaRef
, CodeCompleter
->getAllocator(),
7584 CodeCompleter
->getCodeCompletionTUInfo(),
7585 CodeCompletionContext::CCC_Other
);
7586 Results
.EnterNewScope();
7587 AddObjCExpressionResults(Results
, false);
7588 Results
.ExitScope();
7589 HandleCodeCompleteResults(&SemaRef
, CodeCompleter
,
7590 Results
.getCompletionContext(), Results
.data(),
7594 /// Determine whether the addition of the given flag to an Objective-C
7595 /// property's attributes will cause a conflict.
7596 static bool ObjCPropertyFlagConflicts(unsigned Attributes
, unsigned NewFlag
) {
7597 // Check if we've already added this flag.
7598 if (Attributes
& NewFlag
)
7601 Attributes
|= NewFlag
;
7603 // Check for collisions with "readonly".
7604 if ((Attributes
& ObjCPropertyAttribute::kind_readonly
) &&
7605 (Attributes
& ObjCPropertyAttribute::kind_readwrite
))
7608 // Check for more than one of { assign, copy, retain, strong, weak }.
7609 unsigned AssignCopyRetMask
=
7611 (ObjCPropertyAttribute::kind_assign
|
7612 ObjCPropertyAttribute::kind_unsafe_unretained
|
7613 ObjCPropertyAttribute::kind_copy
| ObjCPropertyAttribute::kind_retain
|
7614 ObjCPropertyAttribute::kind_strong
| ObjCPropertyAttribute::kind_weak
);
7615 if (AssignCopyRetMask
&&
7616 AssignCopyRetMask
!= ObjCPropertyAttribute::kind_assign
&&
7617 AssignCopyRetMask
!= ObjCPropertyAttribute::kind_unsafe_unretained
&&
7618 AssignCopyRetMask
!= ObjCPropertyAttribute::kind_copy
&&
7619 AssignCopyRetMask
!= ObjCPropertyAttribute::kind_retain
&&
7620 AssignCopyRetMask
!= ObjCPropertyAttribute::kind_strong
&&
7621 AssignCopyRetMask
!= ObjCPropertyAttribute::kind_weak
)
7627 void SemaCodeCompletion::CodeCompleteObjCPropertyFlags(Scope
*S
,
7628 ObjCDeclSpec
&ODS
) {
7632 unsigned Attributes
= ODS
.getPropertyAttributes();
7634 ResultBuilder
Results(SemaRef
, CodeCompleter
->getAllocator(),
7635 CodeCompleter
->getCodeCompletionTUInfo(),
7636 CodeCompletionContext::CCC_Other
);
7637 Results
.EnterNewScope();
7638 if (!ObjCPropertyFlagConflicts(Attributes
,
7639 ObjCPropertyAttribute::kind_readonly
))
7640 Results
.AddResult(CodeCompletionResult("readonly"));
7641 if (!ObjCPropertyFlagConflicts(Attributes
,
7642 ObjCPropertyAttribute::kind_assign
))
7643 Results
.AddResult(CodeCompletionResult("assign"));
7644 if (!ObjCPropertyFlagConflicts(Attributes
,
7645 ObjCPropertyAttribute::kind_unsafe_unretained
))
7646 Results
.AddResult(CodeCompletionResult("unsafe_unretained"));
7647 if (!ObjCPropertyFlagConflicts(Attributes
,
7648 ObjCPropertyAttribute::kind_readwrite
))
7649 Results
.AddResult(CodeCompletionResult("readwrite"));
7650 if (!ObjCPropertyFlagConflicts(Attributes
,
7651 ObjCPropertyAttribute::kind_retain
))
7652 Results
.AddResult(CodeCompletionResult("retain"));
7653 if (!ObjCPropertyFlagConflicts(Attributes
,
7654 ObjCPropertyAttribute::kind_strong
))
7655 Results
.AddResult(CodeCompletionResult("strong"));
7656 if (!ObjCPropertyFlagConflicts(Attributes
, ObjCPropertyAttribute::kind_copy
))
7657 Results
.AddResult(CodeCompletionResult("copy"));
7658 if (!ObjCPropertyFlagConflicts(Attributes
,
7659 ObjCPropertyAttribute::kind_nonatomic
))
7660 Results
.AddResult(CodeCompletionResult("nonatomic"));
7661 if (!ObjCPropertyFlagConflicts(Attributes
,
7662 ObjCPropertyAttribute::kind_atomic
))
7663 Results
.AddResult(CodeCompletionResult("atomic"));
7665 // Only suggest "weak" if we're compiling for ARC-with-weak-references or GC.
7666 if (getLangOpts().ObjCWeak
|| getLangOpts().getGC() != LangOptions::NonGC
)
7667 if (!ObjCPropertyFlagConflicts(Attributes
,
7668 ObjCPropertyAttribute::kind_weak
))
7669 Results
.AddResult(CodeCompletionResult("weak"));
7671 if (!ObjCPropertyFlagConflicts(Attributes
,
7672 ObjCPropertyAttribute::kind_setter
)) {
7673 CodeCompletionBuilder
Setter(Results
.getAllocator(),
7674 Results
.getCodeCompletionTUInfo());
7675 Setter
.AddTypedTextChunk("setter");
7676 Setter
.AddTextChunk("=");
7677 Setter
.AddPlaceholderChunk("method");
7678 Results
.AddResult(CodeCompletionResult(Setter
.TakeString()));
7680 if (!ObjCPropertyFlagConflicts(Attributes
,
7681 ObjCPropertyAttribute::kind_getter
)) {
7682 CodeCompletionBuilder
Getter(Results
.getAllocator(),
7683 Results
.getCodeCompletionTUInfo());
7684 Getter
.AddTypedTextChunk("getter");
7685 Getter
.AddTextChunk("=");
7686 Getter
.AddPlaceholderChunk("method");
7687 Results
.AddResult(CodeCompletionResult(Getter
.TakeString()));
7689 if (!ObjCPropertyFlagConflicts(Attributes
,
7690 ObjCPropertyAttribute::kind_nullability
)) {
7691 Results
.AddResult(CodeCompletionResult("nonnull"));
7692 Results
.AddResult(CodeCompletionResult("nullable"));
7693 Results
.AddResult(CodeCompletionResult("null_unspecified"));
7694 Results
.AddResult(CodeCompletionResult("null_resettable"));
7696 Results
.ExitScope();
7697 HandleCodeCompleteResults(&SemaRef
, CodeCompleter
,
7698 Results
.getCompletionContext(), Results
.data(),
7702 /// Describes the kind of Objective-C method that we want to find
7703 /// via code completion.
7704 enum ObjCMethodKind
{
7705 MK_Any
, ///< Any kind of method, provided it means other specified criteria.
7706 MK_ZeroArgSelector
, ///< Zero-argument (unary) selector.
7707 MK_OneArgSelector
///< One-argument selector.
7710 static bool isAcceptableObjCSelector(Selector Sel
, ObjCMethodKind WantKind
,
7711 ArrayRef
<const IdentifierInfo
*> SelIdents
,
7712 bool AllowSameLength
= true) {
7713 unsigned NumSelIdents
= SelIdents
.size();
7714 if (NumSelIdents
> Sel
.getNumArgs())
7720 case MK_ZeroArgSelector
:
7721 return Sel
.isUnarySelector();
7722 case MK_OneArgSelector
:
7723 return Sel
.getNumArgs() == 1;
7726 if (!AllowSameLength
&& NumSelIdents
&& NumSelIdents
== Sel
.getNumArgs())
7729 for (unsigned I
= 0; I
!= NumSelIdents
; ++I
)
7730 if (SelIdents
[I
] != Sel
.getIdentifierInfoForSlot(I
))
7736 static bool isAcceptableObjCMethod(ObjCMethodDecl
*Method
,
7737 ObjCMethodKind WantKind
,
7738 ArrayRef
<const IdentifierInfo
*> SelIdents
,
7739 bool AllowSameLength
= true) {
7740 return isAcceptableObjCSelector(Method
->getSelector(), WantKind
, SelIdents
,
7744 /// A set of selectors, which is used to avoid introducing multiple
7745 /// completions with the same selector into the result set.
7746 typedef llvm::SmallPtrSet
<Selector
, 16> VisitedSelectorSet
;
7748 /// Add all of the Objective-C methods in the given Objective-C
7749 /// container to the set of results.
7751 /// The container will be a class, protocol, category, or implementation of
7752 /// any of the above. This mether will recurse to include methods from
7753 /// the superclasses of classes along with their categories, protocols, and
7754 /// implementations.
7756 /// \param Container the container in which we'll look to find methods.
7758 /// \param WantInstanceMethods Whether to add instance methods (only); if
7759 /// false, this routine will add factory methods (only).
7761 /// \param CurContext the context in which we're performing the lookup that
7764 /// \param AllowSameLength Whether we allow a method to be added to the list
7765 /// when it has the same number of parameters as we have selector identifiers.
7767 /// \param Results the structure into which we'll add results.
7768 static void AddObjCMethods(ObjCContainerDecl
*Container
,
7769 bool WantInstanceMethods
, ObjCMethodKind WantKind
,
7770 ArrayRef
<const IdentifierInfo
*> SelIdents
,
7771 DeclContext
*CurContext
,
7772 VisitedSelectorSet
&Selectors
, bool AllowSameLength
,
7773 ResultBuilder
&Results
, bool InOriginalClass
= true,
7774 bool IsRootClass
= false) {
7775 typedef CodeCompletionResult Result
;
7776 Container
= getContainerDef(Container
);
7777 ObjCInterfaceDecl
*IFace
= dyn_cast
<ObjCInterfaceDecl
>(Container
);
7778 IsRootClass
= IsRootClass
|| (IFace
&& !IFace
->getSuperClass());
7779 for (ObjCMethodDecl
*M
: Container
->methods()) {
7780 // The instance methods on the root class can be messaged via the
7782 if (M
->isInstanceMethod() == WantInstanceMethods
||
7783 (IsRootClass
&& !WantInstanceMethods
)) {
7784 // Check whether the selector identifiers we've been given are a
7785 // subset of the identifiers for this particular method.
7786 if (!isAcceptableObjCMethod(M
, WantKind
, SelIdents
, AllowSameLength
))
7789 if (!Selectors
.insert(M
->getSelector()).second
)
7792 Result R
= Result(M
, Results
.getBasePriority(M
), nullptr);
7793 R
.StartParameter
= SelIdents
.size();
7794 R
.AllParametersAreInformative
= (WantKind
!= MK_Any
);
7795 if (!InOriginalClass
)
7797 Results
.MaybeAddResult(R
, CurContext
);
7801 // Visit the protocols of protocols.
7802 if (const auto *Protocol
= dyn_cast
<ObjCProtocolDecl
>(Container
)) {
7803 if (Protocol
->hasDefinition()) {
7804 const ObjCList
<ObjCProtocolDecl
> &Protocols
=
7805 Protocol
->getReferencedProtocols();
7806 for (ObjCList
<ObjCProtocolDecl
>::iterator I
= Protocols
.begin(),
7807 E
= Protocols
.end();
7809 AddObjCMethods(*I
, WantInstanceMethods
, WantKind
, SelIdents
, CurContext
,
7810 Selectors
, AllowSameLength
, Results
, false, IsRootClass
);
7814 if (!IFace
|| !IFace
->hasDefinition())
7817 // Add methods in protocols.
7818 for (ObjCProtocolDecl
*I
: IFace
->protocols())
7819 AddObjCMethods(I
, WantInstanceMethods
, WantKind
, SelIdents
, CurContext
,
7820 Selectors
, AllowSameLength
, Results
, false, IsRootClass
);
7822 // Add methods in categories.
7823 for (ObjCCategoryDecl
*CatDecl
: IFace
->known_categories()) {
7824 AddObjCMethods(CatDecl
, WantInstanceMethods
, WantKind
, SelIdents
,
7825 CurContext
, Selectors
, AllowSameLength
, Results
,
7826 InOriginalClass
, IsRootClass
);
7828 // Add a categories protocol methods.
7829 const ObjCList
<ObjCProtocolDecl
> &Protocols
=
7830 CatDecl
->getReferencedProtocols();
7831 for (ObjCList
<ObjCProtocolDecl
>::iterator I
= Protocols
.begin(),
7832 E
= Protocols
.end();
7834 AddObjCMethods(*I
, WantInstanceMethods
, WantKind
, SelIdents
, CurContext
,
7835 Selectors
, AllowSameLength
, Results
, false, IsRootClass
);
7837 // Add methods in category implementations.
7838 if (ObjCCategoryImplDecl
*Impl
= CatDecl
->getImplementation())
7839 AddObjCMethods(Impl
, WantInstanceMethods
, WantKind
, SelIdents
, CurContext
,
7840 Selectors
, AllowSameLength
, Results
, InOriginalClass
,
7844 // Add methods in superclass.
7845 // Avoid passing in IsRootClass since root classes won't have super classes.
7846 if (IFace
->getSuperClass())
7847 AddObjCMethods(IFace
->getSuperClass(), WantInstanceMethods
, WantKind
,
7848 SelIdents
, CurContext
, Selectors
, AllowSameLength
, Results
,
7849 /*IsRootClass=*/false);
7851 // Add methods in our implementation, if any.
7852 if (ObjCImplementationDecl
*Impl
= IFace
->getImplementation())
7853 AddObjCMethods(Impl
, WantInstanceMethods
, WantKind
, SelIdents
, CurContext
,
7854 Selectors
, AllowSameLength
, Results
, InOriginalClass
,
7858 void SemaCodeCompletion::CodeCompleteObjCPropertyGetter(Scope
*S
) {
7859 // Try to find the interface where getters might live.
7860 ObjCInterfaceDecl
*Class
=
7861 dyn_cast_or_null
<ObjCInterfaceDecl
>(SemaRef
.CurContext
);
7863 if (ObjCCategoryDecl
*Category
=
7864 dyn_cast_or_null
<ObjCCategoryDecl
>(SemaRef
.CurContext
))
7865 Class
= Category
->getClassInterface();
7871 // Find all of the potential getters.
7872 ResultBuilder
Results(SemaRef
, CodeCompleter
->getAllocator(),
7873 CodeCompleter
->getCodeCompletionTUInfo(),
7874 CodeCompletionContext::CCC_Other
);
7875 Results
.EnterNewScope();
7877 VisitedSelectorSet Selectors
;
7878 AddObjCMethods(Class
, true, MK_ZeroArgSelector
, {}, SemaRef
.CurContext
,
7880 /*AllowSameLength=*/true, Results
);
7881 Results
.ExitScope();
7882 HandleCodeCompleteResults(&SemaRef
, CodeCompleter
,
7883 Results
.getCompletionContext(), Results
.data(),
7887 void SemaCodeCompletion::CodeCompleteObjCPropertySetter(Scope
*S
) {
7888 // Try to find the interface where setters might live.
7889 ObjCInterfaceDecl
*Class
=
7890 dyn_cast_or_null
<ObjCInterfaceDecl
>(SemaRef
.CurContext
);
7892 if (ObjCCategoryDecl
*Category
=
7893 dyn_cast_or_null
<ObjCCategoryDecl
>(SemaRef
.CurContext
))
7894 Class
= Category
->getClassInterface();
7900 // Find all of the potential getters.
7901 ResultBuilder
Results(SemaRef
, CodeCompleter
->getAllocator(),
7902 CodeCompleter
->getCodeCompletionTUInfo(),
7903 CodeCompletionContext::CCC_Other
);
7904 Results
.EnterNewScope();
7906 VisitedSelectorSet Selectors
;
7907 AddObjCMethods(Class
, true, MK_OneArgSelector
, {}, SemaRef
.CurContext
,
7909 /*AllowSameLength=*/true, Results
);
7911 Results
.ExitScope();
7912 HandleCodeCompleteResults(&SemaRef
, CodeCompleter
,
7913 Results
.getCompletionContext(), Results
.data(),
7917 void SemaCodeCompletion::CodeCompleteObjCPassingType(Scope
*S
, ObjCDeclSpec
&DS
,
7919 ResultBuilder
Results(SemaRef
, CodeCompleter
->getAllocator(),
7920 CodeCompleter
->getCodeCompletionTUInfo(),
7921 CodeCompletionContext::CCC_Type
);
7922 Results
.EnterNewScope();
7924 // Add context-sensitive, Objective-C parameter-passing keywords.
7925 bool AddedInOut
= false;
7926 if ((DS
.getObjCDeclQualifier() &
7927 (ObjCDeclSpec::DQ_In
| ObjCDeclSpec::DQ_Inout
)) == 0) {
7928 Results
.AddResult("in");
7929 Results
.AddResult("inout");
7932 if ((DS
.getObjCDeclQualifier() &
7933 (ObjCDeclSpec::DQ_Out
| ObjCDeclSpec::DQ_Inout
)) == 0) {
7934 Results
.AddResult("out");
7936 Results
.AddResult("inout");
7938 if ((DS
.getObjCDeclQualifier() &
7939 (ObjCDeclSpec::DQ_Bycopy
| ObjCDeclSpec::DQ_Byref
|
7940 ObjCDeclSpec::DQ_Oneway
)) == 0) {
7941 Results
.AddResult("bycopy");
7942 Results
.AddResult("byref");
7943 Results
.AddResult("oneway");
7945 if ((DS
.getObjCDeclQualifier() & ObjCDeclSpec::DQ_CSNullability
) == 0) {
7946 Results
.AddResult("nonnull");
7947 Results
.AddResult("nullable");
7948 Results
.AddResult("null_unspecified");
7951 // If we're completing the return type of an Objective-C method and the
7952 // identifier IBAction refers to a macro, provide a completion item for
7954 // IBAction)<#selector#>:(id)sender
7955 if (DS
.getObjCDeclQualifier() == 0 && !IsParameter
&&
7956 SemaRef
.PP
.isMacroDefined("IBAction")) {
7957 CodeCompletionBuilder
Builder(Results
.getAllocator(),
7958 Results
.getCodeCompletionTUInfo(),
7959 CCP_CodePattern
, CXAvailability_Available
);
7960 Builder
.AddTypedTextChunk("IBAction");
7961 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
7962 Builder
.AddPlaceholderChunk("selector");
7963 Builder
.AddChunk(CodeCompletionString::CK_Colon
);
7964 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
7965 Builder
.AddTextChunk("id");
7966 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
7967 Builder
.AddTextChunk("sender");
7968 Results
.AddResult(CodeCompletionResult(Builder
.TakeString()));
7971 // If we're completing the return type, provide 'instancetype'.
7973 Results
.AddResult(CodeCompletionResult("instancetype"));
7976 // Add various builtin type names and specifiers.
7977 AddOrdinaryNameResults(PCC_Type
, S
, SemaRef
, Results
);
7978 Results
.ExitScope();
7980 // Add the various type names
7981 Results
.setFilter(&ResultBuilder::IsOrdinaryNonValueName
);
7982 CodeCompletionDeclConsumer
Consumer(Results
, SemaRef
.CurContext
);
7983 SemaRef
.LookupVisibleDecls(S
, Sema::LookupOrdinaryName
, Consumer
,
7984 CodeCompleter
->includeGlobals(),
7985 CodeCompleter
->loadExternal());
7987 if (CodeCompleter
->includeMacros())
7988 AddMacroResults(SemaRef
.PP
, Results
, CodeCompleter
->loadExternal(), false);
7990 HandleCodeCompleteResults(&SemaRef
, CodeCompleter
,
7991 Results
.getCompletionContext(), Results
.data(),
7995 /// When we have an expression with type "id", we may assume
7996 /// that it has some more-specific class type based on knowledge of
7997 /// common uses of Objective-C. This routine returns that class type,
7998 /// or NULL if no better result could be determined.
7999 static ObjCInterfaceDecl
*GetAssumedMessageSendExprType(Expr
*E
) {
8000 auto *Msg
= dyn_cast_or_null
<ObjCMessageExpr
>(E
);
8004 Selector Sel
= Msg
->getSelector();
8008 const IdentifierInfo
*Id
= Sel
.getIdentifierInfoForSlot(0);
8012 ObjCMethodDecl
*Method
= Msg
->getMethodDecl();
8016 // Determine the class that we're sending the message to.
8017 ObjCInterfaceDecl
*IFace
= nullptr;
8018 switch (Msg
->getReceiverKind()) {
8019 case ObjCMessageExpr::Class
:
8020 if (const ObjCObjectType
*ObjType
=
8021 Msg
->getClassReceiver()->getAs
<ObjCObjectType
>())
8022 IFace
= ObjType
->getInterface();
8025 case ObjCMessageExpr::Instance
: {
8026 QualType T
= Msg
->getInstanceReceiver()->getType();
8027 if (const ObjCObjectPointerType
*Ptr
= T
->getAs
<ObjCObjectPointerType
>())
8028 IFace
= Ptr
->getInterfaceDecl();
8032 case ObjCMessageExpr::SuperInstance
:
8033 case ObjCMessageExpr::SuperClass
:
8040 ObjCInterfaceDecl
*Super
= IFace
->getSuperClass();
8041 if (Method
->isInstanceMethod())
8042 return llvm::StringSwitch
<ObjCInterfaceDecl
*>(Id
->getName())
8043 .Case("retain", IFace
)
8044 .Case("strong", IFace
)
8045 .Case("autorelease", IFace
)
8046 .Case("copy", IFace
)
8047 .Case("copyWithZone", IFace
)
8048 .Case("mutableCopy", IFace
)
8049 .Case("mutableCopyWithZone", IFace
)
8050 .Case("awakeFromCoder", IFace
)
8051 .Case("replacementObjectFromCoder", IFace
)
8052 .Case("class", IFace
)
8053 .Case("classForCoder", IFace
)
8054 .Case("superclass", Super
)
8057 return llvm::StringSwitch
<ObjCInterfaceDecl
*>(Id
->getName())
8059 .Case("alloc", IFace
)
8060 .Case("allocWithZone", IFace
)
8061 .Case("class", IFace
)
8062 .Case("superclass", Super
)
8066 // Add a special completion for a message send to "super", which fills in the
8067 // most likely case of forwarding all of our arguments to the superclass
8070 /// \param S The semantic analysis object.
8072 /// \param NeedSuperKeyword Whether we need to prefix this completion with
8073 /// the "super" keyword. Otherwise, we just need to provide the arguments.
8075 /// \param SelIdents The identifiers in the selector that have already been
8076 /// provided as arguments for a send to "super".
8078 /// \param Results The set of results to augment.
8080 /// \returns the Objective-C method declaration that would be invoked by
8081 /// this "super" completion. If NULL, no completion was added.
8082 static ObjCMethodDecl
*
8083 AddSuperSendCompletion(Sema
&S
, bool NeedSuperKeyword
,
8084 ArrayRef
<const IdentifierInfo
*> SelIdents
,
8085 ResultBuilder
&Results
) {
8086 ObjCMethodDecl
*CurMethod
= S
.getCurMethodDecl();
8090 ObjCInterfaceDecl
*Class
= CurMethod
->getClassInterface();
8094 // Try to find a superclass method with the same selector.
8095 ObjCMethodDecl
*SuperMethod
= nullptr;
8096 while ((Class
= Class
->getSuperClass()) && !SuperMethod
) {
8097 // Check in the class
8098 SuperMethod
= Class
->getMethod(CurMethod
->getSelector(),
8099 CurMethod
->isInstanceMethod());
8101 // Check in categories or class extensions.
8103 for (const auto *Cat
: Class
->known_categories()) {
8104 if ((SuperMethod
= Cat
->getMethod(CurMethod
->getSelector(),
8105 CurMethod
->isInstanceMethod())))
8114 // Check whether the superclass method has the same signature.
8115 if (CurMethod
->param_size() != SuperMethod
->param_size() ||
8116 CurMethod
->isVariadic() != SuperMethod
->isVariadic())
8119 for (ObjCMethodDecl::param_iterator CurP
= CurMethod
->param_begin(),
8120 CurPEnd
= CurMethod
->param_end(),
8121 SuperP
= SuperMethod
->param_begin();
8122 CurP
!= CurPEnd
; ++CurP
, ++SuperP
) {
8123 // Make sure the parameter types are compatible.
8124 if (!S
.Context
.hasSameUnqualifiedType((*CurP
)->getType(),
8125 (*SuperP
)->getType()))
8128 // Make sure we have a parameter name to forward!
8129 if (!(*CurP
)->getIdentifier())
8133 // We have a superclass method. Now, form the send-to-super completion.
8134 CodeCompletionBuilder
Builder(Results
.getAllocator(),
8135 Results
.getCodeCompletionTUInfo());
8137 // Give this completion a return type.
8138 AddResultTypeChunk(S
.Context
, getCompletionPrintingPolicy(S
), SuperMethod
,
8139 Results
.getCompletionContext().getBaseType(), Builder
);
8141 // If we need the "super" keyword, add it (plus some spacing).
8142 if (NeedSuperKeyword
) {
8143 Builder
.AddTypedTextChunk("super");
8144 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
8147 Selector Sel
= CurMethod
->getSelector();
8148 if (Sel
.isUnarySelector()) {
8149 if (NeedSuperKeyword
)
8150 Builder
.AddTextChunk(
8151 Builder
.getAllocator().CopyString(Sel
.getNameForSlot(0)));
8153 Builder
.AddTypedTextChunk(
8154 Builder
.getAllocator().CopyString(Sel
.getNameForSlot(0)));
8156 ObjCMethodDecl::param_iterator CurP
= CurMethod
->param_begin();
8157 for (unsigned I
= 0, N
= Sel
.getNumArgs(); I
!= N
; ++I
, ++CurP
) {
8158 if (I
> SelIdents
.size())
8159 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
8161 if (I
< SelIdents
.size())
8162 Builder
.AddInformativeChunk(
8163 Builder
.getAllocator().CopyString(Sel
.getNameForSlot(I
) + ":"));
8164 else if (NeedSuperKeyword
|| I
> SelIdents
.size()) {
8165 Builder
.AddTextChunk(
8166 Builder
.getAllocator().CopyString(Sel
.getNameForSlot(I
) + ":"));
8167 Builder
.AddPlaceholderChunk(Builder
.getAllocator().CopyString(
8168 (*CurP
)->getIdentifier()->getName()));
8170 Builder
.AddTypedTextChunk(
8171 Builder
.getAllocator().CopyString(Sel
.getNameForSlot(I
) + ":"));
8172 Builder
.AddPlaceholderChunk(Builder
.getAllocator().CopyString(
8173 (*CurP
)->getIdentifier()->getName()));
8178 Results
.AddResult(CodeCompletionResult(Builder
.TakeString(), SuperMethod
,
8179 CCP_SuperCompletion
));
8183 void SemaCodeCompletion::CodeCompleteObjCMessageReceiver(Scope
*S
) {
8184 typedef CodeCompletionResult Result
;
8185 ResultBuilder
Results(
8186 SemaRef
, CodeCompleter
->getAllocator(),
8187 CodeCompleter
->getCodeCompletionTUInfo(),
8188 CodeCompletionContext::CCC_ObjCMessageReceiver
,
8189 getLangOpts().CPlusPlus11
8190 ? &ResultBuilder::IsObjCMessageReceiverOrLambdaCapture
8191 : &ResultBuilder::IsObjCMessageReceiver
);
8193 CodeCompletionDeclConsumer
Consumer(Results
, SemaRef
.CurContext
);
8194 Results
.EnterNewScope();
8195 SemaRef
.LookupVisibleDecls(S
, Sema::LookupOrdinaryName
, Consumer
,
8196 CodeCompleter
->includeGlobals(),
8197 CodeCompleter
->loadExternal());
8199 // If we are in an Objective-C method inside a class that has a superclass,
8200 // add "super" as an option.
8201 if (ObjCMethodDecl
*Method
= SemaRef
.getCurMethodDecl())
8202 if (ObjCInterfaceDecl
*Iface
= Method
->getClassInterface())
8203 if (Iface
->getSuperClass()) {
8204 Results
.AddResult(Result("super"));
8206 AddSuperSendCompletion(SemaRef
, /*NeedSuperKeyword=*/true, {}, Results
);
8209 if (getLangOpts().CPlusPlus11
)
8210 addThisCompletion(SemaRef
, Results
);
8212 Results
.ExitScope();
8214 if (CodeCompleter
->includeMacros())
8215 AddMacroResults(SemaRef
.PP
, Results
, CodeCompleter
->loadExternal(), false);
8216 HandleCodeCompleteResults(&SemaRef
, CodeCompleter
,
8217 Results
.getCompletionContext(), Results
.data(),
8221 void SemaCodeCompletion::CodeCompleteObjCSuperMessage(
8222 Scope
*S
, SourceLocation SuperLoc
,
8223 ArrayRef
<const IdentifierInfo
*> SelIdents
, bool AtArgumentExpression
) {
8224 ObjCInterfaceDecl
*CDecl
= nullptr;
8225 if (ObjCMethodDecl
*CurMethod
= SemaRef
.getCurMethodDecl()) {
8226 // Figure out which interface we're in.
8227 CDecl
= CurMethod
->getClassInterface();
8231 // Find the superclass of this class.
8232 CDecl
= CDecl
->getSuperClass();
8236 if (CurMethod
->isInstanceMethod()) {
8237 // We are inside an instance method, which means that the message
8238 // send [super ...] is actually calling an instance method on the
8240 return CodeCompleteObjCInstanceMessage(S
, nullptr, SelIdents
,
8241 AtArgumentExpression
, CDecl
);
8244 // Fall through to send to the superclass in CDecl.
8246 // "super" may be the name of a type or variable. Figure out which
8248 const IdentifierInfo
*Super
= SemaRef
.getSuperIdentifier();
8250 SemaRef
.LookupSingleName(S
, Super
, SuperLoc
, Sema::LookupOrdinaryName
);
8251 if ((CDecl
= dyn_cast_or_null
<ObjCInterfaceDecl
>(ND
))) {
8252 // "super" names an interface. Use it.
8253 } else if (TypeDecl
*TD
= dyn_cast_or_null
<TypeDecl
>(ND
)) {
8254 if (const ObjCObjectType
*Iface
=
8255 getASTContext().getTypeDeclType(TD
)->getAs
<ObjCObjectType
>())
8256 CDecl
= Iface
->getInterface();
8257 } else if (ND
&& isa
<UnresolvedUsingTypenameDecl
>(ND
)) {
8258 // "super" names an unresolved type; we can't be more specific.
8260 // Assume that "super" names some kind of value and parse that way.
8262 SourceLocation TemplateKWLoc
;
8264 id
.setIdentifier(Super
, SuperLoc
);
8265 ExprResult SuperExpr
=
8266 SemaRef
.ActOnIdExpression(S
, SS
, TemplateKWLoc
, id
,
8267 /*HasTrailingLParen=*/false,
8268 /*IsAddressOfOperand=*/false);
8269 return CodeCompleteObjCInstanceMessage(S
, (Expr
*)SuperExpr
.get(),
8270 SelIdents
, AtArgumentExpression
);
8276 ParsedType Receiver
;
8278 Receiver
= ParsedType::make(getASTContext().getObjCInterfaceType(CDecl
));
8279 return CodeCompleteObjCClassMessage(S
, Receiver
, SelIdents
,
8280 AtArgumentExpression
,
8284 /// Given a set of code-completion results for the argument of a message
8285 /// send, determine the preferred type (if any) for that argument expression.
8286 static QualType
getPreferredArgumentTypeForMessageSend(ResultBuilder
&Results
,
8287 unsigned NumSelIdents
) {
8288 typedef CodeCompletionResult Result
;
8289 ASTContext
&Context
= Results
.getSema().Context
;
8291 QualType PreferredType
;
8292 unsigned BestPriority
= CCP_Unlikely
* 2;
8293 Result
*ResultsData
= Results
.data();
8294 for (unsigned I
= 0, N
= Results
.size(); I
!= N
; ++I
) {
8295 Result
&R
= ResultsData
[I
];
8296 if (R
.Kind
== Result::RK_Declaration
&&
8297 isa
<ObjCMethodDecl
>(R
.Declaration
)) {
8298 if (R
.Priority
<= BestPriority
) {
8299 const ObjCMethodDecl
*Method
= cast
<ObjCMethodDecl
>(R
.Declaration
);
8300 if (NumSelIdents
<= Method
->param_size()) {
8301 QualType MyPreferredType
=
8302 Method
->parameters()[NumSelIdents
- 1]->getType();
8303 if (R
.Priority
< BestPriority
|| PreferredType
.isNull()) {
8304 BestPriority
= R
.Priority
;
8305 PreferredType
= MyPreferredType
;
8306 } else if (!Context
.hasSameUnqualifiedType(PreferredType
,
8308 PreferredType
= QualType();
8315 return PreferredType
;
8319 AddClassMessageCompletions(Sema
&SemaRef
, Scope
*S
, ParsedType Receiver
,
8320 ArrayRef
<const IdentifierInfo
*> SelIdents
,
8321 bool AtArgumentExpression
, bool IsSuper
,
8322 ResultBuilder
&Results
) {
8323 typedef CodeCompletionResult Result
;
8324 ObjCInterfaceDecl
*CDecl
= nullptr;
8326 // If the given name refers to an interface type, retrieve the
8327 // corresponding declaration.
8329 QualType T
= SemaRef
.GetTypeFromParser(Receiver
, nullptr);
8331 if (const ObjCObjectType
*Interface
= T
->getAs
<ObjCObjectType
>())
8332 CDecl
= Interface
->getInterface();
8335 // Add all of the factory methods in this Objective-C class, its protocols,
8336 // superclasses, categories, implementation, etc.
8337 Results
.EnterNewScope();
8339 // If this is a send-to-super, try to add the special "super" send
8342 if (ObjCMethodDecl
*SuperMethod
=
8343 AddSuperSendCompletion(SemaRef
, false, SelIdents
, Results
))
8344 Results
.Ignore(SuperMethod
);
8347 // If we're inside an Objective-C method definition, prefer its selector to
8349 if (ObjCMethodDecl
*CurMethod
= SemaRef
.getCurMethodDecl())
8350 Results
.setPreferredSelector(CurMethod
->getSelector());
8352 VisitedSelectorSet Selectors
;
8354 AddObjCMethods(CDecl
, false, MK_Any
, SelIdents
, SemaRef
.CurContext
,
8355 Selectors
, AtArgumentExpression
, Results
);
8357 // We're messaging "id" as a type; provide all class/factory methods.
8359 // If we have an external source, load the entire class method
8360 // pool from the AST file.
8361 if (SemaRef
.getExternalSource()) {
8362 for (uint32_t I
= 0,
8363 N
= SemaRef
.getExternalSource()->GetNumExternalSelectors();
8365 Selector Sel
= SemaRef
.getExternalSource()->GetExternalSelector(I
);
8366 if (Sel
.isNull() || SemaRef
.ObjC().MethodPool
.count(Sel
))
8369 SemaRef
.ObjC().ReadMethodPool(Sel
);
8373 for (SemaObjC::GlobalMethodPool::iterator
8374 M
= SemaRef
.ObjC().MethodPool
.begin(),
8375 MEnd
= SemaRef
.ObjC().MethodPool
.end();
8377 for (ObjCMethodList
*MethList
= &M
->second
.second
;
8378 MethList
&& MethList
->getMethod(); MethList
= MethList
->getNext()) {
8379 if (!isAcceptableObjCMethod(MethList
->getMethod(), MK_Any
, SelIdents
))
8382 Result
R(MethList
->getMethod(),
8383 Results
.getBasePriority(MethList
->getMethod()), nullptr);
8384 R
.StartParameter
= SelIdents
.size();
8385 R
.AllParametersAreInformative
= false;
8386 Results
.MaybeAddResult(R
, SemaRef
.CurContext
);
8391 Results
.ExitScope();
8394 void SemaCodeCompletion::CodeCompleteObjCClassMessage(
8395 Scope
*S
, ParsedType Receiver
, ArrayRef
<const IdentifierInfo
*> SelIdents
,
8396 bool AtArgumentExpression
, bool IsSuper
) {
8398 QualType T
= SemaRef
.GetTypeFromParser(Receiver
);
8400 ResultBuilder
Results(
8401 SemaRef
, CodeCompleter
->getAllocator(),
8402 CodeCompleter
->getCodeCompletionTUInfo(),
8403 CodeCompletionContext(CodeCompletionContext::CCC_ObjCClassMessage
, T
,
8406 AddClassMessageCompletions(SemaRef
, S
, Receiver
, SelIdents
,
8407 AtArgumentExpression
, IsSuper
, Results
);
8409 // If we're actually at the argument expression (rather than prior to the
8410 // selector), we're actually performing code completion for an expression.
8411 // Determine whether we have a single, best method. If so, we can
8412 // code-complete the expression using the corresponding parameter type as
8413 // our preferred type, improving completion results.
8414 if (AtArgumentExpression
) {
8415 QualType PreferredType
=
8416 getPreferredArgumentTypeForMessageSend(Results
, SelIdents
.size());
8417 if (PreferredType
.isNull())
8418 CodeCompleteOrdinaryName(S
, PCC_Expression
);
8420 CodeCompleteExpression(S
, PreferredType
);
8424 HandleCodeCompleteResults(&SemaRef
, CodeCompleter
,
8425 Results
.getCompletionContext(), Results
.data(),
8429 void SemaCodeCompletion::CodeCompleteObjCInstanceMessage(
8430 Scope
*S
, Expr
*Receiver
, ArrayRef
<const IdentifierInfo
*> SelIdents
,
8431 bool AtArgumentExpression
, ObjCInterfaceDecl
*Super
) {
8432 typedef CodeCompletionResult Result
;
8433 ASTContext
&Context
= getASTContext();
8435 Expr
*RecExpr
= static_cast<Expr
*>(Receiver
);
8437 // If necessary, apply function/array conversion to the receiver.
8438 // C99 6.7.5.3p[7,8].
8440 ExprResult Conv
= SemaRef
.DefaultFunctionArrayLvalueConversion(RecExpr
);
8441 if (Conv
.isInvalid()) // conversion failed. bail.
8443 RecExpr
= Conv
.get();
8445 QualType ReceiverType
= RecExpr
8446 ? RecExpr
->getType()
8447 : Super
? Context
.getObjCObjectPointerType(
8448 Context
.getObjCInterfaceType(Super
))
8449 : Context
.getObjCIdType();
8451 // If we're messaging an expression with type "id" or "Class", check
8452 // whether we know something special about the receiver that allows
8453 // us to assume a more-specific receiver type.
8454 if (ReceiverType
->isObjCIdType() || ReceiverType
->isObjCClassType()) {
8455 if (ObjCInterfaceDecl
*IFace
= GetAssumedMessageSendExprType(RecExpr
)) {
8456 if (ReceiverType
->isObjCClassType())
8457 return CodeCompleteObjCClassMessage(
8458 S
, ParsedType::make(Context
.getObjCInterfaceType(IFace
)), SelIdents
,
8459 AtArgumentExpression
, Super
);
8462 Context
.getObjCObjectPointerType(Context
.getObjCInterfaceType(IFace
));
8464 } else if (RecExpr
&& getLangOpts().CPlusPlus
) {
8465 ExprResult Conv
= SemaRef
.PerformContextuallyConvertToObjCPointer(RecExpr
);
8466 if (Conv
.isUsable()) {
8467 RecExpr
= Conv
.get();
8468 ReceiverType
= RecExpr
->getType();
8472 // Build the set of methods we can see.
8473 ResultBuilder
Results(
8474 SemaRef
, CodeCompleter
->getAllocator(),
8475 CodeCompleter
->getCodeCompletionTUInfo(),
8476 CodeCompletionContext(CodeCompletionContext::CCC_ObjCInstanceMessage
,
8477 ReceiverType
, SelIdents
));
8479 Results
.EnterNewScope();
8481 // If this is a send-to-super, try to add the special "super" send
8484 if (ObjCMethodDecl
*SuperMethod
=
8485 AddSuperSendCompletion(SemaRef
, false, SelIdents
, Results
))
8486 Results
.Ignore(SuperMethod
);
8489 // If we're inside an Objective-C method definition, prefer its selector to
8491 if (ObjCMethodDecl
*CurMethod
= SemaRef
.getCurMethodDecl())
8492 Results
.setPreferredSelector(CurMethod
->getSelector());
8494 // Keep track of the selectors we've already added.
8495 VisitedSelectorSet Selectors
;
8497 // Handle messages to Class. This really isn't a message to an instance
8498 // method, so we treat it the same way we would treat a message send to a
8500 if (ReceiverType
->isObjCClassType() ||
8501 ReceiverType
->isObjCQualifiedClassType()) {
8502 if (ObjCMethodDecl
*CurMethod
= SemaRef
.getCurMethodDecl()) {
8503 if (ObjCInterfaceDecl
*ClassDecl
= CurMethod
->getClassInterface())
8504 AddObjCMethods(ClassDecl
, false, MK_Any
, SelIdents
, SemaRef
.CurContext
,
8505 Selectors
, AtArgumentExpression
, Results
);
8508 // Handle messages to a qualified ID ("id<foo>").
8509 else if (const ObjCObjectPointerType
*QualID
=
8510 ReceiverType
->getAsObjCQualifiedIdType()) {
8511 // Search protocols for instance methods.
8512 for (auto *I
: QualID
->quals())
8513 AddObjCMethods(I
, true, MK_Any
, SelIdents
, SemaRef
.CurContext
, Selectors
,
8514 AtArgumentExpression
, Results
);
8516 // Handle messages to a pointer to interface type.
8517 else if (const ObjCObjectPointerType
*IFacePtr
=
8518 ReceiverType
->getAsObjCInterfacePointerType()) {
8519 // Search the class, its superclasses, etc., for instance methods.
8520 AddObjCMethods(IFacePtr
->getInterfaceDecl(), true, MK_Any
, SelIdents
,
8521 SemaRef
.CurContext
, Selectors
, AtArgumentExpression
,
8524 // Search protocols for instance methods.
8525 for (auto *I
: IFacePtr
->quals())
8526 AddObjCMethods(I
, true, MK_Any
, SelIdents
, SemaRef
.CurContext
, Selectors
,
8527 AtArgumentExpression
, Results
);
8529 // Handle messages to "id".
8530 else if (ReceiverType
->isObjCIdType()) {
8531 // We're messaging "id", so provide all instance methods we know
8532 // about as code-completion results.
8534 // If we have an external source, load the entire class method
8535 // pool from the AST file.
8536 if (SemaRef
.ExternalSource
) {
8537 for (uint32_t I
= 0,
8538 N
= SemaRef
.ExternalSource
->GetNumExternalSelectors();
8540 Selector Sel
= SemaRef
.ExternalSource
->GetExternalSelector(I
);
8541 if (Sel
.isNull() || SemaRef
.ObjC().MethodPool
.count(Sel
))
8544 SemaRef
.ObjC().ReadMethodPool(Sel
);
8548 for (SemaObjC::GlobalMethodPool::iterator
8549 M
= SemaRef
.ObjC().MethodPool
.begin(),
8550 MEnd
= SemaRef
.ObjC().MethodPool
.end();
8552 for (ObjCMethodList
*MethList
= &M
->second
.first
;
8553 MethList
&& MethList
->getMethod(); MethList
= MethList
->getNext()) {
8554 if (!isAcceptableObjCMethod(MethList
->getMethod(), MK_Any
, SelIdents
))
8557 if (!Selectors
.insert(MethList
->getMethod()->getSelector()).second
)
8560 Result
R(MethList
->getMethod(),
8561 Results
.getBasePriority(MethList
->getMethod()), nullptr);
8562 R
.StartParameter
= SelIdents
.size();
8563 R
.AllParametersAreInformative
= false;
8564 Results
.MaybeAddResult(R
, SemaRef
.CurContext
);
8568 Results
.ExitScope();
8570 // If we're actually at the argument expression (rather than prior to the
8571 // selector), we're actually performing code completion for an expression.
8572 // Determine whether we have a single, best method. If so, we can
8573 // code-complete the expression using the corresponding parameter type as
8574 // our preferred type, improving completion results.
8575 if (AtArgumentExpression
) {
8576 QualType PreferredType
=
8577 getPreferredArgumentTypeForMessageSend(Results
, SelIdents
.size());
8578 if (PreferredType
.isNull())
8579 CodeCompleteOrdinaryName(S
, PCC_Expression
);
8581 CodeCompleteExpression(S
, PreferredType
);
8585 HandleCodeCompleteResults(&SemaRef
, CodeCompleter
,
8586 Results
.getCompletionContext(), Results
.data(),
8590 void SemaCodeCompletion::CodeCompleteObjCForCollection(
8591 Scope
*S
, DeclGroupPtrTy IterationVar
) {
8592 CodeCompleteExpressionData Data
;
8593 Data
.ObjCCollection
= true;
8595 if (IterationVar
.getAsOpaquePtr()) {
8596 DeclGroupRef DG
= IterationVar
.get();
8597 for (DeclGroupRef::iterator I
= DG
.begin(), End
= DG
.end(); I
!= End
; ++I
) {
8599 Data
.IgnoreDecls
.push_back(*I
);
8603 CodeCompleteExpression(S
, Data
);
8606 void SemaCodeCompletion::CodeCompleteObjCSelector(
8607 Scope
*S
, ArrayRef
<const IdentifierInfo
*> SelIdents
) {
8608 // If we have an external source, load the entire class method
8609 // pool from the AST file.
8610 if (SemaRef
.ExternalSource
) {
8611 for (uint32_t I
= 0, N
= SemaRef
.ExternalSource
->GetNumExternalSelectors();
8613 Selector Sel
= SemaRef
.ExternalSource
->GetExternalSelector(I
);
8614 if (Sel
.isNull() || SemaRef
.ObjC().MethodPool
.count(Sel
))
8617 SemaRef
.ObjC().ReadMethodPool(Sel
);
8621 ResultBuilder
Results(SemaRef
, CodeCompleter
->getAllocator(),
8622 CodeCompleter
->getCodeCompletionTUInfo(),
8623 CodeCompletionContext::CCC_SelectorName
);
8624 Results
.EnterNewScope();
8625 for (SemaObjC::GlobalMethodPool::iterator
8626 M
= SemaRef
.ObjC().MethodPool
.begin(),
8627 MEnd
= SemaRef
.ObjC().MethodPool
.end();
8630 Selector Sel
= M
->first
;
8631 if (!isAcceptableObjCSelector(Sel
, MK_Any
, SelIdents
))
8634 CodeCompletionBuilder
Builder(Results
.getAllocator(),
8635 Results
.getCodeCompletionTUInfo());
8636 if (Sel
.isUnarySelector()) {
8637 Builder
.AddTypedTextChunk(
8638 Builder
.getAllocator().CopyString(Sel
.getNameForSlot(0)));
8639 Results
.AddResult(Builder
.TakeString());
8643 std::string Accumulator
;
8644 for (unsigned I
= 0, N
= Sel
.getNumArgs(); I
!= N
; ++I
) {
8645 if (I
== SelIdents
.size()) {
8646 if (!Accumulator
.empty()) {
8647 Builder
.AddInformativeChunk(
8648 Builder
.getAllocator().CopyString(Accumulator
));
8649 Accumulator
.clear();
8653 Accumulator
+= Sel
.getNameForSlot(I
);
8656 Builder
.AddTypedTextChunk(Builder
.getAllocator().CopyString(Accumulator
));
8657 Results
.AddResult(Builder
.TakeString());
8659 Results
.ExitScope();
8661 HandleCodeCompleteResults(&SemaRef
, CodeCompleter
,
8662 Results
.getCompletionContext(), Results
.data(),
8666 /// Add all of the protocol declarations that we find in the given
8667 /// (translation unit) context.
8668 static void AddProtocolResults(DeclContext
*Ctx
, DeclContext
*CurContext
,
8669 bool OnlyForwardDeclarations
,
8670 ResultBuilder
&Results
) {
8671 typedef CodeCompletionResult Result
;
8673 for (const auto *D
: Ctx
->decls()) {
8674 // Record any protocols we find.
8675 if (const auto *Proto
= dyn_cast
<ObjCProtocolDecl
>(D
))
8676 if (!OnlyForwardDeclarations
|| !Proto
->hasDefinition())
8678 Result(Proto
, Results
.getBasePriority(Proto
), nullptr), CurContext
,
8683 void SemaCodeCompletion::CodeCompleteObjCProtocolReferences(
8684 ArrayRef
<IdentifierLocPair
> Protocols
) {
8685 ResultBuilder
Results(SemaRef
, CodeCompleter
->getAllocator(),
8686 CodeCompleter
->getCodeCompletionTUInfo(),
8687 CodeCompletionContext::CCC_ObjCProtocolName
);
8689 if (CodeCompleter
->includeGlobals()) {
8690 Results
.EnterNewScope();
8692 // Tell the result set to ignore all of the protocols we have
8694 // FIXME: This doesn't work when caching code-completion results.
8695 for (const IdentifierLocPair
&Pair
: Protocols
)
8696 if (ObjCProtocolDecl
*Protocol
=
8697 SemaRef
.ObjC().LookupProtocol(Pair
.first
, Pair
.second
))
8698 Results
.Ignore(Protocol
);
8700 // Add all protocols.
8701 AddProtocolResults(getASTContext().getTranslationUnitDecl(),
8702 SemaRef
.CurContext
, false, Results
);
8704 Results
.ExitScope();
8707 HandleCodeCompleteResults(&SemaRef
, CodeCompleter
,
8708 Results
.getCompletionContext(), Results
.data(),
8712 void SemaCodeCompletion::CodeCompleteObjCProtocolDecl(Scope
*) {
8713 ResultBuilder
Results(SemaRef
, CodeCompleter
->getAllocator(),
8714 CodeCompleter
->getCodeCompletionTUInfo(),
8715 CodeCompletionContext::CCC_ObjCProtocolName
);
8717 if (CodeCompleter
->includeGlobals()) {
8718 Results
.EnterNewScope();
8720 // Add all protocols.
8721 AddProtocolResults(getASTContext().getTranslationUnitDecl(),
8722 SemaRef
.CurContext
, true, Results
);
8724 Results
.ExitScope();
8727 HandleCodeCompleteResults(&SemaRef
, CodeCompleter
,
8728 Results
.getCompletionContext(), Results
.data(),
8732 /// Add all of the Objective-C interface declarations that we find in
8733 /// the given (translation unit) context.
8734 static void AddInterfaceResults(DeclContext
*Ctx
, DeclContext
*CurContext
,
8735 bool OnlyForwardDeclarations
,
8736 bool OnlyUnimplemented
,
8737 ResultBuilder
&Results
) {
8738 typedef CodeCompletionResult Result
;
8740 for (const auto *D
: Ctx
->decls()) {
8741 // Record any interfaces we find.
8742 if (const auto *Class
= dyn_cast
<ObjCInterfaceDecl
>(D
))
8743 if ((!OnlyForwardDeclarations
|| !Class
->hasDefinition()) &&
8744 (!OnlyUnimplemented
|| !Class
->getImplementation()))
8746 Result(Class
, Results
.getBasePriority(Class
), nullptr), CurContext
,
8751 void SemaCodeCompletion::CodeCompleteObjCInterfaceDecl(Scope
*S
) {
8752 ResultBuilder
Results(SemaRef
, CodeCompleter
->getAllocator(),
8753 CodeCompleter
->getCodeCompletionTUInfo(),
8754 CodeCompletionContext::CCC_ObjCInterfaceName
);
8755 Results
.EnterNewScope();
8757 if (CodeCompleter
->includeGlobals()) {
8759 AddInterfaceResults(getASTContext().getTranslationUnitDecl(),
8760 SemaRef
.CurContext
, false, false, Results
);
8763 Results
.ExitScope();
8765 HandleCodeCompleteResults(&SemaRef
, CodeCompleter
,
8766 Results
.getCompletionContext(), Results
.data(),
8770 void SemaCodeCompletion::CodeCompleteObjCClassForwardDecl(Scope
*S
) {
8771 ResultBuilder
Results(SemaRef
, CodeCompleter
->getAllocator(),
8772 CodeCompleter
->getCodeCompletionTUInfo(),
8773 CodeCompletionContext::CCC_ObjCClassForwardDecl
);
8774 Results
.EnterNewScope();
8776 if (CodeCompleter
->includeGlobals()) {
8778 AddInterfaceResults(getASTContext().getTranslationUnitDecl(),
8779 SemaRef
.CurContext
, false, false, Results
);
8782 Results
.ExitScope();
8784 HandleCodeCompleteResults(&SemaRef
, CodeCompleter
,
8785 Results
.getCompletionContext(), Results
.data(),
8789 void SemaCodeCompletion::CodeCompleteObjCSuperclass(
8790 Scope
*S
, IdentifierInfo
*ClassName
, SourceLocation ClassNameLoc
) {
8791 ResultBuilder
Results(SemaRef
, CodeCompleter
->getAllocator(),
8792 CodeCompleter
->getCodeCompletionTUInfo(),
8793 CodeCompletionContext::CCC_ObjCInterfaceName
);
8794 Results
.EnterNewScope();
8796 // Make sure that we ignore the class we're currently defining.
8797 NamedDecl
*CurClass
= SemaRef
.LookupSingleName(
8798 SemaRef
.TUScope
, ClassName
, ClassNameLoc
, Sema::LookupOrdinaryName
);
8799 if (CurClass
&& isa
<ObjCInterfaceDecl
>(CurClass
))
8800 Results
.Ignore(CurClass
);
8802 if (CodeCompleter
->includeGlobals()) {
8804 AddInterfaceResults(getASTContext().getTranslationUnitDecl(),
8805 SemaRef
.CurContext
, false, false, Results
);
8808 Results
.ExitScope();
8810 HandleCodeCompleteResults(&SemaRef
, CodeCompleter
,
8811 Results
.getCompletionContext(), Results
.data(),
8815 void SemaCodeCompletion::CodeCompleteObjCImplementationDecl(Scope
*S
) {
8816 ResultBuilder
Results(SemaRef
, CodeCompleter
->getAllocator(),
8817 CodeCompleter
->getCodeCompletionTUInfo(),
8818 CodeCompletionContext::CCC_ObjCImplementation
);
8819 Results
.EnterNewScope();
8821 if (CodeCompleter
->includeGlobals()) {
8822 // Add all unimplemented classes.
8823 AddInterfaceResults(getASTContext().getTranslationUnitDecl(),
8824 SemaRef
.CurContext
, false, true, Results
);
8827 Results
.ExitScope();
8829 HandleCodeCompleteResults(&SemaRef
, CodeCompleter
,
8830 Results
.getCompletionContext(), Results
.data(),
8834 void SemaCodeCompletion::CodeCompleteObjCInterfaceCategory(
8835 Scope
*S
, IdentifierInfo
*ClassName
, SourceLocation ClassNameLoc
) {
8836 typedef CodeCompletionResult Result
;
8838 ResultBuilder
Results(SemaRef
, CodeCompleter
->getAllocator(),
8839 CodeCompleter
->getCodeCompletionTUInfo(),
8840 CodeCompletionContext::CCC_ObjCCategoryName
);
8842 // Ignore any categories we find that have already been implemented by this
8844 llvm::SmallPtrSet
<IdentifierInfo
*, 16> CategoryNames
;
8845 NamedDecl
*CurClass
= SemaRef
.LookupSingleName(
8846 SemaRef
.TUScope
, ClassName
, ClassNameLoc
, Sema::LookupOrdinaryName
);
8847 if (ObjCInterfaceDecl
*Class
=
8848 dyn_cast_or_null
<ObjCInterfaceDecl
>(CurClass
)) {
8849 for (const auto *Cat
: Class
->visible_categories())
8850 CategoryNames
.insert(Cat
->getIdentifier());
8853 // Add all of the categories we know about.
8854 Results
.EnterNewScope();
8855 TranslationUnitDecl
*TU
= getASTContext().getTranslationUnitDecl();
8856 for (const auto *D
: TU
->decls())
8857 if (const auto *Category
= dyn_cast
<ObjCCategoryDecl
>(D
))
8858 if (CategoryNames
.insert(Category
->getIdentifier()).second
)
8860 Result(Category
, Results
.getBasePriority(Category
), nullptr),
8861 SemaRef
.CurContext
, nullptr, false);
8862 Results
.ExitScope();
8864 HandleCodeCompleteResults(&SemaRef
, CodeCompleter
,
8865 Results
.getCompletionContext(), Results
.data(),
8869 void SemaCodeCompletion::CodeCompleteObjCImplementationCategory(
8870 Scope
*S
, IdentifierInfo
*ClassName
, SourceLocation ClassNameLoc
) {
8871 typedef CodeCompletionResult Result
;
8873 // Find the corresponding interface. If we couldn't find the interface, the
8874 // program itself is ill-formed. However, we'll try to be helpful still by
8875 // providing the list of all of the categories we know about.
8876 NamedDecl
*CurClass
= SemaRef
.LookupSingleName(
8877 SemaRef
.TUScope
, ClassName
, ClassNameLoc
, Sema::LookupOrdinaryName
);
8878 ObjCInterfaceDecl
*Class
= dyn_cast_or_null
<ObjCInterfaceDecl
>(CurClass
);
8880 return CodeCompleteObjCInterfaceCategory(S
, ClassName
, ClassNameLoc
);
8882 ResultBuilder
Results(SemaRef
, CodeCompleter
->getAllocator(),
8883 CodeCompleter
->getCodeCompletionTUInfo(),
8884 CodeCompletionContext::CCC_ObjCCategoryName
);
8886 // Add all of the categories that have corresponding interface
8887 // declarations in this class and any of its superclasses, except for
8888 // already-implemented categories in the class itself.
8889 llvm::SmallPtrSet
<IdentifierInfo
*, 16> CategoryNames
;
8890 Results
.EnterNewScope();
8891 bool IgnoreImplemented
= true;
8893 for (const auto *Cat
: Class
->visible_categories()) {
8894 if ((!IgnoreImplemented
|| !Cat
->getImplementation()) &&
8895 CategoryNames
.insert(Cat
->getIdentifier()).second
)
8896 Results
.AddResult(Result(Cat
, Results
.getBasePriority(Cat
), nullptr),
8897 SemaRef
.CurContext
, nullptr, false);
8900 Class
= Class
->getSuperClass();
8901 IgnoreImplemented
= false;
8903 Results
.ExitScope();
8905 HandleCodeCompleteResults(&SemaRef
, CodeCompleter
,
8906 Results
.getCompletionContext(), Results
.data(),
8910 void SemaCodeCompletion::CodeCompleteObjCPropertyDefinition(Scope
*S
) {
8911 CodeCompletionContext
CCContext(CodeCompletionContext::CCC_Other
);
8912 ResultBuilder
Results(SemaRef
, CodeCompleter
->getAllocator(),
8913 CodeCompleter
->getCodeCompletionTUInfo(), CCContext
);
8915 // Figure out where this @synthesize lives.
8916 ObjCContainerDecl
*Container
=
8917 dyn_cast_or_null
<ObjCContainerDecl
>(SemaRef
.CurContext
);
8918 if (!Container
|| (!isa
<ObjCImplementationDecl
>(Container
) &&
8919 !isa
<ObjCCategoryImplDecl
>(Container
)))
8922 // Ignore any properties that have already been implemented.
8923 Container
= getContainerDef(Container
);
8924 for (const auto *D
: Container
->decls())
8925 if (const auto *PropertyImpl
= dyn_cast
<ObjCPropertyImplDecl
>(D
))
8926 Results
.Ignore(PropertyImpl
->getPropertyDecl());
8928 // Add any properties that we find.
8929 AddedPropertiesSet AddedProperties
;
8930 Results
.EnterNewScope();
8931 if (ObjCImplementationDecl
*ClassImpl
=
8932 dyn_cast
<ObjCImplementationDecl
>(Container
))
8933 AddObjCProperties(CCContext
, ClassImpl
->getClassInterface(), false,
8934 /*AllowNullaryMethods=*/false, SemaRef
.CurContext
,
8935 AddedProperties
, Results
);
8937 AddObjCProperties(CCContext
,
8938 cast
<ObjCCategoryImplDecl
>(Container
)->getCategoryDecl(),
8939 false, /*AllowNullaryMethods=*/false, SemaRef
.CurContext
,
8940 AddedProperties
, Results
);
8941 Results
.ExitScope();
8943 HandleCodeCompleteResults(&SemaRef
, CodeCompleter
,
8944 Results
.getCompletionContext(), Results
.data(),
8948 void SemaCodeCompletion::CodeCompleteObjCPropertySynthesizeIvar(
8949 Scope
*S
, IdentifierInfo
*PropertyName
) {
8950 typedef CodeCompletionResult Result
;
8951 ResultBuilder
Results(SemaRef
, CodeCompleter
->getAllocator(),
8952 CodeCompleter
->getCodeCompletionTUInfo(),
8953 CodeCompletionContext::CCC_Other
);
8955 // Figure out where this @synthesize lives.
8956 ObjCContainerDecl
*Container
=
8957 dyn_cast_or_null
<ObjCContainerDecl
>(SemaRef
.CurContext
);
8958 if (!Container
|| (!isa
<ObjCImplementationDecl
>(Container
) &&
8959 !isa
<ObjCCategoryImplDecl
>(Container
)))
8962 // Figure out which interface we're looking into.
8963 ObjCInterfaceDecl
*Class
= nullptr;
8964 if (ObjCImplementationDecl
*ClassImpl
=
8965 dyn_cast
<ObjCImplementationDecl
>(Container
))
8966 Class
= ClassImpl
->getClassInterface();
8968 Class
= cast
<ObjCCategoryImplDecl
>(Container
)
8970 ->getClassInterface();
8972 // Determine the type of the property we're synthesizing.
8973 QualType PropertyType
= getASTContext().getObjCIdType();
8975 if (ObjCPropertyDecl
*Property
= Class
->FindPropertyDeclaration(
8976 PropertyName
, ObjCPropertyQueryKind::OBJC_PR_query_instance
)) {
8978 Property
->getType().getNonReferenceType().getUnqualifiedType();
8980 // Give preference to ivars
8981 Results
.setPreferredType(PropertyType
);
8985 // Add all of the instance variables in this class and its superclasses.
8986 Results
.EnterNewScope();
8987 bool SawSimilarlyNamedIvar
= false;
8988 std::string NameWithPrefix
;
8989 NameWithPrefix
+= '_';
8990 NameWithPrefix
+= PropertyName
->getName();
8991 std::string NameWithSuffix
= PropertyName
->getName().str();
8992 NameWithSuffix
+= '_';
8993 for (; Class
; Class
= Class
->getSuperClass()) {
8994 for (ObjCIvarDecl
*Ivar
= Class
->all_declared_ivar_begin(); Ivar
;
8995 Ivar
= Ivar
->getNextIvar()) {
8996 Results
.AddResult(Result(Ivar
, Results
.getBasePriority(Ivar
), nullptr),
8997 SemaRef
.CurContext
, nullptr, false);
8999 // Determine whether we've seen an ivar with a name similar to the
9001 if ((PropertyName
== Ivar
->getIdentifier() ||
9002 NameWithPrefix
== Ivar
->getName() ||
9003 NameWithSuffix
== Ivar
->getName())) {
9004 SawSimilarlyNamedIvar
= true;
9006 // Reduce the priority of this result by one, to give it a slight
9007 // advantage over other results whose names don't match so closely.
9008 if (Results
.size() &&
9009 Results
.data()[Results
.size() - 1].Kind
==
9010 CodeCompletionResult::RK_Declaration
&&
9011 Results
.data()[Results
.size() - 1].Declaration
== Ivar
)
9012 Results
.data()[Results
.size() - 1].Priority
--;
9017 if (!SawSimilarlyNamedIvar
) {
9018 // Create ivar result _propName, that the user can use to synthesize
9019 // an ivar of the appropriate type.
9020 unsigned Priority
= CCP_MemberDeclaration
+ 1;
9021 typedef CodeCompletionResult Result
;
9022 CodeCompletionAllocator
&Allocator
= Results
.getAllocator();
9023 CodeCompletionBuilder
Builder(Allocator
, Results
.getCodeCompletionTUInfo(),
9024 Priority
, CXAvailability_Available
);
9026 PrintingPolicy Policy
= getCompletionPrintingPolicy(SemaRef
);
9027 Builder
.AddResultTypeChunk(GetCompletionTypeString(
9028 PropertyType
, getASTContext(), Policy
, Allocator
));
9029 Builder
.AddTypedTextChunk(Allocator
.CopyString(NameWithPrefix
));
9031 Result(Builder
.TakeString(), Priority
, CXCursor_ObjCIvarDecl
));
9034 Results
.ExitScope();
9036 HandleCodeCompleteResults(&SemaRef
, CodeCompleter
,
9037 Results
.getCompletionContext(), Results
.data(),
9041 // Mapping from selectors to the methods that implement that selector, along
9042 // with the "in original class" flag.
9043 typedef llvm::DenseMap
<Selector
,
9044 llvm::PointerIntPair
<ObjCMethodDecl
*, 1, bool>>
9047 /// Find all of the methods that reside in the given container
9048 /// (and its superclasses, protocols, etc.) that meet the given
9049 /// criteria. Insert those methods into the map of known methods,
9050 /// indexed by selector so they can be easily found.
9051 static void FindImplementableMethods(ASTContext
&Context
,
9052 ObjCContainerDecl
*Container
,
9053 std::optional
<bool> WantInstanceMethods
,
9054 QualType ReturnType
,
9055 KnownMethodsMap
&KnownMethods
,
9056 bool InOriginalClass
= true) {
9057 if (ObjCInterfaceDecl
*IFace
= dyn_cast
<ObjCInterfaceDecl
>(Container
)) {
9058 // Make sure we have a definition; that's what we'll walk.
9059 if (!IFace
->hasDefinition())
9062 IFace
= IFace
->getDefinition();
9065 const ObjCList
<ObjCProtocolDecl
> &Protocols
=
9066 IFace
->getReferencedProtocols();
9067 for (ObjCList
<ObjCProtocolDecl
>::iterator I
= Protocols
.begin(),
9068 E
= Protocols
.end();
9070 FindImplementableMethods(Context
, *I
, WantInstanceMethods
, ReturnType
,
9071 KnownMethods
, InOriginalClass
);
9073 // Add methods from any class extensions and categories.
9074 for (auto *Cat
: IFace
->visible_categories()) {
9075 FindImplementableMethods(Context
, Cat
, WantInstanceMethods
, ReturnType
,
9076 KnownMethods
, false);
9079 // Visit the superclass.
9080 if (IFace
->getSuperClass())
9081 FindImplementableMethods(Context
, IFace
->getSuperClass(),
9082 WantInstanceMethods
, ReturnType
, KnownMethods
,
9086 if (ObjCCategoryDecl
*Category
= dyn_cast
<ObjCCategoryDecl
>(Container
)) {
9087 // Recurse into protocols.
9088 const ObjCList
<ObjCProtocolDecl
> &Protocols
=
9089 Category
->getReferencedProtocols();
9090 for (ObjCList
<ObjCProtocolDecl
>::iterator I
= Protocols
.begin(),
9091 E
= Protocols
.end();
9093 FindImplementableMethods(Context
, *I
, WantInstanceMethods
, ReturnType
,
9094 KnownMethods
, InOriginalClass
);
9096 // If this category is the original class, jump to the interface.
9097 if (InOriginalClass
&& Category
->getClassInterface())
9098 FindImplementableMethods(Context
, Category
->getClassInterface(),
9099 WantInstanceMethods
, ReturnType
, KnownMethods
,
9103 if (ObjCProtocolDecl
*Protocol
= dyn_cast
<ObjCProtocolDecl
>(Container
)) {
9104 // Make sure we have a definition; that's what we'll walk.
9105 if (!Protocol
->hasDefinition())
9107 Protocol
= Protocol
->getDefinition();
9108 Container
= Protocol
;
9110 // Recurse into protocols.
9111 const ObjCList
<ObjCProtocolDecl
> &Protocols
=
9112 Protocol
->getReferencedProtocols();
9113 for (ObjCList
<ObjCProtocolDecl
>::iterator I
= Protocols
.begin(),
9114 E
= Protocols
.end();
9116 FindImplementableMethods(Context
, *I
, WantInstanceMethods
, ReturnType
,
9117 KnownMethods
, false);
9120 // Add methods in this container. This operation occurs last because
9121 // we want the methods from this container to override any methods
9122 // we've previously seen with the same selector.
9123 for (auto *M
: Container
->methods()) {
9124 if (!WantInstanceMethods
|| M
->isInstanceMethod() == *WantInstanceMethods
) {
9125 if (!ReturnType
.isNull() &&
9126 !Context
.hasSameUnqualifiedType(ReturnType
, M
->getReturnType()))
9129 KnownMethods
[M
->getSelector()] =
9130 KnownMethodsMap::mapped_type(M
, InOriginalClass
);
9135 /// Add the parenthesized return or parameter type chunk to a code
9136 /// completion string.
9137 static void AddObjCPassingTypeChunk(QualType Type
, unsigned ObjCDeclQuals
,
9138 ASTContext
&Context
,
9139 const PrintingPolicy
&Policy
,
9140 CodeCompletionBuilder
&Builder
) {
9141 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9142 std::string Quals
= formatObjCParamQualifiers(ObjCDeclQuals
, Type
);
9144 Builder
.AddTextChunk(Builder
.getAllocator().CopyString(Quals
));
9145 Builder
.AddTextChunk(
9146 GetCompletionTypeString(Type
, Context
, Policy
, Builder
.getAllocator()));
9147 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9150 /// Determine whether the given class is or inherits from a class by
9152 static bool InheritsFromClassNamed(ObjCInterfaceDecl
*Class
, StringRef Name
) {
9156 if (Class
->getIdentifier() && Class
->getIdentifier()->getName() == Name
)
9159 return InheritsFromClassNamed(Class
->getSuperClass(), Name
);
9162 /// Add code completions for Objective-C Key-Value Coding (KVC) and
9163 /// Key-Value Observing (KVO).
9164 static void AddObjCKeyValueCompletions(ObjCPropertyDecl
*Property
,
9165 bool IsInstanceMethod
,
9166 QualType ReturnType
, ASTContext
&Context
,
9167 VisitedSelectorSet
&KnownSelectors
,
9168 ResultBuilder
&Results
) {
9169 IdentifierInfo
*PropName
= Property
->getIdentifier();
9170 if (!PropName
|| PropName
->getLength() == 0)
9173 PrintingPolicy Policy
= getCompletionPrintingPolicy(Results
.getSema());
9175 // Builder that will create each code completion.
9176 typedef CodeCompletionResult Result
;
9177 CodeCompletionAllocator
&Allocator
= Results
.getAllocator();
9178 CodeCompletionBuilder
Builder(Allocator
, Results
.getCodeCompletionTUInfo());
9180 // The selector table.
9181 SelectorTable
&Selectors
= Context
.Selectors
;
9183 // The property name, copied into the code completion allocation region
9186 CodeCompletionAllocator
&Allocator
;
9188 const char *CopiedKey
;
9190 KeyHolder(CodeCompletionAllocator
&Allocator
, StringRef Key
)
9191 : Allocator(Allocator
), Key(Key
), CopiedKey(nullptr) {}
9193 operator const char *() {
9197 return CopiedKey
= Allocator
.CopyString(Key
);
9199 } Key(Allocator
, PropName
->getName());
9201 // The uppercased name of the property name.
9202 std::string UpperKey
= std::string(PropName
->getName());
9203 if (!UpperKey
.empty())
9204 UpperKey
[0] = toUppercase(UpperKey
[0]);
9206 bool ReturnTypeMatchesProperty
=
9207 ReturnType
.isNull() ||
9208 Context
.hasSameUnqualifiedType(ReturnType
.getNonReferenceType(),
9209 Property
->getType());
9210 bool ReturnTypeMatchesVoid
= ReturnType
.isNull() || ReturnType
->isVoidType();
9212 // Add the normal accessor -(type)key.
9213 if (IsInstanceMethod
&&
9214 KnownSelectors
.insert(Selectors
.getNullarySelector(PropName
)).second
&&
9215 ReturnTypeMatchesProperty
&& !Property
->getGetterMethodDecl()) {
9216 if (ReturnType
.isNull())
9217 AddObjCPassingTypeChunk(Property
->getType(), /*Quals=*/0, Context
, Policy
,
9220 Builder
.AddTypedTextChunk(Key
);
9221 Results
.AddResult(Result(Builder
.TakeString(), CCP_CodePattern
,
9222 CXCursor_ObjCInstanceMethodDecl
));
9225 // If we have an integral or boolean property (or the user has provided
9226 // an integral or boolean return type), add the accessor -(type)isKey.
9227 if (IsInstanceMethod
&&
9228 ((!ReturnType
.isNull() &&
9229 (ReturnType
->isIntegerType() || ReturnType
->isBooleanType())) ||
9230 (ReturnType
.isNull() && (Property
->getType()->isIntegerType() ||
9231 Property
->getType()->isBooleanType())))) {
9232 std::string SelectorName
= (Twine("is") + UpperKey
).str();
9233 IdentifierInfo
*SelectorId
= &Context
.Idents
.get(SelectorName
);
9234 if (KnownSelectors
.insert(Selectors
.getNullarySelector(SelectorId
))
9236 if (ReturnType
.isNull()) {
9237 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9238 Builder
.AddTextChunk("BOOL");
9239 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9242 Builder
.AddTypedTextChunk(Allocator
.CopyString(SelectorId
->getName()));
9243 Results
.AddResult(Result(Builder
.TakeString(), CCP_CodePattern
,
9244 CXCursor_ObjCInstanceMethodDecl
));
9248 // Add the normal mutator.
9249 if (IsInstanceMethod
&& ReturnTypeMatchesVoid
&&
9250 !Property
->getSetterMethodDecl()) {
9251 std::string SelectorName
= (Twine("set") + UpperKey
).str();
9252 IdentifierInfo
*SelectorId
= &Context
.Idents
.get(SelectorName
);
9253 if (KnownSelectors
.insert(Selectors
.getUnarySelector(SelectorId
)).second
) {
9254 if (ReturnType
.isNull()) {
9255 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9256 Builder
.AddTextChunk("void");
9257 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9260 Builder
.AddTypedTextChunk(
9261 Allocator
.CopyString(SelectorId
->getName() + ":"));
9262 AddObjCPassingTypeChunk(Property
->getType(), /*Quals=*/0, Context
, Policy
,
9264 Builder
.AddTextChunk(Key
);
9265 Results
.AddResult(Result(Builder
.TakeString(), CCP_CodePattern
,
9266 CXCursor_ObjCInstanceMethodDecl
));
9270 // Indexed and unordered accessors
9271 unsigned IndexedGetterPriority
= CCP_CodePattern
;
9272 unsigned IndexedSetterPriority
= CCP_CodePattern
;
9273 unsigned UnorderedGetterPriority
= CCP_CodePattern
;
9274 unsigned UnorderedSetterPriority
= CCP_CodePattern
;
9275 if (const auto *ObjCPointer
=
9276 Property
->getType()->getAs
<ObjCObjectPointerType
>()) {
9277 if (ObjCInterfaceDecl
*IFace
= ObjCPointer
->getInterfaceDecl()) {
9278 // If this interface type is not provably derived from a known
9279 // collection, penalize the corresponding completions.
9280 if (!InheritsFromClassNamed(IFace
, "NSMutableArray")) {
9281 IndexedSetterPriority
+= CCD_ProbablyNotObjCCollection
;
9282 if (!InheritsFromClassNamed(IFace
, "NSArray"))
9283 IndexedGetterPriority
+= CCD_ProbablyNotObjCCollection
;
9286 if (!InheritsFromClassNamed(IFace
, "NSMutableSet")) {
9287 UnorderedSetterPriority
+= CCD_ProbablyNotObjCCollection
;
9288 if (!InheritsFromClassNamed(IFace
, "NSSet"))
9289 UnorderedGetterPriority
+= CCD_ProbablyNotObjCCollection
;
9293 IndexedGetterPriority
+= CCD_ProbablyNotObjCCollection
;
9294 IndexedSetterPriority
+= CCD_ProbablyNotObjCCollection
;
9295 UnorderedGetterPriority
+= CCD_ProbablyNotObjCCollection
;
9296 UnorderedSetterPriority
+= CCD_ProbablyNotObjCCollection
;
9299 // Add -(NSUInteger)countOf<key>
9300 if (IsInstanceMethod
&&
9301 (ReturnType
.isNull() || ReturnType
->isIntegerType())) {
9302 std::string SelectorName
= (Twine("countOf") + UpperKey
).str();
9303 IdentifierInfo
*SelectorId
= &Context
.Idents
.get(SelectorName
);
9304 if (KnownSelectors
.insert(Selectors
.getNullarySelector(SelectorId
))
9306 if (ReturnType
.isNull()) {
9307 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9308 Builder
.AddTextChunk("NSUInteger");
9309 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9312 Builder
.AddTypedTextChunk(Allocator
.CopyString(SelectorId
->getName()));
9314 Result(Builder
.TakeString(),
9315 std::min(IndexedGetterPriority
, UnorderedGetterPriority
),
9316 CXCursor_ObjCInstanceMethodDecl
));
9321 // Add -(id)objectInKeyAtIndex:(NSUInteger)index
9322 if (IsInstanceMethod
&&
9323 (ReturnType
.isNull() || ReturnType
->isObjCObjectPointerType())) {
9324 std::string SelectorName
= (Twine("objectIn") + UpperKey
+ "AtIndex").str();
9325 IdentifierInfo
*SelectorId
= &Context
.Idents
.get(SelectorName
);
9326 if (KnownSelectors
.insert(Selectors
.getUnarySelector(SelectorId
)).second
) {
9327 if (ReturnType
.isNull()) {
9328 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9329 Builder
.AddTextChunk("id");
9330 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9333 Builder
.AddTypedTextChunk(Allocator
.CopyString(SelectorName
+ ":"));
9334 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9335 Builder
.AddTextChunk("NSUInteger");
9336 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9337 Builder
.AddTextChunk("index");
9338 Results
.AddResult(Result(Builder
.TakeString(), IndexedGetterPriority
,
9339 CXCursor_ObjCInstanceMethodDecl
));
9343 // Add -(NSArray *)keyAtIndexes:(NSIndexSet *)indexes
9344 if (IsInstanceMethod
&&
9345 (ReturnType
.isNull() ||
9346 (ReturnType
->isObjCObjectPointerType() &&
9347 ReturnType
->castAs
<ObjCObjectPointerType
>()->getInterfaceDecl() &&
9348 ReturnType
->castAs
<ObjCObjectPointerType
>()
9349 ->getInterfaceDecl()
9350 ->getName() == "NSArray"))) {
9351 std::string SelectorName
= (Twine(Property
->getName()) + "AtIndexes").str();
9352 IdentifierInfo
*SelectorId
= &Context
.Idents
.get(SelectorName
);
9353 if (KnownSelectors
.insert(Selectors
.getUnarySelector(SelectorId
)).second
) {
9354 if (ReturnType
.isNull()) {
9355 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9356 Builder
.AddTextChunk("NSArray *");
9357 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9360 Builder
.AddTypedTextChunk(Allocator
.CopyString(SelectorName
+ ":"));
9361 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9362 Builder
.AddTextChunk("NSIndexSet *");
9363 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9364 Builder
.AddTextChunk("indexes");
9365 Results
.AddResult(Result(Builder
.TakeString(), IndexedGetterPriority
,
9366 CXCursor_ObjCInstanceMethodDecl
));
9370 // Add -(void)getKey:(type **)buffer range:(NSRange)inRange
9371 if (IsInstanceMethod
&& ReturnTypeMatchesVoid
) {
9372 std::string SelectorName
= (Twine("get") + UpperKey
).str();
9373 const IdentifierInfo
*SelectorIds
[2] = {&Context
.Idents
.get(SelectorName
),
9374 &Context
.Idents
.get("range")};
9376 if (KnownSelectors
.insert(Selectors
.getSelector(2, SelectorIds
)).second
) {
9377 if (ReturnType
.isNull()) {
9378 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9379 Builder
.AddTextChunk("void");
9380 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9383 Builder
.AddTypedTextChunk(Allocator
.CopyString(SelectorName
+ ":"));
9384 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9385 Builder
.AddPlaceholderChunk("object-type");
9386 Builder
.AddTextChunk(" **");
9387 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9388 Builder
.AddTextChunk("buffer");
9389 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
9390 Builder
.AddTypedTextChunk("range:");
9391 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9392 Builder
.AddTextChunk("NSRange");
9393 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9394 Builder
.AddTextChunk("inRange");
9395 Results
.AddResult(Result(Builder
.TakeString(), IndexedGetterPriority
,
9396 CXCursor_ObjCInstanceMethodDecl
));
9400 // Mutable indexed accessors
9402 // - (void)insertObject:(type *)object inKeyAtIndex:(NSUInteger)index
9403 if (IsInstanceMethod
&& ReturnTypeMatchesVoid
) {
9404 std::string SelectorName
= (Twine("in") + UpperKey
+ "AtIndex").str();
9405 const IdentifierInfo
*SelectorIds
[2] = {&Context
.Idents
.get("insertObject"),
9406 &Context
.Idents
.get(SelectorName
)};
9408 if (KnownSelectors
.insert(Selectors
.getSelector(2, SelectorIds
)).second
) {
9409 if (ReturnType
.isNull()) {
9410 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9411 Builder
.AddTextChunk("void");
9412 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9415 Builder
.AddTypedTextChunk("insertObject:");
9416 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9417 Builder
.AddPlaceholderChunk("object-type");
9418 Builder
.AddTextChunk(" *");
9419 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9420 Builder
.AddTextChunk("object");
9421 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
9422 Builder
.AddTypedTextChunk(Allocator
.CopyString(SelectorName
+ ":"));
9423 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9424 Builder
.AddPlaceholderChunk("NSUInteger");
9425 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9426 Builder
.AddTextChunk("index");
9427 Results
.AddResult(Result(Builder
.TakeString(), IndexedSetterPriority
,
9428 CXCursor_ObjCInstanceMethodDecl
));
9432 // - (void)insertKey:(NSArray *)array atIndexes:(NSIndexSet *)indexes
9433 if (IsInstanceMethod
&& ReturnTypeMatchesVoid
) {
9434 std::string SelectorName
= (Twine("insert") + UpperKey
).str();
9435 const IdentifierInfo
*SelectorIds
[2] = {&Context
.Idents
.get(SelectorName
),
9436 &Context
.Idents
.get("atIndexes")};
9438 if (KnownSelectors
.insert(Selectors
.getSelector(2, SelectorIds
)).second
) {
9439 if (ReturnType
.isNull()) {
9440 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9441 Builder
.AddTextChunk("void");
9442 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9445 Builder
.AddTypedTextChunk(Allocator
.CopyString(SelectorName
+ ":"));
9446 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9447 Builder
.AddTextChunk("NSArray *");
9448 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9449 Builder
.AddTextChunk("array");
9450 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
9451 Builder
.AddTypedTextChunk("atIndexes:");
9452 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9453 Builder
.AddPlaceholderChunk("NSIndexSet *");
9454 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9455 Builder
.AddTextChunk("indexes");
9456 Results
.AddResult(Result(Builder
.TakeString(), IndexedSetterPriority
,
9457 CXCursor_ObjCInstanceMethodDecl
));
9461 // -(void)removeObjectFromKeyAtIndex:(NSUInteger)index
9462 if (IsInstanceMethod
&& ReturnTypeMatchesVoid
) {
9463 std::string SelectorName
=
9464 (Twine("removeObjectFrom") + UpperKey
+ "AtIndex").str();
9465 const IdentifierInfo
*SelectorId
= &Context
.Idents
.get(SelectorName
);
9466 if (KnownSelectors
.insert(Selectors
.getUnarySelector(SelectorId
)).second
) {
9467 if (ReturnType
.isNull()) {
9468 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9469 Builder
.AddTextChunk("void");
9470 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9473 Builder
.AddTypedTextChunk(Allocator
.CopyString(SelectorName
+ ":"));
9474 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9475 Builder
.AddTextChunk("NSUInteger");
9476 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9477 Builder
.AddTextChunk("index");
9478 Results
.AddResult(Result(Builder
.TakeString(), IndexedSetterPriority
,
9479 CXCursor_ObjCInstanceMethodDecl
));
9483 // -(void)removeKeyAtIndexes:(NSIndexSet *)indexes
9484 if (IsInstanceMethod
&& ReturnTypeMatchesVoid
) {
9485 std::string SelectorName
= (Twine("remove") + UpperKey
+ "AtIndexes").str();
9486 const IdentifierInfo
*SelectorId
= &Context
.Idents
.get(SelectorName
);
9487 if (KnownSelectors
.insert(Selectors
.getUnarySelector(SelectorId
)).second
) {
9488 if (ReturnType
.isNull()) {
9489 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9490 Builder
.AddTextChunk("void");
9491 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9494 Builder
.AddTypedTextChunk(Allocator
.CopyString(SelectorName
+ ":"));
9495 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9496 Builder
.AddTextChunk("NSIndexSet *");
9497 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9498 Builder
.AddTextChunk("indexes");
9499 Results
.AddResult(Result(Builder
.TakeString(), IndexedSetterPriority
,
9500 CXCursor_ObjCInstanceMethodDecl
));
9504 // - (void)replaceObjectInKeyAtIndex:(NSUInteger)index withObject:(id)object
9505 if (IsInstanceMethod
&& ReturnTypeMatchesVoid
) {
9506 std::string SelectorName
=
9507 (Twine("replaceObjectIn") + UpperKey
+ "AtIndex").str();
9508 const IdentifierInfo
*SelectorIds
[2] = {&Context
.Idents
.get(SelectorName
),
9509 &Context
.Idents
.get("withObject")};
9511 if (KnownSelectors
.insert(Selectors
.getSelector(2, SelectorIds
)).second
) {
9512 if (ReturnType
.isNull()) {
9513 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9514 Builder
.AddTextChunk("void");
9515 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9518 Builder
.AddTypedTextChunk(Allocator
.CopyString(SelectorName
+ ":"));
9519 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9520 Builder
.AddPlaceholderChunk("NSUInteger");
9521 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9522 Builder
.AddTextChunk("index");
9523 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
9524 Builder
.AddTypedTextChunk("withObject:");
9525 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9526 Builder
.AddTextChunk("id");
9527 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9528 Builder
.AddTextChunk("object");
9529 Results
.AddResult(Result(Builder
.TakeString(), IndexedSetterPriority
,
9530 CXCursor_ObjCInstanceMethodDecl
));
9534 // - (void)replaceKeyAtIndexes:(NSIndexSet *)indexes withKey:(NSArray *)array
9535 if (IsInstanceMethod
&& ReturnTypeMatchesVoid
) {
9536 std::string SelectorName1
=
9537 (Twine("replace") + UpperKey
+ "AtIndexes").str();
9538 std::string SelectorName2
= (Twine("with") + UpperKey
).str();
9539 const IdentifierInfo
*SelectorIds
[2] = {&Context
.Idents
.get(SelectorName1
),
9540 &Context
.Idents
.get(SelectorName2
)};
9542 if (KnownSelectors
.insert(Selectors
.getSelector(2, SelectorIds
)).second
) {
9543 if (ReturnType
.isNull()) {
9544 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9545 Builder
.AddTextChunk("void");
9546 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9549 Builder
.AddTypedTextChunk(Allocator
.CopyString(SelectorName1
+ ":"));
9550 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9551 Builder
.AddPlaceholderChunk("NSIndexSet *");
9552 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9553 Builder
.AddTextChunk("indexes");
9554 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
9555 Builder
.AddTypedTextChunk(Allocator
.CopyString(SelectorName2
+ ":"));
9556 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9557 Builder
.AddTextChunk("NSArray *");
9558 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9559 Builder
.AddTextChunk("array");
9560 Results
.AddResult(Result(Builder
.TakeString(), IndexedSetterPriority
,
9561 CXCursor_ObjCInstanceMethodDecl
));
9565 // Unordered getters
9566 // - (NSEnumerator *)enumeratorOfKey
9567 if (IsInstanceMethod
&&
9568 (ReturnType
.isNull() ||
9569 (ReturnType
->isObjCObjectPointerType() &&
9570 ReturnType
->castAs
<ObjCObjectPointerType
>()->getInterfaceDecl() &&
9571 ReturnType
->castAs
<ObjCObjectPointerType
>()
9572 ->getInterfaceDecl()
9573 ->getName() == "NSEnumerator"))) {
9574 std::string SelectorName
= (Twine("enumeratorOf") + UpperKey
).str();
9575 const IdentifierInfo
*SelectorId
= &Context
.Idents
.get(SelectorName
);
9576 if (KnownSelectors
.insert(Selectors
.getNullarySelector(SelectorId
))
9578 if (ReturnType
.isNull()) {
9579 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9580 Builder
.AddTextChunk("NSEnumerator *");
9581 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9584 Builder
.AddTypedTextChunk(Allocator
.CopyString(SelectorName
));
9585 Results
.AddResult(Result(Builder
.TakeString(), UnorderedGetterPriority
,
9586 CXCursor_ObjCInstanceMethodDecl
));
9590 // - (type *)memberOfKey:(type *)object
9591 if (IsInstanceMethod
&&
9592 (ReturnType
.isNull() || ReturnType
->isObjCObjectPointerType())) {
9593 std::string SelectorName
= (Twine("memberOf") + UpperKey
).str();
9594 const IdentifierInfo
*SelectorId
= &Context
.Idents
.get(SelectorName
);
9595 if (KnownSelectors
.insert(Selectors
.getUnarySelector(SelectorId
)).second
) {
9596 if (ReturnType
.isNull()) {
9597 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9598 Builder
.AddPlaceholderChunk("object-type");
9599 Builder
.AddTextChunk(" *");
9600 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9603 Builder
.AddTypedTextChunk(Allocator
.CopyString(SelectorName
+ ":"));
9604 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9605 if (ReturnType
.isNull()) {
9606 Builder
.AddPlaceholderChunk("object-type");
9607 Builder
.AddTextChunk(" *");
9609 Builder
.AddTextChunk(GetCompletionTypeString(
9610 ReturnType
, Context
, Policy
, Builder
.getAllocator()));
9612 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9613 Builder
.AddTextChunk("object");
9614 Results
.AddResult(Result(Builder
.TakeString(), UnorderedGetterPriority
,
9615 CXCursor_ObjCInstanceMethodDecl
));
9619 // Mutable unordered accessors
9620 // - (void)addKeyObject:(type *)object
9621 if (IsInstanceMethod
&& ReturnTypeMatchesVoid
) {
9622 std::string SelectorName
=
9623 (Twine("add") + UpperKey
+ Twine("Object")).str();
9624 const IdentifierInfo
*SelectorId
= &Context
.Idents
.get(SelectorName
);
9625 if (KnownSelectors
.insert(Selectors
.getUnarySelector(SelectorId
)).second
) {
9626 if (ReturnType
.isNull()) {
9627 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9628 Builder
.AddTextChunk("void");
9629 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9632 Builder
.AddTypedTextChunk(Allocator
.CopyString(SelectorName
+ ":"));
9633 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9634 Builder
.AddPlaceholderChunk("object-type");
9635 Builder
.AddTextChunk(" *");
9636 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9637 Builder
.AddTextChunk("object");
9638 Results
.AddResult(Result(Builder
.TakeString(), UnorderedSetterPriority
,
9639 CXCursor_ObjCInstanceMethodDecl
));
9643 // - (void)addKey:(NSSet *)objects
9644 if (IsInstanceMethod
&& ReturnTypeMatchesVoid
) {
9645 std::string SelectorName
= (Twine("add") + UpperKey
).str();
9646 const IdentifierInfo
*SelectorId
= &Context
.Idents
.get(SelectorName
);
9647 if (KnownSelectors
.insert(Selectors
.getUnarySelector(SelectorId
)).second
) {
9648 if (ReturnType
.isNull()) {
9649 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9650 Builder
.AddTextChunk("void");
9651 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9654 Builder
.AddTypedTextChunk(Allocator
.CopyString(SelectorName
+ ":"));
9655 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9656 Builder
.AddTextChunk("NSSet *");
9657 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9658 Builder
.AddTextChunk("objects");
9659 Results
.AddResult(Result(Builder
.TakeString(), UnorderedSetterPriority
,
9660 CXCursor_ObjCInstanceMethodDecl
));
9664 // - (void)removeKeyObject:(type *)object
9665 if (IsInstanceMethod
&& ReturnTypeMatchesVoid
) {
9666 std::string SelectorName
=
9667 (Twine("remove") + UpperKey
+ Twine("Object")).str();
9668 const IdentifierInfo
*SelectorId
= &Context
.Idents
.get(SelectorName
);
9669 if (KnownSelectors
.insert(Selectors
.getUnarySelector(SelectorId
)).second
) {
9670 if (ReturnType
.isNull()) {
9671 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9672 Builder
.AddTextChunk("void");
9673 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9676 Builder
.AddTypedTextChunk(Allocator
.CopyString(SelectorName
+ ":"));
9677 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9678 Builder
.AddPlaceholderChunk("object-type");
9679 Builder
.AddTextChunk(" *");
9680 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9681 Builder
.AddTextChunk("object");
9682 Results
.AddResult(Result(Builder
.TakeString(), UnorderedSetterPriority
,
9683 CXCursor_ObjCInstanceMethodDecl
));
9687 // - (void)removeKey:(NSSet *)objects
9688 if (IsInstanceMethod
&& ReturnTypeMatchesVoid
) {
9689 std::string SelectorName
= (Twine("remove") + UpperKey
).str();
9690 const IdentifierInfo
*SelectorId
= &Context
.Idents
.get(SelectorName
);
9691 if (KnownSelectors
.insert(Selectors
.getUnarySelector(SelectorId
)).second
) {
9692 if (ReturnType
.isNull()) {
9693 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9694 Builder
.AddTextChunk("void");
9695 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9698 Builder
.AddTypedTextChunk(Allocator
.CopyString(SelectorName
+ ":"));
9699 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9700 Builder
.AddTextChunk("NSSet *");
9701 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9702 Builder
.AddTextChunk("objects");
9703 Results
.AddResult(Result(Builder
.TakeString(), UnorderedSetterPriority
,
9704 CXCursor_ObjCInstanceMethodDecl
));
9708 // - (void)intersectKey:(NSSet *)objects
9709 if (IsInstanceMethod
&& ReturnTypeMatchesVoid
) {
9710 std::string SelectorName
= (Twine("intersect") + UpperKey
).str();
9711 const IdentifierInfo
*SelectorId
= &Context
.Idents
.get(SelectorName
);
9712 if (KnownSelectors
.insert(Selectors
.getUnarySelector(SelectorId
)).second
) {
9713 if (ReturnType
.isNull()) {
9714 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9715 Builder
.AddTextChunk("void");
9716 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9719 Builder
.AddTypedTextChunk(Allocator
.CopyString(SelectorName
+ ":"));
9720 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9721 Builder
.AddTextChunk("NSSet *");
9722 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9723 Builder
.AddTextChunk("objects");
9724 Results
.AddResult(Result(Builder
.TakeString(), UnorderedSetterPriority
,
9725 CXCursor_ObjCInstanceMethodDecl
));
9729 // Key-Value Observing
9730 // + (NSSet *)keyPathsForValuesAffectingKey
9731 if (!IsInstanceMethod
&&
9732 (ReturnType
.isNull() ||
9733 (ReturnType
->isObjCObjectPointerType() &&
9734 ReturnType
->castAs
<ObjCObjectPointerType
>()->getInterfaceDecl() &&
9735 ReturnType
->castAs
<ObjCObjectPointerType
>()
9736 ->getInterfaceDecl()
9737 ->getName() == "NSSet"))) {
9738 std::string SelectorName
=
9739 (Twine("keyPathsForValuesAffecting") + UpperKey
).str();
9740 const IdentifierInfo
*SelectorId
= &Context
.Idents
.get(SelectorName
);
9741 if (KnownSelectors
.insert(Selectors
.getNullarySelector(SelectorId
))
9743 if (ReturnType
.isNull()) {
9744 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9745 Builder
.AddTextChunk("NSSet<NSString *> *");
9746 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9749 Builder
.AddTypedTextChunk(Allocator
.CopyString(SelectorName
));
9750 Results
.AddResult(Result(Builder
.TakeString(), CCP_CodePattern
,
9751 CXCursor_ObjCClassMethodDecl
));
9755 // + (BOOL)automaticallyNotifiesObserversForKey
9756 if (!IsInstanceMethod
&&
9757 (ReturnType
.isNull() || ReturnType
->isIntegerType() ||
9758 ReturnType
->isBooleanType())) {
9759 std::string SelectorName
=
9760 (Twine("automaticallyNotifiesObserversOf") + UpperKey
).str();
9761 const IdentifierInfo
*SelectorId
= &Context
.Idents
.get(SelectorName
);
9762 if (KnownSelectors
.insert(Selectors
.getNullarySelector(SelectorId
))
9764 if (ReturnType
.isNull()) {
9765 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9766 Builder
.AddTextChunk("BOOL");
9767 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9770 Builder
.AddTypedTextChunk(Allocator
.CopyString(SelectorName
));
9771 Results
.AddResult(Result(Builder
.TakeString(), CCP_CodePattern
,
9772 CXCursor_ObjCClassMethodDecl
));
9777 void SemaCodeCompletion::CodeCompleteObjCMethodDecl(
9778 Scope
*S
, std::optional
<bool> IsInstanceMethod
, ParsedType ReturnTy
) {
9779 ASTContext
&Context
= getASTContext();
9780 // Determine the return type of the method we're declaring, if
9782 QualType ReturnType
= SemaRef
.GetTypeFromParser(ReturnTy
);
9783 Decl
*IDecl
= nullptr;
9784 if (SemaRef
.CurContext
->isObjCContainer()) {
9785 ObjCContainerDecl
*OCD
= dyn_cast
<ObjCContainerDecl
>(SemaRef
.CurContext
);
9788 // Determine where we should start searching for methods.
9789 ObjCContainerDecl
*SearchDecl
= nullptr;
9790 bool IsInImplementation
= false;
9791 if (Decl
*D
= IDecl
) {
9792 if (ObjCImplementationDecl
*Impl
= dyn_cast
<ObjCImplementationDecl
>(D
)) {
9793 SearchDecl
= Impl
->getClassInterface();
9794 IsInImplementation
= true;
9795 } else if (ObjCCategoryImplDecl
*CatImpl
=
9796 dyn_cast
<ObjCCategoryImplDecl
>(D
)) {
9797 SearchDecl
= CatImpl
->getCategoryDecl();
9798 IsInImplementation
= true;
9800 SearchDecl
= dyn_cast
<ObjCContainerDecl
>(D
);
9803 if (!SearchDecl
&& S
) {
9804 if (DeclContext
*DC
= S
->getEntity())
9805 SearchDecl
= dyn_cast
<ObjCContainerDecl
>(DC
);
9809 HandleCodeCompleteResults(&SemaRef
, CodeCompleter
,
9810 CodeCompletionContext::CCC_Other
, nullptr, 0);
9814 // Find all of the methods that we could declare/implement here.
9815 KnownMethodsMap KnownMethods
;
9816 FindImplementableMethods(Context
, SearchDecl
, IsInstanceMethod
, ReturnType
,
9819 // Add declarations or definitions for each of the known methods.
9820 typedef CodeCompletionResult Result
;
9821 ResultBuilder
Results(SemaRef
, CodeCompleter
->getAllocator(),
9822 CodeCompleter
->getCodeCompletionTUInfo(),
9823 CodeCompletionContext::CCC_Other
);
9824 Results
.EnterNewScope();
9825 PrintingPolicy Policy
= getCompletionPrintingPolicy(SemaRef
);
9826 for (KnownMethodsMap::iterator M
= KnownMethods
.begin(),
9827 MEnd
= KnownMethods
.end();
9829 ObjCMethodDecl
*Method
= M
->second
.getPointer();
9830 CodeCompletionBuilder
Builder(Results
.getAllocator(),
9831 Results
.getCodeCompletionTUInfo());
9833 // Add the '-'/'+' prefix if it wasn't provided yet.
9834 if (!IsInstanceMethod
) {
9835 Builder
.AddTextChunk(Method
->isInstanceMethod() ? "-" : "+");
9836 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
9839 // If the result type was not already provided, add it to the
9840 // pattern as (type).
9841 if (ReturnType
.isNull()) {
9842 QualType ResTy
= Method
->getSendResultType().stripObjCKindOfType(Context
);
9843 AttributedType::stripOuterNullability(ResTy
);
9844 AddObjCPassingTypeChunk(ResTy
, Method
->getObjCDeclQualifier(), Context
,
9848 Selector Sel
= Method
->getSelector();
9850 if (Sel
.isUnarySelector()) {
9851 // Unary selectors have no arguments.
9852 Builder
.AddTypedTextChunk(
9853 Builder
.getAllocator().CopyString(Sel
.getNameForSlot(0)));
9855 // Add all parameters to the pattern.
9857 for (ObjCMethodDecl::param_iterator P
= Method
->param_begin(),
9858 PEnd
= Method
->param_end();
9859 P
!= PEnd
; (void)++P
, ++I
) {
9860 // Add the part of the selector name.
9862 Builder
.AddTypedTextChunk(
9863 Builder
.getAllocator().CopyString(Sel
.getNameForSlot(I
) + ":"));
9864 else if (I
< Sel
.getNumArgs()) {
9865 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
9866 Builder
.AddTypedTextChunk(
9867 Builder
.getAllocator().CopyString(Sel
.getNameForSlot(I
) + ":"));
9871 // Add the parameter type.
9873 if ((*P
)->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability
)
9874 ParamType
= (*P
)->getType();
9876 ParamType
= (*P
)->getOriginalType();
9877 ParamType
= ParamType
.substObjCTypeArgs(
9878 Context
, {}, ObjCSubstitutionContext::Parameter
);
9879 AttributedType::stripOuterNullability(ParamType
);
9880 AddObjCPassingTypeChunk(ParamType
, (*P
)->getObjCDeclQualifier(),
9881 Context
, Policy
, Builder
);
9883 if (IdentifierInfo
*Id
= (*P
)->getIdentifier())
9884 Builder
.AddTextChunk(
9885 Builder
.getAllocator().CopyString(Id
->getName()));
9889 if (Method
->isVariadic()) {
9890 if (Method
->param_size() > 0)
9891 Builder
.AddChunk(CodeCompletionString::CK_Comma
);
9892 Builder
.AddTextChunk("...");
9895 if (IsInImplementation
&& Results
.includeCodePatterns()) {
9896 // We will be defining the method here, so add a compound statement.
9897 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
9898 Builder
.AddChunk(CodeCompletionString::CK_LeftBrace
);
9899 Builder
.AddChunk(CodeCompletionString::CK_VerticalSpace
);
9900 if (!Method
->getReturnType()->isVoidType()) {
9901 // If the result type is not void, add a return clause.
9902 Builder
.AddTextChunk("return");
9903 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
9904 Builder
.AddPlaceholderChunk("expression");
9905 Builder
.AddChunk(CodeCompletionString::CK_SemiColon
);
9907 Builder
.AddPlaceholderChunk("statements");
9909 Builder
.AddChunk(CodeCompletionString::CK_VerticalSpace
);
9910 Builder
.AddChunk(CodeCompletionString::CK_RightBrace
);
9913 unsigned Priority
= CCP_CodePattern
;
9914 auto R
= Result(Builder
.TakeString(), Method
, Priority
);
9915 if (!M
->second
.getInt())
9917 Results
.AddResult(std::move(R
));
9920 // Add Key-Value-Coding and Key-Value-Observing accessor methods for all of
9921 // the properties in this class and its categories.
9922 if (Context
.getLangOpts().ObjC
) {
9923 SmallVector
<ObjCContainerDecl
*, 4> Containers
;
9924 Containers
.push_back(SearchDecl
);
9926 VisitedSelectorSet KnownSelectors
;
9927 for (KnownMethodsMap::iterator M
= KnownMethods
.begin(),
9928 MEnd
= KnownMethods
.end();
9930 KnownSelectors
.insert(M
->first
);
9932 ObjCInterfaceDecl
*IFace
= dyn_cast
<ObjCInterfaceDecl
>(SearchDecl
);
9934 if (ObjCCategoryDecl
*Category
= dyn_cast
<ObjCCategoryDecl
>(SearchDecl
))
9935 IFace
= Category
->getClassInterface();
9938 llvm::append_range(Containers
, IFace
->visible_categories());
9940 if (IsInstanceMethod
) {
9941 for (unsigned I
= 0, N
= Containers
.size(); I
!= N
; ++I
)
9942 for (auto *P
: Containers
[I
]->instance_properties())
9943 AddObjCKeyValueCompletions(P
, *IsInstanceMethod
, ReturnType
, Context
,
9944 KnownSelectors
, Results
);
9948 Results
.ExitScope();
9950 HandleCodeCompleteResults(&SemaRef
, CodeCompleter
,
9951 Results
.getCompletionContext(), Results
.data(),
9955 void SemaCodeCompletion::CodeCompleteObjCMethodDeclSelector(
9956 Scope
*S
, bool IsInstanceMethod
, bool AtParameterName
, ParsedType ReturnTy
,
9957 ArrayRef
<const IdentifierInfo
*> SelIdents
) {
9958 // If we have an external source, load the entire class method
9959 // pool from the AST file.
9960 if (SemaRef
.ExternalSource
) {
9961 for (uint32_t I
= 0, N
= SemaRef
.ExternalSource
->GetNumExternalSelectors();
9963 Selector Sel
= SemaRef
.ExternalSource
->GetExternalSelector(I
);
9964 if (Sel
.isNull() || SemaRef
.ObjC().MethodPool
.count(Sel
))
9967 SemaRef
.ObjC().ReadMethodPool(Sel
);
9971 // Build the set of methods we can see.
9972 typedef CodeCompletionResult Result
;
9973 ResultBuilder
Results(SemaRef
, CodeCompleter
->getAllocator(),
9974 CodeCompleter
->getCodeCompletionTUInfo(),
9975 CodeCompletionContext::CCC_Other
);
9978 Results
.setPreferredType(
9979 SemaRef
.GetTypeFromParser(ReturnTy
).getNonReferenceType());
9981 Results
.EnterNewScope();
9982 for (SemaObjC::GlobalMethodPool::iterator
9983 M
= SemaRef
.ObjC().MethodPool
.begin(),
9984 MEnd
= SemaRef
.ObjC().MethodPool
.end();
9986 for (ObjCMethodList
*MethList
= IsInstanceMethod
? &M
->second
.first
9987 : &M
->second
.second
;
9988 MethList
&& MethList
->getMethod(); MethList
= MethList
->getNext()) {
9989 if (!isAcceptableObjCMethod(MethList
->getMethod(), MK_Any
, SelIdents
))
9992 if (AtParameterName
) {
9993 // Suggest parameter names we've seen before.
9994 unsigned NumSelIdents
= SelIdents
.size();
9996 NumSelIdents
<= MethList
->getMethod()->param_size()) {
9997 ParmVarDecl
*Param
=
9998 MethList
->getMethod()->parameters()[NumSelIdents
- 1];
9999 if (Param
->getIdentifier()) {
10000 CodeCompletionBuilder
Builder(Results
.getAllocator(),
10001 Results
.getCodeCompletionTUInfo());
10002 Builder
.AddTypedTextChunk(Builder
.getAllocator().CopyString(
10003 Param
->getIdentifier()->getName()));
10004 Results
.AddResult(Builder
.TakeString());
10011 Result
R(MethList
->getMethod(),
10012 Results
.getBasePriority(MethList
->getMethod()), nullptr);
10013 R
.StartParameter
= SelIdents
.size();
10014 R
.AllParametersAreInformative
= false;
10015 R
.DeclaringEntity
= true;
10016 Results
.MaybeAddResult(R
, SemaRef
.CurContext
);
10020 Results
.ExitScope();
10022 if (!AtParameterName
&& !SelIdents
.empty() &&
10023 SelIdents
.front()->getName().starts_with("init")) {
10024 for (const auto &M
: SemaRef
.PP
.macros()) {
10025 if (M
.first
->getName() != "NS_DESIGNATED_INITIALIZER")
10027 Results
.EnterNewScope();
10028 CodeCompletionBuilder
Builder(Results
.getAllocator(),
10029 Results
.getCodeCompletionTUInfo());
10030 Builder
.AddTypedTextChunk(
10031 Builder
.getAllocator().CopyString(M
.first
->getName()));
10032 Results
.AddResult(CodeCompletionResult(Builder
.TakeString(), CCP_Macro
,
10033 CXCursor_MacroDefinition
));
10034 Results
.ExitScope();
10038 HandleCodeCompleteResults(&SemaRef
, CodeCompleter
,
10039 Results
.getCompletionContext(), Results
.data(),
10043 void SemaCodeCompletion::CodeCompletePreprocessorDirective(bool InConditional
) {
10044 ResultBuilder
Results(SemaRef
, CodeCompleter
->getAllocator(),
10045 CodeCompleter
->getCodeCompletionTUInfo(),
10046 CodeCompletionContext::CCC_PreprocessorDirective
);
10047 Results
.EnterNewScope();
10050 CodeCompletionBuilder
Builder(Results
.getAllocator(),
10051 Results
.getCodeCompletionTUInfo());
10052 Builder
.AddTypedTextChunk("if");
10053 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
10054 Builder
.AddPlaceholderChunk("condition");
10055 Results
.AddResult(Builder
.TakeString());
10058 Builder
.AddTypedTextChunk("ifdef");
10059 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
10060 Builder
.AddPlaceholderChunk("macro");
10061 Results
.AddResult(Builder
.TakeString());
10064 Builder
.AddTypedTextChunk("ifndef");
10065 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
10066 Builder
.AddPlaceholderChunk("macro");
10067 Results
.AddResult(Builder
.TakeString());
10069 if (InConditional
) {
10070 // #elif <condition>
10071 Builder
.AddTypedTextChunk("elif");
10072 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
10073 Builder
.AddPlaceholderChunk("condition");
10074 Results
.AddResult(Builder
.TakeString());
10076 // #elifdef <macro>
10077 Builder
.AddTypedTextChunk("elifdef");
10078 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
10079 Builder
.AddPlaceholderChunk("macro");
10080 Results
.AddResult(Builder
.TakeString());
10082 // #elifndef <macro>
10083 Builder
.AddTypedTextChunk("elifndef");
10084 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
10085 Builder
.AddPlaceholderChunk("macro");
10086 Results
.AddResult(Builder
.TakeString());
10089 Builder
.AddTypedTextChunk("else");
10090 Results
.AddResult(Builder
.TakeString());
10093 Builder
.AddTypedTextChunk("endif");
10094 Results
.AddResult(Builder
.TakeString());
10097 // #include "header"
10098 Builder
.AddTypedTextChunk("include");
10099 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
10100 Builder
.AddTextChunk("\"");
10101 Builder
.AddPlaceholderChunk("header");
10102 Builder
.AddTextChunk("\"");
10103 Results
.AddResult(Builder
.TakeString());
10105 // #include <header>
10106 Builder
.AddTypedTextChunk("include");
10107 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
10108 Builder
.AddTextChunk("<");
10109 Builder
.AddPlaceholderChunk("header");
10110 Builder
.AddTextChunk(">");
10111 Results
.AddResult(Builder
.TakeString());
10114 Builder
.AddTypedTextChunk("define");
10115 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
10116 Builder
.AddPlaceholderChunk("macro");
10117 Results
.AddResult(Builder
.TakeString());
10119 // #define <macro>(<args>)
10120 Builder
.AddTypedTextChunk("define");
10121 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
10122 Builder
.AddPlaceholderChunk("macro");
10123 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
10124 Builder
.AddPlaceholderChunk("args");
10125 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
10126 Results
.AddResult(Builder
.TakeString());
10129 Builder
.AddTypedTextChunk("undef");
10130 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
10131 Builder
.AddPlaceholderChunk("macro");
10132 Results
.AddResult(Builder
.TakeString());
10135 Builder
.AddTypedTextChunk("line");
10136 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
10137 Builder
.AddPlaceholderChunk("number");
10138 Results
.AddResult(Builder
.TakeString());
10140 // #line <number> "filename"
10141 Builder
.AddTypedTextChunk("line");
10142 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
10143 Builder
.AddPlaceholderChunk("number");
10144 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
10145 Builder
.AddTextChunk("\"");
10146 Builder
.AddPlaceholderChunk("filename");
10147 Builder
.AddTextChunk("\"");
10148 Results
.AddResult(Builder
.TakeString());
10150 // #error <message>
10151 Builder
.AddTypedTextChunk("error");
10152 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
10153 Builder
.AddPlaceholderChunk("message");
10154 Results
.AddResult(Builder
.TakeString());
10156 // #pragma <arguments>
10157 Builder
.AddTypedTextChunk("pragma");
10158 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
10159 Builder
.AddPlaceholderChunk("arguments");
10160 Results
.AddResult(Builder
.TakeString());
10162 if (getLangOpts().ObjC
) {
10163 // #import "header"
10164 Builder
.AddTypedTextChunk("import");
10165 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
10166 Builder
.AddTextChunk("\"");
10167 Builder
.AddPlaceholderChunk("header");
10168 Builder
.AddTextChunk("\"");
10169 Results
.AddResult(Builder
.TakeString());
10171 // #import <header>
10172 Builder
.AddTypedTextChunk("import");
10173 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
10174 Builder
.AddTextChunk("<");
10175 Builder
.AddPlaceholderChunk("header");
10176 Builder
.AddTextChunk(">");
10177 Results
.AddResult(Builder
.TakeString());
10180 // #include_next "header"
10181 Builder
.AddTypedTextChunk("include_next");
10182 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
10183 Builder
.AddTextChunk("\"");
10184 Builder
.AddPlaceholderChunk("header");
10185 Builder
.AddTextChunk("\"");
10186 Results
.AddResult(Builder
.TakeString());
10188 // #include_next <header>
10189 Builder
.AddTypedTextChunk("include_next");
10190 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
10191 Builder
.AddTextChunk("<");
10192 Builder
.AddPlaceholderChunk("header");
10193 Builder
.AddTextChunk(">");
10194 Results
.AddResult(Builder
.TakeString());
10196 // #warning <message>
10197 Builder
.AddTypedTextChunk("warning");
10198 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
10199 Builder
.AddPlaceholderChunk("message");
10200 Results
.AddResult(Builder
.TakeString());
10202 // Note: #ident and #sccs are such crazy anachronisms that we don't provide
10203 // completions for them. And __include_macros is a Clang-internal extension
10204 // that we don't want to encourage anyone to use.
10206 // FIXME: we don't support #assert or #unassert, so don't suggest them.
10207 Results
.ExitScope();
10209 HandleCodeCompleteResults(&SemaRef
, CodeCompleter
,
10210 Results
.getCompletionContext(), Results
.data(),
10214 void SemaCodeCompletion::CodeCompleteInPreprocessorConditionalExclusion(
10216 CodeCompleteOrdinaryName(S
, S
->getFnParent()
10217 ? SemaCodeCompletion::PCC_RecoveryInFunction
10218 : SemaCodeCompletion::PCC_Namespace
);
10221 void SemaCodeCompletion::CodeCompletePreprocessorMacroName(bool IsDefinition
) {
10222 ResultBuilder
Results(SemaRef
, CodeCompleter
->getAllocator(),
10223 CodeCompleter
->getCodeCompletionTUInfo(),
10224 IsDefinition
? CodeCompletionContext::CCC_MacroName
10225 : CodeCompletionContext::CCC_MacroNameUse
);
10226 if (!IsDefinition
&& CodeCompleter
->includeMacros()) {
10227 // Add just the names of macros, not their arguments.
10228 CodeCompletionBuilder
Builder(Results
.getAllocator(),
10229 Results
.getCodeCompletionTUInfo());
10230 Results
.EnterNewScope();
10231 for (Preprocessor::macro_iterator M
= SemaRef
.PP
.macro_begin(),
10232 MEnd
= SemaRef
.PP
.macro_end();
10234 Builder
.AddTypedTextChunk(
10235 Builder
.getAllocator().CopyString(M
->first
->getName()));
10236 Results
.AddResult(CodeCompletionResult(
10237 Builder
.TakeString(), CCP_CodePattern
, CXCursor_MacroDefinition
));
10239 Results
.ExitScope();
10240 } else if (IsDefinition
) {
10241 // FIXME: Can we detect when the user just wrote an include guard above?
10244 HandleCodeCompleteResults(&SemaRef
, CodeCompleter
,
10245 Results
.getCompletionContext(), Results
.data(),
10249 void SemaCodeCompletion::CodeCompletePreprocessorExpression() {
10250 ResultBuilder
Results(SemaRef
, CodeCompleter
->getAllocator(),
10251 CodeCompleter
->getCodeCompletionTUInfo(),
10252 CodeCompletionContext::CCC_PreprocessorExpression
);
10254 if (CodeCompleter
->includeMacros())
10255 AddMacroResults(SemaRef
.PP
, Results
, CodeCompleter
->loadExternal(), true);
10257 // defined (<macro>)
10258 Results
.EnterNewScope();
10259 CodeCompletionBuilder
Builder(Results
.getAllocator(),
10260 Results
.getCodeCompletionTUInfo());
10261 Builder
.AddTypedTextChunk("defined");
10262 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
10263 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
10264 Builder
.AddPlaceholderChunk("macro");
10265 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
10266 Results
.AddResult(Builder
.TakeString());
10267 Results
.ExitScope();
10269 HandleCodeCompleteResults(&SemaRef
, CodeCompleter
,
10270 Results
.getCompletionContext(), Results
.data(),
10274 void SemaCodeCompletion::CodeCompletePreprocessorMacroArgument(
10275 Scope
*S
, IdentifierInfo
*Macro
, MacroInfo
*MacroInfo
, unsigned Argument
) {
10276 // FIXME: In the future, we could provide "overload" results, much like we
10277 // do for function calls.
10279 // Now just ignore this. There will be another code-completion callback
10280 // for the expanded tokens.
10283 // This handles completion inside an #include filename, e.g. #include <foo/ba
10284 // We look for the directory "foo" under each directory on the include path,
10285 // list its files, and reassemble the appropriate #include.
10286 void SemaCodeCompletion::CodeCompleteIncludedFile(llvm::StringRef Dir
,
10288 // RelDir should use /, but unescaped \ is possible on windows!
10289 // Our completions will normalize to / for simplicity, this case is rare.
10290 std::string RelDir
= llvm::sys::path::convert_to_slash(Dir
);
10291 // We need the native slashes for the actual file system interactions.
10292 SmallString
<128> NativeRelDir
= StringRef(RelDir
);
10293 llvm::sys::path::native(NativeRelDir
);
10294 llvm::vfs::FileSystem
&FS
=
10295 SemaRef
.getSourceManager().getFileManager().getVirtualFileSystem();
10297 ResultBuilder
Results(SemaRef
, CodeCompleter
->getAllocator(),
10298 CodeCompleter
->getCodeCompletionTUInfo(),
10299 CodeCompletionContext::CCC_IncludedFile
);
10300 llvm::DenseSet
<StringRef
> SeenResults
; // To deduplicate results.
10302 // Helper: adds one file or directory completion result.
10303 auto AddCompletion
= [&](StringRef Filename
, bool IsDirectory
) {
10304 SmallString
<64> TypedChunk
= Filename
;
10305 // Directory completion is up to the slash, e.g. <sys/
10306 TypedChunk
.push_back(IsDirectory
? '/' : Angled
? '>' : '"');
10307 auto R
= SeenResults
.insert(TypedChunk
);
10308 if (R
.second
) { // New completion
10309 const char *InternedTyped
= Results
.getAllocator().CopyString(TypedChunk
);
10310 *R
.first
= InternedTyped
; // Avoid dangling StringRef.
10311 CodeCompletionBuilder
Builder(CodeCompleter
->getAllocator(),
10312 CodeCompleter
->getCodeCompletionTUInfo());
10313 Builder
.AddTypedTextChunk(InternedTyped
);
10314 // The result is a "Pattern", which is pretty opaque.
10315 // We may want to include the real filename to allow smart ranking.
10316 Results
.AddResult(CodeCompletionResult(Builder
.TakeString()));
10320 // Helper: scans IncludeDir for nice files, and adds results for each.
10321 auto AddFilesFromIncludeDir
= [&](StringRef IncludeDir
,
10323 DirectoryLookup::LookupType_t LookupType
) {
10324 llvm::SmallString
<128> Dir
= IncludeDir
;
10325 if (!NativeRelDir
.empty()) {
10326 if (LookupType
== DirectoryLookup::LT_Framework
) {
10327 // For a framework dir, #include <Foo/Bar/> actually maps to
10328 // a path of Foo.framework/Headers/Bar/.
10329 auto Begin
= llvm::sys::path::begin(NativeRelDir
);
10330 auto End
= llvm::sys::path::end(NativeRelDir
);
10332 llvm::sys::path::append(Dir
, *Begin
+ ".framework", "Headers");
10333 llvm::sys::path::append(Dir
, ++Begin
, End
);
10335 llvm::sys::path::append(Dir
, NativeRelDir
);
10339 const StringRef
&Dirname
= llvm::sys::path::filename(Dir
);
10340 const bool isQt
= Dirname
.starts_with("Qt") || Dirname
== "ActiveQt";
10341 const bool ExtensionlessHeaders
=
10342 IsSystem
|| isQt
|| Dir
.ends_with(".framework/Headers");
10343 std::error_code EC
;
10344 unsigned Count
= 0;
10345 for (auto It
= FS
.dir_begin(Dir
, EC
);
10346 !EC
&& It
!= llvm::vfs::directory_iterator(); It
.increment(EC
)) {
10347 if (++Count
== 2500) // If we happen to hit a huge directory,
10348 break; // bail out early so we're not too slow.
10349 StringRef Filename
= llvm::sys::path::filename(It
->path());
10351 // To know whether a symlink should be treated as file or a directory, we
10352 // have to stat it. This should be cheap enough as there shouldn't be many
10354 llvm::sys::fs::file_type Type
= It
->type();
10355 if (Type
== llvm::sys::fs::file_type::symlink_file
) {
10356 if (auto FileStatus
= FS
.status(It
->path()))
10357 Type
= FileStatus
->getType();
10360 case llvm::sys::fs::file_type::directory_file
:
10361 // All entries in a framework directory must have a ".framework" suffix,
10362 // but the suffix does not appear in the source code's include/import.
10363 if (LookupType
== DirectoryLookup::LT_Framework
&&
10364 NativeRelDir
.empty() && !Filename
.consume_back(".framework"))
10367 AddCompletion(Filename
, /*IsDirectory=*/true);
10369 case llvm::sys::fs::file_type::regular_file
: {
10370 // Only files that really look like headers. (Except in special dirs).
10371 const bool IsHeader
= Filename
.ends_with_insensitive(".h") ||
10372 Filename
.ends_with_insensitive(".hh") ||
10373 Filename
.ends_with_insensitive(".hpp") ||
10374 Filename
.ends_with_insensitive(".hxx") ||
10375 Filename
.ends_with_insensitive(".inc") ||
10376 (ExtensionlessHeaders
&& !Filename
.contains('.'));
10379 AddCompletion(Filename
, /*IsDirectory=*/false);
10388 // Helper: adds results relative to IncludeDir, if possible.
10389 auto AddFilesFromDirLookup
= [&](const DirectoryLookup
&IncludeDir
,
10391 switch (IncludeDir
.getLookupType()) {
10392 case DirectoryLookup::LT_HeaderMap
:
10393 // header maps are not (currently) enumerable.
10395 case DirectoryLookup::LT_NormalDir
:
10396 AddFilesFromIncludeDir(IncludeDir
.getDirRef()->getName(), IsSystem
,
10397 DirectoryLookup::LT_NormalDir
);
10399 case DirectoryLookup::LT_Framework
:
10400 AddFilesFromIncludeDir(IncludeDir
.getFrameworkDirRef()->getName(),
10401 IsSystem
, DirectoryLookup::LT_Framework
);
10406 // Finally with all our helpers, we can scan the include path.
10407 // Do this in standard order so deduplication keeps the right file.
10408 // (In case we decide to add more details to the results later).
10409 const auto &S
= SemaRef
.PP
.getHeaderSearchInfo();
10410 using llvm::make_range
;
10412 // The current directory is on the include path for "quoted" includes.
10413 if (auto CurFile
= SemaRef
.PP
.getCurrentFileLexer()->getFileEntry())
10414 AddFilesFromIncludeDir(CurFile
->getDir().getName(), false,
10415 DirectoryLookup::LT_NormalDir
);
10416 for (const auto &D
: make_range(S
.quoted_dir_begin(), S
.quoted_dir_end()))
10417 AddFilesFromDirLookup(D
, false);
10419 for (const auto &D
: make_range(S
.angled_dir_begin(), S
.angled_dir_end()))
10420 AddFilesFromDirLookup(D
, false);
10421 for (const auto &D
: make_range(S
.system_dir_begin(), S
.system_dir_end()))
10422 AddFilesFromDirLookup(D
, true);
10424 HandleCodeCompleteResults(&SemaRef
, CodeCompleter
,
10425 Results
.getCompletionContext(), Results
.data(),
10429 void SemaCodeCompletion::CodeCompleteNaturalLanguage() {
10430 HandleCodeCompleteResults(&SemaRef
, CodeCompleter
,
10431 CodeCompletionContext::CCC_NaturalLanguage
, nullptr,
10435 void SemaCodeCompletion::CodeCompleteAvailabilityPlatformName() {
10436 ResultBuilder
Results(SemaRef
, CodeCompleter
->getAllocator(),
10437 CodeCompleter
->getCodeCompletionTUInfo(),
10438 CodeCompletionContext::CCC_Other
);
10439 Results
.EnterNewScope();
10440 static const char *Platforms
[] = {"macOS", "iOS", "watchOS", "tvOS"};
10441 for (const char *Platform
: llvm::ArrayRef(Platforms
)) {
10442 Results
.AddResult(CodeCompletionResult(Platform
));
10443 Results
.AddResult(CodeCompletionResult(Results
.getAllocator().CopyString(
10444 Twine(Platform
) + "ApplicationExtension")));
10446 Results
.ExitScope();
10447 HandleCodeCompleteResults(&SemaRef
, CodeCompleter
,
10448 Results
.getCompletionContext(), Results
.data(),
10452 void SemaCodeCompletion::GatherGlobalCodeCompletions(
10453 CodeCompletionAllocator
&Allocator
, CodeCompletionTUInfo
&CCTUInfo
,
10454 SmallVectorImpl
<CodeCompletionResult
> &Results
) {
10455 ResultBuilder
Builder(SemaRef
, Allocator
, CCTUInfo
,
10456 CodeCompletionContext::CCC_Recovery
);
10457 if (!CodeCompleter
|| CodeCompleter
->includeGlobals()) {
10458 CodeCompletionDeclConsumer
Consumer(
10459 Builder
, getASTContext().getTranslationUnitDecl());
10460 SemaRef
.LookupVisibleDecls(getASTContext().getTranslationUnitDecl(),
10461 Sema::LookupAnyName
, Consumer
,
10462 !CodeCompleter
|| CodeCompleter
->loadExternal());
10465 if (!CodeCompleter
|| CodeCompleter
->includeMacros())
10466 AddMacroResults(SemaRef
.PP
, Builder
,
10467 !CodeCompleter
|| CodeCompleter
->loadExternal(), true);
10470 Results
.insert(Results
.end(), Builder
.data(),
10471 Builder
.data() + Builder
.size());
10474 SemaCodeCompletion::SemaCodeCompletion(Sema
&S
,
10475 CodeCompleteConsumer
*CompletionConsumer
)
10476 : SemaBase(S
), CodeCompleter(CompletionConsumer
) {}