1 //===---------------- SemaCodeComplete.cpp - Code Completion ----*- C++ -*-===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file defines the code-completion semantic actions.
11 //===----------------------------------------------------------------------===//
12 #include "clang/AST/ASTConcept.h"
13 #include "clang/AST/Decl.h"
14 #include "clang/AST/DeclBase.h"
15 #include "clang/AST/DeclCXX.h"
16 #include "clang/AST/DeclObjC.h"
17 #include "clang/AST/DeclTemplate.h"
18 #include "clang/AST/Expr.h"
19 #include "clang/AST/ExprCXX.h"
20 #include "clang/AST/ExprConcepts.h"
21 #include "clang/AST/ExprObjC.h"
22 #include "clang/AST/NestedNameSpecifier.h"
23 #include "clang/AST/QualTypeNames.h"
24 #include "clang/AST/RecursiveASTVisitor.h"
25 #include "clang/AST/Type.h"
26 #include "clang/Basic/AttributeCommonInfo.h"
27 #include "clang/Basic/CharInfo.h"
28 #include "clang/Basic/OperatorKinds.h"
29 #include "clang/Basic/Specifiers.h"
30 #include "clang/Lex/HeaderSearch.h"
31 #include "clang/Lex/MacroInfo.h"
32 #include "clang/Lex/Preprocessor.h"
33 #include "clang/Sema/CodeCompleteConsumer.h"
34 #include "clang/Sema/DeclSpec.h"
35 #include "clang/Sema/Designator.h"
36 #include "clang/Sema/Lookup.h"
37 #include "clang/Sema/Overload.h"
38 #include "clang/Sema/ParsedAttr.h"
39 #include "clang/Sema/ParsedTemplate.h"
40 #include "clang/Sema/Scope.h"
41 #include "clang/Sema/ScopeInfo.h"
42 #include "clang/Sema/Sema.h"
43 #include "clang/Sema/SemaInternal.h"
44 #include "llvm/ADT/ArrayRef.h"
45 #include "llvm/ADT/DenseSet.h"
46 #include "llvm/ADT/SmallBitVector.h"
47 #include "llvm/ADT/SmallPtrSet.h"
48 #include "llvm/ADT/SmallString.h"
49 #include "llvm/ADT/StringExtras.h"
50 #include "llvm/ADT/StringSwitch.h"
51 #include "llvm/ADT/Twine.h"
52 #include "llvm/ADT/iterator_range.h"
53 #include "llvm/Support/Casting.h"
54 #include "llvm/Support/Path.h"
55 #include "llvm/Support/raw_ostream.h"
62 using namespace clang
;
66 /// A container of code-completion results.
69 /// The type of a name-lookup filter, which can be provided to the
70 /// name-lookup routines to specify which declarations should be included in
71 /// the result set (when it returns true) and which declarations should be
72 /// filtered out (returns false).
73 typedef bool (ResultBuilder::*LookupFilter
)(const NamedDecl
*) const;
75 typedef CodeCompletionResult Result
;
78 /// The actual results we have found.
79 std::vector
<Result
> Results
;
81 /// A record of all of the declarations we have found and placed
82 /// into the result set, used to ensure that no declaration ever gets into
83 /// the result set twice.
84 llvm::SmallPtrSet
<const Decl
*, 16> AllDeclsFound
;
86 typedef std::pair
<const NamedDecl
*, unsigned> DeclIndexPair
;
88 /// An entry in the shadow map, which is optimized to store
89 /// a single (declaration, index) mapping (the common case) but
90 /// can also store a list of (declaration, index) mappings.
91 class ShadowMapEntry
{
92 typedef SmallVector
<DeclIndexPair
, 4> DeclIndexPairVector
;
94 /// Contains either the solitary NamedDecl * or a vector
95 /// of (declaration, index) pairs.
96 llvm::PointerUnion
<const NamedDecl
*, DeclIndexPairVector
*> DeclOrVector
;
98 /// When the entry contains a single declaration, this is
99 /// the index associated with that entry.
100 unsigned SingleDeclIndex
;
103 ShadowMapEntry() : SingleDeclIndex(0) {}
104 ShadowMapEntry(const ShadowMapEntry
&) = delete;
105 ShadowMapEntry(ShadowMapEntry
&&Move
) { *this = std::move(Move
); }
106 ShadowMapEntry
&operator=(const ShadowMapEntry
&) = delete;
107 ShadowMapEntry
&operator=(ShadowMapEntry
&&Move
) {
108 SingleDeclIndex
= Move
.SingleDeclIndex
;
109 DeclOrVector
= Move
.DeclOrVector
;
110 Move
.DeclOrVector
= nullptr;
114 void Add(const NamedDecl
*ND
, unsigned Index
) {
115 if (DeclOrVector
.isNull()) {
116 // 0 - > 1 elements: just set the single element information.
118 SingleDeclIndex
= Index
;
122 if (const NamedDecl
*PrevND
=
123 DeclOrVector
.dyn_cast
<const NamedDecl
*>()) {
124 // 1 -> 2 elements: create the vector of results and push in the
125 // existing declaration.
126 DeclIndexPairVector
*Vec
= new DeclIndexPairVector
;
127 Vec
->push_back(DeclIndexPair(PrevND
, SingleDeclIndex
));
131 // Add the new element to the end of the vector.
132 DeclOrVector
.get
<DeclIndexPairVector
*>()->push_back(
133 DeclIndexPair(ND
, Index
));
137 if (DeclIndexPairVector
*Vec
=
138 DeclOrVector
.dyn_cast
<DeclIndexPairVector
*>()) {
140 DeclOrVector
= ((NamedDecl
*)nullptr);
146 iterator
begin() const;
147 iterator
end() const;
150 /// A mapping from declaration names to the declarations that have
151 /// this name within a particular scope and their index within the list of
153 typedef llvm::DenseMap
<DeclarationName
, ShadowMapEntry
> ShadowMap
;
155 /// The semantic analysis object for which results are being
159 /// The allocator used to allocate new code-completion strings.
160 CodeCompletionAllocator
&Allocator
;
162 CodeCompletionTUInfo
&CCTUInfo
;
164 /// If non-NULL, a filter function used to remove any code-completion
165 /// results that are not desirable.
168 /// Whether we should allow declarations as
169 /// nested-name-specifiers that would otherwise be filtered out.
170 bool AllowNestedNameSpecifiers
;
172 /// If set, the type that we would prefer our resulting value
173 /// declarations to have.
175 /// Closely matching the preferred type gives a boost to a result's
177 CanQualType PreferredType
;
179 /// A list of shadow maps, which is used to model name hiding at
180 /// different levels of, e.g., the inheritance hierarchy.
181 std::list
<ShadowMap
> ShadowMaps
;
183 /// Overloaded C++ member functions found by SemaLookup.
184 /// Used to determine when one overload is dominated by another.
185 llvm::DenseMap
<std::pair
<DeclContext
*, /*Name*/uintptr_t>, ShadowMapEntry
>
188 /// If we're potentially referring to a C++ member function, the set
189 /// of qualifiers applied to the object type.
190 Qualifiers ObjectTypeQualifiers
;
191 /// The kind of the object expression, for rvalue/lvalue overloads.
192 ExprValueKind ObjectKind
;
194 /// Whether the \p ObjectTypeQualifiers field is active.
195 bool HasObjectTypeQualifiers
;
197 /// The selector that we prefer.
198 Selector PreferredSelector
;
200 /// The completion context in which we are gathering results.
201 CodeCompletionContext CompletionContext
;
203 /// If we are in an instance method definition, the \@implementation
205 ObjCImplementationDecl
*ObjCImplementation
;
207 void AdjustResultPriorityForDecl(Result
&R
);
209 void MaybeAddConstructorResults(Result R
);
212 explicit ResultBuilder(Sema
&SemaRef
, CodeCompletionAllocator
&Allocator
,
213 CodeCompletionTUInfo
&CCTUInfo
,
214 const CodeCompletionContext
&CompletionContext
,
215 LookupFilter Filter
= nullptr)
216 : SemaRef(SemaRef
), Allocator(Allocator
), CCTUInfo(CCTUInfo
),
217 Filter(Filter
), AllowNestedNameSpecifiers(false),
218 HasObjectTypeQualifiers(false), CompletionContext(CompletionContext
),
219 ObjCImplementation(nullptr) {
220 // If this is an Objective-C instance method definition, dig out the
221 // corresponding implementation.
222 switch (CompletionContext
.getKind()) {
223 case CodeCompletionContext::CCC_Expression
:
224 case CodeCompletionContext::CCC_ObjCMessageReceiver
:
225 case CodeCompletionContext::CCC_ParenthesizedExpression
:
226 case CodeCompletionContext::CCC_Statement
:
227 case CodeCompletionContext::CCC_Recovery
:
228 if (ObjCMethodDecl
*Method
= SemaRef
.getCurMethodDecl())
229 if (Method
->isInstanceMethod())
230 if (ObjCInterfaceDecl
*Interface
= Method
->getClassInterface())
231 ObjCImplementation
= Interface
->getImplementation();
239 /// Determine the priority for a reference to the given declaration.
240 unsigned getBasePriority(const NamedDecl
*D
);
242 /// Whether we should include code patterns in the completion
244 bool includeCodePatterns() const {
245 return SemaRef
.CodeCompleter
&&
246 SemaRef
.CodeCompleter
->includeCodePatterns();
249 /// Set the filter used for code-completion results.
250 void setFilter(LookupFilter Filter
) { this->Filter
= Filter
; }
252 Result
*data() { return Results
.empty() ? nullptr : &Results
.front(); }
253 unsigned size() const { return Results
.size(); }
254 bool empty() const { return Results
.empty(); }
256 /// Specify the preferred type.
257 void setPreferredType(QualType T
) {
258 PreferredType
= SemaRef
.Context
.getCanonicalType(T
);
261 /// Set the cv-qualifiers on the object type, for us in filtering
262 /// calls to member functions.
264 /// When there are qualifiers in this set, they will be used to filter
265 /// out member functions that aren't available (because there will be a
266 /// cv-qualifier mismatch) or prefer functions with an exact qualifier
268 void setObjectTypeQualifiers(Qualifiers Quals
, ExprValueKind Kind
) {
269 ObjectTypeQualifiers
= Quals
;
271 HasObjectTypeQualifiers
= true;
274 /// Set the preferred selector.
276 /// When an Objective-C method declaration result is added, and that
277 /// method's selector matches this preferred selector, we give that method
278 /// a slight priority boost.
279 void setPreferredSelector(Selector Sel
) { PreferredSelector
= Sel
; }
281 /// Retrieve the code-completion context for which results are
283 const CodeCompletionContext
&getCompletionContext() const {
284 return CompletionContext
;
287 /// Specify whether nested-name-specifiers are allowed.
288 void allowNestedNameSpecifiers(bool Allow
= true) {
289 AllowNestedNameSpecifiers
= Allow
;
292 /// Return the semantic analysis object for which we are collecting
293 /// code completion results.
294 Sema
&getSema() const { return SemaRef
; }
296 /// Retrieve the allocator used to allocate code completion strings.
297 CodeCompletionAllocator
&getAllocator() const { return Allocator
; }
299 CodeCompletionTUInfo
&getCodeCompletionTUInfo() const { return CCTUInfo
; }
301 /// Determine whether the given declaration is at all interesting
302 /// as a code-completion result.
304 /// \param ND the declaration that we are inspecting.
306 /// \param AsNestedNameSpecifier will be set true if this declaration is
307 /// only interesting when it is a nested-name-specifier.
308 bool isInterestingDecl(const NamedDecl
*ND
,
309 bool &AsNestedNameSpecifier
) const;
311 /// Check whether the result is hidden by the Hiding declaration.
313 /// \returns true if the result is hidden and cannot be found, false if
314 /// the hidden result could still be found. When false, \p R may be
315 /// modified to describe how the result can be found (e.g., via extra
317 bool CheckHiddenResult(Result
&R
, DeclContext
*CurContext
,
318 const NamedDecl
*Hiding
);
320 /// Add a new result to this result set (if it isn't already in one
321 /// of the shadow maps), or replace an existing result (for, e.g., a
324 /// \param R the result to add (if it is unique).
326 /// \param CurContext the context in which this result will be named.
327 void MaybeAddResult(Result R
, DeclContext
*CurContext
= nullptr);
329 /// Add a new result to this result set, where we already know
330 /// the hiding declaration (if any).
332 /// \param R the result to add (if it is unique).
334 /// \param CurContext the context in which this result will be named.
336 /// \param Hiding the declaration that hides the result.
338 /// \param InBaseClass whether the result was found in a base
339 /// class of the searched context.
340 void AddResult(Result R
, DeclContext
*CurContext
, NamedDecl
*Hiding
,
343 /// Add a new non-declaration result to this result set.
344 void AddResult(Result R
);
346 /// Enter into a new scope.
347 void EnterNewScope();
349 /// Exit from the current scope.
352 /// Ignore this declaration, if it is seen again.
353 void Ignore(const Decl
*D
) { AllDeclsFound
.insert(D
->getCanonicalDecl()); }
355 /// Add a visited context.
356 void addVisitedContext(DeclContext
*Ctx
) {
357 CompletionContext
.addVisitedContext(Ctx
);
360 /// \name Name lookup predicates
362 /// These predicates can be passed to the name lookup functions to filter the
363 /// results of name lookup. All of the predicates have the same type, so that
366 bool IsOrdinaryName(const NamedDecl
*ND
) const;
367 bool IsOrdinaryNonTypeName(const NamedDecl
*ND
) const;
368 bool IsIntegralConstantValue(const NamedDecl
*ND
) const;
369 bool IsOrdinaryNonValueName(const NamedDecl
*ND
) const;
370 bool IsNestedNameSpecifier(const NamedDecl
*ND
) const;
371 bool IsEnum(const NamedDecl
*ND
) const;
372 bool IsClassOrStruct(const NamedDecl
*ND
) const;
373 bool IsUnion(const NamedDecl
*ND
) const;
374 bool IsNamespace(const NamedDecl
*ND
) const;
375 bool IsNamespaceOrAlias(const NamedDecl
*ND
) const;
376 bool IsType(const NamedDecl
*ND
) const;
377 bool IsMember(const NamedDecl
*ND
) const;
378 bool IsObjCIvar(const NamedDecl
*ND
) const;
379 bool IsObjCMessageReceiver(const NamedDecl
*ND
) const;
380 bool IsObjCMessageReceiverOrLambdaCapture(const NamedDecl
*ND
) const;
381 bool IsObjCCollection(const NamedDecl
*ND
) const;
382 bool IsImpossibleToSatisfy(const NamedDecl
*ND
) const;
387 void PreferredTypeBuilder::enterReturn(Sema
&S
, SourceLocation Tok
) {
390 if (isa
<BlockDecl
>(S
.CurContext
)) {
391 if (sema::BlockScopeInfo
*BSI
= S
.getCurBlock()) {
392 ComputeType
= nullptr;
393 Type
= BSI
->ReturnType
;
396 } else if (const auto *Function
= dyn_cast
<FunctionDecl
>(S
.CurContext
)) {
397 ComputeType
= nullptr;
398 Type
= Function
->getReturnType();
400 } else if (const auto *Method
= dyn_cast
<ObjCMethodDecl
>(S
.CurContext
)) {
401 ComputeType
= nullptr;
402 Type
= Method
->getReturnType();
407 void PreferredTypeBuilder::enterVariableInit(SourceLocation Tok
, Decl
*D
) {
410 auto *VD
= llvm::dyn_cast_or_null
<ValueDecl
>(D
);
411 ComputeType
= nullptr;
412 Type
= VD
? VD
->getType() : QualType();
416 static QualType
getDesignatedType(QualType BaseType
, const Designation
&Desig
);
418 void PreferredTypeBuilder::enterDesignatedInitializer(SourceLocation Tok
,
420 const Designation
&D
) {
423 ComputeType
= nullptr;
424 Type
= getDesignatedType(BaseType
, D
);
428 void PreferredTypeBuilder::enterFunctionArgument(
429 SourceLocation Tok
, llvm::function_ref
<QualType()> ComputeType
) {
432 this->ComputeType
= ComputeType
;
437 void PreferredTypeBuilder::enterParenExpr(SourceLocation Tok
,
438 SourceLocation LParLoc
) {
441 // expected type for parenthesized expression does not change.
442 if (ExpectedLoc
== LParLoc
)
446 static QualType
getPreferredTypeOfBinaryRHS(Sema
&S
, Expr
*LHS
,
451 QualType LHSType
= LHS
->getType();
452 if (LHSType
->isPointerType()) {
453 if (Op
== tok::plus
|| Op
== tok::plusequal
|| Op
== tok::minusequal
)
454 return S
.getASTContext().getPointerDiffType();
455 // Pointer difference is more common than subtracting an int from a pointer.
456 if (Op
== tok::minus
)
461 // No way to infer the type of RHS from LHS.
464 // Prefer the type of the left operand for all of these.
465 // Arithmetic operations.
469 case tok::minusequal
:
471 case tok::percentequal
:
473 case tok::slashequal
:
478 // Comparison operators.
479 case tok::equalequal
:
480 case tok::exclaimequal
:
484 case tok::greaterequal
:
486 return LHS
->getType();
487 // Binary shifts are often overloaded, so don't try to guess those.
488 case tok::greatergreater
:
489 case tok::greatergreaterequal
:
491 case tok::lesslessequal
:
492 if (LHSType
->isIntegralOrEnumerationType())
493 return S
.getASTContext().IntTy
;
495 // Logical operators, assume we want bool.
498 case tok::caretcaret
:
499 return S
.getASTContext().BoolTy
;
500 // Operators often used for bit manipulation are typically used with the type
501 // of the left argument.
505 case tok::caretequal
:
508 if (LHSType
->isIntegralOrEnumerationType())
511 // RHS should be a pointer to a member of the 'LHS' type, but we can't give
512 // any particular type here.
513 case tok::periodstar
:
517 // FIXME(ibiryukov): handle the missing op, re-add the assertion.
518 // assert(false && "unhandled binary op");
523 /// Get preferred type for an argument of an unary expression. \p ContextType is
524 /// preferred type of the whole unary expression.
525 static QualType
getPreferredTypeOfUnaryArg(Sema
&S
, QualType ContextType
,
529 return S
.getASTContext().BoolTy
;
531 if (!ContextType
.isNull() && ContextType
->isPointerType())
532 return ContextType
->getPointeeType();
535 if (ContextType
.isNull())
537 return S
.getASTContext().getPointerType(ContextType
.getNonReferenceType());
541 case tok::minusminus
:
543 if (ContextType
.isNull())
544 return S
.getASTContext().IntTy
;
545 // leave as is, these operators typically return the same type.
551 assert(false && "unhandled unary op");
556 void PreferredTypeBuilder::enterBinary(Sema
&S
, SourceLocation Tok
, Expr
*LHS
,
560 ComputeType
= nullptr;
561 Type
= getPreferredTypeOfBinaryRHS(S
, LHS
, Op
);
565 void PreferredTypeBuilder::enterMemAccess(Sema
&S
, SourceLocation Tok
,
567 if (!Enabled
|| !Base
)
569 // Do we have expected type for Base?
570 if (ExpectedLoc
!= Base
->getBeginLoc())
572 // Keep the expected type, only update the location.
576 void PreferredTypeBuilder::enterUnary(Sema
&S
, SourceLocation Tok
,
577 tok::TokenKind OpKind
,
578 SourceLocation OpLoc
) {
581 ComputeType
= nullptr;
582 Type
= getPreferredTypeOfUnaryArg(S
, this->get(OpLoc
), OpKind
);
586 void PreferredTypeBuilder::enterSubscript(Sema
&S
, SourceLocation Tok
,
590 ComputeType
= nullptr;
591 Type
= S
.getASTContext().IntTy
;
595 void PreferredTypeBuilder::enterTypeCast(SourceLocation Tok
,
599 ComputeType
= nullptr;
600 Type
= !CastType
.isNull() ? CastType
.getCanonicalType() : QualType();
604 void PreferredTypeBuilder::enterCondition(Sema
&S
, SourceLocation Tok
) {
607 ComputeType
= nullptr;
608 Type
= S
.getASTContext().BoolTy
;
612 class ResultBuilder::ShadowMapEntry::iterator
{
613 llvm::PointerUnion
<const NamedDecl
*, const DeclIndexPair
*> DeclOrIterator
;
614 unsigned SingleDeclIndex
;
617 typedef DeclIndexPair value_type
;
618 typedef value_type reference
;
619 typedef std::ptrdiff_t difference_type
;
620 typedef std::input_iterator_tag iterator_category
;
626 pointer(const DeclIndexPair
&Value
) : Value(Value
) {}
628 const DeclIndexPair
*operator->() const { return &Value
; }
631 iterator() : DeclOrIterator((NamedDecl
*)nullptr), SingleDeclIndex(0) {}
633 iterator(const NamedDecl
*SingleDecl
, unsigned Index
)
634 : DeclOrIterator(SingleDecl
), SingleDeclIndex(Index
) {}
636 iterator(const DeclIndexPair
*Iterator
)
637 : DeclOrIterator(Iterator
), SingleDeclIndex(0) {}
639 iterator
&operator++() {
640 if (DeclOrIterator
.is
<const NamedDecl
*>()) {
641 DeclOrIterator
= (NamedDecl
*)nullptr;
646 const DeclIndexPair
*I
= DeclOrIterator
.get
<const DeclIndexPair
*>();
652 /*iterator operator++(int) {
658 reference
operator*() const {
659 if (const NamedDecl
*ND
= DeclOrIterator
.dyn_cast
<const NamedDecl
*>())
660 return reference(ND
, SingleDeclIndex
);
662 return *DeclOrIterator
.get
<const DeclIndexPair
*>();
665 pointer
operator->() const { return pointer(**this); }
667 friend bool operator==(const iterator
&X
, const iterator
&Y
) {
668 return X
.DeclOrIterator
.getOpaqueValue() ==
669 Y
.DeclOrIterator
.getOpaqueValue() &&
670 X
.SingleDeclIndex
== Y
.SingleDeclIndex
;
673 friend bool operator!=(const iterator
&X
, const iterator
&Y
) {
678 ResultBuilder::ShadowMapEntry::iterator
679 ResultBuilder::ShadowMapEntry::begin() const {
680 if (DeclOrVector
.isNull())
683 if (const NamedDecl
*ND
= DeclOrVector
.dyn_cast
<const NamedDecl
*>())
684 return iterator(ND
, SingleDeclIndex
);
686 return iterator(DeclOrVector
.get
<DeclIndexPairVector
*>()->begin());
689 ResultBuilder::ShadowMapEntry::iterator
690 ResultBuilder::ShadowMapEntry::end() const {
691 if (DeclOrVector
.is
<const NamedDecl
*>() || DeclOrVector
.isNull())
694 return iterator(DeclOrVector
.get
<DeclIndexPairVector
*>()->end());
697 /// Compute the qualification required to get from the current context
698 /// (\p CurContext) to the target context (\p TargetContext).
700 /// \param Context the AST context in which the qualification will be used.
702 /// \param CurContext the context where an entity is being named, which is
703 /// typically based on the current scope.
705 /// \param TargetContext the context in which the named entity actually
708 /// \returns a nested name specifier that refers into the target context, or
709 /// NULL if no qualification is needed.
710 static NestedNameSpecifier
*
711 getRequiredQualification(ASTContext
&Context
, const DeclContext
*CurContext
,
712 const DeclContext
*TargetContext
) {
713 SmallVector
<const DeclContext
*, 4> TargetParents
;
715 for (const DeclContext
*CommonAncestor
= TargetContext
;
716 CommonAncestor
&& !CommonAncestor
->Encloses(CurContext
);
717 CommonAncestor
= CommonAncestor
->getLookupParent()) {
718 if (CommonAncestor
->isTransparentContext() ||
719 CommonAncestor
->isFunctionOrMethod())
722 TargetParents
.push_back(CommonAncestor
);
725 NestedNameSpecifier
*Result
= nullptr;
726 while (!TargetParents
.empty()) {
727 const DeclContext
*Parent
= TargetParents
.pop_back_val();
729 if (const auto *Namespace
= dyn_cast
<NamespaceDecl
>(Parent
)) {
730 if (!Namespace
->getIdentifier())
733 Result
= NestedNameSpecifier::Create(Context
, Result
, Namespace
);
734 } else if (const auto *TD
= dyn_cast
<TagDecl
>(Parent
))
735 Result
= NestedNameSpecifier::Create(
736 Context
, Result
, false, Context
.getTypeDeclType(TD
).getTypePtr());
741 // Some declarations have reserved names that we don't want to ever show.
742 // Filter out names reserved for the implementation if they come from a
744 static bool shouldIgnoreDueToReservedName(const NamedDecl
*ND
, Sema
&SemaRef
) {
745 ReservedIdentifierStatus Status
= ND
->isReserved(SemaRef
.getLangOpts());
746 // Ignore reserved names for compiler provided decls.
747 if (isReservedInAllContexts(Status
) && ND
->getLocation().isInvalid())
750 // For system headers ignore only double-underscore names.
751 // This allows for system headers providing private symbols with a single
753 if (Status
== ReservedIdentifierStatus::StartsWithDoubleUnderscore
&&
754 SemaRef
.SourceMgr
.isInSystemHeader(
755 SemaRef
.SourceMgr
.getSpellingLoc(ND
->getLocation())))
761 bool ResultBuilder::isInterestingDecl(const NamedDecl
*ND
,
762 bool &AsNestedNameSpecifier
) const {
763 AsNestedNameSpecifier
= false;
766 ND
= ND
->getUnderlyingDecl();
768 // Skip unnamed entities.
769 if (!ND
->getDeclName())
772 // Friend declarations and declarations introduced due to friends are never
774 if (ND
->getFriendObjectKind() == Decl::FOK_Undeclared
)
777 // Class template (partial) specializations are never added as results.
778 if (isa
<ClassTemplateSpecializationDecl
>(ND
) ||
779 isa
<ClassTemplatePartialSpecializationDecl
>(ND
))
782 // Using declarations themselves are never added as results.
783 if (isa
<UsingDecl
>(ND
))
786 if (shouldIgnoreDueToReservedName(ND
, SemaRef
))
789 if (Filter
== &ResultBuilder::IsNestedNameSpecifier
||
790 (isa
<NamespaceDecl
>(ND
) && Filter
!= &ResultBuilder::IsNamespace
&&
791 Filter
!= &ResultBuilder::IsNamespaceOrAlias
&& Filter
!= nullptr))
792 AsNestedNameSpecifier
= true;
794 // Filter out any unwanted results.
795 if (Filter
&& !(this->*Filter
)(Named
)) {
796 // Check whether it is interesting as a nested-name-specifier.
797 if (AllowNestedNameSpecifiers
&& SemaRef
.getLangOpts().CPlusPlus
&&
798 IsNestedNameSpecifier(ND
) &&
799 (Filter
!= &ResultBuilder::IsMember
||
800 (isa
<CXXRecordDecl
>(ND
) &&
801 cast
<CXXRecordDecl
>(ND
)->isInjectedClassName()))) {
802 AsNestedNameSpecifier
= true;
808 // ... then it must be interesting!
812 bool ResultBuilder::CheckHiddenResult(Result
&R
, DeclContext
*CurContext
,
813 const NamedDecl
*Hiding
) {
814 // In C, there is no way to refer to a hidden name.
815 // FIXME: This isn't true; we can find a tag name hidden by an ordinary
816 // name if we introduce the tag type.
817 if (!SemaRef
.getLangOpts().CPlusPlus
)
820 const DeclContext
*HiddenCtx
=
821 R
.Declaration
->getDeclContext()->getRedeclContext();
823 // There is no way to qualify a name declared in a function or method.
824 if (HiddenCtx
->isFunctionOrMethod())
827 if (HiddenCtx
== Hiding
->getDeclContext()->getRedeclContext())
830 // We can refer to the result with the appropriate qualification. Do it.
832 R
.QualifierIsInformative
= false;
835 R
.Qualifier
= getRequiredQualification(SemaRef
.Context
, CurContext
,
836 R
.Declaration
->getDeclContext());
840 /// A simplified classification of types used to determine whether two
841 /// types are "similar enough" when adjusting priorities.
842 SimplifiedTypeClass
clang::getSimplifiedTypeClass(CanQualType T
) {
843 switch (T
->getTypeClass()) {
845 switch (cast
<BuiltinType
>(T
)->getKind()) {
846 case BuiltinType::Void
:
849 case BuiltinType::NullPtr
:
852 case BuiltinType::Overload
:
853 case BuiltinType::Dependent
:
856 case BuiltinType::ObjCId
:
857 case BuiltinType::ObjCClass
:
858 case BuiltinType::ObjCSel
:
859 return STC_ObjectiveC
;
862 return STC_Arithmetic
;
866 return STC_Arithmetic
;
871 case Type::BlockPointer
:
874 case Type::LValueReference
:
875 case Type::RValueReference
:
876 return getSimplifiedTypeClass(T
->getAs
<ReferenceType
>()->getPointeeType());
878 case Type::ConstantArray
:
879 case Type::IncompleteArray
:
880 case Type::VariableArray
:
881 case Type::DependentSizedArray
:
884 case Type::DependentSizedExtVector
:
886 case Type::ExtVector
:
887 return STC_Arithmetic
;
889 case Type::FunctionProto
:
890 case Type::FunctionNoProto
:
897 return STC_Arithmetic
;
899 case Type::ObjCObject
:
900 case Type::ObjCInterface
:
901 case Type::ObjCObjectPointer
:
902 return STC_ObjectiveC
;
909 /// Get the type that a given expression will have if this declaration
910 /// is used as an expression in its "typical" code-completion form.
911 QualType
clang::getDeclUsageType(ASTContext
&C
, const NamedDecl
*ND
) {
912 ND
= ND
->getUnderlyingDecl();
914 if (const auto *Type
= dyn_cast
<TypeDecl
>(ND
))
915 return C
.getTypeDeclType(Type
);
916 if (const auto *Iface
= dyn_cast
<ObjCInterfaceDecl
>(ND
))
917 return C
.getObjCInterfaceType(Iface
);
920 if (const FunctionDecl
*Function
= ND
->getAsFunction())
921 T
= Function
->getCallResultType();
922 else if (const auto *Method
= dyn_cast
<ObjCMethodDecl
>(ND
))
923 T
= Method
->getSendResultType();
924 else if (const auto *Enumerator
= dyn_cast
<EnumConstantDecl
>(ND
))
925 T
= C
.getTypeDeclType(cast
<EnumDecl
>(Enumerator
->getDeclContext()));
926 else if (const auto *Property
= dyn_cast
<ObjCPropertyDecl
>(ND
))
927 T
= Property
->getType();
928 else if (const auto *Value
= dyn_cast
<ValueDecl
>(ND
))
929 T
= Value
->getType();
934 // Dig through references, function pointers, and block pointers to
935 // get down to the likely type of an expression when the entity is
938 if (const auto *Ref
= T
->getAs
<ReferenceType
>()) {
939 T
= Ref
->getPointeeType();
943 if (const auto *Pointer
= T
->getAs
<PointerType
>()) {
944 if (Pointer
->getPointeeType()->isFunctionType()) {
945 T
= Pointer
->getPointeeType();
952 if (const auto *Block
= T
->getAs
<BlockPointerType
>()) {
953 T
= Block
->getPointeeType();
957 if (const auto *Function
= T
->getAs
<FunctionType
>()) {
958 T
= Function
->getReturnType();
968 unsigned ResultBuilder::getBasePriority(const NamedDecl
*ND
) {
972 // Context-based decisions.
973 const DeclContext
*LexicalDC
= ND
->getLexicalDeclContext();
974 if (LexicalDC
->isFunctionOrMethod()) {
975 // _cmd is relatively rare
976 if (const auto *ImplicitParam
= dyn_cast
<ImplicitParamDecl
>(ND
))
977 if (ImplicitParam
->getIdentifier() &&
978 ImplicitParam
->getIdentifier()->isStr("_cmd"))
981 return CCP_LocalDeclaration
;
984 const DeclContext
*DC
= ND
->getDeclContext()->getRedeclContext();
985 if (DC
->isRecord() || isa
<ObjCContainerDecl
>(DC
)) {
986 // Explicit destructor calls are very rare.
987 if (isa
<CXXDestructorDecl
>(ND
))
989 // Explicit operator and conversion function calls are also very rare.
990 auto DeclNameKind
= ND
->getDeclName().getNameKind();
991 if (DeclNameKind
== DeclarationName::CXXOperatorName
||
992 DeclNameKind
== DeclarationName::CXXLiteralOperatorName
||
993 DeclNameKind
== DeclarationName::CXXConversionFunctionName
)
995 return CCP_MemberDeclaration
;
998 // Content-based decisions.
999 if (isa
<EnumConstantDecl
>(ND
))
1000 return CCP_Constant
;
1002 // Use CCP_Type for type declarations unless we're in a statement, Objective-C
1003 // message receiver, or parenthesized expression context. There, it's as
1004 // likely that the user will want to write a type as other declarations.
1005 if ((isa
<TypeDecl
>(ND
) || isa
<ObjCInterfaceDecl
>(ND
)) &&
1006 !(CompletionContext
.getKind() == CodeCompletionContext::CCC_Statement
||
1007 CompletionContext
.getKind() ==
1008 CodeCompletionContext::CCC_ObjCMessageReceiver
||
1009 CompletionContext
.getKind() ==
1010 CodeCompletionContext::CCC_ParenthesizedExpression
))
1013 return CCP_Declaration
;
1016 void ResultBuilder::AdjustResultPriorityForDecl(Result
&R
) {
1017 // If this is an Objective-C method declaration whose selector matches our
1018 // preferred selector, give it a priority boost.
1019 if (!PreferredSelector
.isNull())
1020 if (const auto *Method
= dyn_cast
<ObjCMethodDecl
>(R
.Declaration
))
1021 if (PreferredSelector
== Method
->getSelector())
1022 R
.Priority
+= CCD_SelectorMatch
;
1024 // If we have a preferred type, adjust the priority for results with exactly-
1025 // matching or nearly-matching types.
1026 if (!PreferredType
.isNull()) {
1027 QualType T
= getDeclUsageType(SemaRef
.Context
, R
.Declaration
);
1029 CanQualType TC
= SemaRef
.Context
.getCanonicalType(T
);
1030 // Check for exactly-matching types (modulo qualifiers).
1031 if (SemaRef
.Context
.hasSameUnqualifiedType(PreferredType
, TC
))
1032 R
.Priority
/= CCF_ExactTypeMatch
;
1033 // Check for nearly-matching types, based on classification of each.
1034 else if ((getSimplifiedTypeClass(PreferredType
) ==
1035 getSimplifiedTypeClass(TC
)) &&
1036 !(PreferredType
->isEnumeralType() && TC
->isEnumeralType()))
1037 R
.Priority
/= CCF_SimilarTypeMatch
;
1042 static DeclContext::lookup_result
getConstructors(ASTContext
&Context
,
1043 const CXXRecordDecl
*Record
) {
1044 QualType RecordTy
= Context
.getTypeDeclType(Record
);
1045 DeclarationName ConstructorName
=
1046 Context
.DeclarationNames
.getCXXConstructorName(
1047 Context
.getCanonicalType(RecordTy
));
1048 return Record
->lookup(ConstructorName
);
1051 void ResultBuilder::MaybeAddConstructorResults(Result R
) {
1052 if (!SemaRef
.getLangOpts().CPlusPlus
|| !R
.Declaration
||
1053 !CompletionContext
.wantConstructorResults())
1056 const NamedDecl
*D
= R
.Declaration
;
1057 const CXXRecordDecl
*Record
= nullptr;
1058 if (const ClassTemplateDecl
*ClassTemplate
= dyn_cast
<ClassTemplateDecl
>(D
))
1059 Record
= ClassTemplate
->getTemplatedDecl();
1060 else if ((Record
= dyn_cast
<CXXRecordDecl
>(D
))) {
1061 // Skip specializations and partial specializations.
1062 if (isa
<ClassTemplateSpecializationDecl
>(Record
))
1065 // There are no constructors here.
1069 Record
= Record
->getDefinition();
1073 for (NamedDecl
*Ctor
: getConstructors(SemaRef
.Context
, Record
)) {
1074 R
.Declaration
= Ctor
;
1075 R
.CursorKind
= getCursorKindForDecl(R
.Declaration
);
1076 Results
.push_back(R
);
1080 static bool isConstructor(const Decl
*ND
) {
1081 if (const auto *Tmpl
= dyn_cast
<FunctionTemplateDecl
>(ND
))
1082 ND
= Tmpl
->getTemplatedDecl();
1083 return isa
<CXXConstructorDecl
>(ND
);
1086 void ResultBuilder::MaybeAddResult(Result R
, DeclContext
*CurContext
) {
1087 assert(!ShadowMaps
.empty() && "Must enter into a results scope");
1089 if (R
.Kind
!= Result::RK_Declaration
) {
1090 // For non-declaration results, just add the result.
1091 Results
.push_back(R
);
1095 // Look through using declarations.
1096 if (const UsingShadowDecl
*Using
= dyn_cast
<UsingShadowDecl
>(R
.Declaration
)) {
1097 CodeCompletionResult
Result(Using
->getTargetDecl(),
1098 getBasePriority(Using
->getTargetDecl()),
1100 (R
.Availability
== CXAvailability_Available
||
1101 R
.Availability
== CXAvailability_Deprecated
),
1102 std::move(R
.FixIts
));
1103 Result
.ShadowDecl
= Using
;
1104 MaybeAddResult(Result
, CurContext
);
1108 const Decl
*CanonDecl
= R
.Declaration
->getCanonicalDecl();
1109 unsigned IDNS
= CanonDecl
->getIdentifierNamespace();
1111 bool AsNestedNameSpecifier
= false;
1112 if (!isInterestingDecl(R
.Declaration
, AsNestedNameSpecifier
))
1115 // C++ constructors are never found by name lookup.
1116 if (isConstructor(R
.Declaration
))
1119 ShadowMap
&SMap
= ShadowMaps
.back();
1120 ShadowMapEntry::iterator I
, IEnd
;
1121 ShadowMap::iterator NamePos
= SMap
.find(R
.Declaration
->getDeclName());
1122 if (NamePos
!= SMap
.end()) {
1123 I
= NamePos
->second
.begin();
1124 IEnd
= NamePos
->second
.end();
1127 for (; I
!= IEnd
; ++I
) {
1128 const NamedDecl
*ND
= I
->first
;
1129 unsigned Index
= I
->second
;
1130 if (ND
->getCanonicalDecl() == CanonDecl
) {
1131 // This is a redeclaration. Always pick the newer declaration.
1132 Results
[Index
].Declaration
= R
.Declaration
;
1139 // This is a new declaration in this scope. However, check whether this
1140 // declaration name is hidden by a similarly-named declaration in an outer
1142 std::list
<ShadowMap
>::iterator SM
, SMEnd
= ShadowMaps
.end();
1144 for (SM
= ShadowMaps
.begin(); SM
!= SMEnd
; ++SM
) {
1145 ShadowMapEntry::iterator I
, IEnd
;
1146 ShadowMap::iterator NamePos
= SM
->find(R
.Declaration
->getDeclName());
1147 if (NamePos
!= SM
->end()) {
1148 I
= NamePos
->second
.begin();
1149 IEnd
= NamePos
->second
.end();
1151 for (; I
!= IEnd
; ++I
) {
1152 // A tag declaration does not hide a non-tag declaration.
1153 if (I
->first
->hasTagIdentifierNamespace() &&
1154 (IDNS
& (Decl::IDNS_Member
| Decl::IDNS_Ordinary
|
1155 Decl::IDNS_LocalExtern
| Decl::IDNS_ObjCProtocol
)))
1158 // Protocols are in distinct namespaces from everything else.
1159 if (((I
->first
->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol
) ||
1160 (IDNS
& Decl::IDNS_ObjCProtocol
)) &&
1161 I
->first
->getIdentifierNamespace() != IDNS
)
1164 // The newly-added result is hidden by an entry in the shadow map.
1165 if (CheckHiddenResult(R
, CurContext
, I
->first
))
1172 // Make sure that any given declaration only shows up in the result set once.
1173 if (!AllDeclsFound
.insert(CanonDecl
).second
)
1176 // If the filter is for nested-name-specifiers, then this result starts a
1177 // nested-name-specifier.
1178 if (AsNestedNameSpecifier
) {
1179 R
.StartsNestedNameSpecifier
= true;
1180 R
.Priority
= CCP_NestedNameSpecifier
;
1182 AdjustResultPriorityForDecl(R
);
1184 // If this result is supposed to have an informative qualifier, add one.
1185 if (R
.QualifierIsInformative
&& !R
.Qualifier
&&
1186 !R
.StartsNestedNameSpecifier
) {
1187 const DeclContext
*Ctx
= R
.Declaration
->getDeclContext();
1188 if (const NamespaceDecl
*Namespace
= dyn_cast
<NamespaceDecl
>(Ctx
))
1190 NestedNameSpecifier::Create(SemaRef
.Context
, nullptr, Namespace
);
1191 else if (const TagDecl
*Tag
= dyn_cast
<TagDecl
>(Ctx
))
1192 R
.Qualifier
= NestedNameSpecifier::Create(
1193 SemaRef
.Context
, nullptr, false,
1194 SemaRef
.Context
.getTypeDeclType(Tag
).getTypePtr());
1196 R
.QualifierIsInformative
= false;
1199 // Insert this result into the set of results and into the current shadow
1201 SMap
[R
.Declaration
->getDeclName()].Add(R
.Declaration
, Results
.size());
1202 Results
.push_back(R
);
1204 if (!AsNestedNameSpecifier
)
1205 MaybeAddConstructorResults(R
);
1208 static void setInBaseClass(ResultBuilder::Result
&R
) {
1209 R
.Priority
+= CCD_InBaseClass
;
1210 R
.InBaseClass
= true;
1213 enum class OverloadCompare
{ BothViable
, Dominates
, Dominated
};
1214 // Will Candidate ever be called on the object, when overloaded with Incumbent?
1215 // Returns Dominates if Candidate is always called, Dominated if Incumbent is
1216 // always called, BothViable if either may be called depending on arguments.
1217 // Precondition: must actually be overloads!
1218 static OverloadCompare
compareOverloads(const CXXMethodDecl
&Candidate
,
1219 const CXXMethodDecl
&Incumbent
,
1220 const Qualifiers
&ObjectQuals
,
1221 ExprValueKind ObjectKind
) {
1222 // Base/derived shadowing is handled elsewhere.
1223 if (Candidate
.getDeclContext() != Incumbent
.getDeclContext())
1224 return OverloadCompare::BothViable
;
1225 if (Candidate
.isVariadic() != Incumbent
.isVariadic() ||
1226 Candidate
.getNumParams() != Incumbent
.getNumParams() ||
1227 Candidate
.getMinRequiredArguments() !=
1228 Incumbent
.getMinRequiredArguments())
1229 return OverloadCompare::BothViable
;
1230 for (unsigned I
= 0, E
= Candidate
.getNumParams(); I
!= E
; ++I
)
1231 if (Candidate
.parameters()[I
]->getType().getCanonicalType() !=
1232 Incumbent
.parameters()[I
]->getType().getCanonicalType())
1233 return OverloadCompare::BothViable
;
1234 if (!Candidate
.specific_attrs
<EnableIfAttr
>().empty() ||
1235 !Incumbent
.specific_attrs
<EnableIfAttr
>().empty())
1236 return OverloadCompare::BothViable
;
1237 // At this point, we know calls can't pick one or the other based on
1238 // arguments, so one of the two must win. (Or both fail, handled elsewhere).
1239 RefQualifierKind CandidateRef
= Candidate
.getRefQualifier();
1240 RefQualifierKind IncumbentRef
= Incumbent
.getRefQualifier();
1241 if (CandidateRef
!= IncumbentRef
) {
1242 // If the object kind is LValue/RValue, there's one acceptable ref-qualifier
1243 // and it can't be mixed with ref-unqualified overloads (in valid code).
1245 // For xvalue objects, we prefer the rvalue overload even if we have to
1246 // add qualifiers (which is rare, because const&& is rare).
1247 if (ObjectKind
== clang::VK_XValue
)
1248 return CandidateRef
== RQ_RValue
? OverloadCompare::Dominates
1249 : OverloadCompare::Dominated
;
1251 // Now the ref qualifiers are the same (or we're in some invalid state).
1252 // So make some decision based on the qualifiers.
1253 Qualifiers CandidateQual
= Candidate
.getMethodQualifiers();
1254 Qualifiers IncumbentQual
= Incumbent
.getMethodQualifiers();
1255 bool CandidateSuperset
= CandidateQual
.compatiblyIncludes(IncumbentQual
);
1256 bool IncumbentSuperset
= IncumbentQual
.compatiblyIncludes(CandidateQual
);
1257 if (CandidateSuperset
== IncumbentSuperset
)
1258 return OverloadCompare::BothViable
;
1259 return IncumbentSuperset
? OverloadCompare::Dominates
1260 : OverloadCompare::Dominated
;
1263 void ResultBuilder::AddResult(Result R
, DeclContext
*CurContext
,
1264 NamedDecl
*Hiding
, bool InBaseClass
= false) {
1265 if (R
.Kind
!= Result::RK_Declaration
) {
1266 // For non-declaration results, just add the result.
1267 Results
.push_back(R
);
1271 // Look through using declarations.
1272 if (const auto *Using
= dyn_cast
<UsingShadowDecl
>(R
.Declaration
)) {
1273 CodeCompletionResult
Result(Using
->getTargetDecl(),
1274 getBasePriority(Using
->getTargetDecl()),
1276 (R
.Availability
== CXAvailability_Available
||
1277 R
.Availability
== CXAvailability_Deprecated
),
1278 std::move(R
.FixIts
));
1279 Result
.ShadowDecl
= Using
;
1280 AddResult(Result
, CurContext
, Hiding
);
1284 bool AsNestedNameSpecifier
= false;
1285 if (!isInterestingDecl(R
.Declaration
, AsNestedNameSpecifier
))
1288 // C++ constructors are never found by name lookup.
1289 if (isConstructor(R
.Declaration
))
1292 if (Hiding
&& CheckHiddenResult(R
, CurContext
, Hiding
))
1295 // Make sure that any given declaration only shows up in the result set once.
1296 if (!AllDeclsFound
.insert(R
.Declaration
->getCanonicalDecl()).second
)
1299 // If the filter is for nested-name-specifiers, then this result starts a
1300 // nested-name-specifier.
1301 if (AsNestedNameSpecifier
) {
1302 R
.StartsNestedNameSpecifier
= true;
1303 R
.Priority
= CCP_NestedNameSpecifier
;
1304 } else if (Filter
== &ResultBuilder::IsMember
&& !R
.Qualifier
&&
1307 R
.Declaration
->getDeclContext()->getRedeclContext()))
1308 R
.QualifierIsInformative
= true;
1310 // If this result is supposed to have an informative qualifier, add one.
1311 if (R
.QualifierIsInformative
&& !R
.Qualifier
&&
1312 !R
.StartsNestedNameSpecifier
) {
1313 const DeclContext
*Ctx
= R
.Declaration
->getDeclContext();
1314 if (const auto *Namespace
= dyn_cast
<NamespaceDecl
>(Ctx
))
1316 NestedNameSpecifier::Create(SemaRef
.Context
, nullptr, Namespace
);
1317 else if (const auto *Tag
= dyn_cast
<TagDecl
>(Ctx
))
1318 R
.Qualifier
= NestedNameSpecifier::Create(
1319 SemaRef
.Context
, nullptr, false,
1320 SemaRef
.Context
.getTypeDeclType(Tag
).getTypePtr());
1322 R
.QualifierIsInformative
= false;
1325 // Adjust the priority if this result comes from a base class.
1329 AdjustResultPriorityForDecl(R
);
1331 if (HasObjectTypeQualifiers
)
1332 if (const auto *Method
= dyn_cast
<CXXMethodDecl
>(R
.Declaration
))
1333 if (Method
->isInstance()) {
1334 Qualifiers MethodQuals
= Method
->getMethodQualifiers();
1335 if (ObjectTypeQualifiers
== MethodQuals
)
1336 R
.Priority
+= CCD_ObjectQualifierMatch
;
1337 else if (ObjectTypeQualifiers
- MethodQuals
) {
1338 // The method cannot be invoked, because doing so would drop
1342 // Detect cases where a ref-qualified method cannot be invoked.
1343 switch (Method
->getRefQualifier()) {
1345 if (ObjectKind
!= VK_LValue
&& !MethodQuals
.hasConst())
1349 if (ObjectKind
== VK_LValue
)
1356 /// Check whether this dominates another overloaded method, which should
1357 /// be suppressed (or vice versa).
1358 /// Motivating case is const_iterator begin() const vs iterator begin().
1359 auto &OverloadSet
= OverloadMap
[std::make_pair(
1360 CurContext
, Method
->getDeclName().getAsOpaqueInteger())];
1361 for (const DeclIndexPair Entry
: OverloadSet
) {
1362 Result
&Incumbent
= Results
[Entry
.second
];
1363 switch (compareOverloads(*Method
,
1364 *cast
<CXXMethodDecl
>(Incumbent
.Declaration
),
1365 ObjectTypeQualifiers
, ObjectKind
)) {
1366 case OverloadCompare::Dominates
:
1367 // Replace the dominated overload with this one.
1368 // FIXME: if the overload dominates multiple incumbents then we
1369 // should remove all. But two overloads is by far the common case.
1370 Incumbent
= std::move(R
);
1372 case OverloadCompare::Dominated
:
1373 // This overload can't be called, drop it.
1375 case OverloadCompare::BothViable
:
1379 OverloadSet
.Add(Method
, Results
.size());
1382 // Insert this result into the set of results.
1383 Results
.push_back(R
);
1385 if (!AsNestedNameSpecifier
)
1386 MaybeAddConstructorResults(R
);
1389 void ResultBuilder::AddResult(Result R
) {
1390 assert(R
.Kind
!= Result::RK_Declaration
&&
1391 "Declaration results need more context");
1392 Results
.push_back(R
);
1395 /// Enter into a new scope.
1396 void ResultBuilder::EnterNewScope() { ShadowMaps
.emplace_back(); }
1398 /// Exit from the current scope.
1399 void ResultBuilder::ExitScope() {
1400 ShadowMaps
.pop_back();
1403 /// Determines whether this given declaration will be found by
1404 /// ordinary name lookup.
1405 bool ResultBuilder::IsOrdinaryName(const NamedDecl
*ND
) const {
1406 ND
= ND
->getUnderlyingDecl();
1408 // If name lookup finds a local extern declaration, then we are in a
1409 // context where it behaves like an ordinary name.
1410 unsigned IDNS
= Decl::IDNS_Ordinary
| Decl::IDNS_LocalExtern
;
1411 if (SemaRef
.getLangOpts().CPlusPlus
)
1412 IDNS
|= Decl::IDNS_Tag
| Decl::IDNS_Namespace
| Decl::IDNS_Member
;
1413 else if (SemaRef
.getLangOpts().ObjC
) {
1414 if (isa
<ObjCIvarDecl
>(ND
))
1418 return ND
->getIdentifierNamespace() & IDNS
;
1421 /// Determines whether this given declaration will be found by
1422 /// ordinary name lookup but is not a type name.
1423 bool ResultBuilder::IsOrdinaryNonTypeName(const NamedDecl
*ND
) const {
1424 ND
= ND
->getUnderlyingDecl();
1425 if (isa
<TypeDecl
>(ND
))
1427 // Objective-C interfaces names are not filtered by this method because they
1428 // can be used in a class property expression. We can still filter out
1429 // @class declarations though.
1430 if (const auto *ID
= dyn_cast
<ObjCInterfaceDecl
>(ND
)) {
1431 if (!ID
->getDefinition())
1435 unsigned IDNS
= Decl::IDNS_Ordinary
| Decl::IDNS_LocalExtern
;
1436 if (SemaRef
.getLangOpts().CPlusPlus
)
1437 IDNS
|= Decl::IDNS_Tag
| Decl::IDNS_Namespace
| Decl::IDNS_Member
;
1438 else if (SemaRef
.getLangOpts().ObjC
) {
1439 if (isa
<ObjCIvarDecl
>(ND
))
1443 return ND
->getIdentifierNamespace() & IDNS
;
1446 bool ResultBuilder::IsIntegralConstantValue(const NamedDecl
*ND
) const {
1447 if (!IsOrdinaryNonTypeName(ND
))
1450 if (const auto *VD
= dyn_cast
<ValueDecl
>(ND
->getUnderlyingDecl()))
1451 if (VD
->getType()->isIntegralOrEnumerationType())
1457 /// Determines whether this given declaration will be found by
1458 /// ordinary name lookup.
1459 bool ResultBuilder::IsOrdinaryNonValueName(const NamedDecl
*ND
) const {
1460 ND
= ND
->getUnderlyingDecl();
1462 unsigned IDNS
= Decl::IDNS_Ordinary
| Decl::IDNS_LocalExtern
;
1463 if (SemaRef
.getLangOpts().CPlusPlus
)
1464 IDNS
|= Decl::IDNS_Tag
| Decl::IDNS_Namespace
;
1466 return (ND
->getIdentifierNamespace() & IDNS
) && !isa
<ValueDecl
>(ND
) &&
1467 !isa
<FunctionTemplateDecl
>(ND
) && !isa
<ObjCPropertyDecl
>(ND
);
1470 /// Determines whether the given declaration is suitable as the
1471 /// start of a C++ nested-name-specifier, e.g., a class or namespace.
1472 bool ResultBuilder::IsNestedNameSpecifier(const NamedDecl
*ND
) const {
1473 // Allow us to find class templates, too.
1474 if (const auto *ClassTemplate
= dyn_cast
<ClassTemplateDecl
>(ND
))
1475 ND
= ClassTemplate
->getTemplatedDecl();
1477 return SemaRef
.isAcceptableNestedNameSpecifier(ND
);
1480 /// Determines whether the given declaration is an enumeration.
1481 bool ResultBuilder::IsEnum(const NamedDecl
*ND
) const {
1482 return isa
<EnumDecl
>(ND
);
1485 /// Determines whether the given declaration is a class or struct.
1486 bool ResultBuilder::IsClassOrStruct(const NamedDecl
*ND
) const {
1487 // Allow us to find class templates, too.
1488 if (const auto *ClassTemplate
= dyn_cast
<ClassTemplateDecl
>(ND
))
1489 ND
= ClassTemplate
->getTemplatedDecl();
1491 // For purposes of this check, interfaces match too.
1492 if (const auto *RD
= dyn_cast
<RecordDecl
>(ND
))
1493 return RD
->getTagKind() == TTK_Class
|| RD
->getTagKind() == TTK_Struct
||
1494 RD
->getTagKind() == TTK_Interface
;
1499 /// Determines whether the given declaration is a union.
1500 bool ResultBuilder::IsUnion(const NamedDecl
*ND
) const {
1501 // Allow us to find class templates, too.
1502 if (const auto *ClassTemplate
= dyn_cast
<ClassTemplateDecl
>(ND
))
1503 ND
= ClassTemplate
->getTemplatedDecl();
1505 if (const auto *RD
= dyn_cast
<RecordDecl
>(ND
))
1506 return RD
->getTagKind() == TTK_Union
;
1511 /// Determines whether the given declaration is a namespace.
1512 bool ResultBuilder::IsNamespace(const NamedDecl
*ND
) const {
1513 return isa
<NamespaceDecl
>(ND
);
1516 /// Determines whether the given declaration is a namespace or
1517 /// namespace alias.
1518 bool ResultBuilder::IsNamespaceOrAlias(const NamedDecl
*ND
) const {
1519 return isa
<NamespaceDecl
>(ND
->getUnderlyingDecl());
1522 /// Determines whether the given declaration is a type.
1523 bool ResultBuilder::IsType(const NamedDecl
*ND
) const {
1524 ND
= ND
->getUnderlyingDecl();
1525 return isa
<TypeDecl
>(ND
) || isa
<ObjCInterfaceDecl
>(ND
);
1528 /// Determines which members of a class should be visible via
1529 /// "." or "->". Only value declarations, nested name specifiers, and
1530 /// using declarations thereof should show up.
1531 bool ResultBuilder::IsMember(const NamedDecl
*ND
) const {
1532 ND
= ND
->getUnderlyingDecl();
1533 return isa
<ValueDecl
>(ND
) || isa
<FunctionTemplateDecl
>(ND
) ||
1534 isa
<ObjCPropertyDecl
>(ND
);
1537 static bool isObjCReceiverType(ASTContext
&C
, QualType T
) {
1538 T
= C
.getCanonicalType(T
);
1539 switch (T
->getTypeClass()) {
1540 case Type::ObjCObject
:
1541 case Type::ObjCInterface
:
1542 case Type::ObjCObjectPointer
:
1546 switch (cast
<BuiltinType
>(T
)->getKind()) {
1547 case BuiltinType::ObjCId
:
1548 case BuiltinType::ObjCClass
:
1549 case BuiltinType::ObjCSel
:
1561 if (!C
.getLangOpts().CPlusPlus
)
1564 // FIXME: We could perform more analysis here to determine whether a
1565 // particular class type has any conversions to Objective-C types. For now,
1566 // just accept all class types.
1567 return T
->isDependentType() || T
->isRecordType();
1570 bool ResultBuilder::IsObjCMessageReceiver(const NamedDecl
*ND
) const {
1571 QualType T
= getDeclUsageType(SemaRef
.Context
, ND
);
1575 T
= SemaRef
.Context
.getBaseElementType(T
);
1576 return isObjCReceiverType(SemaRef
.Context
, T
);
1579 bool ResultBuilder::IsObjCMessageReceiverOrLambdaCapture(
1580 const NamedDecl
*ND
) const {
1581 if (IsObjCMessageReceiver(ND
))
1584 const auto *Var
= dyn_cast
<VarDecl
>(ND
);
1588 return Var
->hasLocalStorage() && !Var
->hasAttr
<BlocksAttr
>();
1591 bool ResultBuilder::IsObjCCollection(const NamedDecl
*ND
) const {
1592 if ((SemaRef
.getLangOpts().CPlusPlus
&& !IsOrdinaryName(ND
)) ||
1593 (!SemaRef
.getLangOpts().CPlusPlus
&& !IsOrdinaryNonTypeName(ND
)))
1596 QualType T
= getDeclUsageType(SemaRef
.Context
, ND
);
1600 T
= SemaRef
.Context
.getBaseElementType(T
);
1601 return T
->isObjCObjectType() || T
->isObjCObjectPointerType() ||
1602 T
->isObjCIdType() ||
1603 (SemaRef
.getLangOpts().CPlusPlus
&& T
->isRecordType());
1606 bool ResultBuilder::IsImpossibleToSatisfy(const NamedDecl
*ND
) const {
1610 /// Determines whether the given declaration is an Objective-C
1611 /// instance variable.
1612 bool ResultBuilder::IsObjCIvar(const NamedDecl
*ND
) const {
1613 return isa
<ObjCIvarDecl
>(ND
);
1618 /// Visible declaration consumer that adds a code-completion result
1619 /// for each visible declaration.
1620 class CodeCompletionDeclConsumer
: public VisibleDeclConsumer
{
1621 ResultBuilder
&Results
;
1622 DeclContext
*InitialLookupCtx
;
1623 // NamingClass and BaseType are used for access-checking. See
1624 // Sema::IsSimplyAccessible for details.
1625 CXXRecordDecl
*NamingClass
;
1627 std::vector
<FixItHint
> FixIts
;
1630 CodeCompletionDeclConsumer(
1631 ResultBuilder
&Results
, DeclContext
*InitialLookupCtx
,
1632 QualType BaseType
= QualType(),
1633 std::vector
<FixItHint
> FixIts
= std::vector
<FixItHint
>())
1634 : Results(Results
), InitialLookupCtx(InitialLookupCtx
),
1635 FixIts(std::move(FixIts
)) {
1636 NamingClass
= llvm::dyn_cast
<CXXRecordDecl
>(InitialLookupCtx
);
1637 // If BaseType was not provided explicitly, emulate implicit 'this->'.
1638 if (BaseType
.isNull()) {
1639 auto ThisType
= Results
.getSema().getCurrentThisType();
1640 if (!ThisType
.isNull()) {
1641 assert(ThisType
->isPointerType());
1642 BaseType
= ThisType
->getPointeeType();
1644 NamingClass
= BaseType
->getAsCXXRecordDecl();
1647 this->BaseType
= BaseType
;
1650 void FoundDecl(NamedDecl
*ND
, NamedDecl
*Hiding
, DeclContext
*Ctx
,
1651 bool InBaseClass
) override
{
1652 ResultBuilder::Result
Result(ND
, Results
.getBasePriority(ND
), nullptr,
1653 false, IsAccessible(ND
, Ctx
), FixIts
);
1654 Results
.AddResult(Result
, InitialLookupCtx
, Hiding
, InBaseClass
);
1657 void EnteredContext(DeclContext
*Ctx
) override
{
1658 Results
.addVisitedContext(Ctx
);
1662 bool IsAccessible(NamedDecl
*ND
, DeclContext
*Ctx
) {
1663 // Naming class to use for access check. In most cases it was provided
1664 // explicitly (e.g. member access (lhs.foo) or qualified lookup (X::)),
1665 // for unqualified lookup we fallback to the \p Ctx in which we found the
1667 auto *NamingClass
= this->NamingClass
;
1668 QualType BaseType
= this->BaseType
;
1669 if (auto *Cls
= llvm::dyn_cast_or_null
<CXXRecordDecl
>(Ctx
)) {
1672 // When we emulate implicit 'this->' in an unqualified lookup, we might
1673 // end up with an invalid naming class. In that case, we avoid emulating
1674 // 'this->' qualifier to satisfy preconditions of the access checking.
1675 if (NamingClass
->getCanonicalDecl() != Cls
->getCanonicalDecl() &&
1676 !NamingClass
->isDerivedFrom(Cls
)) {
1678 BaseType
= QualType();
1681 // The decl was found outside the C++ class, so only ObjC access checks
1682 // apply. Those do not rely on NamingClass and BaseType, so we clear them
1684 NamingClass
= nullptr;
1685 BaseType
= QualType();
1687 return Results
.getSema().IsSimplyAccessible(ND
, NamingClass
, BaseType
);
1692 /// Add type specifiers for the current language as keyword results.
1693 static void AddTypeSpecifierResults(const LangOptions
&LangOpts
,
1694 ResultBuilder
&Results
) {
1695 typedef CodeCompletionResult Result
;
1696 Results
.AddResult(Result("short", CCP_Type
));
1697 Results
.AddResult(Result("long", CCP_Type
));
1698 Results
.AddResult(Result("signed", CCP_Type
));
1699 Results
.AddResult(Result("unsigned", CCP_Type
));
1700 Results
.AddResult(Result("void", CCP_Type
));
1701 Results
.AddResult(Result("char", CCP_Type
));
1702 Results
.AddResult(Result("int", CCP_Type
));
1703 Results
.AddResult(Result("float", CCP_Type
));
1704 Results
.AddResult(Result("double", CCP_Type
));
1705 Results
.AddResult(Result("enum", CCP_Type
));
1706 Results
.AddResult(Result("struct", CCP_Type
));
1707 Results
.AddResult(Result("union", CCP_Type
));
1708 Results
.AddResult(Result("const", CCP_Type
));
1709 Results
.AddResult(Result("volatile", CCP_Type
));
1713 Results
.AddResult(Result("_Complex", CCP_Type
));
1714 Results
.AddResult(Result("_Imaginary", CCP_Type
));
1715 Results
.AddResult(Result("_Bool", CCP_Type
));
1716 Results
.AddResult(Result("restrict", CCP_Type
));
1719 CodeCompletionBuilder
Builder(Results
.getAllocator(),
1720 Results
.getCodeCompletionTUInfo());
1721 if (LangOpts
.CPlusPlus
) {
1724 Result("bool", CCP_Type
+ (LangOpts
.ObjC
? CCD_bool_in_ObjC
: 0)));
1725 Results
.AddResult(Result("class", CCP_Type
));
1726 Results
.AddResult(Result("wchar_t", CCP_Type
));
1729 Builder
.AddTypedTextChunk("typename");
1730 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
1731 Builder
.AddPlaceholderChunk("name");
1732 Results
.AddResult(Result(Builder
.TakeString()));
1734 if (LangOpts
.CPlusPlus11
) {
1735 Results
.AddResult(Result("auto", CCP_Type
));
1736 Results
.AddResult(Result("char16_t", CCP_Type
));
1737 Results
.AddResult(Result("char32_t", CCP_Type
));
1739 Builder
.AddTypedTextChunk("decltype");
1740 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
1741 Builder
.AddPlaceholderChunk("expression");
1742 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
1743 Results
.AddResult(Result(Builder
.TakeString()));
1746 Results
.AddResult(Result("__auto_type", CCP_Type
));
1749 if (LangOpts
.GNUKeywords
) {
1750 // FIXME: Enable when we actually support decimal floating point.
1751 // Results.AddResult(Result("_Decimal32"));
1752 // Results.AddResult(Result("_Decimal64"));
1753 // Results.AddResult(Result("_Decimal128"));
1755 Builder
.AddTypedTextChunk("typeof");
1756 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
1757 Builder
.AddPlaceholderChunk("expression");
1758 Results
.AddResult(Result(Builder
.TakeString()));
1760 Builder
.AddTypedTextChunk("typeof");
1761 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
1762 Builder
.AddPlaceholderChunk("type");
1763 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
1764 Results
.AddResult(Result(Builder
.TakeString()));
1768 Results
.AddResult(Result("_Nonnull", CCP_Type
));
1769 Results
.AddResult(Result("_Null_unspecified", CCP_Type
));
1770 Results
.AddResult(Result("_Nullable", CCP_Type
));
1773 static void AddStorageSpecifiers(Sema::ParserCompletionContext CCC
,
1774 const LangOptions
&LangOpts
,
1775 ResultBuilder
&Results
) {
1776 typedef CodeCompletionResult Result
;
1777 // Note: we don't suggest either "auto" or "register", because both
1778 // are pointless as storage specifiers. Elsewhere, we suggest "auto"
1779 // in C++0x as a type specifier.
1780 Results
.AddResult(Result("extern"));
1781 Results
.AddResult(Result("static"));
1783 if (LangOpts
.CPlusPlus11
) {
1784 CodeCompletionAllocator
&Allocator
= Results
.getAllocator();
1785 CodeCompletionBuilder
Builder(Allocator
, Results
.getCodeCompletionTUInfo());
1788 Builder
.AddTypedTextChunk("alignas");
1789 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
1790 Builder
.AddPlaceholderChunk("expression");
1791 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
1792 Results
.AddResult(Result(Builder
.TakeString()));
1794 Results
.AddResult(Result("constexpr"));
1795 Results
.AddResult(Result("thread_local"));
1799 static void AddFunctionSpecifiers(Sema::ParserCompletionContext CCC
,
1800 const LangOptions
&LangOpts
,
1801 ResultBuilder
&Results
) {
1802 typedef CodeCompletionResult Result
;
1804 case Sema::PCC_Class
:
1805 case Sema::PCC_MemberTemplate
:
1806 if (LangOpts
.CPlusPlus
) {
1807 Results
.AddResult(Result("explicit"));
1808 Results
.AddResult(Result("friend"));
1809 Results
.AddResult(Result("mutable"));
1810 Results
.AddResult(Result("virtual"));
1814 case Sema::PCC_ObjCInterface
:
1815 case Sema::PCC_ObjCImplementation
:
1816 case Sema::PCC_Namespace
:
1817 case Sema::PCC_Template
:
1818 if (LangOpts
.CPlusPlus
|| LangOpts
.C99
)
1819 Results
.AddResult(Result("inline"));
1822 case Sema::PCC_ObjCInstanceVariableList
:
1823 case Sema::PCC_Expression
:
1824 case Sema::PCC_Statement
:
1825 case Sema::PCC_ForInit
:
1826 case Sema::PCC_Condition
:
1827 case Sema::PCC_RecoveryInFunction
:
1828 case Sema::PCC_Type
:
1829 case Sema::PCC_ParenthesizedExpression
:
1830 case Sema::PCC_LocalDeclarationSpecifiers
:
1835 static void AddObjCExpressionResults(ResultBuilder
&Results
, bool NeedAt
);
1836 static void AddObjCStatementResults(ResultBuilder
&Results
, bool NeedAt
);
1837 static void AddObjCVisibilityResults(const LangOptions
&LangOpts
,
1838 ResultBuilder
&Results
, bool NeedAt
);
1839 static void AddObjCImplementationResults(const LangOptions
&LangOpts
,
1840 ResultBuilder
&Results
, bool NeedAt
);
1841 static void AddObjCInterfaceResults(const LangOptions
&LangOpts
,
1842 ResultBuilder
&Results
, bool NeedAt
);
1843 static void AddObjCTopLevelResults(ResultBuilder
&Results
, bool NeedAt
);
1845 static void AddTypedefResult(ResultBuilder
&Results
) {
1846 CodeCompletionBuilder
Builder(Results
.getAllocator(),
1847 Results
.getCodeCompletionTUInfo());
1848 Builder
.AddTypedTextChunk("typedef");
1849 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
1850 Builder
.AddPlaceholderChunk("type");
1851 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
1852 Builder
.AddPlaceholderChunk("name");
1853 Builder
.AddChunk(CodeCompletionString::CK_SemiColon
);
1854 Results
.AddResult(CodeCompletionResult(Builder
.TakeString()));
1857 // using name = type
1858 static void AddUsingAliasResult(CodeCompletionBuilder
&Builder
,
1859 ResultBuilder
&Results
) {
1860 Builder
.AddTypedTextChunk("using");
1861 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
1862 Builder
.AddPlaceholderChunk("name");
1863 Builder
.AddChunk(CodeCompletionString::CK_Equal
);
1864 Builder
.AddPlaceholderChunk("type");
1865 Builder
.AddChunk(CodeCompletionString::CK_SemiColon
);
1866 Results
.AddResult(CodeCompletionResult(Builder
.TakeString()));
1869 static bool WantTypesInContext(Sema::ParserCompletionContext CCC
,
1870 const LangOptions
&LangOpts
) {
1872 case Sema::PCC_Namespace
:
1873 case Sema::PCC_Class
:
1874 case Sema::PCC_ObjCInstanceVariableList
:
1875 case Sema::PCC_Template
:
1876 case Sema::PCC_MemberTemplate
:
1877 case Sema::PCC_Statement
:
1878 case Sema::PCC_RecoveryInFunction
:
1879 case Sema::PCC_Type
:
1880 case Sema::PCC_ParenthesizedExpression
:
1881 case Sema::PCC_LocalDeclarationSpecifiers
:
1884 case Sema::PCC_Expression
:
1885 case Sema::PCC_Condition
:
1886 return LangOpts
.CPlusPlus
;
1888 case Sema::PCC_ObjCInterface
:
1889 case Sema::PCC_ObjCImplementation
:
1892 case Sema::PCC_ForInit
:
1893 return LangOpts
.CPlusPlus
|| LangOpts
.ObjC
|| LangOpts
.C99
;
1896 llvm_unreachable("Invalid ParserCompletionContext!");
1899 static PrintingPolicy
getCompletionPrintingPolicy(const ASTContext
&Context
,
1900 const Preprocessor
&PP
) {
1901 PrintingPolicy Policy
= Sema::getPrintingPolicy(Context
, PP
);
1902 Policy
.AnonymousTagLocations
= false;
1903 Policy
.SuppressStrongLifetime
= true;
1904 Policy
.SuppressUnwrittenScope
= true;
1905 Policy
.SuppressScope
= true;
1906 Policy
.CleanUglifiedParameters
= true;
1910 /// Retrieve a printing policy suitable for code completion.
1911 static PrintingPolicy
getCompletionPrintingPolicy(Sema
&S
) {
1912 return getCompletionPrintingPolicy(S
.Context
, S
.PP
);
1915 /// Retrieve the string representation of the given type as a string
1916 /// that has the appropriate lifetime for code completion.
1918 /// This routine provides a fast path where we provide constant strings for
1919 /// common type names.
1920 static const char *GetCompletionTypeString(QualType T
, ASTContext
&Context
,
1921 const PrintingPolicy
&Policy
,
1922 CodeCompletionAllocator
&Allocator
) {
1923 if (!T
.getLocalQualifiers()) {
1924 // Built-in type names are constant strings.
1925 if (const BuiltinType
*BT
= dyn_cast
<BuiltinType
>(T
))
1926 return BT
->getNameAsCString(Policy
);
1928 // Anonymous tag types are constant strings.
1929 if (const TagType
*TagT
= dyn_cast
<TagType
>(T
))
1930 if (TagDecl
*Tag
= TagT
->getDecl())
1931 if (!Tag
->hasNameForLinkage()) {
1932 switch (Tag
->getTagKind()) {
1934 return "struct <anonymous>";
1936 return "__interface <anonymous>";
1938 return "class <anonymous>";
1940 return "union <anonymous>";
1942 return "enum <anonymous>";
1947 // Slow path: format the type as a string.
1949 T
.getAsStringInternal(Result
, Policy
);
1950 return Allocator
.CopyString(Result
);
1953 /// Add a completion for "this", if we're in a member function.
1954 static void addThisCompletion(Sema
&S
, ResultBuilder
&Results
) {
1955 QualType ThisTy
= S
.getCurrentThisType();
1956 if (ThisTy
.isNull())
1959 CodeCompletionAllocator
&Allocator
= Results
.getAllocator();
1960 CodeCompletionBuilder
Builder(Allocator
, Results
.getCodeCompletionTUInfo());
1961 PrintingPolicy Policy
= getCompletionPrintingPolicy(S
);
1962 Builder
.AddResultTypeChunk(
1963 GetCompletionTypeString(ThisTy
, S
.Context
, Policy
, Allocator
));
1964 Builder
.AddTypedTextChunk("this");
1965 Results
.AddResult(CodeCompletionResult(Builder
.TakeString()));
1968 static void AddStaticAssertResult(CodeCompletionBuilder
&Builder
,
1969 ResultBuilder
&Results
,
1970 const LangOptions
&LangOpts
) {
1971 if (!LangOpts
.CPlusPlus11
)
1974 Builder
.AddTypedTextChunk("static_assert");
1975 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
1976 Builder
.AddPlaceholderChunk("expression");
1977 Builder
.AddChunk(CodeCompletionString::CK_Comma
);
1978 Builder
.AddPlaceholderChunk("message");
1979 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
1980 Builder
.AddChunk(CodeCompletionString::CK_SemiColon
);
1981 Results
.AddResult(CodeCompletionResult(Builder
.TakeString()));
1984 static void AddOverrideResults(ResultBuilder
&Results
,
1985 const CodeCompletionContext
&CCContext
,
1986 CodeCompletionBuilder
&Builder
) {
1987 Sema
&S
= Results
.getSema();
1988 const auto *CR
= llvm::dyn_cast
<CXXRecordDecl
>(S
.CurContext
);
1989 // If not inside a class/struct/union return empty.
1992 // First store overrides within current class.
1993 // These are stored by name to make querying fast in the later step.
1994 llvm::StringMap
<std::vector
<FunctionDecl
*>> Overrides
;
1995 for (auto *Method
: CR
->methods()) {
1996 if (!Method
->isVirtual() || !Method
->getIdentifier())
1998 Overrides
[Method
->getName()].push_back(Method
);
2001 for (const auto &Base
: CR
->bases()) {
2002 const auto *BR
= Base
.getType().getTypePtr()->getAsCXXRecordDecl();
2005 for (auto *Method
: BR
->methods()) {
2006 if (!Method
->isVirtual() || !Method
->getIdentifier())
2008 const auto it
= Overrides
.find(Method
->getName());
2009 bool IsOverriden
= false;
2010 if (it
!= Overrides
.end()) {
2011 for (auto *MD
: it
->second
) {
2012 // If the method in current body is not an overload of this virtual
2013 // function, then it overrides this one.
2014 if (!S
.IsOverload(MD
, Method
, false)) {
2021 // Generates a new CodeCompletionResult by taking this function and
2022 // converting it into an override declaration with only one chunk in the
2023 // final CodeCompletionString as a TypedTextChunk.
2024 std::string OverrideSignature
;
2025 llvm::raw_string_ostream
OS(OverrideSignature
);
2026 CodeCompletionResult
CCR(Method
, 0);
2027 PrintingPolicy Policy
=
2028 getCompletionPrintingPolicy(S
.getASTContext(), S
.getPreprocessor());
2029 auto *CCS
= CCR
.createCodeCompletionStringForOverride(
2030 S
.getPreprocessor(), S
.getASTContext(), Builder
,
2031 /*IncludeBriefComments=*/false, CCContext
, Policy
);
2032 Results
.AddResult(CodeCompletionResult(CCS
, Method
, CCP_CodePattern
));
2038 /// Add language constructs that show up for "ordinary" names.
2039 static void AddOrdinaryNameResults(Sema::ParserCompletionContext CCC
, Scope
*S
,
2040 Sema
&SemaRef
, ResultBuilder
&Results
) {
2041 CodeCompletionAllocator
&Allocator
= Results
.getAllocator();
2042 CodeCompletionBuilder
Builder(Allocator
, Results
.getCodeCompletionTUInfo());
2044 typedef CodeCompletionResult Result
;
2046 case Sema::PCC_Namespace
:
2047 if (SemaRef
.getLangOpts().CPlusPlus
) {
2048 if (Results
.includeCodePatterns()) {
2049 // namespace <identifier> { declarations }
2050 Builder
.AddTypedTextChunk("namespace");
2051 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2052 Builder
.AddPlaceholderChunk("identifier");
2053 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2054 Builder
.AddChunk(CodeCompletionString::CK_LeftBrace
);
2055 Builder
.AddChunk(CodeCompletionString::CK_VerticalSpace
);
2056 Builder
.AddPlaceholderChunk("declarations");
2057 Builder
.AddChunk(CodeCompletionString::CK_VerticalSpace
);
2058 Builder
.AddChunk(CodeCompletionString::CK_RightBrace
);
2059 Results
.AddResult(Result(Builder
.TakeString()));
2062 // namespace identifier = identifier ;
2063 Builder
.AddTypedTextChunk("namespace");
2064 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2065 Builder
.AddPlaceholderChunk("name");
2066 Builder
.AddChunk(CodeCompletionString::CK_Equal
);
2067 Builder
.AddPlaceholderChunk("namespace");
2068 Builder
.AddChunk(CodeCompletionString::CK_SemiColon
);
2069 Results
.AddResult(Result(Builder
.TakeString()));
2072 Builder
.AddTypedTextChunk("using namespace");
2073 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2074 Builder
.AddPlaceholderChunk("identifier");
2075 Builder
.AddChunk(CodeCompletionString::CK_SemiColon
);
2076 Results
.AddResult(Result(Builder
.TakeString()));
2078 // asm(string-literal)
2079 Builder
.AddTypedTextChunk("asm");
2080 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
2081 Builder
.AddPlaceholderChunk("string-literal");
2082 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
2083 Results
.AddResult(Result(Builder
.TakeString()));
2085 if (Results
.includeCodePatterns()) {
2086 // Explicit template instantiation
2087 Builder
.AddTypedTextChunk("template");
2088 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2089 Builder
.AddPlaceholderChunk("declaration");
2090 Results
.AddResult(Result(Builder
.TakeString()));
2092 Results
.AddResult(Result("template", CodeCompletionResult::RK_Keyword
));
2096 if (SemaRef
.getLangOpts().ObjC
)
2097 AddObjCTopLevelResults(Results
, true);
2099 AddTypedefResult(Results
);
2102 case Sema::PCC_Class
:
2103 if (SemaRef
.getLangOpts().CPlusPlus
) {
2104 // Using declaration
2105 Builder
.AddTypedTextChunk("using");
2106 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2107 Builder
.AddPlaceholderChunk("qualifier");
2108 Builder
.AddTextChunk("::");
2109 Builder
.AddPlaceholderChunk("name");
2110 Builder
.AddChunk(CodeCompletionString::CK_SemiColon
);
2111 Results
.AddResult(Result(Builder
.TakeString()));
2113 if (SemaRef
.getLangOpts().CPlusPlus11
)
2114 AddUsingAliasResult(Builder
, Results
);
2116 // using typename qualifier::name (only in a dependent context)
2117 if (SemaRef
.CurContext
->isDependentContext()) {
2118 Builder
.AddTypedTextChunk("using typename");
2119 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2120 Builder
.AddPlaceholderChunk("qualifier");
2121 Builder
.AddTextChunk("::");
2122 Builder
.AddPlaceholderChunk("name");
2123 Builder
.AddChunk(CodeCompletionString::CK_SemiColon
);
2124 Results
.AddResult(Result(Builder
.TakeString()));
2127 AddStaticAssertResult(Builder
, Results
, SemaRef
.getLangOpts());
2129 if (CCC
== Sema::PCC_Class
) {
2130 AddTypedefResult(Results
);
2132 bool IsNotInheritanceScope
= !S
->isClassInheritanceScope();
2134 Builder
.AddTypedTextChunk("public");
2135 if (IsNotInheritanceScope
&& Results
.includeCodePatterns())
2136 Builder
.AddChunk(CodeCompletionString::CK_Colon
);
2137 Results
.AddResult(Result(Builder
.TakeString()));
2140 Builder
.AddTypedTextChunk("protected");
2141 if (IsNotInheritanceScope
&& Results
.includeCodePatterns())
2142 Builder
.AddChunk(CodeCompletionString::CK_Colon
);
2143 Results
.AddResult(Result(Builder
.TakeString()));
2146 Builder
.AddTypedTextChunk("private");
2147 if (IsNotInheritanceScope
&& Results
.includeCodePatterns())
2148 Builder
.AddChunk(CodeCompletionString::CK_Colon
);
2149 Results
.AddResult(Result(Builder
.TakeString()));
2151 // FIXME: This adds override results only if we are at the first word of
2152 // the declaration/definition. Also call this from other sides to have
2154 AddOverrideResults(Results
, CodeCompletionContext::CCC_ClassStructUnion
,
2160 case Sema::PCC_Template
:
2161 case Sema::PCC_MemberTemplate
:
2162 if (SemaRef
.getLangOpts().CPlusPlus
&& Results
.includeCodePatterns()) {
2163 // template < parameters >
2164 Builder
.AddTypedTextChunk("template");
2165 Builder
.AddChunk(CodeCompletionString::CK_LeftAngle
);
2166 Builder
.AddPlaceholderChunk("parameters");
2167 Builder
.AddChunk(CodeCompletionString::CK_RightAngle
);
2168 Results
.AddResult(Result(Builder
.TakeString()));
2170 Results
.AddResult(Result("template", CodeCompletionResult::RK_Keyword
));
2173 AddStorageSpecifiers(CCC
, SemaRef
.getLangOpts(), Results
);
2174 AddFunctionSpecifiers(CCC
, SemaRef
.getLangOpts(), Results
);
2177 case Sema::PCC_ObjCInterface
:
2178 AddObjCInterfaceResults(SemaRef
.getLangOpts(), Results
, true);
2179 AddStorageSpecifiers(CCC
, SemaRef
.getLangOpts(), Results
);
2180 AddFunctionSpecifiers(CCC
, SemaRef
.getLangOpts(), Results
);
2183 case Sema::PCC_ObjCImplementation
:
2184 AddObjCImplementationResults(SemaRef
.getLangOpts(), Results
, true);
2185 AddStorageSpecifiers(CCC
, SemaRef
.getLangOpts(), Results
);
2186 AddFunctionSpecifiers(CCC
, SemaRef
.getLangOpts(), Results
);
2189 case Sema::PCC_ObjCInstanceVariableList
:
2190 AddObjCVisibilityResults(SemaRef
.getLangOpts(), Results
, true);
2193 case Sema::PCC_RecoveryInFunction
:
2194 case Sema::PCC_Statement
: {
2195 if (SemaRef
.getLangOpts().CPlusPlus11
)
2196 AddUsingAliasResult(Builder
, Results
);
2198 AddTypedefResult(Results
);
2200 if (SemaRef
.getLangOpts().CPlusPlus
&& Results
.includeCodePatterns() &&
2201 SemaRef
.getLangOpts().CXXExceptions
) {
2202 Builder
.AddTypedTextChunk("try");
2203 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2204 Builder
.AddChunk(CodeCompletionString::CK_LeftBrace
);
2205 Builder
.AddChunk(CodeCompletionString::CK_VerticalSpace
);
2206 Builder
.AddPlaceholderChunk("statements");
2207 Builder
.AddChunk(CodeCompletionString::CK_VerticalSpace
);
2208 Builder
.AddChunk(CodeCompletionString::CK_RightBrace
);
2209 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2210 Builder
.AddTextChunk("catch");
2211 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2212 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
2213 Builder
.AddPlaceholderChunk("declaration");
2214 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
2215 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2216 Builder
.AddChunk(CodeCompletionString::CK_LeftBrace
);
2217 Builder
.AddChunk(CodeCompletionString::CK_VerticalSpace
);
2218 Builder
.AddPlaceholderChunk("statements");
2219 Builder
.AddChunk(CodeCompletionString::CK_VerticalSpace
);
2220 Builder
.AddChunk(CodeCompletionString::CK_RightBrace
);
2221 Results
.AddResult(Result(Builder
.TakeString()));
2223 if (SemaRef
.getLangOpts().ObjC
)
2224 AddObjCStatementResults(Results
, true);
2226 if (Results
.includeCodePatterns()) {
2227 // if (condition) { statements }
2228 Builder
.AddTypedTextChunk("if");
2229 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2230 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
2231 if (SemaRef
.getLangOpts().CPlusPlus
)
2232 Builder
.AddPlaceholderChunk("condition");
2234 Builder
.AddPlaceholderChunk("expression");
2235 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
2236 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2237 Builder
.AddChunk(CodeCompletionString::CK_LeftBrace
);
2238 Builder
.AddChunk(CodeCompletionString::CK_VerticalSpace
);
2239 Builder
.AddPlaceholderChunk("statements");
2240 Builder
.AddChunk(CodeCompletionString::CK_VerticalSpace
);
2241 Builder
.AddChunk(CodeCompletionString::CK_RightBrace
);
2242 Results
.AddResult(Result(Builder
.TakeString()));
2244 // switch (condition) { }
2245 Builder
.AddTypedTextChunk("switch");
2246 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2247 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
2248 if (SemaRef
.getLangOpts().CPlusPlus
)
2249 Builder
.AddPlaceholderChunk("condition");
2251 Builder
.AddPlaceholderChunk("expression");
2252 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
2253 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2254 Builder
.AddChunk(CodeCompletionString::CK_LeftBrace
);
2255 Builder
.AddChunk(CodeCompletionString::CK_VerticalSpace
);
2256 Builder
.AddPlaceholderChunk("cases");
2257 Builder
.AddChunk(CodeCompletionString::CK_VerticalSpace
);
2258 Builder
.AddChunk(CodeCompletionString::CK_RightBrace
);
2259 Results
.AddResult(Result(Builder
.TakeString()));
2262 // Switch-specific statements.
2263 if (SemaRef
.getCurFunction() &&
2264 !SemaRef
.getCurFunction()->SwitchStack
.empty()) {
2266 Builder
.AddTypedTextChunk("case");
2267 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2268 Builder
.AddPlaceholderChunk("expression");
2269 Builder
.AddChunk(CodeCompletionString::CK_Colon
);
2270 Results
.AddResult(Result(Builder
.TakeString()));
2273 Builder
.AddTypedTextChunk("default");
2274 Builder
.AddChunk(CodeCompletionString::CK_Colon
);
2275 Results
.AddResult(Result(Builder
.TakeString()));
2278 if (Results
.includeCodePatterns()) {
2279 /// while (condition) { statements }
2280 Builder
.AddTypedTextChunk("while");
2281 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2282 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
2283 if (SemaRef
.getLangOpts().CPlusPlus
)
2284 Builder
.AddPlaceholderChunk("condition");
2286 Builder
.AddPlaceholderChunk("expression");
2287 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
2288 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2289 Builder
.AddChunk(CodeCompletionString::CK_LeftBrace
);
2290 Builder
.AddChunk(CodeCompletionString::CK_VerticalSpace
);
2291 Builder
.AddPlaceholderChunk("statements");
2292 Builder
.AddChunk(CodeCompletionString::CK_VerticalSpace
);
2293 Builder
.AddChunk(CodeCompletionString::CK_RightBrace
);
2294 Results
.AddResult(Result(Builder
.TakeString()));
2296 // do { statements } while ( expression );
2297 Builder
.AddTypedTextChunk("do");
2298 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2299 Builder
.AddChunk(CodeCompletionString::CK_LeftBrace
);
2300 Builder
.AddChunk(CodeCompletionString::CK_VerticalSpace
);
2301 Builder
.AddPlaceholderChunk("statements");
2302 Builder
.AddChunk(CodeCompletionString::CK_VerticalSpace
);
2303 Builder
.AddChunk(CodeCompletionString::CK_RightBrace
);
2304 Builder
.AddTextChunk("while");
2305 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2306 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
2307 Builder
.AddPlaceholderChunk("expression");
2308 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
2309 Results
.AddResult(Result(Builder
.TakeString()));
2311 // for ( for-init-statement ; condition ; expression ) { statements }
2312 Builder
.AddTypedTextChunk("for");
2313 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2314 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
2315 if (SemaRef
.getLangOpts().CPlusPlus
|| SemaRef
.getLangOpts().C99
)
2316 Builder
.AddPlaceholderChunk("init-statement");
2318 Builder
.AddPlaceholderChunk("init-expression");
2319 Builder
.AddChunk(CodeCompletionString::CK_SemiColon
);
2320 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2321 Builder
.AddPlaceholderChunk("condition");
2322 Builder
.AddChunk(CodeCompletionString::CK_SemiColon
);
2323 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2324 Builder
.AddPlaceholderChunk("inc-expression");
2325 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
2326 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2327 Builder
.AddChunk(CodeCompletionString::CK_LeftBrace
);
2328 Builder
.AddChunk(CodeCompletionString::CK_VerticalSpace
);
2329 Builder
.AddPlaceholderChunk("statements");
2330 Builder
.AddChunk(CodeCompletionString::CK_VerticalSpace
);
2331 Builder
.AddChunk(CodeCompletionString::CK_RightBrace
);
2332 Results
.AddResult(Result(Builder
.TakeString()));
2334 if (SemaRef
.getLangOpts().CPlusPlus11
|| SemaRef
.getLangOpts().ObjC
) {
2335 // for ( range_declaration (:|in) range_expression ) { statements }
2336 Builder
.AddTypedTextChunk("for");
2337 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2338 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
2339 Builder
.AddPlaceholderChunk("range-declaration");
2340 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2341 if (SemaRef
.getLangOpts().ObjC
)
2342 Builder
.AddTextChunk("in");
2344 Builder
.AddChunk(CodeCompletionString::CK_Colon
);
2345 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2346 Builder
.AddPlaceholderChunk("range-expression");
2347 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
2348 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2349 Builder
.AddChunk(CodeCompletionString::CK_LeftBrace
);
2350 Builder
.AddChunk(CodeCompletionString::CK_VerticalSpace
);
2351 Builder
.AddPlaceholderChunk("statements");
2352 Builder
.AddChunk(CodeCompletionString::CK_VerticalSpace
);
2353 Builder
.AddChunk(CodeCompletionString::CK_RightBrace
);
2354 Results
.AddResult(Result(Builder
.TakeString()));
2358 if (S
->getContinueParent()) {
2360 Builder
.AddTypedTextChunk("continue");
2361 Builder
.AddChunk(CodeCompletionString::CK_SemiColon
);
2362 Results
.AddResult(Result(Builder
.TakeString()));
2365 if (S
->getBreakParent()) {
2367 Builder
.AddTypedTextChunk("break");
2368 Builder
.AddChunk(CodeCompletionString::CK_SemiColon
);
2369 Results
.AddResult(Result(Builder
.TakeString()));
2372 // "return expression ;" or "return ;", depending on the return type.
2373 QualType ReturnType
;
2374 if (const auto *Function
= dyn_cast
<FunctionDecl
>(SemaRef
.CurContext
))
2375 ReturnType
= Function
->getReturnType();
2376 else if (const auto *Method
= dyn_cast
<ObjCMethodDecl
>(SemaRef
.CurContext
))
2377 ReturnType
= Method
->getReturnType();
2378 else if (SemaRef
.getCurBlock() &&
2379 !SemaRef
.getCurBlock()->ReturnType
.isNull())
2380 ReturnType
= SemaRef
.getCurBlock()->ReturnType
;;
2381 if (ReturnType
.isNull() || ReturnType
->isVoidType()) {
2382 Builder
.AddTypedTextChunk("return");
2383 Builder
.AddChunk(CodeCompletionString::CK_SemiColon
);
2384 Results
.AddResult(Result(Builder
.TakeString()));
2386 assert(!ReturnType
.isNull());
2387 // "return expression ;"
2388 Builder
.AddTypedTextChunk("return");
2389 Builder
.AddChunk(clang::CodeCompletionString::CK_HorizontalSpace
);
2390 Builder
.AddPlaceholderChunk("expression");
2391 Builder
.AddChunk(CodeCompletionString::CK_SemiColon
);
2392 Results
.AddResult(Result(Builder
.TakeString()));
2393 // When boolean, also add 'return true;' and 'return false;'.
2394 if (ReturnType
->isBooleanType()) {
2395 Builder
.AddTypedTextChunk("return true");
2396 Builder
.AddChunk(CodeCompletionString::CK_SemiColon
);
2397 Results
.AddResult(Result(Builder
.TakeString()));
2399 Builder
.AddTypedTextChunk("return false");
2400 Builder
.AddChunk(CodeCompletionString::CK_SemiColon
);
2401 Results
.AddResult(Result(Builder
.TakeString()));
2403 // For pointers, suggest 'return nullptr' in C++.
2404 if (SemaRef
.getLangOpts().CPlusPlus11
&&
2405 (ReturnType
->isPointerType() || ReturnType
->isMemberPointerType())) {
2406 Builder
.AddTypedTextChunk("return nullptr");
2407 Builder
.AddChunk(CodeCompletionString::CK_SemiColon
);
2408 Results
.AddResult(Result(Builder
.TakeString()));
2412 // goto identifier ;
2413 Builder
.AddTypedTextChunk("goto");
2414 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2415 Builder
.AddPlaceholderChunk("label");
2416 Builder
.AddChunk(CodeCompletionString::CK_SemiColon
);
2417 Results
.AddResult(Result(Builder
.TakeString()));
2420 Builder
.AddTypedTextChunk("using namespace");
2421 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2422 Builder
.AddPlaceholderChunk("identifier");
2423 Builder
.AddChunk(CodeCompletionString::CK_SemiColon
);
2424 Results
.AddResult(Result(Builder
.TakeString()));
2426 AddStaticAssertResult(Builder
, Results
, SemaRef
.getLangOpts());
2430 // Fall through (for statement expressions).
2431 case Sema::PCC_ForInit
:
2432 case Sema::PCC_Condition
:
2433 AddStorageSpecifiers(CCC
, SemaRef
.getLangOpts(), Results
);
2434 // Fall through: conditions and statements can have expressions.
2437 case Sema::PCC_ParenthesizedExpression
:
2438 if (SemaRef
.getLangOpts().ObjCAutoRefCount
&&
2439 CCC
== Sema::PCC_ParenthesizedExpression
) {
2440 // (__bridge <type>)<expression>
2441 Builder
.AddTypedTextChunk("__bridge");
2442 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2443 Builder
.AddPlaceholderChunk("type");
2444 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
2445 Builder
.AddPlaceholderChunk("expression");
2446 Results
.AddResult(Result(Builder
.TakeString()));
2448 // (__bridge_transfer <Objective-C type>)<expression>
2449 Builder
.AddTypedTextChunk("__bridge_transfer");
2450 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2451 Builder
.AddPlaceholderChunk("Objective-C type");
2452 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
2453 Builder
.AddPlaceholderChunk("expression");
2454 Results
.AddResult(Result(Builder
.TakeString()));
2456 // (__bridge_retained <CF type>)<expression>
2457 Builder
.AddTypedTextChunk("__bridge_retained");
2458 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2459 Builder
.AddPlaceholderChunk("CF type");
2460 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
2461 Builder
.AddPlaceholderChunk("expression");
2462 Results
.AddResult(Result(Builder
.TakeString()));
2467 case Sema::PCC_Expression
: {
2468 if (SemaRef
.getLangOpts().CPlusPlus
) {
2469 // 'this', if we're in a non-static member function.
2470 addThisCompletion(SemaRef
, Results
);
2473 Builder
.AddResultTypeChunk("bool");
2474 Builder
.AddTypedTextChunk("true");
2475 Results
.AddResult(Result(Builder
.TakeString()));
2478 Builder
.AddResultTypeChunk("bool");
2479 Builder
.AddTypedTextChunk("false");
2480 Results
.AddResult(Result(Builder
.TakeString()));
2482 if (SemaRef
.getLangOpts().RTTI
) {
2483 // dynamic_cast < type-id > ( expression )
2484 Builder
.AddTypedTextChunk("dynamic_cast");
2485 Builder
.AddChunk(CodeCompletionString::CK_LeftAngle
);
2486 Builder
.AddPlaceholderChunk("type");
2487 Builder
.AddChunk(CodeCompletionString::CK_RightAngle
);
2488 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
2489 Builder
.AddPlaceholderChunk("expression");
2490 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
2491 Results
.AddResult(Result(Builder
.TakeString()));
2494 // static_cast < type-id > ( expression )
2495 Builder
.AddTypedTextChunk("static_cast");
2496 Builder
.AddChunk(CodeCompletionString::CK_LeftAngle
);
2497 Builder
.AddPlaceholderChunk("type");
2498 Builder
.AddChunk(CodeCompletionString::CK_RightAngle
);
2499 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
2500 Builder
.AddPlaceholderChunk("expression");
2501 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
2502 Results
.AddResult(Result(Builder
.TakeString()));
2504 // reinterpret_cast < type-id > ( expression )
2505 Builder
.AddTypedTextChunk("reinterpret_cast");
2506 Builder
.AddChunk(CodeCompletionString::CK_LeftAngle
);
2507 Builder
.AddPlaceholderChunk("type");
2508 Builder
.AddChunk(CodeCompletionString::CK_RightAngle
);
2509 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
2510 Builder
.AddPlaceholderChunk("expression");
2511 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
2512 Results
.AddResult(Result(Builder
.TakeString()));
2514 // const_cast < type-id > ( expression )
2515 Builder
.AddTypedTextChunk("const_cast");
2516 Builder
.AddChunk(CodeCompletionString::CK_LeftAngle
);
2517 Builder
.AddPlaceholderChunk("type");
2518 Builder
.AddChunk(CodeCompletionString::CK_RightAngle
);
2519 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
2520 Builder
.AddPlaceholderChunk("expression");
2521 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
2522 Results
.AddResult(Result(Builder
.TakeString()));
2524 if (SemaRef
.getLangOpts().RTTI
) {
2525 // typeid ( expression-or-type )
2526 Builder
.AddResultTypeChunk("std::type_info");
2527 Builder
.AddTypedTextChunk("typeid");
2528 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
2529 Builder
.AddPlaceholderChunk("expression-or-type");
2530 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
2531 Results
.AddResult(Result(Builder
.TakeString()));
2535 Builder
.AddTypedTextChunk("new");
2536 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2537 Builder
.AddPlaceholderChunk("type");
2538 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
2539 Builder
.AddPlaceholderChunk("expressions");
2540 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
2541 Results
.AddResult(Result(Builder
.TakeString()));
2543 // new T [ ] ( ... )
2544 Builder
.AddTypedTextChunk("new");
2545 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2546 Builder
.AddPlaceholderChunk("type");
2547 Builder
.AddChunk(CodeCompletionString::CK_LeftBracket
);
2548 Builder
.AddPlaceholderChunk("size");
2549 Builder
.AddChunk(CodeCompletionString::CK_RightBracket
);
2550 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
2551 Builder
.AddPlaceholderChunk("expressions");
2552 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
2553 Results
.AddResult(Result(Builder
.TakeString()));
2555 // delete expression
2556 Builder
.AddResultTypeChunk("void");
2557 Builder
.AddTypedTextChunk("delete");
2558 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2559 Builder
.AddPlaceholderChunk("expression");
2560 Results
.AddResult(Result(Builder
.TakeString()));
2562 // delete [] expression
2563 Builder
.AddResultTypeChunk("void");
2564 Builder
.AddTypedTextChunk("delete");
2565 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2566 Builder
.AddChunk(CodeCompletionString::CK_LeftBracket
);
2567 Builder
.AddChunk(CodeCompletionString::CK_RightBracket
);
2568 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2569 Builder
.AddPlaceholderChunk("expression");
2570 Results
.AddResult(Result(Builder
.TakeString()));
2572 if (SemaRef
.getLangOpts().CXXExceptions
) {
2574 Builder
.AddResultTypeChunk("void");
2575 Builder
.AddTypedTextChunk("throw");
2576 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
2577 Builder
.AddPlaceholderChunk("expression");
2578 Results
.AddResult(Result(Builder
.TakeString()));
2583 if (SemaRef
.getLangOpts().CPlusPlus11
) {
2585 Builder
.AddResultTypeChunk("std::nullptr_t");
2586 Builder
.AddTypedTextChunk("nullptr");
2587 Results
.AddResult(Result(Builder
.TakeString()));
2590 Builder
.AddResultTypeChunk("size_t");
2591 Builder
.AddTypedTextChunk("alignof");
2592 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
2593 Builder
.AddPlaceholderChunk("type");
2594 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
2595 Results
.AddResult(Result(Builder
.TakeString()));
2598 Builder
.AddResultTypeChunk("bool");
2599 Builder
.AddTypedTextChunk("noexcept");
2600 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
2601 Builder
.AddPlaceholderChunk("expression");
2602 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
2603 Results
.AddResult(Result(Builder
.TakeString()));
2605 // sizeof... expression
2606 Builder
.AddResultTypeChunk("size_t");
2607 Builder
.AddTypedTextChunk("sizeof...");
2608 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
2609 Builder
.AddPlaceholderChunk("parameter-pack");
2610 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
2611 Results
.AddResult(Result(Builder
.TakeString()));
2615 if (SemaRef
.getLangOpts().ObjC
) {
2616 // Add "super", if we're in an Objective-C class with a superclass.
2617 if (ObjCMethodDecl
*Method
= SemaRef
.getCurMethodDecl()) {
2618 // The interface can be NULL.
2619 if (ObjCInterfaceDecl
*ID
= Method
->getClassInterface())
2620 if (ID
->getSuperClass()) {
2621 std::string SuperType
;
2622 SuperType
= ID
->getSuperClass()->getNameAsString();
2623 if (Method
->isInstanceMethod())
2626 Builder
.AddResultTypeChunk(Allocator
.CopyString(SuperType
));
2627 Builder
.AddTypedTextChunk("super");
2628 Results
.AddResult(Result(Builder
.TakeString()));
2632 AddObjCExpressionResults(Results
, true);
2635 if (SemaRef
.getLangOpts().C11
) {
2637 Builder
.AddResultTypeChunk("size_t");
2638 if (SemaRef
.PP
.isMacroDefined("alignof"))
2639 Builder
.AddTypedTextChunk("alignof");
2641 Builder
.AddTypedTextChunk("_Alignof");
2642 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
2643 Builder
.AddPlaceholderChunk("type");
2644 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
2645 Results
.AddResult(Result(Builder
.TakeString()));
2648 // sizeof expression
2649 Builder
.AddResultTypeChunk("size_t");
2650 Builder
.AddTypedTextChunk("sizeof");
2651 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
2652 Builder
.AddPlaceholderChunk("expression-or-type");
2653 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
2654 Results
.AddResult(Result(Builder
.TakeString()));
2658 case Sema::PCC_Type
:
2659 case Sema::PCC_LocalDeclarationSpecifiers
:
2663 if (WantTypesInContext(CCC
, SemaRef
.getLangOpts()))
2664 AddTypeSpecifierResults(SemaRef
.getLangOpts(), Results
);
2666 if (SemaRef
.getLangOpts().CPlusPlus
&& CCC
!= Sema::PCC_Type
)
2667 Results
.AddResult(Result("operator"));
2670 /// If the given declaration has an associated type, add it as a result
2672 static void AddResultTypeChunk(ASTContext
&Context
,
2673 const PrintingPolicy
&Policy
,
2674 const NamedDecl
*ND
, QualType BaseType
,
2675 CodeCompletionBuilder
&Result
) {
2679 // Skip constructors and conversion functions, which have their return types
2680 // built into their names.
2681 if (isConstructor(ND
) || isa
<CXXConversionDecl
>(ND
))
2684 // Determine the type of the declaration (if it has a type).
2686 if (const FunctionDecl
*Function
= ND
->getAsFunction())
2687 T
= Function
->getReturnType();
2688 else if (const auto *Method
= dyn_cast
<ObjCMethodDecl
>(ND
)) {
2689 if (!BaseType
.isNull())
2690 T
= Method
->getSendResultType(BaseType
);
2692 T
= Method
->getReturnType();
2693 } else if (const auto *Enumerator
= dyn_cast
<EnumConstantDecl
>(ND
)) {
2694 T
= Context
.getTypeDeclType(cast
<TypeDecl
>(Enumerator
->getDeclContext()));
2695 T
= clang::TypeName::getFullyQualifiedType(T
, Context
);
2696 } else if (isa
<UnresolvedUsingValueDecl
>(ND
)) {
2697 /* Do nothing: ignore unresolved using declarations*/
2698 } else if (const auto *Ivar
= dyn_cast
<ObjCIvarDecl
>(ND
)) {
2699 if (!BaseType
.isNull())
2700 T
= Ivar
->getUsageType(BaseType
);
2702 T
= Ivar
->getType();
2703 } else if (const auto *Value
= dyn_cast
<ValueDecl
>(ND
)) {
2704 T
= Value
->getType();
2705 } else if (const auto *Property
= dyn_cast
<ObjCPropertyDecl
>(ND
)) {
2706 if (!BaseType
.isNull())
2707 T
= Property
->getUsageType(BaseType
);
2709 T
= Property
->getType();
2712 if (T
.isNull() || Context
.hasSameType(T
, Context
.DependentTy
))
2715 Result
.AddResultTypeChunk(
2716 GetCompletionTypeString(T
, Context
, Policy
, Result
.getAllocator()));
2719 static void MaybeAddSentinel(Preprocessor
&PP
,
2720 const NamedDecl
*FunctionOrMethod
,
2721 CodeCompletionBuilder
&Result
) {
2722 if (SentinelAttr
*Sentinel
= FunctionOrMethod
->getAttr
<SentinelAttr
>())
2723 if (Sentinel
->getSentinel() == 0) {
2724 if (PP
.getLangOpts().ObjC
&& PP
.isMacroDefined("nil"))
2725 Result
.AddTextChunk(", nil");
2726 else if (PP
.isMacroDefined("NULL"))
2727 Result
.AddTextChunk(", NULL");
2729 Result
.AddTextChunk(", (void*)0");
2733 static std::string
formatObjCParamQualifiers(unsigned ObjCQuals
,
2736 if (ObjCQuals
& Decl::OBJC_TQ_In
)
2738 else if (ObjCQuals
& Decl::OBJC_TQ_Inout
)
2740 else if (ObjCQuals
& Decl::OBJC_TQ_Out
)
2742 if (ObjCQuals
& Decl::OBJC_TQ_Bycopy
)
2743 Result
+= "bycopy ";
2744 else if (ObjCQuals
& Decl::OBJC_TQ_Byref
)
2746 if (ObjCQuals
& Decl::OBJC_TQ_Oneway
)
2747 Result
+= "oneway ";
2748 if (ObjCQuals
& Decl::OBJC_TQ_CSNullability
) {
2749 if (auto nullability
= AttributedType::stripOuterNullability(Type
)) {
2750 switch (*nullability
) {
2751 case NullabilityKind::NonNull
:
2752 Result
+= "nonnull ";
2755 case NullabilityKind::Nullable
:
2756 Result
+= "nullable ";
2759 case NullabilityKind::Unspecified
:
2760 Result
+= "null_unspecified ";
2763 case NullabilityKind::NullableResult
:
2764 llvm_unreachable("Not supported as a context-sensitive keyword!");
2772 /// Tries to find the most appropriate type location for an Objective-C
2773 /// block placeholder.
2775 /// This function ignores things like typedefs and qualifiers in order to
2776 /// present the most relevant and accurate block placeholders in code completion
2778 static void findTypeLocationForBlockDecl(const TypeSourceInfo
*TSInfo
,
2779 FunctionTypeLoc
&Block
,
2780 FunctionProtoTypeLoc
&BlockProto
,
2781 bool SuppressBlock
= false) {
2784 TypeLoc TL
= TSInfo
->getTypeLoc().getUnqualifiedLoc();
2786 // Look through typedefs.
2787 if (!SuppressBlock
) {
2788 if (TypedefTypeLoc TypedefTL
= TL
.getAsAdjusted
<TypedefTypeLoc
>()) {
2789 if (TypeSourceInfo
*InnerTSInfo
=
2790 TypedefTL
.getTypedefNameDecl()->getTypeSourceInfo()) {
2791 TL
= InnerTSInfo
->getTypeLoc().getUnqualifiedLoc();
2796 // Look through qualified types
2797 if (QualifiedTypeLoc QualifiedTL
= TL
.getAs
<QualifiedTypeLoc
>()) {
2798 TL
= QualifiedTL
.getUnqualifiedLoc();
2802 if (AttributedTypeLoc AttrTL
= TL
.getAs
<AttributedTypeLoc
>()) {
2803 TL
= AttrTL
.getModifiedLoc();
2808 // Try to get the function prototype behind the block pointer type,
2810 if (BlockPointerTypeLoc BlockPtr
= TL
.getAs
<BlockPointerTypeLoc
>()) {
2811 TL
= BlockPtr
.getPointeeLoc().IgnoreParens();
2812 Block
= TL
.getAs
<FunctionTypeLoc
>();
2813 BlockProto
= TL
.getAs
<FunctionProtoTypeLoc
>();
2820 formatBlockPlaceholder(const PrintingPolicy
&Policy
, const NamedDecl
*BlockDecl
,
2821 FunctionTypeLoc
&Block
, FunctionProtoTypeLoc
&BlockProto
,
2822 bool SuppressBlockName
= false,
2823 bool SuppressBlock
= false,
2824 Optional
<ArrayRef
<QualType
>> ObjCSubsts
= None
);
2827 FormatFunctionParameter(const PrintingPolicy
&Policy
,
2828 const DeclaratorDecl
*Param
, bool SuppressName
= false,
2829 bool SuppressBlock
= false,
2830 Optional
<ArrayRef
<QualType
>> ObjCSubsts
= None
) {
2831 // Params are unavailable in FunctionTypeLoc if the FunctionType is invalid.
2832 // It would be better to pass in the param Type, which is usually available.
2833 // But this case is rare, so just pretend we fell back to int as elsewhere.
2836 Decl::ObjCDeclQualifier ObjCQual
= Decl::OBJC_TQ_None
;
2837 if (const auto *PVD
= dyn_cast
<ParmVarDecl
>(Param
))
2838 ObjCQual
= PVD
->getObjCDeclQualifier();
2839 bool ObjCMethodParam
= isa
<ObjCMethodDecl
>(Param
->getDeclContext());
2840 if (Param
->getType()->isDependentType() ||
2841 !Param
->getType()->isBlockPointerType()) {
2842 // The argument for a dependent or non-block parameter is a placeholder
2843 // containing that parameter's type.
2846 if (Param
->getIdentifier() && !ObjCMethodParam
&& !SuppressName
)
2847 Result
= std::string(Param
->getIdentifier()->deuglifiedName());
2849 QualType Type
= Param
->getType();
2851 Type
= Type
.substObjCTypeArgs(Param
->getASTContext(), *ObjCSubsts
,
2852 ObjCSubstitutionContext::Parameter
);
2853 if (ObjCMethodParam
) {
2854 Result
= "(" + formatObjCParamQualifiers(ObjCQual
, Type
);
2855 Result
+= Type
.getAsString(Policy
) + ")";
2856 if (Param
->getIdentifier() && !SuppressName
)
2857 Result
+= Param
->getIdentifier()->deuglifiedName();
2859 Type
.getAsStringInternal(Result
, Policy
);
2864 // The argument for a block pointer parameter is a block literal with
2865 // the appropriate type.
2866 FunctionTypeLoc Block
;
2867 FunctionProtoTypeLoc BlockProto
;
2868 findTypeLocationForBlockDecl(Param
->getTypeSourceInfo(), Block
, BlockProto
,
2870 // Try to retrieve the block type information from the property if this is a
2871 // parameter in a setter.
2872 if (!Block
&& ObjCMethodParam
&&
2873 cast
<ObjCMethodDecl
>(Param
->getDeclContext())->isPropertyAccessor()) {
2874 if (const auto *PD
= cast
<ObjCMethodDecl
>(Param
->getDeclContext())
2875 ->findPropertyDecl(/*CheckOverrides=*/false))
2876 findTypeLocationForBlockDecl(PD
->getTypeSourceInfo(), Block
, BlockProto
,
2881 // We were unable to find a FunctionProtoTypeLoc with parameter names
2882 // for the block; just use the parameter type as a placeholder.
2884 if (!ObjCMethodParam
&& Param
->getIdentifier())
2885 Result
= std::string(Param
->getIdentifier()->deuglifiedName());
2887 QualType Type
= Param
->getType().getUnqualifiedType();
2889 if (ObjCMethodParam
) {
2890 Result
= Type
.getAsString(Policy
);
2891 std::string Quals
= formatObjCParamQualifiers(ObjCQual
, Type
);
2893 Result
= "(" + Quals
+ " " + Result
+ ")";
2894 if (Result
.back() != ')')
2896 if (Param
->getIdentifier())
2897 Result
+= Param
->getIdentifier()->deuglifiedName();
2899 Type
.getAsStringInternal(Result
, Policy
);
2905 // We have the function prototype behind the block pointer type, as it was
2906 // written in the source.
2907 return formatBlockPlaceholder(Policy
, Param
, Block
, BlockProto
,
2908 /*SuppressBlockName=*/false, SuppressBlock
,
2912 /// Returns a placeholder string that corresponds to an Objective-C block
2915 /// \param BlockDecl A declaration with an Objective-C block type.
2917 /// \param Block The most relevant type location for that block type.
2919 /// \param SuppressBlockName Determines whether or not the name of the block
2920 /// declaration is included in the resulting string.
2922 formatBlockPlaceholder(const PrintingPolicy
&Policy
, const NamedDecl
*BlockDecl
,
2923 FunctionTypeLoc
&Block
, FunctionProtoTypeLoc
&BlockProto
,
2924 bool SuppressBlockName
, bool SuppressBlock
,
2925 Optional
<ArrayRef
<QualType
>> ObjCSubsts
) {
2927 QualType ResultType
= Block
.getTypePtr()->getReturnType();
2930 ResultType
.substObjCTypeArgs(BlockDecl
->getASTContext(), *ObjCSubsts
,
2931 ObjCSubstitutionContext::Result
);
2932 if (!ResultType
->isVoidType() || SuppressBlock
)
2933 ResultType
.getAsStringInternal(Result
, Policy
);
2935 // Format the parameter list.
2937 if (!BlockProto
|| Block
.getNumParams() == 0) {
2938 if (BlockProto
&& BlockProto
.getTypePtr()->isVariadic())
2944 for (unsigned I
= 0, N
= Block
.getNumParams(); I
!= N
; ++I
) {
2947 Params
+= FormatFunctionParameter(Policy
, Block
.getParam(I
),
2948 /*SuppressName=*/false,
2949 /*SuppressBlock=*/true, ObjCSubsts
);
2951 if (I
== N
- 1 && BlockProto
.getTypePtr()->isVariadic())
2957 if (SuppressBlock
) {
2958 // Format as a parameter.
2959 Result
= Result
+ " (^";
2960 if (!SuppressBlockName
&& BlockDecl
->getIdentifier())
2961 Result
+= BlockDecl
->getIdentifier()->getName();
2965 // Format as a block literal argument.
2966 Result
= '^' + Result
;
2969 if (!SuppressBlockName
&& BlockDecl
->getIdentifier())
2970 Result
+= BlockDecl
->getIdentifier()->getName();
2976 static std::string
GetDefaultValueString(const ParmVarDecl
*Param
,
2977 const SourceManager
&SM
,
2978 const LangOptions
&LangOpts
) {
2979 const SourceRange SrcRange
= Param
->getDefaultArgRange();
2980 CharSourceRange CharSrcRange
= CharSourceRange::getTokenRange(SrcRange
);
2981 bool Invalid
= CharSrcRange
.isInvalid();
2985 Lexer::getSourceText(CharSrcRange
, SM
, LangOpts
, &Invalid
);
2989 if (srcText
.empty() || srcText
== "=") {
2990 // Lexer can't determine the value.
2991 // This happens if the code is incorrect (for example class is forward
2995 std::string
DefValue(srcText
.str());
2996 // FIXME: remove this check if the Lexer::getSourceText value is fixed and
2997 // this value always has (or always does not have) '=' in front of it
2998 if (DefValue
.at(0) != '=') {
2999 // If we don't have '=' in front of value.
3000 // Lexer returns built-in types values without '=' and user-defined types
3002 return " = " + DefValue
;
3004 return " " + DefValue
;
3007 /// Add function parameter chunks to the given code completion string.
3008 static void AddFunctionParameterChunks(Preprocessor
&PP
,
3009 const PrintingPolicy
&Policy
,
3010 const FunctionDecl
*Function
,
3011 CodeCompletionBuilder
&Result
,
3013 bool InOptional
= false) {
3014 bool FirstParameter
= true;
3016 for (unsigned P
= Start
, N
= Function
->getNumParams(); P
!= N
; ++P
) {
3017 const ParmVarDecl
*Param
= Function
->getParamDecl(P
);
3019 if (Param
->hasDefaultArg() && !InOptional
) {
3020 // When we see an optional default argument, put that argument and
3021 // the remaining default arguments into a new, optional string.
3022 CodeCompletionBuilder
Opt(Result
.getAllocator(),
3023 Result
.getCodeCompletionTUInfo());
3024 if (!FirstParameter
)
3025 Opt
.AddChunk(CodeCompletionString::CK_Comma
);
3026 AddFunctionParameterChunks(PP
, Policy
, Function
, Opt
, P
, true);
3027 Result
.AddOptionalChunk(Opt
.TakeString());
3032 FirstParameter
= false;
3034 Result
.AddChunk(CodeCompletionString::CK_Comma
);
3038 // Format the placeholder string.
3039 std::string PlaceholderStr
= FormatFunctionParameter(Policy
, Param
);
3040 if (Param
->hasDefaultArg())
3042 GetDefaultValueString(Param
, PP
.getSourceManager(), PP
.getLangOpts());
3044 if (Function
->isVariadic() && P
== N
- 1)
3045 PlaceholderStr
+= ", ...";
3047 // Add the placeholder string.
3048 Result
.AddPlaceholderChunk(
3049 Result
.getAllocator().CopyString(PlaceholderStr
));
3052 if (const auto *Proto
= Function
->getType()->getAs
<FunctionProtoType
>())
3053 if (Proto
->isVariadic()) {
3054 if (Proto
->getNumParams() == 0)
3055 Result
.AddPlaceholderChunk("...");
3057 MaybeAddSentinel(PP
, Function
, Result
);
3061 /// Add template parameter chunks to the given code completion string.
3062 static void AddTemplateParameterChunks(
3063 ASTContext
&Context
, const PrintingPolicy
&Policy
,
3064 const TemplateDecl
*Template
, CodeCompletionBuilder
&Result
,
3065 unsigned MaxParameters
= 0, unsigned Start
= 0, bool InDefaultArg
= false) {
3066 bool FirstParameter
= true;
3068 // Prefer to take the template parameter names from the first declaration of
3070 Template
= cast
<TemplateDecl
>(Template
->getCanonicalDecl());
3072 TemplateParameterList
*Params
= Template
->getTemplateParameters();
3073 TemplateParameterList::iterator PEnd
= Params
->end();
3075 PEnd
= Params
->begin() + MaxParameters
;
3076 for (TemplateParameterList::iterator P
= Params
->begin() + Start
; P
!= PEnd
;
3078 bool HasDefaultArg
= false;
3079 std::string PlaceholderStr
;
3080 if (TemplateTypeParmDecl
*TTP
= dyn_cast
<TemplateTypeParmDecl
>(*P
)) {
3081 if (TTP
->wasDeclaredWithTypename())
3082 PlaceholderStr
= "typename";
3083 else if (const auto *TC
= TTP
->getTypeConstraint()) {
3084 llvm::raw_string_ostream
OS(PlaceholderStr
);
3085 TC
->print(OS
, Policy
);
3088 PlaceholderStr
= "class";
3090 if (TTP
->getIdentifier()) {
3091 PlaceholderStr
+= ' ';
3092 PlaceholderStr
+= TTP
->getIdentifier()->deuglifiedName();
3095 HasDefaultArg
= TTP
->hasDefaultArgument();
3096 } else if (NonTypeTemplateParmDecl
*NTTP
=
3097 dyn_cast
<NonTypeTemplateParmDecl
>(*P
)) {
3098 if (NTTP
->getIdentifier())
3099 PlaceholderStr
= std::string(NTTP
->getIdentifier()->deuglifiedName());
3100 NTTP
->getType().getAsStringInternal(PlaceholderStr
, Policy
);
3101 HasDefaultArg
= NTTP
->hasDefaultArgument();
3103 assert(isa
<TemplateTemplateParmDecl
>(*P
));
3104 TemplateTemplateParmDecl
*TTP
= cast
<TemplateTemplateParmDecl
>(*P
);
3106 // Since putting the template argument list into the placeholder would
3107 // be very, very long, we just use an abbreviation.
3108 PlaceholderStr
= "template<...> class";
3109 if (TTP
->getIdentifier()) {
3110 PlaceholderStr
+= ' ';
3111 PlaceholderStr
+= TTP
->getIdentifier()->deuglifiedName();
3114 HasDefaultArg
= TTP
->hasDefaultArgument();
3117 if (HasDefaultArg
&& !InDefaultArg
) {
3118 // When we see an optional default argument, put that argument and
3119 // the remaining default arguments into a new, optional string.
3120 CodeCompletionBuilder
Opt(Result
.getAllocator(),
3121 Result
.getCodeCompletionTUInfo());
3122 if (!FirstParameter
)
3123 Opt
.AddChunk(CodeCompletionString::CK_Comma
);
3124 AddTemplateParameterChunks(Context
, Policy
, Template
, Opt
, MaxParameters
,
3125 P
- Params
->begin(), true);
3126 Result
.AddOptionalChunk(Opt
.TakeString());
3130 InDefaultArg
= false;
3133 FirstParameter
= false;
3135 Result
.AddChunk(CodeCompletionString::CK_Comma
);
3137 // Add the placeholder string.
3138 Result
.AddPlaceholderChunk(
3139 Result
.getAllocator().CopyString(PlaceholderStr
));
3143 /// Add a qualifier to the given code-completion string, if the
3144 /// provided nested-name-specifier is non-NULL.
3145 static void AddQualifierToCompletionString(CodeCompletionBuilder
&Result
,
3146 NestedNameSpecifier
*Qualifier
,
3147 bool QualifierIsInformative
,
3148 ASTContext
&Context
,
3149 const PrintingPolicy
&Policy
) {
3153 std::string PrintedNNS
;
3155 llvm::raw_string_ostream
OS(PrintedNNS
);
3156 Qualifier
->print(OS
, Policy
);
3158 if (QualifierIsInformative
)
3159 Result
.AddInformativeChunk(Result
.getAllocator().CopyString(PrintedNNS
));
3161 Result
.AddTextChunk(Result
.getAllocator().CopyString(PrintedNNS
));
3165 AddFunctionTypeQualsToCompletionString(CodeCompletionBuilder
&Result
,
3166 const FunctionDecl
*Function
) {
3167 const auto *Proto
= Function
->getType()->getAs
<FunctionProtoType
>();
3168 if (!Proto
|| !Proto
->getMethodQuals())
3171 // FIXME: Add ref-qualifier!
3173 // Handle single qualifiers without copying
3174 if (Proto
->getMethodQuals().hasOnlyConst()) {
3175 Result
.AddInformativeChunk(" const");
3179 if (Proto
->getMethodQuals().hasOnlyVolatile()) {
3180 Result
.AddInformativeChunk(" volatile");
3184 if (Proto
->getMethodQuals().hasOnlyRestrict()) {
3185 Result
.AddInformativeChunk(" restrict");
3189 // Handle multiple qualifiers.
3190 std::string QualsStr
;
3191 if (Proto
->isConst())
3192 QualsStr
+= " const";
3193 if (Proto
->isVolatile())
3194 QualsStr
+= " volatile";
3195 if (Proto
->isRestrict())
3196 QualsStr
+= " restrict";
3197 Result
.AddInformativeChunk(Result
.getAllocator().CopyString(QualsStr
));
3200 /// Add the name of the given declaration
3201 static void AddTypedNameChunk(ASTContext
&Context
, const PrintingPolicy
&Policy
,
3202 const NamedDecl
*ND
,
3203 CodeCompletionBuilder
&Result
) {
3204 DeclarationName Name
= ND
->getDeclName();
3208 switch (Name
.getNameKind()) {
3209 case DeclarationName::CXXOperatorName
: {
3210 const char *OperatorName
= nullptr;
3211 switch (Name
.getCXXOverloadedOperator()) {
3213 case OO_Conditional
:
3214 case NUM_OVERLOADED_OPERATORS
:
3215 OperatorName
= "operator";
3218 #define OVERLOADED_OPERATOR(Name, Spelling, Token, Unary, Binary, MemberOnly) \
3220 OperatorName = "operator" Spelling; \
3222 #define OVERLOADED_OPERATOR_MULTI(Name, Spelling, Unary, Binary, MemberOnly)
3223 #include "clang/Basic/OperatorKinds.def"
3226 OperatorName
= "operator new";
3229 OperatorName
= "operator delete";
3232 OperatorName
= "operator new[]";
3234 case OO_Array_Delete
:
3235 OperatorName
= "operator delete[]";
3238 OperatorName
= "operator()";
3241 OperatorName
= "operator[]";
3244 Result
.AddTypedTextChunk(OperatorName
);
3248 case DeclarationName::Identifier
:
3249 case DeclarationName::CXXConversionFunctionName
:
3250 case DeclarationName::CXXDestructorName
:
3251 case DeclarationName::CXXLiteralOperatorName
:
3252 Result
.AddTypedTextChunk(
3253 Result
.getAllocator().CopyString(ND
->getNameAsString()));
3256 case DeclarationName::CXXDeductionGuideName
:
3257 case DeclarationName::CXXUsingDirective
:
3258 case DeclarationName::ObjCZeroArgSelector
:
3259 case DeclarationName::ObjCOneArgSelector
:
3260 case DeclarationName::ObjCMultiArgSelector
:
3263 case DeclarationName::CXXConstructorName
: {
3264 CXXRecordDecl
*Record
= nullptr;
3265 QualType Ty
= Name
.getCXXNameType();
3266 if (const auto *RecordTy
= Ty
->getAs
<RecordType
>())
3267 Record
= cast
<CXXRecordDecl
>(RecordTy
->getDecl());
3268 else if (const auto *InjectedTy
= Ty
->getAs
<InjectedClassNameType
>())
3269 Record
= InjectedTy
->getDecl();
3271 Result
.AddTypedTextChunk(
3272 Result
.getAllocator().CopyString(ND
->getNameAsString()));
3276 Result
.AddTypedTextChunk(
3277 Result
.getAllocator().CopyString(Record
->getNameAsString()));
3278 if (ClassTemplateDecl
*Template
= Record
->getDescribedClassTemplate()) {
3279 Result
.AddChunk(CodeCompletionString::CK_LeftAngle
);
3280 AddTemplateParameterChunks(Context
, Policy
, Template
, Result
);
3281 Result
.AddChunk(CodeCompletionString::CK_RightAngle
);
3288 CodeCompletionString
*CodeCompletionResult::CreateCodeCompletionString(
3289 Sema
&S
, const CodeCompletionContext
&CCContext
,
3290 CodeCompletionAllocator
&Allocator
, CodeCompletionTUInfo
&CCTUInfo
,
3291 bool IncludeBriefComments
) {
3292 return CreateCodeCompletionString(S
.Context
, S
.PP
, CCContext
, Allocator
,
3293 CCTUInfo
, IncludeBriefComments
);
3296 CodeCompletionString
*CodeCompletionResult::CreateCodeCompletionStringForMacro(
3297 Preprocessor
&PP
, CodeCompletionAllocator
&Allocator
,
3298 CodeCompletionTUInfo
&CCTUInfo
) {
3299 assert(Kind
== RK_Macro
);
3300 CodeCompletionBuilder
Result(Allocator
, CCTUInfo
, Priority
, Availability
);
3301 const MacroInfo
*MI
= PP
.getMacroInfo(Macro
);
3302 Result
.AddTypedTextChunk(Result
.getAllocator().CopyString(Macro
->getName()));
3304 if (!MI
|| !MI
->isFunctionLike())
3305 return Result
.TakeString();
3307 // Format a function-like macro with placeholders for the arguments.
3308 Result
.AddChunk(CodeCompletionString::CK_LeftParen
);
3309 MacroInfo::param_iterator A
= MI
->param_begin(), AEnd
= MI
->param_end();
3311 // C99 variadic macros add __VA_ARGS__ at the end. Skip it.
3312 if (MI
->isC99Varargs()) {
3316 Result
.AddPlaceholderChunk("...");
3320 for (MacroInfo::param_iterator A
= MI
->param_begin(); A
!= AEnd
; ++A
) {
3321 if (A
!= MI
->param_begin())
3322 Result
.AddChunk(CodeCompletionString::CK_Comma
);
3324 if (MI
->isVariadic() && (A
+ 1) == AEnd
) {
3325 SmallString
<32> Arg
= (*A
)->getName();
3326 if (MI
->isC99Varargs())
3330 Result
.AddPlaceholderChunk(Result
.getAllocator().CopyString(Arg
));
3334 // Non-variadic macros are simple.
3335 Result
.AddPlaceholderChunk(
3336 Result
.getAllocator().CopyString((*A
)->getName()));
3338 Result
.AddChunk(CodeCompletionString::CK_RightParen
);
3339 return Result
.TakeString();
3342 /// If possible, create a new code completion string for the given
3345 /// \returns Either a new, heap-allocated code completion string describing
3346 /// how to use this result, or NULL to indicate that the string or name of the
3347 /// result is all that is needed.
3348 CodeCompletionString
*CodeCompletionResult::CreateCodeCompletionString(
3349 ASTContext
&Ctx
, Preprocessor
&PP
, const CodeCompletionContext
&CCContext
,
3350 CodeCompletionAllocator
&Allocator
, CodeCompletionTUInfo
&CCTUInfo
,
3351 bool IncludeBriefComments
) {
3352 if (Kind
== RK_Macro
)
3353 return CreateCodeCompletionStringForMacro(PP
, Allocator
, CCTUInfo
);
3355 CodeCompletionBuilder
Result(Allocator
, CCTUInfo
, Priority
, Availability
);
3357 PrintingPolicy Policy
= getCompletionPrintingPolicy(Ctx
, PP
);
3358 if (Kind
== RK_Pattern
) {
3359 Pattern
->Priority
= Priority
;
3360 Pattern
->Availability
= Availability
;
3363 Result
.addParentContext(Declaration
->getDeclContext());
3364 Pattern
->ParentName
= Result
.getParentName();
3365 if (const RawComment
*RC
=
3366 getPatternCompletionComment(Ctx
, Declaration
)) {
3367 Result
.addBriefComment(RC
->getBriefText(Ctx
));
3368 Pattern
->BriefComment
= Result
.getBriefComment();
3375 if (Kind
== RK_Keyword
) {
3376 Result
.AddTypedTextChunk(Keyword
);
3377 return Result
.TakeString();
3379 assert(Kind
== RK_Declaration
&& "Missed a result kind?");
3380 return createCodeCompletionStringForDecl(
3381 PP
, Ctx
, Result
, IncludeBriefComments
, CCContext
, Policy
);
3384 static void printOverrideString(const CodeCompletionString
&CCS
,
3385 std::string
&BeforeName
,
3386 std::string
&NameAndSignature
) {
3387 bool SeenTypedChunk
= false;
3388 for (auto &Chunk
: CCS
) {
3389 if (Chunk
.Kind
== CodeCompletionString::CK_Optional
) {
3390 assert(SeenTypedChunk
&& "optional parameter before name");
3391 // Note that we put all chunks inside into NameAndSignature.
3392 printOverrideString(*Chunk
.Optional
, NameAndSignature
, NameAndSignature
);
3395 SeenTypedChunk
|= Chunk
.Kind
== CodeCompletionString::CK_TypedText
;
3397 NameAndSignature
+= Chunk
.Text
;
3399 BeforeName
+= Chunk
.Text
;
3403 CodeCompletionString
*
3404 CodeCompletionResult::createCodeCompletionStringForOverride(
3405 Preprocessor
&PP
, ASTContext
&Ctx
, CodeCompletionBuilder
&Result
,
3406 bool IncludeBriefComments
, const CodeCompletionContext
&CCContext
,
3407 PrintingPolicy
&Policy
) {
3408 auto *CCS
= createCodeCompletionStringForDecl(PP
, Ctx
, Result
,
3409 /*IncludeBriefComments=*/false,
3411 std::string BeforeName
;
3412 std::string NameAndSignature
;
3413 // For overrides all chunks go into the result, none are informative.
3414 printOverrideString(*CCS
, BeforeName
, NameAndSignature
);
3415 NameAndSignature
+= " override";
3417 Result
.AddTextChunk(Result
.getAllocator().CopyString(BeforeName
));
3418 Result
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
3419 Result
.AddTypedTextChunk(Result
.getAllocator().CopyString(NameAndSignature
));
3420 return Result
.TakeString();
3423 // FIXME: Right now this works well with lambdas. Add support for other functor
3424 // types like std::function.
3425 static const NamedDecl
*extractFunctorCallOperator(const NamedDecl
*ND
) {
3426 const auto *VD
= dyn_cast
<VarDecl
>(ND
);
3429 const auto *RecordDecl
= VD
->getType()->getAsCXXRecordDecl();
3430 if (!RecordDecl
|| !RecordDecl
->isLambda())
3432 return RecordDecl
->getLambdaCallOperator();
3435 CodeCompletionString
*CodeCompletionResult::createCodeCompletionStringForDecl(
3436 Preprocessor
&PP
, ASTContext
&Ctx
, CodeCompletionBuilder
&Result
,
3437 bool IncludeBriefComments
, const CodeCompletionContext
&CCContext
,
3438 PrintingPolicy
&Policy
) {
3439 const NamedDecl
*ND
= Declaration
;
3440 Result
.addParentContext(ND
->getDeclContext());
3442 if (IncludeBriefComments
) {
3443 // Add documentation comment, if it exists.
3444 if (const RawComment
*RC
= getCompletionComment(Ctx
, Declaration
)) {
3445 Result
.addBriefComment(RC
->getBriefText(Ctx
));
3449 if (StartsNestedNameSpecifier
) {
3450 Result
.AddTypedTextChunk(
3451 Result
.getAllocator().CopyString(ND
->getNameAsString()));
3452 Result
.AddTextChunk("::");
3453 return Result
.TakeString();
3456 for (const auto *I
: ND
->specific_attrs
<AnnotateAttr
>())
3457 Result
.AddAnnotation(Result
.getAllocator().CopyString(I
->getAnnotation()));
3459 auto AddFunctionTypeAndResult
= [&](const FunctionDecl
*Function
) {
3460 AddResultTypeChunk(Ctx
, Policy
, Function
, CCContext
.getBaseType(), Result
);
3461 AddQualifierToCompletionString(Result
, Qualifier
, QualifierIsInformative
,
3463 AddTypedNameChunk(Ctx
, Policy
, ND
, Result
);
3464 Result
.AddChunk(CodeCompletionString::CK_LeftParen
);
3465 AddFunctionParameterChunks(PP
, Policy
, Function
, Result
);
3466 Result
.AddChunk(CodeCompletionString::CK_RightParen
);
3467 AddFunctionTypeQualsToCompletionString(Result
, Function
);
3470 if (const auto *Function
= dyn_cast
<FunctionDecl
>(ND
)) {
3471 AddFunctionTypeAndResult(Function
);
3472 return Result
.TakeString();
3475 if (const auto *CallOperator
=
3476 dyn_cast_or_null
<FunctionDecl
>(extractFunctorCallOperator(ND
))) {
3477 AddFunctionTypeAndResult(CallOperator
);
3478 return Result
.TakeString();
3481 AddResultTypeChunk(Ctx
, Policy
, ND
, CCContext
.getBaseType(), Result
);
3483 if (const FunctionTemplateDecl
*FunTmpl
=
3484 dyn_cast
<FunctionTemplateDecl
>(ND
)) {
3485 AddQualifierToCompletionString(Result
, Qualifier
, QualifierIsInformative
,
3487 FunctionDecl
*Function
= FunTmpl
->getTemplatedDecl();
3488 AddTypedNameChunk(Ctx
, Policy
, Function
, Result
);
3490 // Figure out which template parameters are deduced (or have default
3492 llvm::SmallBitVector Deduced
;
3493 Sema::MarkDeducedTemplateParameters(Ctx
, FunTmpl
, Deduced
);
3494 unsigned LastDeducibleArgument
;
3495 for (LastDeducibleArgument
= Deduced
.size(); LastDeducibleArgument
> 0;
3496 --LastDeducibleArgument
) {
3497 if (!Deduced
[LastDeducibleArgument
- 1]) {
3498 // C++0x: Figure out if the template argument has a default. If so,
3499 // the user doesn't need to type this argument.
3500 // FIXME: We need to abstract template parameters better!
3501 bool HasDefaultArg
= false;
3502 NamedDecl
*Param
= FunTmpl
->getTemplateParameters()->getParam(
3503 LastDeducibleArgument
- 1);
3504 if (TemplateTypeParmDecl
*TTP
= dyn_cast
<TemplateTypeParmDecl
>(Param
))
3505 HasDefaultArg
= TTP
->hasDefaultArgument();
3506 else if (NonTypeTemplateParmDecl
*NTTP
=
3507 dyn_cast
<NonTypeTemplateParmDecl
>(Param
))
3508 HasDefaultArg
= NTTP
->hasDefaultArgument();
3510 assert(isa
<TemplateTemplateParmDecl
>(Param
));
3512 cast
<TemplateTemplateParmDecl
>(Param
)->hasDefaultArgument();
3520 if (LastDeducibleArgument
) {
3521 // Some of the function template arguments cannot be deduced from a
3522 // function call, so we introduce an explicit template argument list
3523 // containing all of the arguments up to the first deducible argument.
3524 Result
.AddChunk(CodeCompletionString::CK_LeftAngle
);
3525 AddTemplateParameterChunks(Ctx
, Policy
, FunTmpl
, Result
,
3526 LastDeducibleArgument
);
3527 Result
.AddChunk(CodeCompletionString::CK_RightAngle
);
3530 // Add the function parameters
3531 Result
.AddChunk(CodeCompletionString::CK_LeftParen
);
3532 AddFunctionParameterChunks(PP
, Policy
, Function
, Result
);
3533 Result
.AddChunk(CodeCompletionString::CK_RightParen
);
3534 AddFunctionTypeQualsToCompletionString(Result
, Function
);
3535 return Result
.TakeString();
3538 if (const auto *Template
= dyn_cast
<TemplateDecl
>(ND
)) {
3539 AddQualifierToCompletionString(Result
, Qualifier
, QualifierIsInformative
,
3541 Result
.AddTypedTextChunk(
3542 Result
.getAllocator().CopyString(Template
->getNameAsString()));
3543 Result
.AddChunk(CodeCompletionString::CK_LeftAngle
);
3544 AddTemplateParameterChunks(Ctx
, Policy
, Template
, Result
);
3545 Result
.AddChunk(CodeCompletionString::CK_RightAngle
);
3546 return Result
.TakeString();
3549 if (const auto *Method
= dyn_cast
<ObjCMethodDecl
>(ND
)) {
3550 Selector Sel
= Method
->getSelector();
3551 if (Sel
.isUnarySelector()) {
3552 Result
.AddTypedTextChunk(
3553 Result
.getAllocator().CopyString(Sel
.getNameForSlot(0)));
3554 return Result
.TakeString();
3557 std::string SelName
= Sel
.getNameForSlot(0).str();
3559 if (StartParameter
== 0)
3560 Result
.AddTypedTextChunk(Result
.getAllocator().CopyString(SelName
));
3562 Result
.AddInformativeChunk(Result
.getAllocator().CopyString(SelName
));
3564 // If there is only one parameter, and we're past it, add an empty
3565 // typed-text chunk since there is nothing to type.
3566 if (Method
->param_size() == 1)
3567 Result
.AddTypedTextChunk("");
3570 // The extra Idx < Sel.getNumArgs() check is needed due to legacy C-style
3571 // method parameters.
3572 for (ObjCMethodDecl::param_const_iterator P
= Method
->param_begin(),
3573 PEnd
= Method
->param_end();
3574 P
!= PEnd
&& Idx
< Sel
.getNumArgs(); (void)++P
, ++Idx
) {
3576 std::string Keyword
;
3577 if (Idx
> StartParameter
)
3578 Result
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
3579 if (IdentifierInfo
*II
= Sel
.getIdentifierInfoForSlot(Idx
))
3580 Keyword
+= II
->getName();
3582 if (Idx
< StartParameter
|| AllParametersAreInformative
)
3583 Result
.AddInformativeChunk(Result
.getAllocator().CopyString(Keyword
));
3585 Result
.AddTypedTextChunk(Result
.getAllocator().CopyString(Keyword
));
3588 // If we're before the starting parameter, skip the placeholder.
3589 if (Idx
< StartParameter
)
3593 QualType ParamType
= (*P
)->getType();
3594 Optional
<ArrayRef
<QualType
>> ObjCSubsts
;
3595 if (!CCContext
.getBaseType().isNull())
3596 ObjCSubsts
= CCContext
.getBaseType()->getObjCSubstitutions(Method
);
3598 if (ParamType
->isBlockPointerType() && !DeclaringEntity
)
3599 Arg
= FormatFunctionParameter(Policy
, *P
, true,
3600 /*SuppressBlock=*/false, ObjCSubsts
);
3603 ParamType
= ParamType
.substObjCTypeArgs(
3604 Ctx
, *ObjCSubsts
, ObjCSubstitutionContext::Parameter
);
3605 Arg
= "(" + formatObjCParamQualifiers((*P
)->getObjCDeclQualifier(),
3607 Arg
+= ParamType
.getAsString(Policy
) + ")";
3608 if (IdentifierInfo
*II
= (*P
)->getIdentifier())
3609 if (DeclaringEntity
|| AllParametersAreInformative
)
3610 Arg
+= II
->getName();
3613 if (Method
->isVariadic() && (P
+ 1) == PEnd
)
3616 if (DeclaringEntity
)
3617 Result
.AddTextChunk(Result
.getAllocator().CopyString(Arg
));
3618 else if (AllParametersAreInformative
)
3619 Result
.AddInformativeChunk(Result
.getAllocator().CopyString(Arg
));
3621 Result
.AddPlaceholderChunk(Result
.getAllocator().CopyString(Arg
));
3624 if (Method
->isVariadic()) {
3625 if (Method
->param_size() == 0) {
3626 if (DeclaringEntity
)
3627 Result
.AddTextChunk(", ...");
3628 else if (AllParametersAreInformative
)
3629 Result
.AddInformativeChunk(", ...");
3631 Result
.AddPlaceholderChunk(", ...");
3634 MaybeAddSentinel(PP
, Method
, Result
);
3637 return Result
.TakeString();
3641 AddQualifierToCompletionString(Result
, Qualifier
, QualifierIsInformative
,
3644 Result
.AddTypedTextChunk(
3645 Result
.getAllocator().CopyString(ND
->getNameAsString()));
3646 return Result
.TakeString();
3649 const RawComment
*clang::getCompletionComment(const ASTContext
&Ctx
,
3650 const NamedDecl
*ND
) {
3653 if (auto *RC
= Ctx
.getRawCommentForAnyRedecl(ND
))
3656 // Try to find comment from a property for ObjC methods.
3657 const auto *M
= dyn_cast
<ObjCMethodDecl
>(ND
);
3660 const ObjCPropertyDecl
*PDecl
= M
->findPropertyDecl();
3664 return Ctx
.getRawCommentForAnyRedecl(PDecl
);
3667 const RawComment
*clang::getPatternCompletionComment(const ASTContext
&Ctx
,
3668 const NamedDecl
*ND
) {
3669 const auto *M
= dyn_cast_or_null
<ObjCMethodDecl
>(ND
);
3670 if (!M
|| !M
->isPropertyAccessor())
3673 // Provide code completion comment for self.GetterName where
3674 // GetterName is the getter method for a property with name
3675 // different from the property name (declared via a property
3676 // getter attribute.
3677 const ObjCPropertyDecl
*PDecl
= M
->findPropertyDecl();
3680 if (PDecl
->getGetterName() == M
->getSelector() &&
3681 PDecl
->getIdentifier() != M
->getIdentifier()) {
3682 if (auto *RC
= Ctx
.getRawCommentForAnyRedecl(M
))
3684 if (auto *RC
= Ctx
.getRawCommentForAnyRedecl(PDecl
))
3690 const RawComment
*clang::getParameterComment(
3691 const ASTContext
&Ctx
,
3692 const CodeCompleteConsumer::OverloadCandidate
&Result
, unsigned ArgIndex
) {
3693 auto FDecl
= Result
.getFunction();
3696 if (ArgIndex
< FDecl
->getNumParams())
3697 return Ctx
.getRawCommentForAnyRedecl(FDecl
->getParamDecl(ArgIndex
));
3701 static void AddOverloadAggregateChunks(const RecordDecl
*RD
,
3702 const PrintingPolicy
&Policy
,
3703 CodeCompletionBuilder
&Result
,
3704 unsigned CurrentArg
) {
3705 unsigned ChunkIndex
= 0;
3706 auto AddChunk
= [&](llvm::StringRef Placeholder
) {
3708 Result
.AddChunk(CodeCompletionString::CK_Comma
);
3709 const char *Copy
= Result
.getAllocator().CopyString(Placeholder
);
3710 if (ChunkIndex
== CurrentArg
)
3711 Result
.AddCurrentParameterChunk(Copy
);
3713 Result
.AddPlaceholderChunk(Copy
);
3716 // Aggregate initialization has all bases followed by all fields.
3717 // (Bases are not legal in C++11 but in that case we never get here).
3718 if (auto *CRD
= llvm::dyn_cast
<CXXRecordDecl
>(RD
)) {
3719 for (const auto &Base
: CRD
->bases())
3720 AddChunk(Base
.getType().getAsString(Policy
));
3722 for (const auto &Field
: RD
->fields())
3723 AddChunk(FormatFunctionParameter(Policy
, Field
));
3726 /// Add function overload parameter chunks to the given code completion
3728 static void AddOverloadParameterChunks(
3729 ASTContext
&Context
, const PrintingPolicy
&Policy
,
3730 const FunctionDecl
*Function
, const FunctionProtoType
*Prototype
,
3731 FunctionProtoTypeLoc PrototypeLoc
, CodeCompletionBuilder
&Result
,
3732 unsigned CurrentArg
, unsigned Start
= 0, bool InOptional
= false) {
3733 if (!Function
&& !Prototype
) {
3734 Result
.AddChunk(CodeCompletionString::CK_CurrentParameter
, "...");
3738 bool FirstParameter
= true;
3739 unsigned NumParams
=
3740 Function
? Function
->getNumParams() : Prototype
->getNumParams();
3742 for (unsigned P
= Start
; P
!= NumParams
; ++P
) {
3743 if (Function
&& Function
->getParamDecl(P
)->hasDefaultArg() && !InOptional
) {
3744 // When we see an optional default argument, put that argument and
3745 // the remaining default arguments into a new, optional string.
3746 CodeCompletionBuilder
Opt(Result
.getAllocator(),
3747 Result
.getCodeCompletionTUInfo());
3748 if (!FirstParameter
)
3749 Opt
.AddChunk(CodeCompletionString::CK_Comma
);
3750 // Optional sections are nested.
3751 AddOverloadParameterChunks(Context
, Policy
, Function
, Prototype
,
3752 PrototypeLoc
, Opt
, CurrentArg
, P
,
3753 /*InOptional=*/true);
3754 Result
.AddOptionalChunk(Opt
.TakeString());
3759 FirstParameter
= false;
3761 Result
.AddChunk(CodeCompletionString::CK_Comma
);
3765 // Format the placeholder string.
3766 std::string Placeholder
;
3767 assert(P
< Prototype
->getNumParams());
3768 if (Function
|| PrototypeLoc
) {
3769 const ParmVarDecl
*Param
=
3770 Function
? Function
->getParamDecl(P
) : PrototypeLoc
.getParam(P
);
3771 Placeholder
= FormatFunctionParameter(Policy
, Param
);
3772 if (Param
->hasDefaultArg())
3773 Placeholder
+= GetDefaultValueString(Param
, Context
.getSourceManager(),
3774 Context
.getLangOpts());
3776 Placeholder
= Prototype
->getParamType(P
).getAsString(Policy
);
3779 if (P
== CurrentArg
)
3780 Result
.AddCurrentParameterChunk(
3781 Result
.getAllocator().CopyString(Placeholder
));
3783 Result
.AddPlaceholderChunk(Result
.getAllocator().CopyString(Placeholder
));
3786 if (Prototype
&& Prototype
->isVariadic()) {
3787 CodeCompletionBuilder
Opt(Result
.getAllocator(),
3788 Result
.getCodeCompletionTUInfo());
3789 if (!FirstParameter
)
3790 Opt
.AddChunk(CodeCompletionString::CK_Comma
);
3792 if (CurrentArg
< NumParams
)
3793 Opt
.AddPlaceholderChunk("...");
3795 Opt
.AddCurrentParameterChunk("...");
3797 Result
.AddOptionalChunk(Opt
.TakeString());
3802 formatTemplateParameterPlaceholder(const NamedDecl
*Param
, bool &Optional
,
3803 const PrintingPolicy
&Policy
) {
3804 if (const auto *Type
= dyn_cast
<TemplateTypeParmDecl
>(Param
)) {
3805 Optional
= Type
->hasDefaultArgument();
3806 } else if (const auto *NonType
= dyn_cast
<NonTypeTemplateParmDecl
>(Param
)) {
3807 Optional
= NonType
->hasDefaultArgument();
3808 } else if (const auto *Template
= dyn_cast
<TemplateTemplateParmDecl
>(Param
)) {
3809 Optional
= Template
->hasDefaultArgument();
3812 llvm::raw_string_ostream
OS(Result
);
3813 Param
->print(OS
, Policy
);
3817 static std::string
templateResultType(const TemplateDecl
*TD
,
3818 const PrintingPolicy
&Policy
) {
3819 if (const auto *CTD
= dyn_cast
<ClassTemplateDecl
>(TD
))
3820 return CTD
->getTemplatedDecl()->getKindName().str();
3821 if (const auto *VTD
= dyn_cast
<VarTemplateDecl
>(TD
))
3822 return VTD
->getTemplatedDecl()->getType().getAsString(Policy
);
3823 if (const auto *FTD
= dyn_cast
<FunctionTemplateDecl
>(TD
))
3824 return FTD
->getTemplatedDecl()->getReturnType().getAsString(Policy
);
3825 if (isa
<TypeAliasTemplateDecl
>(TD
))
3827 if (isa
<TemplateTemplateParmDecl
>(TD
))
3829 if (isa
<ConceptDecl
>(TD
))
3834 static CodeCompletionString
*createTemplateSignatureString(
3835 const TemplateDecl
*TD
, CodeCompletionBuilder
&Builder
, unsigned CurrentArg
,
3836 const PrintingPolicy
&Policy
) {
3837 llvm::ArrayRef
<NamedDecl
*> Params
= TD
->getTemplateParameters()->asArray();
3838 CodeCompletionBuilder
OptionalBuilder(Builder
.getAllocator(),
3839 Builder
.getCodeCompletionTUInfo());
3840 std::string ResultType
= templateResultType(TD
, Policy
);
3841 if (!ResultType
.empty())
3842 Builder
.AddResultTypeChunk(Builder
.getAllocator().CopyString(ResultType
));
3843 Builder
.AddTextChunk(
3844 Builder
.getAllocator().CopyString(TD
->getNameAsString()));
3845 Builder
.AddChunk(CodeCompletionString::CK_LeftAngle
);
3846 // Initially we're writing into the main string. Once we see an optional arg
3847 // (with default), we're writing into the nested optional chunk.
3848 CodeCompletionBuilder
*Current
= &Builder
;
3849 for (unsigned I
= 0; I
< Params
.size(); ++I
) {
3850 bool Optional
= false;
3851 std::string Placeholder
=
3852 formatTemplateParameterPlaceholder(Params
[I
], Optional
, Policy
);
3854 Current
= &OptionalBuilder
;
3856 Current
->AddChunk(CodeCompletionString::CK_Comma
);
3857 Current
->AddChunk(I
== CurrentArg
3858 ? CodeCompletionString::CK_CurrentParameter
3859 : CodeCompletionString::CK_Placeholder
,
3860 Current
->getAllocator().CopyString(Placeholder
));
3862 // Add the optional chunk to the main string if we ever used it.
3863 if (Current
== &OptionalBuilder
)
3864 Builder
.AddOptionalChunk(OptionalBuilder
.TakeString());
3865 Builder
.AddChunk(CodeCompletionString::CK_RightAngle
);
3866 // For function templates, ResultType was the function's return type.
3867 // Give some clue this is a function. (Don't show the possibly-bulky params).
3868 if (isa
<FunctionTemplateDecl
>(TD
))
3869 Builder
.AddInformativeChunk("()");
3870 return Builder
.TakeString();
3873 CodeCompletionString
*
3874 CodeCompleteConsumer::OverloadCandidate::CreateSignatureString(
3875 unsigned CurrentArg
, Sema
&S
, CodeCompletionAllocator
&Allocator
,
3876 CodeCompletionTUInfo
&CCTUInfo
, bool IncludeBriefComments
,
3877 bool Braced
) const {
3878 PrintingPolicy Policy
= getCompletionPrintingPolicy(S
);
3879 // Show signatures of constructors as they are declared:
3880 // vector(int n) rather than vector<string>(int n)
3881 // This is less noisy without being less clear, and avoids tricky cases.
3882 Policy
.SuppressTemplateArgsInCXXConstructors
= true;
3884 // FIXME: Set priority, availability appropriately.
3885 CodeCompletionBuilder
Result(Allocator
, CCTUInfo
, 1,
3886 CXAvailability_Available
);
3888 if (getKind() == CK_Template
)
3889 return createTemplateSignatureString(getTemplate(), Result
, CurrentArg
,
3892 FunctionDecl
*FDecl
= getFunction();
3893 const FunctionProtoType
*Proto
=
3894 dyn_cast_or_null
<FunctionProtoType
>(getFunctionType());
3896 // First, the name/type of the callee.
3897 if (getKind() == CK_Aggregate
) {
3898 Result
.AddTextChunk(
3899 Result
.getAllocator().CopyString(getAggregate()->getName()));
3901 if (IncludeBriefComments
) {
3902 if (auto RC
= getParameterComment(S
.getASTContext(), *this, CurrentArg
))
3903 Result
.addBriefComment(RC
->getBriefText(S
.getASTContext()));
3905 AddResultTypeChunk(S
.Context
, Policy
, FDecl
, QualType(), Result
);
3908 llvm::raw_string_ostream
OS(Name
);
3909 FDecl
->getDeclName().print(OS
, Policy
);
3910 Result
.AddTextChunk(Result
.getAllocator().CopyString(OS
.str()));
3912 // Function without a declaration. Just give the return type.
3913 Result
.AddResultTypeChunk(Result
.getAllocator().CopyString(
3914 getFunctionType()->getReturnType().getAsString(Policy
)));
3917 // Next, the brackets and parameters.
3918 Result
.AddChunk(Braced
? CodeCompletionString::CK_LeftBrace
3919 : CodeCompletionString::CK_LeftParen
);
3920 if (getKind() == CK_Aggregate
)
3921 AddOverloadAggregateChunks(getAggregate(), Policy
, Result
, CurrentArg
);
3923 AddOverloadParameterChunks(S
.getASTContext(), Policy
, FDecl
, Proto
,
3924 getFunctionProtoTypeLoc(), Result
, CurrentArg
);
3925 Result
.AddChunk(Braced
? CodeCompletionString::CK_RightBrace
3926 : CodeCompletionString::CK_RightParen
);
3928 return Result
.TakeString();
3931 unsigned clang::getMacroUsagePriority(StringRef MacroName
,
3932 const LangOptions
&LangOpts
,
3933 bool PreferredTypeIsPointer
) {
3934 unsigned Priority
= CCP_Macro
;
3936 // Treat the "nil", "Nil" and "NULL" macros as null pointer constants.
3937 if (MacroName
.equals("nil") || MacroName
.equals("NULL") ||
3938 MacroName
.equals("Nil")) {
3939 Priority
= CCP_Constant
;
3940 if (PreferredTypeIsPointer
)
3941 Priority
= Priority
/ CCF_SimilarTypeMatch
;
3943 // Treat "YES", "NO", "true", and "false" as constants.
3944 else if (MacroName
.equals("YES") || MacroName
.equals("NO") ||
3945 MacroName
.equals("true") || MacroName
.equals("false"))
3946 Priority
= CCP_Constant
;
3947 // Treat "bool" as a type.
3948 else if (MacroName
.equals("bool"))
3949 Priority
= CCP_Type
+ (LangOpts
.ObjC
? CCD_bool_in_ObjC
: 0);
3954 CXCursorKind
clang::getCursorKindForDecl(const Decl
*D
) {
3956 return CXCursor_UnexposedDecl
;
3958 switch (D
->getKind()) {
3960 return CXCursor_EnumDecl
;
3961 case Decl::EnumConstant
:
3962 return CXCursor_EnumConstantDecl
;
3964 return CXCursor_FieldDecl
;
3965 case Decl::Function
:
3966 return CXCursor_FunctionDecl
;
3967 case Decl::ObjCCategory
:
3968 return CXCursor_ObjCCategoryDecl
;
3969 case Decl::ObjCCategoryImpl
:
3970 return CXCursor_ObjCCategoryImplDecl
;
3971 case Decl::ObjCImplementation
:
3972 return CXCursor_ObjCImplementationDecl
;
3974 case Decl::ObjCInterface
:
3975 return CXCursor_ObjCInterfaceDecl
;
3976 case Decl::ObjCIvar
:
3977 return CXCursor_ObjCIvarDecl
;
3978 case Decl::ObjCMethod
:
3979 return cast
<ObjCMethodDecl
>(D
)->isInstanceMethod()
3980 ? CXCursor_ObjCInstanceMethodDecl
3981 : CXCursor_ObjCClassMethodDecl
;
3982 case Decl::CXXMethod
:
3983 return CXCursor_CXXMethod
;
3984 case Decl::CXXConstructor
:
3985 return CXCursor_Constructor
;
3986 case Decl::CXXDestructor
:
3987 return CXCursor_Destructor
;
3988 case Decl::CXXConversion
:
3989 return CXCursor_ConversionFunction
;
3990 case Decl::ObjCProperty
:
3991 return CXCursor_ObjCPropertyDecl
;
3992 case Decl::ObjCProtocol
:
3993 return CXCursor_ObjCProtocolDecl
;
3995 return CXCursor_ParmDecl
;
3997 return CXCursor_TypedefDecl
;
3998 case Decl::TypeAlias
:
3999 return CXCursor_TypeAliasDecl
;
4000 case Decl::TypeAliasTemplate
:
4001 return CXCursor_TypeAliasTemplateDecl
;
4003 return CXCursor_VarDecl
;
4004 case Decl::Namespace
:
4005 return CXCursor_Namespace
;
4006 case Decl::NamespaceAlias
:
4007 return CXCursor_NamespaceAlias
;
4008 case Decl::TemplateTypeParm
:
4009 return CXCursor_TemplateTypeParameter
;
4010 case Decl::NonTypeTemplateParm
:
4011 return CXCursor_NonTypeTemplateParameter
;
4012 case Decl::TemplateTemplateParm
:
4013 return CXCursor_TemplateTemplateParameter
;
4014 case Decl::FunctionTemplate
:
4015 return CXCursor_FunctionTemplate
;
4016 case Decl::ClassTemplate
:
4017 return CXCursor_ClassTemplate
;
4018 case Decl::AccessSpec
:
4019 return CXCursor_CXXAccessSpecifier
;
4020 case Decl::ClassTemplatePartialSpecialization
:
4021 return CXCursor_ClassTemplatePartialSpecialization
;
4022 case Decl::UsingDirective
:
4023 return CXCursor_UsingDirective
;
4024 case Decl::StaticAssert
:
4025 return CXCursor_StaticAssert
;
4027 return CXCursor_FriendDecl
;
4028 case Decl::TranslationUnit
:
4029 return CXCursor_TranslationUnit
;
4032 case Decl::UnresolvedUsingValue
:
4033 case Decl::UnresolvedUsingTypename
:
4034 return CXCursor_UsingDeclaration
;
4036 case Decl::UsingEnum
:
4037 return CXCursor_EnumDecl
;
4039 case Decl::ObjCPropertyImpl
:
4040 switch (cast
<ObjCPropertyImplDecl
>(D
)->getPropertyImplementation()) {
4041 case ObjCPropertyImplDecl::Dynamic
:
4042 return CXCursor_ObjCDynamicDecl
;
4044 case ObjCPropertyImplDecl::Synthesize
:
4045 return CXCursor_ObjCSynthesizeDecl
;
4047 llvm_unreachable("Unexpected Kind!");
4050 return CXCursor_ModuleImportDecl
;
4052 case Decl::ObjCTypeParam
:
4053 return CXCursor_TemplateTypeParameter
;
4056 return CXCursor_ConceptDecl
;
4059 if (const auto *TD
= dyn_cast
<TagDecl
>(D
)) {
4060 switch (TD
->getTagKind()) {
4061 case TTK_Interface
: // fall through
4063 return CXCursor_StructDecl
;
4065 return CXCursor_ClassDecl
;
4067 return CXCursor_UnionDecl
;
4069 return CXCursor_EnumDecl
;
4074 return CXCursor_UnexposedDecl
;
4077 static void AddMacroResults(Preprocessor
&PP
, ResultBuilder
&Results
,
4078 bool LoadExternal
, bool IncludeUndefined
,
4079 bool TargetTypeIsPointer
= false) {
4080 typedef CodeCompletionResult Result
;
4082 Results
.EnterNewScope();
4084 for (Preprocessor::macro_iterator M
= PP
.macro_begin(LoadExternal
),
4085 MEnd
= PP
.macro_end(LoadExternal
);
4087 auto MD
= PP
.getMacroDefinition(M
->first
);
4088 if (IncludeUndefined
|| MD
) {
4089 MacroInfo
*MI
= MD
.getMacroInfo();
4090 if (MI
&& MI
->isUsedForHeaderGuard())
4094 Result(M
->first
, MI
,
4095 getMacroUsagePriority(M
->first
->getName(), PP
.getLangOpts(),
4096 TargetTypeIsPointer
)));
4100 Results
.ExitScope();
4103 static void AddPrettyFunctionResults(const LangOptions
&LangOpts
,
4104 ResultBuilder
&Results
) {
4105 typedef CodeCompletionResult Result
;
4107 Results
.EnterNewScope();
4109 Results
.AddResult(Result("__PRETTY_FUNCTION__", CCP_Constant
));
4110 Results
.AddResult(Result("__FUNCTION__", CCP_Constant
));
4111 if (LangOpts
.C99
|| LangOpts
.CPlusPlus11
)
4112 Results
.AddResult(Result("__func__", CCP_Constant
));
4113 Results
.ExitScope();
4116 static void HandleCodeCompleteResults(Sema
*S
,
4117 CodeCompleteConsumer
*CodeCompleter
,
4118 CodeCompletionContext Context
,
4119 CodeCompletionResult
*Results
,
4120 unsigned NumResults
) {
4122 CodeCompleter
->ProcessCodeCompleteResults(*S
, Context
, Results
, NumResults
);
4125 static CodeCompletionContext
4126 mapCodeCompletionContext(Sema
&S
, Sema::ParserCompletionContext PCC
) {
4128 case Sema::PCC_Namespace
:
4129 return CodeCompletionContext::CCC_TopLevel
;
4131 case Sema::PCC_Class
:
4132 return CodeCompletionContext::CCC_ClassStructUnion
;
4134 case Sema::PCC_ObjCInterface
:
4135 return CodeCompletionContext::CCC_ObjCInterface
;
4137 case Sema::PCC_ObjCImplementation
:
4138 return CodeCompletionContext::CCC_ObjCImplementation
;
4140 case Sema::PCC_ObjCInstanceVariableList
:
4141 return CodeCompletionContext::CCC_ObjCIvarList
;
4143 case Sema::PCC_Template
:
4144 case Sema::PCC_MemberTemplate
:
4145 if (S
.CurContext
->isFileContext())
4146 return CodeCompletionContext::CCC_TopLevel
;
4147 if (S
.CurContext
->isRecord())
4148 return CodeCompletionContext::CCC_ClassStructUnion
;
4149 return CodeCompletionContext::CCC_Other
;
4151 case Sema::PCC_RecoveryInFunction
:
4152 return CodeCompletionContext::CCC_Recovery
;
4154 case Sema::PCC_ForInit
:
4155 if (S
.getLangOpts().CPlusPlus
|| S
.getLangOpts().C99
||
4156 S
.getLangOpts().ObjC
)
4157 return CodeCompletionContext::CCC_ParenthesizedExpression
;
4159 return CodeCompletionContext::CCC_Expression
;
4161 case Sema::PCC_Expression
:
4162 return CodeCompletionContext::CCC_Expression
;
4163 case Sema::PCC_Condition
:
4164 return CodeCompletionContext(CodeCompletionContext::CCC_Expression
,
4165 S
.getASTContext().BoolTy
);
4167 case Sema::PCC_Statement
:
4168 return CodeCompletionContext::CCC_Statement
;
4170 case Sema::PCC_Type
:
4171 return CodeCompletionContext::CCC_Type
;
4173 case Sema::PCC_ParenthesizedExpression
:
4174 return CodeCompletionContext::CCC_ParenthesizedExpression
;
4176 case Sema::PCC_LocalDeclarationSpecifiers
:
4177 return CodeCompletionContext::CCC_Type
;
4180 llvm_unreachable("Invalid ParserCompletionContext!");
4183 /// If we're in a C++ virtual member function, add completion results
4184 /// that invoke the functions we override, since it's common to invoke the
4185 /// overridden function as well as adding new functionality.
4187 /// \param S The semantic analysis object for which we are generating results.
4189 /// \param InContext This context in which the nested-name-specifier preceding
4190 /// the code-completion point
4191 static void MaybeAddOverrideCalls(Sema
&S
, DeclContext
*InContext
,
4192 ResultBuilder
&Results
) {
4193 // Look through blocks.
4194 DeclContext
*CurContext
= S
.CurContext
;
4195 while (isa
<BlockDecl
>(CurContext
))
4196 CurContext
= CurContext
->getParent();
4198 CXXMethodDecl
*Method
= dyn_cast
<CXXMethodDecl
>(CurContext
);
4199 if (!Method
|| !Method
->isVirtual())
4202 // We need to have names for all of the parameters, if we're going to
4203 // generate a forwarding call.
4204 for (auto *P
: Method
->parameters())
4205 if (!P
->getDeclName())
4208 PrintingPolicy Policy
= getCompletionPrintingPolicy(S
);
4209 for (const CXXMethodDecl
*Overridden
: Method
->overridden_methods()) {
4210 CodeCompletionBuilder
Builder(Results
.getAllocator(),
4211 Results
.getCodeCompletionTUInfo());
4212 if (Overridden
->getCanonicalDecl() == Method
->getCanonicalDecl())
4215 // If we need a nested-name-specifier, add one now.
4217 NestedNameSpecifier
*NNS
= getRequiredQualification(
4218 S
.Context
, CurContext
, Overridden
->getDeclContext());
4221 llvm::raw_string_ostream
OS(Str
);
4222 NNS
->print(OS
, Policy
);
4223 Builder
.AddTextChunk(Results
.getAllocator().CopyString(OS
.str()));
4225 } else if (!InContext
->Equals(Overridden
->getDeclContext()))
4228 Builder
.AddTypedTextChunk(
4229 Results
.getAllocator().CopyString(Overridden
->getNameAsString()));
4230 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
4231 bool FirstParam
= true;
4232 for (auto *P
: Method
->parameters()) {
4236 Builder
.AddChunk(CodeCompletionString::CK_Comma
);
4238 Builder
.AddPlaceholderChunk(
4239 Results
.getAllocator().CopyString(P
->getIdentifier()->getName()));
4241 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
4242 Results
.AddResult(CodeCompletionResult(
4243 Builder
.TakeString(), CCP_SuperCompletion
, CXCursor_CXXMethod
,
4244 CXAvailability_Available
, Overridden
));
4245 Results
.Ignore(Overridden
);
4249 void Sema::CodeCompleteModuleImport(SourceLocation ImportLoc
,
4250 ModuleIdPath Path
) {
4251 typedef CodeCompletionResult Result
;
4252 ResultBuilder
Results(*this, CodeCompleter
->getAllocator(),
4253 CodeCompleter
->getCodeCompletionTUInfo(),
4254 CodeCompletionContext::CCC_Other
);
4255 Results
.EnterNewScope();
4257 CodeCompletionAllocator
&Allocator
= Results
.getAllocator();
4258 CodeCompletionBuilder
Builder(Allocator
, Results
.getCodeCompletionTUInfo());
4259 typedef CodeCompletionResult Result
;
4261 // Enumerate all top-level modules.
4262 SmallVector
<Module
*, 8> Modules
;
4263 PP
.getHeaderSearchInfo().collectAllModules(Modules
);
4264 for (unsigned I
= 0, N
= Modules
.size(); I
!= N
; ++I
) {
4265 Builder
.AddTypedTextChunk(
4266 Builder
.getAllocator().CopyString(Modules
[I
]->Name
));
4267 Results
.AddResult(Result(
4268 Builder
.TakeString(), CCP_Declaration
, CXCursor_ModuleImportDecl
,
4269 Modules
[I
]->isAvailable() ? CXAvailability_Available
4270 : CXAvailability_NotAvailable
));
4272 } else if (getLangOpts().Modules
) {
4273 // Load the named module.
4275 PP
.getModuleLoader().loadModule(ImportLoc
, Path
, Module::AllVisible
,
4276 /*IsInclusionDirective=*/false);
4277 // Enumerate submodules.
4279 for (Module::submodule_iterator Sub
= Mod
->submodule_begin(),
4280 SubEnd
= Mod
->submodule_end();
4281 Sub
!= SubEnd
; ++Sub
) {
4283 Builder
.AddTypedTextChunk(
4284 Builder
.getAllocator().CopyString((*Sub
)->Name
));
4285 Results
.AddResult(Result(
4286 Builder
.TakeString(), CCP_Declaration
, CXCursor_ModuleImportDecl
,
4287 (*Sub
)->isAvailable() ? CXAvailability_Available
4288 : CXAvailability_NotAvailable
));
4292 Results
.ExitScope();
4293 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
4294 Results
.data(), Results
.size());
4297 void Sema::CodeCompleteOrdinaryName(Scope
*S
,
4298 ParserCompletionContext CompletionContext
) {
4299 ResultBuilder
Results(*this, CodeCompleter
->getAllocator(),
4300 CodeCompleter
->getCodeCompletionTUInfo(),
4301 mapCodeCompletionContext(*this, CompletionContext
));
4302 Results
.EnterNewScope();
4304 // Determine how to filter results, e.g., so that the names of
4305 // values (functions, enumerators, function templates, etc.) are
4306 // only allowed where we can have an expression.
4307 switch (CompletionContext
) {
4310 case PCC_ObjCInterface
:
4311 case PCC_ObjCImplementation
:
4312 case PCC_ObjCInstanceVariableList
:
4314 case PCC_MemberTemplate
:
4316 case PCC_LocalDeclarationSpecifiers
:
4317 Results
.setFilter(&ResultBuilder::IsOrdinaryNonValueName
);
4321 case PCC_ParenthesizedExpression
:
4322 case PCC_Expression
:
4325 if (WantTypesInContext(CompletionContext
, getLangOpts()))
4326 Results
.setFilter(&ResultBuilder::IsOrdinaryName
);
4328 Results
.setFilter(&ResultBuilder::IsOrdinaryNonTypeName
);
4330 if (getLangOpts().CPlusPlus
)
4331 MaybeAddOverrideCalls(*this, /*InContext=*/nullptr, Results
);
4334 case PCC_RecoveryInFunction
:
4339 // If we are in a C++ non-static member function, check the qualifiers on
4340 // the member function to filter/prioritize the results list.
4341 auto ThisType
= getCurrentThisType();
4342 if (!ThisType
.isNull())
4343 Results
.setObjectTypeQualifiers(ThisType
->getPointeeType().getQualifiers(),
4346 CodeCompletionDeclConsumer
Consumer(Results
, CurContext
);
4347 LookupVisibleDecls(S
, LookupOrdinaryName
, Consumer
,
4348 CodeCompleter
->includeGlobals(),
4349 CodeCompleter
->loadExternal());
4351 AddOrdinaryNameResults(CompletionContext
, S
, *this, Results
);
4352 Results
.ExitScope();
4354 switch (CompletionContext
) {
4355 case PCC_ParenthesizedExpression
:
4356 case PCC_Expression
:
4358 case PCC_RecoveryInFunction
:
4359 if (S
->getFnParent())
4360 AddPrettyFunctionResults(getLangOpts(), Results
);
4365 case PCC_ObjCInterface
:
4366 case PCC_ObjCImplementation
:
4367 case PCC_ObjCInstanceVariableList
:
4369 case PCC_MemberTemplate
:
4373 case PCC_LocalDeclarationSpecifiers
:
4377 if (CodeCompleter
->includeMacros())
4378 AddMacroResults(PP
, Results
, CodeCompleter
->loadExternal(), false);
4380 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
4381 Results
.data(), Results
.size());
4384 static void AddClassMessageCompletions(Sema
&SemaRef
, Scope
*S
,
4385 ParsedType Receiver
,
4386 ArrayRef
<IdentifierInfo
*> SelIdents
,
4387 bool AtArgumentExpression
, bool IsSuper
,
4388 ResultBuilder
&Results
);
4390 void Sema::CodeCompleteDeclSpec(Scope
*S
, DeclSpec
&DS
,
4391 bool AllowNonIdentifiers
,
4392 bool AllowNestedNameSpecifiers
) {
4393 typedef CodeCompletionResult Result
;
4394 ResultBuilder
Results(
4395 *this, CodeCompleter
->getAllocator(),
4396 CodeCompleter
->getCodeCompletionTUInfo(),
4397 AllowNestedNameSpecifiers
4398 // FIXME: Try to separate codepath leading here to deduce whether we
4399 // need an existing symbol or a new one.
4400 ? CodeCompletionContext::CCC_SymbolOrNewName
4401 : CodeCompletionContext::CCC_NewName
);
4402 Results
.EnterNewScope();
4404 // Type qualifiers can come after names.
4405 Results
.AddResult(Result("const"));
4406 Results
.AddResult(Result("volatile"));
4407 if (getLangOpts().C99
)
4408 Results
.AddResult(Result("restrict"));
4410 if (getLangOpts().CPlusPlus
) {
4411 if (getLangOpts().CPlusPlus11
&&
4412 (DS
.getTypeSpecType() == DeclSpec::TST_class
||
4413 DS
.getTypeSpecType() == DeclSpec::TST_struct
))
4414 Results
.AddResult("final");
4416 if (AllowNonIdentifiers
) {
4417 Results
.AddResult(Result("operator"));
4420 // Add nested-name-specifiers.
4421 if (AllowNestedNameSpecifiers
) {
4422 Results
.allowNestedNameSpecifiers();
4423 Results
.setFilter(&ResultBuilder::IsImpossibleToSatisfy
);
4424 CodeCompletionDeclConsumer
Consumer(Results
, CurContext
);
4425 LookupVisibleDecls(S
, LookupNestedNameSpecifierName
, Consumer
,
4426 CodeCompleter
->includeGlobals(),
4427 CodeCompleter
->loadExternal());
4428 Results
.setFilter(nullptr);
4431 Results
.ExitScope();
4433 // If we're in a context where we might have an expression (rather than a
4434 // declaration), and what we've seen so far is an Objective-C type that could
4435 // be a receiver of a class message, this may be a class message send with
4436 // the initial opening bracket '[' missing. Add appropriate completions.
4437 if (AllowNonIdentifiers
&& !AllowNestedNameSpecifiers
&&
4438 DS
.getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier
&&
4439 DS
.getTypeSpecType() == DeclSpec::TST_typename
&&
4440 DS
.getTypeSpecComplex() == DeclSpec::TSC_unspecified
&&
4441 DS
.getTypeSpecSign() == TypeSpecifierSign::Unspecified
&&
4442 !DS
.isTypeAltiVecVector() && S
&&
4443 (S
->getFlags() & Scope::DeclScope
) != 0 &&
4444 (S
->getFlags() & (Scope::ClassScope
| Scope::TemplateParamScope
|
4445 Scope::FunctionPrototypeScope
| Scope::AtCatchScope
)) ==
4447 ParsedType T
= DS
.getRepAsType();
4448 if (!T
.get().isNull() && T
.get()->isObjCObjectOrInterfaceType())
4449 AddClassMessageCompletions(*this, S
, T
, None
, false, false, Results
);
4452 // Note that we intentionally suppress macro results here, since we do not
4453 // encourage using macros to produce the names of entities.
4455 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
4456 Results
.data(), Results
.size());
4459 static const char *underscoreAttrScope(llvm::StringRef Scope
) {
4460 if (Scope
== "clang")
4467 static const char *noUnderscoreAttrScope(llvm::StringRef Scope
) {
4468 if (Scope
== "_Clang")
4470 if (Scope
== "__gnu__")
4475 void Sema::CodeCompleteAttribute(AttributeCommonInfo::Syntax Syntax
,
4476 AttributeCompletion Completion
,
4477 const IdentifierInfo
*InScope
) {
4478 if (Completion
== AttributeCompletion::None
)
4480 ResultBuilder
Results(*this, CodeCompleter
->getAllocator(),
4481 CodeCompleter
->getCodeCompletionTUInfo(),
4482 CodeCompletionContext::CCC_Attribute
);
4484 // We're going to iterate over the normalized spellings of the attribute.
4485 // These don't include "underscore guarding": the normalized spelling is
4486 // clang::foo but you can also write _Clang::__foo__.
4488 // (Clang supports a mix like clang::__foo__ but we won't suggest it: either
4489 // you care about clashing with macros or you don't).
4491 // So if we're already in a scope, we determine its canonical spellings
4492 // (for comparison with normalized attr spelling) and remember whether it was
4493 // underscore-guarded (so we know how to spell contained attributes).
4494 llvm::StringRef InScopeName
;
4495 bool InScopeUnderscore
= false;
4497 InScopeName
= InScope
->getName();
4498 if (const char *NoUnderscore
= noUnderscoreAttrScope(InScopeName
)) {
4499 InScopeName
= NoUnderscore
;
4500 InScopeUnderscore
= true;
4503 bool SyntaxSupportsGuards
= Syntax
== AttributeCommonInfo::AS_GNU
||
4504 Syntax
== AttributeCommonInfo::AS_CXX11
||
4505 Syntax
== AttributeCommonInfo::AS_C2x
;
4507 llvm::DenseSet
<llvm::StringRef
> FoundScopes
;
4508 auto AddCompletions
= [&](const ParsedAttrInfo
&A
) {
4509 if (A
.IsTargetSpecific
&& !A
.existsInTarget(Context
.getTargetInfo()))
4511 if (!A
.acceptsLangOpts(getLangOpts()))
4513 for (const auto &S
: A
.Spellings
) {
4514 if (S
.Syntax
!= Syntax
)
4516 llvm::StringRef Name
= S
.NormalizedFullName
;
4517 llvm::StringRef Scope
;
4518 if ((Syntax
== AttributeCommonInfo::AS_CXX11
||
4519 Syntax
== AttributeCommonInfo::AS_C2x
)) {
4520 std::tie(Scope
, Name
) = Name
.split("::");
4521 if (Name
.empty()) // oops, unscoped
4522 std::swap(Name
, Scope
);
4525 // Do we just want a list of scopes rather than attributes?
4526 if (Completion
== AttributeCompletion::Scope
) {
4527 // Make sure to emit each scope only once.
4528 if (!Scope
.empty() && FoundScopes
.insert(Scope
).second
) {
4530 CodeCompletionResult(Results
.getAllocator().CopyString(Scope
)));
4531 // Include alternate form (__gnu__ instead of gnu).
4532 if (const char *Scope2
= underscoreAttrScope(Scope
))
4533 Results
.AddResult(CodeCompletionResult(Scope2
));
4538 // If a scope was specified, it must match but we don't need to print it.
4539 if (!InScopeName
.empty()) {
4540 if (Scope
!= InScopeName
)
4545 auto Add
= [&](llvm::StringRef Scope
, llvm::StringRef Name
,
4547 CodeCompletionBuilder
Builder(Results
.getAllocator(),
4548 Results
.getCodeCompletionTUInfo());
4549 llvm::SmallString
<32> Text
;
4550 if (!Scope
.empty()) {
4559 Builder
.AddTypedTextChunk(Results
.getAllocator().CopyString(Text
));
4561 if (!A
.ArgNames
.empty()) {
4562 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
, "(");
4564 for (const char *Arg
: A
.ArgNames
) {
4566 Builder
.AddChunk(CodeCompletionString::CK_Comma
, ", ");
4568 Builder
.AddPlaceholderChunk(Arg
);
4570 Builder
.AddChunk(CodeCompletionString::CK_RightParen
, ")");
4573 Results
.AddResult(Builder
.TakeString());
4576 // Generate the non-underscore-guarded result.
4577 // Note this is (a suffix of) the NormalizedFullName, no need to copy.
4578 // If an underscore-guarded scope was specified, only the
4579 // underscore-guarded attribute name is relevant.
4580 if (!InScopeUnderscore
)
4581 Add(Scope
, Name
, /*Underscores=*/false);
4583 // Generate the underscore-guarded version, for syntaxes that support it.
4584 // We skip this if the scope was already spelled and not guarded, or
4585 // we must spell it and can't guard it.
4586 if (!(InScope
&& !InScopeUnderscore
) && SyntaxSupportsGuards
) {
4587 llvm::SmallString
<32> Guarded
;
4588 if (Scope
.empty()) {
4589 Add(Scope
, Name
, /*Underscores=*/true);
4591 const char *GuardedScope
= underscoreAttrScope(Scope
);
4594 Add(GuardedScope
, Name
, /*Underscores=*/true);
4598 // It may be nice to include the Kind so we can look up the docs later.
4602 for (const auto *A
: ParsedAttrInfo::getAllBuiltin())
4604 for (const auto &Entry
: ParsedAttrInfoRegistry::entries())
4605 AddCompletions(*Entry
.instantiate());
4607 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
4608 Results
.data(), Results
.size());
4611 struct Sema::CodeCompleteExpressionData
{
4612 CodeCompleteExpressionData(QualType PreferredType
= QualType(),
4613 bool IsParenthesized
= false)
4614 : PreferredType(PreferredType
), IntegralConstantExpression(false),
4615 ObjCCollection(false), IsParenthesized(IsParenthesized
) {}
4617 QualType PreferredType
;
4618 bool IntegralConstantExpression
;
4619 bool ObjCCollection
;
4620 bool IsParenthesized
;
4621 SmallVector
<Decl
*, 4> IgnoreDecls
;
4625 /// Information that allows to avoid completing redundant enumerators.
4626 struct CoveredEnumerators
{
4627 llvm::SmallPtrSet
<EnumConstantDecl
*, 8> Seen
;
4628 NestedNameSpecifier
*SuggestedQualifier
= nullptr;
4632 static void AddEnumerators(ResultBuilder
&Results
, ASTContext
&Context
,
4633 EnumDecl
*Enum
, DeclContext
*CurContext
,
4634 const CoveredEnumerators
&Enumerators
) {
4635 NestedNameSpecifier
*Qualifier
= Enumerators
.SuggestedQualifier
;
4636 if (Context
.getLangOpts().CPlusPlus
&& !Qualifier
&& Enumerators
.Seen
.empty()) {
4637 // If there are no prior enumerators in C++, check whether we have to
4638 // qualify the names of the enumerators that we suggest, because they
4639 // may not be visible in this scope.
4640 Qualifier
= getRequiredQualification(Context
, CurContext
, Enum
);
4643 Results
.EnterNewScope();
4644 for (auto *E
: Enum
->enumerators()) {
4645 if (Enumerators
.Seen
.count(E
))
4648 CodeCompletionResult
R(E
, CCP_EnumInCase
, Qualifier
);
4649 Results
.AddResult(R
, CurContext
, nullptr, false);
4651 Results
.ExitScope();
4654 /// Try to find a corresponding FunctionProtoType for function-like types (e.g.
4655 /// function pointers, std::function, etc).
4656 static const FunctionProtoType
*TryDeconstructFunctionLike(QualType T
) {
4657 assert(!T
.isNull());
4658 // Try to extract first template argument from std::function<> and similar.
4659 // Note we only handle the sugared types, they closely match what users wrote.
4660 // We explicitly choose to not handle ClassTemplateSpecializationDecl.
4661 if (auto *Specialization
= T
->getAs
<TemplateSpecializationType
>()) {
4662 if (Specialization
->getNumArgs() != 1)
4664 const TemplateArgument
&Argument
= Specialization
->getArg(0);
4665 if (Argument
.getKind() != TemplateArgument::Type
)
4667 return Argument
.getAsType()->getAs
<FunctionProtoType
>();
4669 // Handle other cases.
4670 if (T
->isPointerType())
4671 T
= T
->getPointeeType();
4672 return T
->getAs
<FunctionProtoType
>();
4675 /// Adds a pattern completion for a lambda expression with the specified
4676 /// parameter types and placeholders for parameter names.
4677 static void AddLambdaCompletion(ResultBuilder
&Results
,
4678 llvm::ArrayRef
<QualType
> Parameters
,
4679 const LangOptions
&LangOpts
) {
4680 if (!Results
.includeCodePatterns())
4682 CodeCompletionBuilder
Completion(Results
.getAllocator(),
4683 Results
.getCodeCompletionTUInfo());
4684 // [](<parameters>) {}
4685 Completion
.AddChunk(CodeCompletionString::CK_LeftBracket
);
4686 Completion
.AddPlaceholderChunk("=");
4687 Completion
.AddChunk(CodeCompletionString::CK_RightBracket
);
4688 if (!Parameters
.empty()) {
4689 Completion
.AddChunk(CodeCompletionString::CK_LeftParen
);
4691 for (auto Parameter
: Parameters
) {
4693 Completion
.AddChunk(CodeCompletionString::ChunkKind::CK_Comma
);
4697 constexpr llvm::StringLiteral NamePlaceholder
= "!#!NAME_GOES_HERE!#!";
4698 std::string Type
= std::string(NamePlaceholder
);
4699 Parameter
.getAsStringInternal(Type
, PrintingPolicy(LangOpts
));
4700 llvm::StringRef Prefix
, Suffix
;
4701 std::tie(Prefix
, Suffix
) = llvm::StringRef(Type
).split(NamePlaceholder
);
4702 Prefix
= Prefix
.rtrim();
4703 Suffix
= Suffix
.ltrim();
4705 Completion
.AddTextChunk(Completion
.getAllocator().CopyString(Prefix
));
4706 Completion
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
4707 Completion
.AddPlaceholderChunk("parameter");
4708 Completion
.AddTextChunk(Completion
.getAllocator().CopyString(Suffix
));
4710 Completion
.AddChunk(CodeCompletionString::CK_RightParen
);
4712 Completion
.AddChunk(clang::CodeCompletionString::CK_HorizontalSpace
);
4713 Completion
.AddChunk(CodeCompletionString::CK_LeftBrace
);
4714 Completion
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
4715 Completion
.AddPlaceholderChunk("body");
4716 Completion
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
4717 Completion
.AddChunk(CodeCompletionString::CK_RightBrace
);
4719 Results
.AddResult(Completion
.TakeString());
4722 /// Perform code-completion in an expression context when we know what
4723 /// type we're looking for.
4724 void Sema::CodeCompleteExpression(Scope
*S
,
4725 const CodeCompleteExpressionData
&Data
) {
4726 ResultBuilder
Results(
4727 *this, CodeCompleter
->getAllocator(),
4728 CodeCompleter
->getCodeCompletionTUInfo(),
4729 CodeCompletionContext(
4730 Data
.IsParenthesized
4731 ? CodeCompletionContext::CCC_ParenthesizedExpression
4732 : CodeCompletionContext::CCC_Expression
,
4733 Data
.PreferredType
));
4735 Data
.IsParenthesized
? PCC_ParenthesizedExpression
: PCC_Expression
;
4736 if (Data
.ObjCCollection
)
4737 Results
.setFilter(&ResultBuilder::IsObjCCollection
);
4738 else if (Data
.IntegralConstantExpression
)
4739 Results
.setFilter(&ResultBuilder::IsIntegralConstantValue
);
4740 else if (WantTypesInContext(PCC
, getLangOpts()))
4741 Results
.setFilter(&ResultBuilder::IsOrdinaryName
);
4743 Results
.setFilter(&ResultBuilder::IsOrdinaryNonTypeName
);
4745 if (!Data
.PreferredType
.isNull())
4746 Results
.setPreferredType(Data
.PreferredType
.getNonReferenceType());
4748 // Ignore any declarations that we were told that we don't care about.
4749 for (unsigned I
= 0, N
= Data
.IgnoreDecls
.size(); I
!= N
; ++I
)
4750 Results
.Ignore(Data
.IgnoreDecls
[I
]);
4752 CodeCompletionDeclConsumer
Consumer(Results
, CurContext
);
4753 LookupVisibleDecls(S
, LookupOrdinaryName
, Consumer
,
4754 CodeCompleter
->includeGlobals(),
4755 CodeCompleter
->loadExternal());
4757 Results
.EnterNewScope();
4758 AddOrdinaryNameResults(PCC
, S
, *this, Results
);
4759 Results
.ExitScope();
4761 bool PreferredTypeIsPointer
= false;
4762 if (!Data
.PreferredType
.isNull()) {
4763 PreferredTypeIsPointer
= Data
.PreferredType
->isAnyPointerType() ||
4764 Data
.PreferredType
->isMemberPointerType() ||
4765 Data
.PreferredType
->isBlockPointerType();
4766 if (Data
.PreferredType
->isEnumeralType()) {
4767 EnumDecl
*Enum
= Data
.PreferredType
->castAs
<EnumType
>()->getDecl();
4768 if (auto *Def
= Enum
->getDefinition())
4770 // FIXME: collect covered enumerators in cases like:
4771 // if (x == my_enum::one) { ... } else if (x == ^) {}
4772 AddEnumerators(Results
, Context
, Enum
, CurContext
, CoveredEnumerators());
4776 if (S
->getFnParent() && !Data
.ObjCCollection
&&
4777 !Data
.IntegralConstantExpression
)
4778 AddPrettyFunctionResults(getLangOpts(), Results
);
4780 if (CodeCompleter
->includeMacros())
4781 AddMacroResults(PP
, Results
, CodeCompleter
->loadExternal(), false,
4782 PreferredTypeIsPointer
);
4784 // Complete a lambda expression when preferred type is a function.
4785 if (!Data
.PreferredType
.isNull() && getLangOpts().CPlusPlus11
) {
4786 if (const FunctionProtoType
*F
=
4787 TryDeconstructFunctionLike(Data
.PreferredType
))
4788 AddLambdaCompletion(Results
, F
->getParamTypes(), getLangOpts());
4791 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
4792 Results
.data(), Results
.size());
4795 void Sema::CodeCompleteExpression(Scope
*S
, QualType PreferredType
,
4796 bool IsParenthesized
) {
4797 return CodeCompleteExpression(
4798 S
, CodeCompleteExpressionData(PreferredType
, IsParenthesized
));
4801 void Sema::CodeCompletePostfixExpression(Scope
*S
, ExprResult E
,
4802 QualType PreferredType
) {
4804 CodeCompleteExpression(S
, PreferredType
);
4805 else if (getLangOpts().ObjC
)
4806 CodeCompleteObjCInstanceMessage(S
, E
.get(), None
, false);
4809 /// The set of properties that have already been added, referenced by
4811 typedef llvm::SmallPtrSet
<IdentifierInfo
*, 16> AddedPropertiesSet
;
4813 /// Retrieve the container definition, if any?
4814 static ObjCContainerDecl
*getContainerDef(ObjCContainerDecl
*Container
) {
4815 if (ObjCInterfaceDecl
*Interface
= dyn_cast
<ObjCInterfaceDecl
>(Container
)) {
4816 if (Interface
->hasDefinition())
4817 return Interface
->getDefinition();
4822 if (ObjCProtocolDecl
*Protocol
= dyn_cast
<ObjCProtocolDecl
>(Container
)) {
4823 if (Protocol
->hasDefinition())
4824 return Protocol
->getDefinition();
4831 /// Adds a block invocation code completion result for the given block
4832 /// declaration \p BD.
4833 static void AddObjCBlockCall(ASTContext
&Context
, const PrintingPolicy
&Policy
,
4834 CodeCompletionBuilder
&Builder
,
4835 const NamedDecl
*BD
,
4836 const FunctionTypeLoc
&BlockLoc
,
4837 const FunctionProtoTypeLoc
&BlockProtoLoc
) {
4838 Builder
.AddResultTypeChunk(
4839 GetCompletionTypeString(BlockLoc
.getReturnLoc().getType(), Context
,
4840 Policy
, Builder
.getAllocator()));
4842 AddTypedNameChunk(Context
, Policy
, BD
, Builder
);
4843 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
4845 if (BlockProtoLoc
&& BlockProtoLoc
.getTypePtr()->isVariadic()) {
4846 Builder
.AddPlaceholderChunk("...");
4848 for (unsigned I
= 0, N
= BlockLoc
.getNumParams(); I
!= N
; ++I
) {
4850 Builder
.AddChunk(CodeCompletionString::CK_Comma
);
4852 // Format the placeholder string.
4853 std::string PlaceholderStr
=
4854 FormatFunctionParameter(Policy
, BlockLoc
.getParam(I
));
4856 if (I
== N
- 1 && BlockProtoLoc
&&
4857 BlockProtoLoc
.getTypePtr()->isVariadic())
4858 PlaceholderStr
+= ", ...";
4860 // Add the placeholder string.
4861 Builder
.AddPlaceholderChunk(
4862 Builder
.getAllocator().CopyString(PlaceholderStr
));
4866 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
4870 AddObjCProperties(const CodeCompletionContext
&CCContext
,
4871 ObjCContainerDecl
*Container
, bool AllowCategories
,
4872 bool AllowNullaryMethods
, DeclContext
*CurContext
,
4873 AddedPropertiesSet
&AddedProperties
, ResultBuilder
&Results
,
4874 bool IsBaseExprStatement
= false,
4875 bool IsClassProperty
= false, bool InOriginalClass
= true) {
4876 typedef CodeCompletionResult Result
;
4878 // Retrieve the definition.
4879 Container
= getContainerDef(Container
);
4881 // Add properties in this container.
4882 const auto AddProperty
= [&](const ObjCPropertyDecl
*P
) {
4883 if (!AddedProperties
.insert(P
->getIdentifier()).second
)
4886 // FIXME: Provide block invocation completion for non-statement
4888 if (!P
->getType().getTypePtr()->isBlockPointerType() ||
4889 !IsBaseExprStatement
) {
4890 Result R
= Result(P
, Results
.getBasePriority(P
), nullptr);
4891 if (!InOriginalClass
)
4893 Results
.MaybeAddResult(R
, CurContext
);
4897 // Block setter and invocation completion is provided only when we are able
4898 // to find the FunctionProtoTypeLoc with parameter names for the block.
4899 FunctionTypeLoc BlockLoc
;
4900 FunctionProtoTypeLoc BlockProtoLoc
;
4901 findTypeLocationForBlockDecl(P
->getTypeSourceInfo(), BlockLoc
,
4904 Result R
= Result(P
, Results
.getBasePriority(P
), nullptr);
4905 if (!InOriginalClass
)
4907 Results
.MaybeAddResult(R
, CurContext
);
4911 // The default completion result for block properties should be the block
4912 // invocation completion when the base expression is a statement.
4913 CodeCompletionBuilder
Builder(Results
.getAllocator(),
4914 Results
.getCodeCompletionTUInfo());
4915 AddObjCBlockCall(Container
->getASTContext(),
4916 getCompletionPrintingPolicy(Results
.getSema()), Builder
, P
,
4917 BlockLoc
, BlockProtoLoc
);
4918 Result R
= Result(Builder
.TakeString(), P
, Results
.getBasePriority(P
));
4919 if (!InOriginalClass
)
4921 Results
.MaybeAddResult(R
, CurContext
);
4923 // Provide additional block setter completion iff the base expression is a
4924 // statement and the block property is mutable.
4925 if (!P
->isReadOnly()) {
4926 CodeCompletionBuilder
Builder(Results
.getAllocator(),
4927 Results
.getCodeCompletionTUInfo());
4928 AddResultTypeChunk(Container
->getASTContext(),
4929 getCompletionPrintingPolicy(Results
.getSema()), P
,
4930 CCContext
.getBaseType(), Builder
);
4931 Builder
.AddTypedTextChunk(
4932 Results
.getAllocator().CopyString(P
->getName()));
4933 Builder
.AddChunk(CodeCompletionString::CK_Equal
);
4935 std::string PlaceholderStr
= formatBlockPlaceholder(
4936 getCompletionPrintingPolicy(Results
.getSema()), P
, BlockLoc
,
4937 BlockProtoLoc
, /*SuppressBlockName=*/true);
4938 // Add the placeholder string.
4939 Builder
.AddPlaceholderChunk(
4940 Builder
.getAllocator().CopyString(PlaceholderStr
));
4942 // When completing blocks properties that return void the default
4943 // property completion result should show up before the setter,
4944 // otherwise the setter completion should show up before the default
4945 // property completion, as we normally want to use the result of the
4948 Result(Builder
.TakeString(), P
,
4949 Results
.getBasePriority(P
) +
4950 (BlockLoc
.getTypePtr()->getReturnType()->isVoidType()
4951 ? CCD_BlockPropertySetter
4952 : -CCD_BlockPropertySetter
));
4953 if (!InOriginalClass
)
4955 Results
.MaybeAddResult(R
, CurContext
);
4959 if (IsClassProperty
) {
4960 for (const auto *P
: Container
->class_properties())
4963 for (const auto *P
: Container
->instance_properties())
4967 // Add nullary methods or implicit class properties
4968 if (AllowNullaryMethods
) {
4969 ASTContext
&Context
= Container
->getASTContext();
4970 PrintingPolicy Policy
= getCompletionPrintingPolicy(Results
.getSema());
4971 // Adds a method result
4972 const auto AddMethod
= [&](const ObjCMethodDecl
*M
) {
4973 IdentifierInfo
*Name
= M
->getSelector().getIdentifierInfoForSlot(0);
4976 if (!AddedProperties
.insert(Name
).second
)
4978 CodeCompletionBuilder
Builder(Results
.getAllocator(),
4979 Results
.getCodeCompletionTUInfo());
4980 AddResultTypeChunk(Context
, Policy
, M
, CCContext
.getBaseType(), Builder
);
4981 Builder
.AddTypedTextChunk(
4982 Results
.getAllocator().CopyString(Name
->getName()));
4983 Result R
= Result(Builder
.TakeString(), M
,
4984 CCP_MemberDeclaration
+ CCD_MethodAsProperty
);
4985 if (!InOriginalClass
)
4987 Results
.MaybeAddResult(R
, CurContext
);
4990 if (IsClassProperty
) {
4991 for (const auto *M
: Container
->methods()) {
4992 // Gather the class method that can be used as implicit property
4993 // getters. Methods with arguments or methods that return void aren't
4994 // added to the results as they can't be used as a getter.
4995 if (!M
->getSelector().isUnarySelector() ||
4996 M
->getReturnType()->isVoidType() || M
->isInstanceMethod())
5001 for (auto *M
: Container
->methods()) {
5002 if (M
->getSelector().isUnarySelector())
5008 // Add properties in referenced protocols.
5009 if (ObjCProtocolDecl
*Protocol
= dyn_cast
<ObjCProtocolDecl
>(Container
)) {
5010 for (auto *P
: Protocol
->protocols())
5011 AddObjCProperties(CCContext
, P
, AllowCategories
, AllowNullaryMethods
,
5012 CurContext
, AddedProperties
, Results
,
5013 IsBaseExprStatement
, IsClassProperty
,
5014 /*InOriginalClass*/ false);
5015 } else if (ObjCInterfaceDecl
*IFace
=
5016 dyn_cast
<ObjCInterfaceDecl
>(Container
)) {
5017 if (AllowCategories
) {
5018 // Look through categories.
5019 for (auto *Cat
: IFace
->known_categories())
5020 AddObjCProperties(CCContext
, Cat
, AllowCategories
, AllowNullaryMethods
,
5021 CurContext
, AddedProperties
, Results
,
5022 IsBaseExprStatement
, IsClassProperty
,
5026 // Look through protocols.
5027 for (auto *I
: IFace
->all_referenced_protocols())
5028 AddObjCProperties(CCContext
, I
, AllowCategories
, AllowNullaryMethods
,
5029 CurContext
, AddedProperties
, Results
,
5030 IsBaseExprStatement
, IsClassProperty
,
5031 /*InOriginalClass*/ false);
5033 // Look in the superclass.
5034 if (IFace
->getSuperClass())
5035 AddObjCProperties(CCContext
, IFace
->getSuperClass(), AllowCategories
,
5036 AllowNullaryMethods
, CurContext
, AddedProperties
,
5037 Results
, IsBaseExprStatement
, IsClassProperty
,
5038 /*InOriginalClass*/ false);
5039 } else if (const auto *Category
=
5040 dyn_cast
<ObjCCategoryDecl
>(Container
)) {
5041 // Look through protocols.
5042 for (auto *P
: Category
->protocols())
5043 AddObjCProperties(CCContext
, P
, AllowCategories
, AllowNullaryMethods
,
5044 CurContext
, AddedProperties
, Results
,
5045 IsBaseExprStatement
, IsClassProperty
,
5046 /*InOriginalClass*/ false);
5050 static void AddRecordMembersCompletionResults(
5051 Sema
&SemaRef
, ResultBuilder
&Results
, Scope
*S
, QualType BaseType
,
5052 ExprValueKind BaseKind
, RecordDecl
*RD
, Optional
<FixItHint
> AccessOpFixIt
) {
5053 // Indicate that we are performing a member access, and the cv-qualifiers
5054 // for the base object type.
5055 Results
.setObjectTypeQualifiers(BaseType
.getQualifiers(), BaseKind
);
5057 // Access to a C/C++ class, struct, or union.
5058 Results
.allowNestedNameSpecifiers();
5059 std::vector
<FixItHint
> FixIts
;
5061 FixIts
.emplace_back(*AccessOpFixIt
);
5062 CodeCompletionDeclConsumer
Consumer(Results
, RD
, BaseType
, std::move(FixIts
));
5063 SemaRef
.LookupVisibleDecls(RD
, Sema::LookupMemberName
, Consumer
,
5064 SemaRef
.CodeCompleter
->includeGlobals(),
5065 /*IncludeDependentBases=*/true,
5066 SemaRef
.CodeCompleter
->loadExternal());
5068 if (SemaRef
.getLangOpts().CPlusPlus
) {
5069 if (!Results
.empty()) {
5070 // The "template" keyword can follow "->" or "." in the grammar.
5071 // However, we only want to suggest the template keyword if something
5073 bool IsDependent
= BaseType
->isDependentType();
5075 for (Scope
*DepScope
= S
; DepScope
; DepScope
= DepScope
->getParent())
5076 if (DeclContext
*Ctx
= DepScope
->getEntity()) {
5077 IsDependent
= Ctx
->isDependentContext();
5083 Results
.AddResult(CodeCompletionResult("template"));
5088 // Returns the RecordDecl inside the BaseType, falling back to primary template
5089 // in case of specializations. Since we might not have a decl for the
5090 // instantiation/specialization yet, e.g. dependent code.
5091 static RecordDecl
*getAsRecordDecl(const QualType BaseType
) {
5092 if (auto *RD
= BaseType
->getAsRecordDecl()) {
5093 if (const auto *CTSD
=
5094 llvm::dyn_cast
<ClassTemplateSpecializationDecl
>(RD
)) {
5095 // Template might not be instantiated yet, fall back to primary template
5097 if (CTSD
->getTemplateSpecializationKind() == TSK_Undeclared
)
5098 RD
= CTSD
->getSpecializedTemplate()->getTemplatedDecl();
5103 if (const auto *TST
= BaseType
->getAs
<TemplateSpecializationType
>()) {
5104 if (const auto *TD
= dyn_cast_or_null
<ClassTemplateDecl
>(
5105 TST
->getTemplateName().getAsTemplateDecl())) {
5106 return TD
->getTemplatedDecl();
5114 // Collects completion-relevant information about a concept-constrainted type T.
5115 // In particular, examines the constraint expressions to find members of T.
5117 // The design is very simple: we walk down each constraint looking for
5118 // expressions of the form T.foo().
5119 // If we're extra lucky, the return type is specified.
5120 // We don't do any clever handling of && or || in constraint expressions, we
5121 // take members from both branches.
5123 // For example, given:
5124 // template <class T> concept X = requires (T t, string& s) { t.print(s); };
5125 // template <X U> void foo(U u) { u.^ }
5126 // We want to suggest the inferred member function 'print(string)'.
5127 // We see that u has type U, so X<U> holds.
5128 // X<U> requires t.print(s) to be valid, where t has type U (substituted for T).
5129 // By looking at the CallExpr we find the signature of print().
5131 // While we tend to know in advance which kind of members (access via . -> ::)
5132 // we want, it's simpler just to gather them all and post-filter.
5134 // FIXME: some of this machinery could be used for non-concept type-parms too,
5135 // enabling completion for type parameters based on other uses of that param.
5137 // FIXME: there are other cases where a type can be constrained by a concept,
5138 // e.g. inside `if constexpr(ConceptSpecializationExpr) { ... }`
5141 // Describes a likely member of a type, inferred by concept constraints.
5142 // Offered as a code completion for T. T-> and T:: contexts.
5144 // Always non-null: we only handle members with ordinary identifier names.
5145 const IdentifierInfo
*Name
= nullptr;
5146 // Set for functions we've seen called.
5147 // We don't have the declared parameter types, only the actual types of
5148 // arguments we've seen. These are still valuable, as it's hard to render
5149 // a useful function completion with neither parameter types nor names!
5150 llvm::Optional
<SmallVector
<QualType
, 1>> ArgTypes
;
5151 // Whether this is accessed as T.member, T->member, or T::member.
5152 enum AccessOperator
{
5157 // What's known about the type of a variable or return type of a function.
5158 const TypeConstraint
*ResultType
= nullptr;
5159 // FIXME: also track:
5160 // - kind of entity (function/variable/type), to expose structured results
5161 // - template args kinds/types, as a proxy for template params
5163 // For now we simply return these results as "pattern" strings.
5164 CodeCompletionString
*render(Sema
&S
, CodeCompletionAllocator
&Alloc
,
5165 CodeCompletionTUInfo
&Info
) const {
5166 CodeCompletionBuilder
B(Alloc
, Info
);
5169 std::string AsString
;
5171 llvm::raw_string_ostream
OS(AsString
);
5172 QualType ExactType
= deduceType(*ResultType
);
5173 if (!ExactType
.isNull())
5174 ExactType
.print(OS
, getCompletionPrintingPolicy(S
));
5176 ResultType
->print(OS
, getCompletionPrintingPolicy(S
));
5178 B
.AddResultTypeChunk(Alloc
.CopyString(AsString
));
5181 B
.AddTypedTextChunk(Alloc
.CopyString(Name
->getName()));
5182 // Function argument list
5184 B
.AddChunk(clang::CodeCompletionString::CK_LeftParen
);
5186 for (QualType Arg
: *ArgTypes
) {
5190 B
.AddChunk(clang::CodeCompletionString::CK_Comma
);
5191 B
.AddChunk(clang::CodeCompletionString::CK_HorizontalSpace
);
5193 B
.AddPlaceholderChunk(Alloc
.CopyString(
5194 Arg
.getAsString(getCompletionPrintingPolicy(S
))));
5196 B
.AddChunk(clang::CodeCompletionString::CK_RightParen
);
5198 return B
.TakeString();
5202 // BaseType is the type parameter T to infer members from.
5203 // T must be accessible within S, as we use it to find the template entity
5204 // that T is attached to in order to gather the relevant constraints.
5205 ConceptInfo(const TemplateTypeParmType
&BaseType
, Scope
*S
) {
5206 auto *TemplatedEntity
= getTemplatedEntity(BaseType
.getDecl(), S
);
5207 for (const Expr
*E
: constraintsForTemplatedEntity(TemplatedEntity
))
5208 believe(E
, &BaseType
);
5211 std::vector
<Member
> members() {
5212 std::vector
<Member
> Results
;
5213 for (const auto &E
: this->Results
)
5214 Results
.push_back(E
.second
);
5215 llvm::sort(Results
, [](const Member
&L
, const Member
&R
) {
5216 return L
.Name
->getName() < R
.Name
->getName();
5222 // Infer members of T, given that the expression E (dependent on T) is true.
5223 void believe(const Expr
*E
, const TemplateTypeParmType
*T
) {
5226 if (auto *CSE
= dyn_cast
<ConceptSpecializationExpr
>(E
)) {
5227 // If the concept is
5228 // template <class A, class B> concept CD = f<A, B>();
5229 // And the concept specialization is
5231 // Then we're substituting T for B, so we want to make f<A, B>() true
5232 // by adding members to B - i.e. believe(f<A, B>(), B);
5235 // - we don't attempt to substitute int for A
5236 // - when T is used in other ways (like CD<T*>) we ignore it
5237 ConceptDecl
*CD
= CSE
->getNamedConcept();
5238 TemplateParameterList
*Params
= CD
->getTemplateParameters();
5240 for (const auto &Arg
: CSE
->getTemplateArguments()) {
5241 if (Index
>= Params
->size())
5242 break; // Won't happen in valid code.
5243 if (isApprox(Arg
, T
)) {
5244 auto *TTPD
= dyn_cast
<TemplateTypeParmDecl
>(Params
->getParam(Index
));
5247 // T was used as an argument, and bound to the parameter TT.
5248 auto *TT
= cast
<TemplateTypeParmType
>(TTPD
->getTypeForDecl());
5249 // So now we know the constraint as a function of TT is true.
5250 believe(CD
->getConstraintExpr(), TT
);
5251 // (concepts themselves have no associated constraints to require)
5256 } else if (auto *BO
= dyn_cast
<BinaryOperator
>(E
)) {
5257 // For A && B, we can infer members from both branches.
5258 // For A || B, the union is still more useful than the intersection.
5259 if (BO
->getOpcode() == BO_LAnd
|| BO
->getOpcode() == BO_LOr
) {
5260 believe(BO
->getLHS(), T
);
5261 believe(BO
->getRHS(), T
);
5263 } else if (auto *RE
= dyn_cast
<RequiresExpr
>(E
)) {
5264 // A requires(){...} lets us infer members from each requirement.
5265 for (const concepts::Requirement
*Req
: RE
->getRequirements()) {
5266 if (!Req
->isDependent())
5267 continue; // Can't tell us anything about T.
5268 // Now Req cannot a substitution-error: those aren't dependent.
5270 if (auto *TR
= dyn_cast
<concepts::TypeRequirement
>(Req
)) {
5271 // Do a full traversal so we get `foo` from `typename T::foo::bar`.
5272 QualType AssertedType
= TR
->getType()->getType();
5273 ValidVisitor(this, T
).TraverseType(AssertedType
);
5274 } else if (auto *ER
= dyn_cast
<concepts::ExprRequirement
>(Req
)) {
5275 ValidVisitor
Visitor(this, T
);
5276 // If we have a type constraint on the value of the expression,
5277 // AND the whole outer expression describes a member, then we'll
5278 // be able to use the constraint to provide the return type.
5279 if (ER
->getReturnTypeRequirement().isTypeConstraint()) {
5281 ER
->getReturnTypeRequirement().getTypeConstraint();
5282 Visitor
.OuterExpr
= ER
->getExpr();
5284 Visitor
.TraverseStmt(ER
->getExpr());
5285 } else if (auto *NR
= dyn_cast
<concepts::NestedRequirement
>(Req
)) {
5286 believe(NR
->getConstraintExpr(), T
);
5292 // This visitor infers members of T based on traversing expressions/types
5293 // that involve T. It is invoked with code known to be valid for T.
5294 class ValidVisitor
: public RecursiveASTVisitor
<ValidVisitor
> {
5296 const TemplateTypeParmType
*T
;
5298 CallExpr
*Caller
= nullptr;
5299 Expr
*Callee
= nullptr;
5302 // If set, OuterExpr is constrained by OuterType.
5303 Expr
*OuterExpr
= nullptr;
5304 const TypeConstraint
*OuterType
= nullptr;
5306 ValidVisitor(ConceptInfo
*Outer
, const TemplateTypeParmType
*T
)
5307 : Outer(Outer
), T(T
) {
5311 // In T.foo or T->foo, `foo` is a member function/variable.
5312 bool VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr
*E
) {
5313 const Type
*Base
= E
->getBaseType().getTypePtr();
5314 bool IsArrow
= E
->isArrow();
5315 if (Base
->isPointerType() && IsArrow
) {
5317 Base
= Base
->getPointeeType().getTypePtr();
5319 if (isApprox(Base
, T
))
5320 addValue(E
, E
->getMember(), IsArrow
? Member::Arrow
: Member::Dot
);
5324 // In T::foo, `foo` is a static member function/variable.
5325 bool VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr
*E
) {
5326 if (E
->getQualifier() && isApprox(E
->getQualifier()->getAsType(), T
))
5327 addValue(E
, E
->getDeclName(), Member::Colons
);
5331 // In T::typename foo, `foo` is a type.
5332 bool VisitDependentNameType(DependentNameType
*DNT
) {
5333 const auto *Q
= DNT
->getQualifier();
5334 if (Q
&& isApprox(Q
->getAsType(), T
))
5335 addType(DNT
->getIdentifier());
5339 // In T::foo::bar, `foo` must be a type.
5340 // VisitNNS() doesn't exist, and TraverseNNS isn't always called :-(
5341 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNSL
) {
5343 NestedNameSpecifier
*NNS
= NNSL
.getNestedNameSpecifier();
5344 const auto *Q
= NNS
->getPrefix();
5345 if (Q
&& isApprox(Q
->getAsType(), T
))
5346 addType(NNS
->getAsIdentifier());
5348 // FIXME: also handle T::foo<X>::bar
5349 return RecursiveASTVisitor::TraverseNestedNameSpecifierLoc(NNSL
);
5352 // FIXME also handle T::foo<X>
5354 // Track the innermost caller/callee relationship so we can tell if a
5355 // nested expr is being called as a function.
5356 bool VisitCallExpr(CallExpr
*CE
) {
5358 Callee
= CE
->getCallee();
5363 void addResult(Member
&&M
) {
5364 auto R
= Outer
->Results
.try_emplace(M
.Name
);
5365 Member
&O
= R
.first
->second
;
5366 // Overwrite existing if the new member has more info.
5367 // The preference of . vs :: vs -> is fairly arbitrary.
5368 if (/*Inserted*/ R
.second
||
5369 std::make_tuple(M
.ArgTypes
.has_value(), M
.ResultType
!= nullptr,
5370 M
.Operator
) > std::make_tuple(O
.ArgTypes
.has_value(),
5371 O
.ResultType
!= nullptr,
5376 void addType(const IdentifierInfo
*Name
) {
5381 M
.Operator
= Member::Colons
;
5382 addResult(std::move(M
));
5385 void addValue(Expr
*E
, DeclarationName Name
,
5386 Member::AccessOperator Operator
) {
5387 if (!Name
.isIdentifier())
5390 Result
.Name
= Name
.getAsIdentifierInfo();
5391 Result
.Operator
= Operator
;
5392 // If this is the callee of an immediately-enclosing CallExpr, then
5393 // treat it as a method, otherwise it's a variable.
5394 if (Caller
!= nullptr && Callee
== E
) {
5395 Result
.ArgTypes
.emplace();
5396 for (const auto *Arg
: Caller
->arguments())
5397 Result
.ArgTypes
->push_back(Arg
->getType());
5398 if (Caller
== OuterExpr
) {
5399 Result
.ResultType
= OuterType
;
5403 Result
.ResultType
= OuterType
;
5405 addResult(std::move(Result
));
5409 static bool isApprox(const TemplateArgument
&Arg
, const Type
*T
) {
5410 return Arg
.getKind() == TemplateArgument::Type
&&
5411 isApprox(Arg
.getAsType().getTypePtr(), T
);
5414 static bool isApprox(const Type
*T1
, const Type
*T2
) {
5416 T1
->getCanonicalTypeUnqualified() ==
5417 T2
->getCanonicalTypeUnqualified();
5420 // Returns the DeclContext immediately enclosed by the template parameter
5421 // scope. For primary templates, this is the templated (e.g.) CXXRecordDecl.
5422 // For specializations, this is e.g. ClassTemplatePartialSpecializationDecl.
5423 static DeclContext
*getTemplatedEntity(const TemplateTypeParmDecl
*D
,
5427 Scope
*Inner
= nullptr;
5429 if (S
->isTemplateParamScope() && S
->isDeclScope(D
))
5430 return Inner
? Inner
->getEntity() : nullptr;
5437 // Gets all the type constraint expressions that might apply to the type
5438 // variables associated with DC (as returned by getTemplatedEntity()).
5439 static SmallVector
<const Expr
*, 1>
5440 constraintsForTemplatedEntity(DeclContext
*DC
) {
5441 SmallVector
<const Expr
*, 1> Result
;
5444 // Primary templates can have constraints.
5445 if (const auto *TD
= cast
<Decl
>(DC
)->getDescribedTemplate())
5446 TD
->getAssociatedConstraints(Result
);
5447 // Partial specializations may have constraints.
5448 if (const auto *CTPSD
=
5449 dyn_cast
<ClassTemplatePartialSpecializationDecl
>(DC
))
5450 CTPSD
->getAssociatedConstraints(Result
);
5451 if (const auto *VTPSD
= dyn_cast
<VarTemplatePartialSpecializationDecl
>(DC
))
5452 VTPSD
->getAssociatedConstraints(Result
);
5456 // Attempt to find the unique type satisfying a constraint.
5457 // This lets us show e.g. `int` instead of `std::same_as<int>`.
5458 static QualType
deduceType(const TypeConstraint
&T
) {
5459 // Assume a same_as<T> return type constraint is std::same_as or equivalent.
5460 // In this case the return type is T.
5461 DeclarationName DN
= T
.getNamedConcept()->getDeclName();
5462 if (DN
.isIdentifier() && DN
.getAsIdentifierInfo()->isStr("same_as"))
5463 if (const auto *Args
= T
.getTemplateArgsAsWritten())
5464 if (Args
->getNumTemplateArgs() == 1) {
5465 const auto &Arg
= Args
->arguments().front().getArgument();
5466 if (Arg
.getKind() == TemplateArgument::Type
)
5467 return Arg
.getAsType();
5472 llvm::DenseMap
<const IdentifierInfo
*, Member
> Results
;
5475 // Returns a type for E that yields acceptable member completions.
5476 // In particular, when E->getType() is DependentTy, try to guess a likely type.
5477 // We accept some lossiness (like dropping parameters).
5478 // We only try to handle common expressions on the LHS of MemberExpr.
5479 QualType
getApproximateType(const Expr
*E
) {
5480 QualType Unresolved
= E
->getType();
5481 if (Unresolved
.isNull() ||
5482 !Unresolved
->isSpecificBuiltinType(BuiltinType::Dependent
))
5484 E
= E
->IgnoreParens();
5485 // A call: approximate-resolve callee to a function type, get its return type
5486 if (const CallExpr
*CE
= llvm::dyn_cast
<CallExpr
>(E
)) {
5487 QualType Callee
= getApproximateType(CE
->getCallee());
5488 if (Callee
.isNull() ||
5489 Callee
->isSpecificPlaceholderType(BuiltinType::BoundMember
))
5490 Callee
= Expr::findBoundMemberType(CE
->getCallee());
5491 if (Callee
.isNull())
5494 if (const auto *FnTypePtr
= Callee
->getAs
<PointerType
>()) {
5495 Callee
= FnTypePtr
->getPointeeType();
5496 } else if (const auto *BPT
= Callee
->getAs
<BlockPointerType
>()) {
5497 Callee
= BPT
->getPointeeType();
5499 if (const FunctionType
*FnType
= Callee
->getAs
<FunctionType
>())
5500 return FnType
->getReturnType().getNonReferenceType();
5502 // Unresolved call: try to guess the return type.
5503 if (const auto *OE
= llvm::dyn_cast
<OverloadExpr
>(CE
->getCallee())) {
5504 // If all candidates have the same approximate return type, use it.
5505 // Discard references and const to allow more to be "the same".
5506 // (In particular, if there's one candidate + ADL, resolve it).
5507 const Type
*Common
= nullptr;
5508 for (const auto *D
: OE
->decls()) {
5509 QualType ReturnType
;
5510 if (const auto *FD
= llvm::dyn_cast
<FunctionDecl
>(D
))
5511 ReturnType
= FD
->getReturnType();
5512 else if (const auto *FTD
= llvm::dyn_cast
<FunctionTemplateDecl
>(D
))
5513 ReturnType
= FTD
->getTemplatedDecl()->getReturnType();
5514 if (ReturnType
.isNull())
5516 const Type
*Candidate
=
5517 ReturnType
.getNonReferenceType().getCanonicalType().getTypePtr();
5518 if (Common
&& Common
!= Candidate
)
5519 return Unresolved
; // Multiple candidates.
5522 if (Common
!= nullptr)
5523 return QualType(Common
, 0);
5526 // A dependent member: approximate-resolve the base, then lookup.
5527 if (const auto *CDSME
= llvm::dyn_cast
<CXXDependentScopeMemberExpr
>(E
)) {
5528 QualType Base
= CDSME
->isImplicitAccess()
5529 ? CDSME
->getBaseType()
5530 : getApproximateType(CDSME
->getBase());
5531 if (CDSME
->isArrow() && !Base
.isNull())
5532 Base
= Base
->getPointeeType(); // could handle unique_ptr etc here?
5536 : llvm::dyn_cast_or_null
<CXXRecordDecl
>(getAsRecordDecl(Base
));
5537 if (RD
&& RD
->isCompleteDefinition()) {
5538 // Look up member heuristically, including in bases.
5539 for (const auto *Member
: RD
->lookupDependentName(
5540 CDSME
->getMember(), [](const NamedDecl
*Member
) {
5541 return llvm::isa
<ValueDecl
>(Member
);
5543 return llvm::cast
<ValueDecl
>(Member
)->getType().getNonReferenceType();
5550 // If \p Base is ParenListExpr, assume a chain of comma operators and pick the
5551 // last expr. We expect other ParenListExprs to be resolved to e.g. constructor
5552 // calls before here. (So the ParenListExpr should be nonempty, but check just
5554 Expr
*unwrapParenList(Expr
*Base
) {
5555 if (auto *PLE
= llvm::dyn_cast_or_null
<ParenListExpr
>(Base
)) {
5556 if (PLE
->getNumExprs() == 0)
5558 Base
= PLE
->getExpr(PLE
->getNumExprs() - 1);
5565 void Sema::CodeCompleteMemberReferenceExpr(Scope
*S
, Expr
*Base
,
5567 SourceLocation OpLoc
, bool IsArrow
,
5568 bool IsBaseExprStatement
,
5569 QualType PreferredType
) {
5570 Base
= unwrapParenList(Base
);
5571 OtherOpBase
= unwrapParenList(OtherOpBase
);
5572 if (!Base
|| !CodeCompleter
)
5575 ExprResult ConvertedBase
= PerformMemberExprBaseConversion(Base
, IsArrow
);
5576 if (ConvertedBase
.isInvalid())
5578 QualType ConvertedBaseType
= getApproximateType(ConvertedBase
.get());
5580 enum CodeCompletionContext::Kind contextKind
;
5583 if (const auto *Ptr
= ConvertedBaseType
->getAs
<PointerType
>())
5584 ConvertedBaseType
= Ptr
->getPointeeType();
5588 contextKind
= CodeCompletionContext::CCC_ArrowMemberAccess
;
5590 if (ConvertedBaseType
->isObjCObjectPointerType() ||
5591 ConvertedBaseType
->isObjCObjectOrInterfaceType()) {
5592 contextKind
= CodeCompletionContext::CCC_ObjCPropertyAccess
;
5594 contextKind
= CodeCompletionContext::CCC_DotMemberAccess
;
5598 CodeCompletionContext
CCContext(contextKind
, ConvertedBaseType
);
5599 CCContext
.setPreferredType(PreferredType
);
5600 ResultBuilder
Results(*this, CodeCompleter
->getAllocator(),
5601 CodeCompleter
->getCodeCompletionTUInfo(), CCContext
,
5602 &ResultBuilder::IsMember
);
5604 auto DoCompletion
= [&](Expr
*Base
, bool IsArrow
,
5605 Optional
<FixItHint
> AccessOpFixIt
) -> bool {
5609 ExprResult ConvertedBase
= PerformMemberExprBaseConversion(Base
, IsArrow
);
5610 if (ConvertedBase
.isInvalid())
5612 Base
= ConvertedBase
.get();
5614 QualType BaseType
= getApproximateType(Base
);
5615 if (BaseType
.isNull())
5617 ExprValueKind BaseKind
= Base
->getValueKind();
5620 if (const PointerType
*Ptr
= BaseType
->getAs
<PointerType
>()) {
5621 BaseType
= Ptr
->getPointeeType();
5622 BaseKind
= VK_LValue
;
5623 } else if (BaseType
->isObjCObjectPointerType() ||
5624 BaseType
->isTemplateTypeParmType()) {
5625 // Both cases (dot/arrow) handled below.
5631 if (RecordDecl
*RD
= getAsRecordDecl(BaseType
)) {
5632 AddRecordMembersCompletionResults(*this, Results
, S
, BaseType
, BaseKind
,
5633 RD
, std::move(AccessOpFixIt
));
5634 } else if (const auto *TTPT
=
5635 dyn_cast
<TemplateTypeParmType
>(BaseType
.getTypePtr())) {
5637 IsArrow
? ConceptInfo::Member::Arrow
: ConceptInfo::Member::Dot
;
5638 for (const auto &R
: ConceptInfo(*TTPT
, S
).members()) {
5639 if (R
.Operator
!= Operator
)
5641 CodeCompletionResult
Result(
5642 R
.render(*this, CodeCompleter
->getAllocator(),
5643 CodeCompleter
->getCodeCompletionTUInfo()));
5645 Result
.FixIts
.push_back(*AccessOpFixIt
);
5646 Results
.AddResult(std::move(Result
));
5648 } else if (!IsArrow
&& BaseType
->isObjCObjectPointerType()) {
5649 // Objective-C property reference. Bail if we're performing fix-it code
5650 // completion since Objective-C properties are normally backed by ivars,
5651 // most Objective-C fix-its here would have little value.
5652 if (AccessOpFixIt
) {
5655 AddedPropertiesSet AddedProperties
;
5657 if (const ObjCObjectPointerType
*ObjCPtr
=
5658 BaseType
->getAsObjCInterfacePointerType()) {
5659 // Add property results based on our interface.
5660 assert(ObjCPtr
&& "Non-NULL pointer guaranteed above!");
5661 AddObjCProperties(CCContext
, ObjCPtr
->getInterfaceDecl(), true,
5662 /*AllowNullaryMethods=*/true, CurContext
,
5663 AddedProperties
, Results
, IsBaseExprStatement
);
5666 // Add properties from the protocols in a qualified interface.
5667 for (auto *I
: BaseType
->castAs
<ObjCObjectPointerType
>()->quals())
5668 AddObjCProperties(CCContext
, I
, true, /*AllowNullaryMethods=*/true,
5669 CurContext
, AddedProperties
, Results
,
5670 IsBaseExprStatement
, /*IsClassProperty*/ false,
5671 /*InOriginalClass*/ false);
5672 } else if ((IsArrow
&& BaseType
->isObjCObjectPointerType()) ||
5673 (!IsArrow
&& BaseType
->isObjCObjectType())) {
5674 // Objective-C instance variable access. Bail if we're performing fix-it
5675 // code completion since Objective-C properties are normally backed by
5676 // ivars, most Objective-C fix-its here would have little value.
5677 if (AccessOpFixIt
) {
5680 ObjCInterfaceDecl
*Class
= nullptr;
5681 if (const ObjCObjectPointerType
*ObjCPtr
=
5682 BaseType
->getAs
<ObjCObjectPointerType
>())
5683 Class
= ObjCPtr
->getInterfaceDecl();
5685 Class
= BaseType
->castAs
<ObjCObjectType
>()->getInterface();
5687 // Add all ivars from this class and its superclasses.
5689 CodeCompletionDeclConsumer
Consumer(Results
, Class
, BaseType
);
5690 Results
.setFilter(&ResultBuilder::IsObjCIvar
);
5692 Class
, LookupMemberName
, Consumer
, CodeCompleter
->includeGlobals(),
5693 /*IncludeDependentBases=*/false, CodeCompleter
->loadExternal());
5697 // FIXME: How do we cope with isa?
5701 Results
.EnterNewScope();
5703 bool CompletionSucceded
= DoCompletion(Base
, IsArrow
, None
);
5704 if (CodeCompleter
->includeFixIts()) {
5705 const CharSourceRange OpRange
=
5706 CharSourceRange::getTokenRange(OpLoc
, OpLoc
);
5707 CompletionSucceded
|= DoCompletion(
5708 OtherOpBase
, !IsArrow
,
5709 FixItHint::CreateReplacement(OpRange
, IsArrow
? "." : "->"));
5712 Results
.ExitScope();
5714 if (!CompletionSucceded
)
5717 // Hand off the results found for code completion.
5718 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
5719 Results
.data(), Results
.size());
5722 void Sema::CodeCompleteObjCClassPropertyRefExpr(Scope
*S
,
5723 IdentifierInfo
&ClassName
,
5724 SourceLocation ClassNameLoc
,
5725 bool IsBaseExprStatement
) {
5726 IdentifierInfo
*ClassNamePtr
= &ClassName
;
5727 ObjCInterfaceDecl
*IFace
= getObjCInterfaceDecl(ClassNamePtr
, ClassNameLoc
);
5730 CodeCompletionContext
CCContext(
5731 CodeCompletionContext::CCC_ObjCPropertyAccess
);
5732 ResultBuilder
Results(*this, CodeCompleter
->getAllocator(),
5733 CodeCompleter
->getCodeCompletionTUInfo(), CCContext
,
5734 &ResultBuilder::IsMember
);
5735 Results
.EnterNewScope();
5736 AddedPropertiesSet AddedProperties
;
5737 AddObjCProperties(CCContext
, IFace
, true,
5738 /*AllowNullaryMethods=*/true, CurContext
, AddedProperties
,
5739 Results
, IsBaseExprStatement
,
5740 /*IsClassProperty=*/true);
5741 Results
.ExitScope();
5742 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
5743 Results
.data(), Results
.size());
5746 void Sema::CodeCompleteTag(Scope
*S
, unsigned TagSpec
) {
5750 ResultBuilder::LookupFilter Filter
= nullptr;
5751 enum CodeCompletionContext::Kind ContextKind
=
5752 CodeCompletionContext::CCC_Other
;
5753 switch ((DeclSpec::TST
)TagSpec
) {
5754 case DeclSpec::TST_enum
:
5755 Filter
= &ResultBuilder::IsEnum
;
5756 ContextKind
= CodeCompletionContext::CCC_EnumTag
;
5759 case DeclSpec::TST_union
:
5760 Filter
= &ResultBuilder::IsUnion
;
5761 ContextKind
= CodeCompletionContext::CCC_UnionTag
;
5764 case DeclSpec::TST_struct
:
5765 case DeclSpec::TST_class
:
5766 case DeclSpec::TST_interface
:
5767 Filter
= &ResultBuilder::IsClassOrStruct
;
5768 ContextKind
= CodeCompletionContext::CCC_ClassOrStructTag
;
5772 llvm_unreachable("Unknown type specifier kind in CodeCompleteTag");
5775 ResultBuilder
Results(*this, CodeCompleter
->getAllocator(),
5776 CodeCompleter
->getCodeCompletionTUInfo(), ContextKind
);
5777 CodeCompletionDeclConsumer
Consumer(Results
, CurContext
);
5779 // First pass: look for tags.
5780 Results
.setFilter(Filter
);
5781 LookupVisibleDecls(S
, LookupTagName
, Consumer
,
5782 CodeCompleter
->includeGlobals(),
5783 CodeCompleter
->loadExternal());
5785 if (CodeCompleter
->includeGlobals()) {
5786 // Second pass: look for nested name specifiers.
5787 Results
.setFilter(&ResultBuilder::IsNestedNameSpecifier
);
5788 LookupVisibleDecls(S
, LookupNestedNameSpecifierName
, Consumer
,
5789 CodeCompleter
->includeGlobals(),
5790 CodeCompleter
->loadExternal());
5793 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
5794 Results
.data(), Results
.size());
5797 static void AddTypeQualifierResults(DeclSpec
&DS
, ResultBuilder
&Results
,
5798 const LangOptions
&LangOpts
) {
5799 if (!(DS
.getTypeQualifiers() & DeclSpec::TQ_const
))
5800 Results
.AddResult("const");
5801 if (!(DS
.getTypeQualifiers() & DeclSpec::TQ_volatile
))
5802 Results
.AddResult("volatile");
5803 if (LangOpts
.C99
&& !(DS
.getTypeQualifiers() & DeclSpec::TQ_restrict
))
5804 Results
.AddResult("restrict");
5805 if (LangOpts
.C11
&& !(DS
.getTypeQualifiers() & DeclSpec::TQ_atomic
))
5806 Results
.AddResult("_Atomic");
5807 if (LangOpts
.MSVCCompat
&& !(DS
.getTypeQualifiers() & DeclSpec::TQ_unaligned
))
5808 Results
.AddResult("__unaligned");
5811 void Sema::CodeCompleteTypeQualifiers(DeclSpec
&DS
) {
5812 ResultBuilder
Results(*this, CodeCompleter
->getAllocator(),
5813 CodeCompleter
->getCodeCompletionTUInfo(),
5814 CodeCompletionContext::CCC_TypeQualifiers
);
5815 Results
.EnterNewScope();
5816 AddTypeQualifierResults(DS
, Results
, LangOpts
);
5817 Results
.ExitScope();
5818 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
5819 Results
.data(), Results
.size());
5822 void Sema::CodeCompleteFunctionQualifiers(DeclSpec
&DS
, Declarator
&D
,
5823 const VirtSpecifiers
*VS
) {
5824 ResultBuilder
Results(*this, CodeCompleter
->getAllocator(),
5825 CodeCompleter
->getCodeCompletionTUInfo(),
5826 CodeCompletionContext::CCC_TypeQualifiers
);
5827 Results
.EnterNewScope();
5828 AddTypeQualifierResults(DS
, Results
, LangOpts
);
5829 if (LangOpts
.CPlusPlus11
) {
5830 Results
.AddResult("noexcept");
5831 if (D
.getContext() == DeclaratorContext::Member
&& !D
.isCtorOrDtor() &&
5832 !D
.isStaticMember()) {
5833 if (!VS
|| !VS
->isFinalSpecified())
5834 Results
.AddResult("final");
5835 if (!VS
|| !VS
->isOverrideSpecified())
5836 Results
.AddResult("override");
5839 Results
.ExitScope();
5840 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
5841 Results
.data(), Results
.size());
5844 void Sema::CodeCompleteBracketDeclarator(Scope
*S
) {
5845 CodeCompleteExpression(S
, QualType(getASTContext().getSizeType()));
5848 void Sema::CodeCompleteCase(Scope
*S
) {
5849 if (getCurFunction()->SwitchStack
.empty() || !CodeCompleter
)
5852 SwitchStmt
*Switch
= getCurFunction()->SwitchStack
.back().getPointer();
5853 // Condition expression might be invalid, do not continue in this case.
5854 if (!Switch
->getCond())
5856 QualType type
= Switch
->getCond()->IgnoreImplicit()->getType();
5857 if (!type
->isEnumeralType()) {
5858 CodeCompleteExpressionData
Data(type
);
5859 Data
.IntegralConstantExpression
= true;
5860 CodeCompleteExpression(S
, Data
);
5864 // Code-complete the cases of a switch statement over an enumeration type
5865 // by providing the list of
5866 EnumDecl
*Enum
= type
->castAs
<EnumType
>()->getDecl();
5867 if (EnumDecl
*Def
= Enum
->getDefinition())
5870 // Determine which enumerators we have already seen in the switch statement.
5871 // FIXME: Ideally, we would also be able to look *past* the code-completion
5872 // token, in case we are code-completing in the middle of the switch and not
5873 // at the end. However, we aren't able to do so at the moment.
5874 CoveredEnumerators Enumerators
;
5875 for (SwitchCase
*SC
= Switch
->getSwitchCaseList(); SC
;
5876 SC
= SC
->getNextSwitchCase()) {
5877 CaseStmt
*Case
= dyn_cast
<CaseStmt
>(SC
);
5881 Expr
*CaseVal
= Case
->getLHS()->IgnoreParenCasts();
5882 if (auto *DRE
= dyn_cast
<DeclRefExpr
>(CaseVal
))
5883 if (auto *Enumerator
=
5884 dyn_cast
<EnumConstantDecl
>(DRE
->getDecl())) {
5885 // We look into the AST of the case statement to determine which
5886 // enumerator was named. Alternatively, we could compute the value of
5887 // the integral constant expression, then compare it against the
5888 // values of each enumerator. However, value-based approach would not
5889 // work as well with C++ templates where enumerators declared within a
5890 // template are type- and value-dependent.
5891 Enumerators
.Seen
.insert(Enumerator
);
5893 // If this is a qualified-id, keep track of the nested-name-specifier
5894 // so that we can reproduce it as part of code completion, e.g.,
5896 // switch (TagD.getKind()) {
5897 // case TagDecl::TK_enum:
5901 // At the XXX, our completions are TagDecl::TK_union,
5902 // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
5903 // TK_struct, and TK_class.
5904 Enumerators
.SuggestedQualifier
= DRE
->getQualifier();
5908 // Add any enumerators that have not yet been mentioned.
5909 ResultBuilder
Results(*this, CodeCompleter
->getAllocator(),
5910 CodeCompleter
->getCodeCompletionTUInfo(),
5911 CodeCompletionContext::CCC_Expression
);
5912 AddEnumerators(Results
, Context
, Enum
, CurContext
, Enumerators
);
5914 if (CodeCompleter
->includeMacros()) {
5915 AddMacroResults(PP
, Results
, CodeCompleter
->loadExternal(), false);
5917 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
5918 Results
.data(), Results
.size());
5921 static bool anyNullArguments(ArrayRef
<Expr
*> Args
) {
5922 if (Args
.size() && !Args
.data())
5925 for (unsigned I
= 0; I
!= Args
.size(); ++I
)
5932 typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate
;
5934 static void mergeCandidatesWithResults(
5935 Sema
&SemaRef
, SmallVectorImpl
<ResultCandidate
> &Results
,
5936 OverloadCandidateSet
&CandidateSet
, SourceLocation Loc
, size_t ArgSize
) {
5937 // Sort the overload candidate set by placing the best overloads first.
5938 llvm::stable_sort(CandidateSet
, [&](const OverloadCandidate
&X
,
5939 const OverloadCandidate
&Y
) {
5940 return isBetterOverloadCandidate(SemaRef
, X
, Y
, Loc
,
5941 CandidateSet
.getKind());
5944 // Add the remaining viable overload candidates as code-completion results.
5945 for (OverloadCandidate
&Candidate
: CandidateSet
) {
5946 if (Candidate
.Function
) {
5947 if (Candidate
.Function
->isDeleted())
5949 if (shouldEnforceArgLimit(/*PartialOverloading=*/true,
5950 Candidate
.Function
) &&
5951 Candidate
.Function
->getNumParams() <= ArgSize
&&
5952 // Having zero args is annoying, normally we don't surface a function
5953 // with 2 params, if you already have 2 params, because you are
5954 // inserting the 3rd now. But with zero, it helps the user to figure
5955 // out there are no overloads that take any arguments. Hence we are
5956 // keeping the overload.
5960 if (Candidate
.Viable
)
5961 Results
.push_back(ResultCandidate(Candidate
.Function
));
5965 /// Get the type of the Nth parameter from a given set of overload
5967 static QualType
getParamType(Sema
&SemaRef
,
5968 ArrayRef
<ResultCandidate
> Candidates
, unsigned N
) {
5970 // Given the overloads 'Candidates' for a function call matching all arguments
5971 // up to N, return the type of the Nth parameter if it is the same for all
5972 // overload candidates.
5974 for (auto &Candidate
: Candidates
) {
5975 QualType CandidateParamType
= Candidate
.getParamType(N
);
5976 if (CandidateParamType
.isNull())
5978 if (ParamType
.isNull()) {
5979 ParamType
= CandidateParamType
;
5982 if (!SemaRef
.Context
.hasSameUnqualifiedType(
5983 ParamType
.getNonReferenceType(),
5984 CandidateParamType
.getNonReferenceType()))
5985 // Two conflicting types, give up.
5993 ProduceSignatureHelp(Sema
&SemaRef
, MutableArrayRef
<ResultCandidate
> Candidates
,
5994 unsigned CurrentArg
, SourceLocation OpenParLoc
,
5996 if (Candidates
.empty())
5998 if (SemaRef
.getPreprocessor().isCodeCompletionReached())
5999 SemaRef
.CodeCompleter
->ProcessOverloadCandidates(
6000 SemaRef
, CurrentArg
, Candidates
.data(), Candidates
.size(), OpenParLoc
,
6002 return getParamType(SemaRef
, Candidates
, CurrentArg
);
6005 // Given a callee expression `Fn`, if the call is through a function pointer,
6006 // try to find the declaration of the corresponding function pointer type,
6007 // so that we can recover argument names from it.
6008 static FunctionProtoTypeLoc
GetPrototypeLoc(Expr
*Fn
) {
6010 if (const auto *T
= Fn
->getType().getTypePtr()->getAs
<TypedefType
>()) {
6011 Target
= T
->getDecl()->getTypeSourceInfo()->getTypeLoc();
6013 } else if (const auto *DR
= dyn_cast
<DeclRefExpr
>(Fn
)) {
6014 const auto *D
= DR
->getDecl();
6015 if (const auto *const VD
= dyn_cast
<VarDecl
>(D
)) {
6016 Target
= VD
->getTypeSourceInfo()->getTypeLoc();
6023 if (auto P
= Target
.getAs
<PointerTypeLoc
>()) {
6024 Target
= P
.getPointeeLoc();
6027 if (auto P
= Target
.getAs
<ParenTypeLoc
>()) {
6028 Target
= P
.getInnerLoc();
6031 if (auto F
= Target
.getAs
<FunctionProtoTypeLoc
>()) {
6038 QualType
Sema::ProduceCallSignatureHelp(Expr
*Fn
, ArrayRef
<Expr
*> Args
,
6039 SourceLocation OpenParLoc
) {
6040 Fn
= unwrapParenList(Fn
);
6041 if (!CodeCompleter
|| !Fn
)
6044 // FIXME: Provide support for variadic template functions.
6045 // Ignore type-dependent call expressions entirely.
6046 if (Fn
->isTypeDependent() || anyNullArguments(Args
))
6048 // In presence of dependent args we surface all possible signatures using the
6049 // non-dependent args in the prefix. Afterwards we do a post filtering to make
6050 // sure provided candidates satisfy parameter count restrictions.
6051 auto ArgsWithoutDependentTypes
=
6052 Args
.take_while([](Expr
*Arg
) { return !Arg
->isTypeDependent(); });
6054 SmallVector
<ResultCandidate
, 8> Results
;
6056 Expr
*NakedFn
= Fn
->IgnoreParenCasts();
6057 // Build an overload candidate set based on the functions we find.
6058 SourceLocation Loc
= Fn
->getExprLoc();
6059 OverloadCandidateSet
CandidateSet(Loc
, OverloadCandidateSet::CSK_Normal
);
6061 if (auto ULE
= dyn_cast
<UnresolvedLookupExpr
>(NakedFn
)) {
6062 AddOverloadedCallCandidates(ULE
, ArgsWithoutDependentTypes
, CandidateSet
,
6063 /*PartialOverloading=*/true);
6064 } else if (auto UME
= dyn_cast
<UnresolvedMemberExpr
>(NakedFn
)) {
6065 TemplateArgumentListInfo TemplateArgsBuffer
, *TemplateArgs
= nullptr;
6066 if (UME
->hasExplicitTemplateArgs()) {
6067 UME
->copyTemplateArgumentsInto(TemplateArgsBuffer
);
6068 TemplateArgs
= &TemplateArgsBuffer
;
6071 // Add the base as first argument (use a nullptr if the base is implicit).
6072 SmallVector
<Expr
*, 12> ArgExprs(
6073 1, UME
->isImplicitAccess() ? nullptr : UME
->getBase());
6074 ArgExprs
.append(ArgsWithoutDependentTypes
.begin(),
6075 ArgsWithoutDependentTypes
.end());
6076 UnresolvedSet
<8> Decls
;
6077 Decls
.append(UME
->decls_begin(), UME
->decls_end());
6078 const bool FirstArgumentIsBase
= !UME
->isImplicitAccess() && UME
->getBase();
6079 AddFunctionCandidates(Decls
, ArgExprs
, CandidateSet
, TemplateArgs
,
6080 /*SuppressUserConversions=*/false,
6081 /*PartialOverloading=*/true, FirstArgumentIsBase
);
6083 FunctionDecl
*FD
= nullptr;
6084 if (auto *MCE
= dyn_cast
<MemberExpr
>(NakedFn
))
6085 FD
= dyn_cast
<FunctionDecl
>(MCE
->getMemberDecl());
6086 else if (auto *DRE
= dyn_cast
<DeclRefExpr
>(NakedFn
))
6087 FD
= dyn_cast
<FunctionDecl
>(DRE
->getDecl());
6088 if (FD
) { // We check whether it's a resolved function declaration.
6089 if (!getLangOpts().CPlusPlus
||
6090 !FD
->getType()->getAs
<FunctionProtoType
>())
6091 Results
.push_back(ResultCandidate(FD
));
6093 AddOverloadCandidate(FD
, DeclAccessPair::make(FD
, FD
->getAccess()),
6094 ArgsWithoutDependentTypes
, CandidateSet
,
6095 /*SuppressUserConversions=*/false,
6096 /*PartialOverloading=*/true);
6098 } else if (auto DC
= NakedFn
->getType()->getAsCXXRecordDecl()) {
6099 // If expression's type is CXXRecordDecl, it may overload the function
6100 // call operator, so we check if it does and add them as candidates.
6101 // A complete type is needed to lookup for member function call operators.
6102 if (isCompleteType(Loc
, NakedFn
->getType())) {
6103 DeclarationName OpName
=
6104 Context
.DeclarationNames
.getCXXOperatorName(OO_Call
);
6105 LookupResult
R(*this, OpName
, Loc
, LookupOrdinaryName
);
6106 LookupQualifiedName(R
, DC
);
6107 R
.suppressDiagnostics();
6108 SmallVector
<Expr
*, 12> ArgExprs(1, NakedFn
);
6109 ArgExprs
.append(ArgsWithoutDependentTypes
.begin(),
6110 ArgsWithoutDependentTypes
.end());
6111 AddFunctionCandidates(R
.asUnresolvedSet(), ArgExprs
, CandidateSet
,
6112 /*ExplicitArgs=*/nullptr,
6113 /*SuppressUserConversions=*/false,
6114 /*PartialOverloading=*/true);
6117 // Lastly we check whether expression's type is function pointer or
6120 FunctionProtoTypeLoc P
= GetPrototypeLoc(NakedFn
);
6121 QualType T
= NakedFn
->getType();
6122 if (!T
->getPointeeType().isNull())
6123 T
= T
->getPointeeType();
6125 if (auto FP
= T
->getAs
<FunctionProtoType
>()) {
6126 if (!TooManyArguments(FP
->getNumParams(),
6127 ArgsWithoutDependentTypes
.size(),
6128 /*PartialOverloading=*/true) ||
6131 Results
.push_back(ResultCandidate(P
));
6133 Results
.push_back(ResultCandidate(FP
));
6136 } else if (auto FT
= T
->getAs
<FunctionType
>())
6137 // No prototype and declaration, it may be a K & R style function.
6138 Results
.push_back(ResultCandidate(FT
));
6141 mergeCandidatesWithResults(*this, Results
, CandidateSet
, Loc
, Args
.size());
6142 QualType ParamType
= ProduceSignatureHelp(*this, Results
, Args
.size(),
6143 OpenParLoc
, /*Braced=*/false);
6144 return !CandidateSet
.empty() ? ParamType
: QualType();
6147 // Determine which param to continue aggregate initialization from after
6148 // a designated initializer.
6150 // Given struct S { int a,b,c,d,e; }:
6151 // after `S{.b=1,` we want to suggest c to continue
6152 // after `S{.b=1, 2,` we continue with d (this is legal C and ext in C++)
6153 // after `S{.b=1, .a=2,` we continue with b (this is legal C and ext in C++)
6155 // Possible outcomes:
6156 // - we saw a designator for a field, and continue from the returned index.
6157 // Only aggregate initialization is allowed.
6158 // - we saw a designator, but it was complex or we couldn't find the field.
6159 // Only aggregate initialization is possible, but we can't assist with it.
6160 // Returns an out-of-range index.
6161 // - we saw no designators, just positional arguments.
6163 static llvm::Optional
<unsigned>
6164 getNextAggregateIndexAfterDesignatedInit(const ResultCandidate
&Aggregate
,
6165 ArrayRef
<Expr
*> Args
) {
6166 static constexpr unsigned Invalid
= std::numeric_limits
<unsigned>::max();
6167 assert(Aggregate
.getKind() == ResultCandidate::CK_Aggregate
);
6169 // Look for designated initializers.
6170 // They're in their syntactic form, not yet resolved to fields.
6171 IdentifierInfo
*DesignatedFieldName
= nullptr;
6172 unsigned ArgsAfterDesignator
= 0;
6173 for (const Expr
*Arg
: Args
) {
6174 if (const auto *DIE
= dyn_cast
<DesignatedInitExpr
>(Arg
)) {
6175 if (DIE
->size() == 1 && DIE
->getDesignator(0)->isFieldDesignator()) {
6176 DesignatedFieldName
= DIE
->getDesignator(0)->getFieldName();
6177 ArgsAfterDesignator
= 0;
6179 return Invalid
; // Complicated designator.
6181 } else if (isa
<DesignatedInitUpdateExpr
>(Arg
)) {
6182 return Invalid
; // Unsupported.
6184 ++ArgsAfterDesignator
;
6187 if (!DesignatedFieldName
)
6190 // Find the index within the class's fields.
6191 // (Probing getParamDecl() directly would be quadratic in number of fields).
6192 unsigned DesignatedIndex
= 0;
6193 const FieldDecl
*DesignatedField
= nullptr;
6194 for (const auto *Field
: Aggregate
.getAggregate()->fields()) {
6195 if (Field
->getIdentifier() == DesignatedFieldName
) {
6196 DesignatedField
= Field
;
6201 if (!DesignatedField
)
6202 return Invalid
; // Designator referred to a missing field, give up.
6204 // Find the index within the aggregate (which may have leading bases).
6205 unsigned AggregateSize
= Aggregate
.getNumParams();
6206 while (DesignatedIndex
< AggregateSize
&&
6207 Aggregate
.getParamDecl(DesignatedIndex
) != DesignatedField
)
6210 // Continue from the index after the last named field.
6211 return DesignatedIndex
+ ArgsAfterDesignator
+ 1;
6214 QualType
Sema::ProduceConstructorSignatureHelp(QualType Type
,
6216 ArrayRef
<Expr
*> Args
,
6217 SourceLocation OpenParLoc
,
6221 SmallVector
<ResultCandidate
, 8> Results
;
6223 // A complete type is needed to lookup for constructors.
6225 isCompleteType(Loc
, Type
) ? Type
->getAsRecordDecl() : nullptr;
6228 CXXRecordDecl
*CRD
= dyn_cast
<CXXRecordDecl
>(RD
);
6230 // Consider aggregate initialization.
6231 // We don't check that types so far are correct.
6232 // We also don't handle C99/C++17 brace-elision, we assume init-list elements
6233 // are 1:1 with fields.
6234 // FIXME: it would be nice to support "unwrapping" aggregates that contain
6235 // a single subaggregate, like std::array<T, N> -> T __elements[N].
6236 if (Braced
&& !RD
->isUnion() &&
6237 (!LangOpts
.CPlusPlus
|| (CRD
&& CRD
->isAggregate()))) {
6238 ResultCandidate
AggregateSig(RD
);
6239 unsigned AggregateSize
= AggregateSig
.getNumParams();
6241 if (auto NextIndex
=
6242 getNextAggregateIndexAfterDesignatedInit(AggregateSig
, Args
)) {
6243 // A designator was used, only aggregate init is possible.
6244 if (*NextIndex
>= AggregateSize
)
6246 Results
.push_back(AggregateSig
);
6247 return ProduceSignatureHelp(*this, Results
, *NextIndex
, OpenParLoc
,
6251 // Describe aggregate initialization, but also constructors below.
6252 if (Args
.size() < AggregateSize
)
6253 Results
.push_back(AggregateSig
);
6256 // FIXME: Provide support for member initializers.
6257 // FIXME: Provide support for variadic template constructors.
6260 OverloadCandidateSet
CandidateSet(Loc
, OverloadCandidateSet::CSK_Normal
);
6261 for (NamedDecl
*C
: LookupConstructors(CRD
)) {
6262 if (auto *FD
= dyn_cast
<FunctionDecl
>(C
)) {
6263 // FIXME: we can't yet provide correct signature help for initializer
6264 // list constructors, so skip them entirely.
6265 if (Braced
&& LangOpts
.CPlusPlus
&& isInitListConstructor(FD
))
6267 AddOverloadCandidate(FD
, DeclAccessPair::make(FD
, C
->getAccess()), Args
,
6269 /*SuppressUserConversions=*/false,
6270 /*PartialOverloading=*/true,
6271 /*AllowExplicit*/ true);
6272 } else if (auto *FTD
= dyn_cast
<FunctionTemplateDecl
>(C
)) {
6273 if (Braced
&& LangOpts
.CPlusPlus
&&
6274 isInitListConstructor(FTD
->getTemplatedDecl()))
6277 AddTemplateOverloadCandidate(
6278 FTD
, DeclAccessPair::make(FTD
, C
->getAccess()),
6279 /*ExplicitTemplateArgs=*/nullptr, Args
, CandidateSet
,
6280 /*SuppressUserConversions=*/false,
6281 /*PartialOverloading=*/true);
6284 mergeCandidatesWithResults(*this, Results
, CandidateSet
, Loc
, Args
.size());
6287 return ProduceSignatureHelp(*this, Results
, Args
.size(), OpenParLoc
, Braced
);
6290 QualType
Sema::ProduceCtorInitMemberSignatureHelp(
6291 Decl
*ConstructorDecl
, CXXScopeSpec SS
, ParsedType TemplateTypeTy
,
6292 ArrayRef
<Expr
*> ArgExprs
, IdentifierInfo
*II
, SourceLocation OpenParLoc
,
6297 CXXConstructorDecl
*Constructor
=
6298 dyn_cast
<CXXConstructorDecl
>(ConstructorDecl
);
6301 // FIXME: Add support for Base class constructors as well.
6302 if (ValueDecl
*MemberDecl
= tryLookupCtorInitMemberDecl(
6303 Constructor
->getParent(), SS
, TemplateTypeTy
, II
))
6304 return ProduceConstructorSignatureHelp(MemberDecl
->getType(),
6305 MemberDecl
->getLocation(), ArgExprs
,
6306 OpenParLoc
, Braced
);
6310 static bool argMatchesTemplateParams(const ParsedTemplateArgument
&Arg
,
6312 const TemplateParameterList
&Params
) {
6313 const NamedDecl
*Param
;
6314 if (Index
< Params
.size())
6315 Param
= Params
.getParam(Index
);
6316 else if (Params
.hasParameterPack())
6317 Param
= Params
.asArray().back();
6319 return false; // too many args
6321 switch (Arg
.getKind()) {
6322 case ParsedTemplateArgument::Type
:
6323 return llvm::isa
<TemplateTypeParmDecl
>(Param
); // constraints not checked
6324 case ParsedTemplateArgument::NonType
:
6325 return llvm::isa
<NonTypeTemplateParmDecl
>(Param
); // type not checked
6326 case ParsedTemplateArgument::Template
:
6327 return llvm::isa
<TemplateTemplateParmDecl
>(Param
); // signature not checked
6329 llvm_unreachable("Unhandled switch case");
6332 QualType
Sema::ProduceTemplateArgumentSignatureHelp(
6333 TemplateTy ParsedTemplate
, ArrayRef
<ParsedTemplateArgument
> Args
,
6334 SourceLocation LAngleLoc
) {
6335 if (!CodeCompleter
|| !ParsedTemplate
)
6338 SmallVector
<ResultCandidate
, 8> Results
;
6339 auto Consider
= [&](const TemplateDecl
*TD
) {
6340 // Only add if the existing args are compatible with the template.
6341 bool Matches
= true;
6342 for (unsigned I
= 0; I
< Args
.size(); ++I
) {
6343 if (!argMatchesTemplateParams(Args
[I
], I
, *TD
->getTemplateParameters())) {
6349 Results
.emplace_back(TD
);
6352 TemplateName Template
= ParsedTemplate
.get();
6353 if (const auto *TD
= Template
.getAsTemplateDecl()) {
6355 } else if (const auto *OTS
= Template
.getAsOverloadedTemplate()) {
6356 for (const NamedDecl
*ND
: *OTS
)
6357 if (const auto *TD
= llvm::dyn_cast
<TemplateDecl
>(ND
))
6360 return ProduceSignatureHelp(*this, Results
, Args
.size(), LAngleLoc
,
6364 static QualType
getDesignatedType(QualType BaseType
, const Designation
&Desig
) {
6365 for (unsigned I
= 0; I
< Desig
.getNumDesignators(); ++I
) {
6366 if (BaseType
.isNull())
6369 const auto &D
= Desig
.getDesignator(I
);
6370 if (D
.isArrayDesignator() || D
.isArrayRangeDesignator()) {
6371 if (BaseType
->isArrayType())
6372 NextType
= BaseType
->getAsArrayTypeUnsafe()->getElementType();
6374 assert(D
.isFieldDesignator());
6375 auto *RD
= getAsRecordDecl(BaseType
);
6376 if (RD
&& RD
->isCompleteDefinition()) {
6377 for (const auto *Member
: RD
->lookup(D
.getField()))
6378 if (const FieldDecl
*FD
= llvm::dyn_cast
<FieldDecl
>(Member
)) {
6379 NextType
= FD
->getType();
6384 BaseType
= NextType
;
6389 void Sema::CodeCompleteDesignator(QualType BaseType
,
6390 llvm::ArrayRef
<Expr
*> InitExprs
,
6391 const Designation
&D
) {
6392 BaseType
= getDesignatedType(BaseType
, D
);
6393 if (BaseType
.isNull())
6395 const auto *RD
= getAsRecordDecl(BaseType
);
6396 if (!RD
|| RD
->fields().empty())
6399 CodeCompletionContext
CCC(CodeCompletionContext::CCC_DotMemberAccess
,
6401 ResultBuilder
Results(*this, CodeCompleter
->getAllocator(),
6402 CodeCompleter
->getCodeCompletionTUInfo(), CCC
);
6404 Results
.EnterNewScope();
6405 for (const Decl
*D
: RD
->decls()) {
6406 const FieldDecl
*FD
;
6407 if (auto *IFD
= dyn_cast
<IndirectFieldDecl
>(D
))
6408 FD
= IFD
->getAnonField();
6409 else if (auto *DFD
= dyn_cast
<FieldDecl
>(D
))
6414 // FIXME: Make use of previous designators to mark any fields before those
6415 // inaccessible, and also compute the next initializer priority.
6416 ResultBuilder::Result
Result(FD
, Results
.getBasePriority(FD
));
6417 Results
.AddResult(Result
, CurContext
, /*Hiding=*/nullptr);
6419 Results
.ExitScope();
6420 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
6421 Results
.data(), Results
.size());
6424 void Sema::CodeCompleteInitializer(Scope
*S
, Decl
*D
) {
6425 ValueDecl
*VD
= dyn_cast_or_null
<ValueDecl
>(D
);
6427 CodeCompleteOrdinaryName(S
, PCC_Expression
);
6431 CodeCompleteExpressionData Data
;
6432 Data
.PreferredType
= VD
->getType();
6433 // Ignore VD to avoid completing the variable itself, e.g. in 'int foo = ^'.
6434 Data
.IgnoreDecls
.push_back(VD
);
6436 CodeCompleteExpression(S
, Data
);
6439 void Sema::CodeCompleteAfterIf(Scope
*S
, bool IsBracedThen
) {
6440 ResultBuilder
Results(*this, CodeCompleter
->getAllocator(),
6441 CodeCompleter
->getCodeCompletionTUInfo(),
6442 mapCodeCompletionContext(*this, PCC_Statement
));
6443 Results
.setFilter(&ResultBuilder::IsOrdinaryName
);
6444 Results
.EnterNewScope();
6446 CodeCompletionDeclConsumer
Consumer(Results
, CurContext
);
6447 LookupVisibleDecls(S
, LookupOrdinaryName
, Consumer
,
6448 CodeCompleter
->includeGlobals(),
6449 CodeCompleter
->loadExternal());
6451 AddOrdinaryNameResults(PCC_Statement
, S
, *this, Results
);
6454 CodeCompletionBuilder
Builder(Results
.getAllocator(),
6455 Results
.getCodeCompletionTUInfo());
6457 auto AddElseBodyPattern
= [&] {
6459 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
6460 Builder
.AddChunk(CodeCompletionString::CK_LeftBrace
);
6461 Builder
.AddChunk(CodeCompletionString::CK_VerticalSpace
);
6462 Builder
.AddPlaceholderChunk("statements");
6463 Builder
.AddChunk(CodeCompletionString::CK_VerticalSpace
);
6464 Builder
.AddChunk(CodeCompletionString::CK_RightBrace
);
6466 Builder
.AddChunk(CodeCompletionString::CK_VerticalSpace
);
6467 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
6468 Builder
.AddPlaceholderChunk("statement");
6469 Builder
.AddChunk(CodeCompletionString::CK_SemiColon
);
6472 Builder
.AddTypedTextChunk("else");
6473 if (Results
.includeCodePatterns())
6474 AddElseBodyPattern();
6475 Results
.AddResult(Builder
.TakeString());
6478 Builder
.AddTypedTextChunk("else if");
6479 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
6480 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
6481 if (getLangOpts().CPlusPlus
)
6482 Builder
.AddPlaceholderChunk("condition");
6484 Builder
.AddPlaceholderChunk("expression");
6485 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
6486 if (Results
.includeCodePatterns()) {
6487 AddElseBodyPattern();
6489 Results
.AddResult(Builder
.TakeString());
6491 Results
.ExitScope();
6493 if (S
->getFnParent())
6494 AddPrettyFunctionResults(getLangOpts(), Results
);
6496 if (CodeCompleter
->includeMacros())
6497 AddMacroResults(PP
, Results
, CodeCompleter
->loadExternal(), false);
6499 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
6500 Results
.data(), Results
.size());
6503 void Sema::CodeCompleteQualifiedId(Scope
*S
, CXXScopeSpec
&SS
,
6504 bool EnteringContext
,
6505 bool IsUsingDeclaration
, QualType BaseType
,
6506 QualType PreferredType
) {
6507 if (SS
.isEmpty() || !CodeCompleter
)
6510 CodeCompletionContext
CC(CodeCompletionContext::CCC_Symbol
, PreferredType
);
6511 CC
.setIsUsingDeclaration(IsUsingDeclaration
);
6512 CC
.setCXXScopeSpecifier(SS
);
6514 // We want to keep the scope specifier even if it's invalid (e.g. the scope
6515 // "a::b::" is not corresponding to any context/namespace in the AST), since
6516 // it can be useful for global code completion which have information about
6517 // contexts/symbols that are not in the AST.
6518 if (SS
.isInvalid()) {
6519 // As SS is invalid, we try to collect accessible contexts from the current
6520 // scope with a dummy lookup so that the completion consumer can try to
6521 // guess what the specified scope is.
6522 ResultBuilder
DummyResults(*this, CodeCompleter
->getAllocator(),
6523 CodeCompleter
->getCodeCompletionTUInfo(), CC
);
6524 if (!PreferredType
.isNull())
6525 DummyResults
.setPreferredType(PreferredType
);
6526 if (S
->getEntity()) {
6527 CodeCompletionDeclConsumer
Consumer(DummyResults
, S
->getEntity(),
6529 LookupVisibleDecls(S
, LookupOrdinaryName
, Consumer
,
6530 /*IncludeGlobalScope=*/false,
6531 /*LoadExternal=*/false);
6533 HandleCodeCompleteResults(this, CodeCompleter
,
6534 DummyResults
.getCompletionContext(), nullptr, 0);
6537 // Always pretend to enter a context to ensure that a dependent type
6538 // resolves to a dependent record.
6539 DeclContext
*Ctx
= computeDeclContext(SS
, /*EnteringContext=*/true);
6541 // Try to instantiate any non-dependent declaration contexts before
6542 // we look in them. Bail out if we fail.
6543 NestedNameSpecifier
*NNS
= SS
.getScopeRep();
6544 if (NNS
!= nullptr && SS
.isValid() && !NNS
->isDependent()) {
6545 if (Ctx
== nullptr || RequireCompleteDeclContext(SS
, Ctx
))
6549 ResultBuilder
Results(*this, CodeCompleter
->getAllocator(),
6550 CodeCompleter
->getCodeCompletionTUInfo(), CC
);
6551 if (!PreferredType
.isNull())
6552 Results
.setPreferredType(PreferredType
);
6553 Results
.EnterNewScope();
6555 // The "template" keyword can follow "::" in the grammar, but only
6556 // put it into the grammar if the nested-name-specifier is dependent.
6557 // FIXME: results is always empty, this appears to be dead.
6558 if (!Results
.empty() && NNS
->isDependent())
6559 Results
.AddResult("template");
6561 // If the scope is a concept-constrained type parameter, infer nested
6562 // members based on the constraints.
6563 if (const auto *TTPT
=
6564 dyn_cast_or_null
<TemplateTypeParmType
>(NNS
->getAsType())) {
6565 for (const auto &R
: ConceptInfo(*TTPT
, S
).members()) {
6566 if (R
.Operator
!= ConceptInfo::Member::Colons
)
6568 Results
.AddResult(CodeCompletionResult(
6569 R
.render(*this, CodeCompleter
->getAllocator(),
6570 CodeCompleter
->getCodeCompletionTUInfo())));
6574 // Add calls to overridden virtual functions, if there are any.
6576 // FIXME: This isn't wonderful, because we don't know whether we're actually
6577 // in a context that permits expressions. This is a general issue with
6578 // qualified-id completions.
6579 if (Ctx
&& !EnteringContext
)
6580 MaybeAddOverrideCalls(*this, Ctx
, Results
);
6581 Results
.ExitScope();
6584 (CodeCompleter
->includeNamespaceLevelDecls() || !Ctx
->isFileContext())) {
6585 CodeCompletionDeclConsumer
Consumer(Results
, Ctx
, BaseType
);
6586 LookupVisibleDecls(Ctx
, LookupOrdinaryName
, Consumer
,
6587 /*IncludeGlobalScope=*/true,
6588 /*IncludeDependentBases=*/true,
6589 CodeCompleter
->loadExternal());
6592 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
6593 Results
.data(), Results
.size());
6596 void Sema::CodeCompleteUsing(Scope
*S
) {
6600 // This can be both a using alias or using declaration, in the former we
6601 // expect a new name and a symbol in the latter case.
6602 CodeCompletionContext
Context(CodeCompletionContext::CCC_SymbolOrNewName
);
6603 Context
.setIsUsingDeclaration(true);
6605 ResultBuilder
Results(*this, CodeCompleter
->getAllocator(),
6606 CodeCompleter
->getCodeCompletionTUInfo(), Context
,
6607 &ResultBuilder::IsNestedNameSpecifier
);
6608 Results
.EnterNewScope();
6610 // If we aren't in class scope, we could see the "namespace" keyword.
6611 if (!S
->isClassScope())
6612 Results
.AddResult(CodeCompletionResult("namespace"));
6614 // After "using", we can see anything that would start a
6615 // nested-name-specifier.
6616 CodeCompletionDeclConsumer
Consumer(Results
, CurContext
);
6617 LookupVisibleDecls(S
, LookupOrdinaryName
, Consumer
,
6618 CodeCompleter
->includeGlobals(),
6619 CodeCompleter
->loadExternal());
6620 Results
.ExitScope();
6622 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
6623 Results
.data(), Results
.size());
6626 void Sema::CodeCompleteUsingDirective(Scope
*S
) {
6630 // After "using namespace", we expect to see a namespace name or namespace
6632 ResultBuilder
Results(*this, CodeCompleter
->getAllocator(),
6633 CodeCompleter
->getCodeCompletionTUInfo(),
6634 CodeCompletionContext::CCC_Namespace
,
6635 &ResultBuilder::IsNamespaceOrAlias
);
6636 Results
.EnterNewScope();
6637 CodeCompletionDeclConsumer
Consumer(Results
, CurContext
);
6638 LookupVisibleDecls(S
, LookupOrdinaryName
, Consumer
,
6639 CodeCompleter
->includeGlobals(),
6640 CodeCompleter
->loadExternal());
6641 Results
.ExitScope();
6642 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
6643 Results
.data(), Results
.size());
6646 void Sema::CodeCompleteNamespaceDecl(Scope
*S
) {
6650 DeclContext
*Ctx
= S
->getEntity();
6651 if (!S
->getParent())
6652 Ctx
= Context
.getTranslationUnitDecl();
6654 bool SuppressedGlobalResults
=
6655 Ctx
&& !CodeCompleter
->includeGlobals() && isa
<TranslationUnitDecl
>(Ctx
);
6657 ResultBuilder
Results(*this, CodeCompleter
->getAllocator(),
6658 CodeCompleter
->getCodeCompletionTUInfo(),
6659 SuppressedGlobalResults
6660 ? CodeCompletionContext::CCC_Namespace
6661 : CodeCompletionContext::CCC_Other
,
6662 &ResultBuilder::IsNamespace
);
6664 if (Ctx
&& Ctx
->isFileContext() && !SuppressedGlobalResults
) {
6665 // We only want to see those namespaces that have already been defined
6666 // within this scope, because its likely that the user is creating an
6667 // extended namespace declaration. Keep track of the most recent
6668 // definition of each namespace.
6669 std::map
<NamespaceDecl
*, NamespaceDecl
*> OrigToLatest
;
6670 for (DeclContext::specific_decl_iterator
<NamespaceDecl
>
6671 NS(Ctx
->decls_begin()),
6672 NSEnd(Ctx
->decls_end());
6674 OrigToLatest
[NS
->getOriginalNamespace()] = *NS
;
6676 // Add the most recent definition (or extended definition) of each
6677 // namespace to the list of results.
6678 Results
.EnterNewScope();
6679 for (std::map
<NamespaceDecl
*, NamespaceDecl
*>::iterator
6680 NS
= OrigToLatest
.begin(),
6681 NSEnd
= OrigToLatest
.end();
6684 CodeCompletionResult(NS
->second
, Results
.getBasePriority(NS
->second
),
6686 CurContext
, nullptr, false);
6687 Results
.ExitScope();
6690 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
6691 Results
.data(), Results
.size());
6694 void Sema::CodeCompleteNamespaceAliasDecl(Scope
*S
) {
6698 // After "namespace", we expect to see a namespace or alias.
6699 ResultBuilder
Results(*this, CodeCompleter
->getAllocator(),
6700 CodeCompleter
->getCodeCompletionTUInfo(),
6701 CodeCompletionContext::CCC_Namespace
,
6702 &ResultBuilder::IsNamespaceOrAlias
);
6703 CodeCompletionDeclConsumer
Consumer(Results
, CurContext
);
6704 LookupVisibleDecls(S
, LookupOrdinaryName
, Consumer
,
6705 CodeCompleter
->includeGlobals(),
6706 CodeCompleter
->loadExternal());
6707 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
6708 Results
.data(), Results
.size());
6711 void Sema::CodeCompleteOperatorName(Scope
*S
) {
6715 typedef CodeCompletionResult Result
;
6716 ResultBuilder
Results(*this, CodeCompleter
->getAllocator(),
6717 CodeCompleter
->getCodeCompletionTUInfo(),
6718 CodeCompletionContext::CCC_Type
,
6719 &ResultBuilder::IsType
);
6720 Results
.EnterNewScope();
6722 // Add the names of overloadable operators. Note that OO_Conditional is not
6723 // actually overloadable.
6724 #define OVERLOADED_OPERATOR(Name, Spelling, Token, Unary, Binary, MemberOnly) \
6725 if (OO_##Name != OO_Conditional) \
6726 Results.AddResult(Result(Spelling));
6727 #include "clang/Basic/OperatorKinds.def"
6729 // Add any type names visible from the current scope
6730 Results
.allowNestedNameSpecifiers();
6731 CodeCompletionDeclConsumer
Consumer(Results
, CurContext
);
6732 LookupVisibleDecls(S
, LookupOrdinaryName
, Consumer
,
6733 CodeCompleter
->includeGlobals(),
6734 CodeCompleter
->loadExternal());
6736 // Add any type specifiers
6737 AddTypeSpecifierResults(getLangOpts(), Results
);
6738 Results
.ExitScope();
6740 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
6741 Results
.data(), Results
.size());
6744 void Sema::CodeCompleteConstructorInitializer(
6745 Decl
*ConstructorD
, ArrayRef
<CXXCtorInitializer
*> Initializers
) {
6749 AdjustDeclIfTemplate(ConstructorD
);
6751 auto *Constructor
= dyn_cast
<CXXConstructorDecl
>(ConstructorD
);
6755 ResultBuilder
Results(*this, CodeCompleter
->getAllocator(),
6756 CodeCompleter
->getCodeCompletionTUInfo(),
6757 CodeCompletionContext::CCC_Symbol
);
6758 Results
.EnterNewScope();
6760 // Fill in any already-initialized fields or base classes.
6761 llvm::SmallPtrSet
<FieldDecl
*, 4> InitializedFields
;
6762 llvm::SmallPtrSet
<CanQualType
, 4> InitializedBases
;
6763 for (unsigned I
= 0, E
= Initializers
.size(); I
!= E
; ++I
) {
6764 if (Initializers
[I
]->isBaseInitializer())
6765 InitializedBases
.insert(Context
.getCanonicalType(
6766 QualType(Initializers
[I
]->getBaseClass(), 0)));
6768 InitializedFields
.insert(
6769 cast
<FieldDecl
>(Initializers
[I
]->getAnyMember()));
6772 // Add completions for base classes.
6773 PrintingPolicy Policy
= getCompletionPrintingPolicy(*this);
6774 bool SawLastInitializer
= Initializers
.empty();
6775 CXXRecordDecl
*ClassDecl
= Constructor
->getParent();
6777 auto GenerateCCS
= [&](const NamedDecl
*ND
, const char *Name
) {
6778 CodeCompletionBuilder
Builder(Results
.getAllocator(),
6779 Results
.getCodeCompletionTUInfo());
6780 Builder
.AddTypedTextChunk(Name
);
6781 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
6782 if (const auto *Function
= dyn_cast
<FunctionDecl
>(ND
))
6783 AddFunctionParameterChunks(PP
, Policy
, Function
, Builder
);
6784 else if (const auto *FunTemplDecl
= dyn_cast
<FunctionTemplateDecl
>(ND
))
6785 AddFunctionParameterChunks(PP
, Policy
, FunTemplDecl
->getTemplatedDecl(),
6787 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
6788 return Builder
.TakeString();
6790 auto AddDefaultCtorInit
= [&](const char *Name
, const char *Type
,
6791 const NamedDecl
*ND
) {
6792 CodeCompletionBuilder
Builder(Results
.getAllocator(),
6793 Results
.getCodeCompletionTUInfo());
6794 Builder
.AddTypedTextChunk(Name
);
6795 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
6796 Builder
.AddPlaceholderChunk(Type
);
6797 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
6799 auto CCR
= CodeCompletionResult(
6800 Builder
.TakeString(), ND
,
6801 SawLastInitializer
? CCP_NextInitializer
: CCP_MemberDeclaration
);
6802 if (isa
<FieldDecl
>(ND
))
6803 CCR
.CursorKind
= CXCursor_MemberRef
;
6804 return Results
.AddResult(CCR
);
6806 return Results
.AddResult(CodeCompletionResult(
6807 Builder
.TakeString(),
6808 SawLastInitializer
? CCP_NextInitializer
: CCP_MemberDeclaration
));
6810 auto AddCtorsWithName
= [&](const CXXRecordDecl
*RD
, unsigned int Priority
,
6811 const char *Name
, const FieldDecl
*FD
) {
6813 return AddDefaultCtorInit(Name
,
6814 FD
? Results
.getAllocator().CopyString(
6815 FD
->getType().getAsString(Policy
))
6818 auto Ctors
= getConstructors(Context
, RD
);
6819 if (Ctors
.begin() == Ctors
.end())
6820 return AddDefaultCtorInit(Name
, Name
, RD
);
6821 for (const NamedDecl
*Ctor
: Ctors
) {
6822 auto CCR
= CodeCompletionResult(GenerateCCS(Ctor
, Name
), RD
, Priority
);
6823 CCR
.CursorKind
= getCursorKindForDecl(Ctor
);
6824 Results
.AddResult(CCR
);
6827 auto AddBase
= [&](const CXXBaseSpecifier
&Base
) {
6828 const char *BaseName
=
6829 Results
.getAllocator().CopyString(Base
.getType().getAsString(Policy
));
6830 const auto *RD
= Base
.getType()->getAsCXXRecordDecl();
6832 RD
, SawLastInitializer
? CCP_NextInitializer
: CCP_MemberDeclaration
,
6835 auto AddField
= [&](const FieldDecl
*FD
) {
6836 const char *FieldName
=
6837 Results
.getAllocator().CopyString(FD
->getIdentifier()->getName());
6838 const CXXRecordDecl
*RD
= FD
->getType()->getAsCXXRecordDecl();
6840 RD
, SawLastInitializer
? CCP_NextInitializer
: CCP_MemberDeclaration
,
6844 for (const auto &Base
: ClassDecl
->bases()) {
6845 if (!InitializedBases
.insert(Context
.getCanonicalType(Base
.getType()))
6847 SawLastInitializer
=
6848 !Initializers
.empty() && Initializers
.back()->isBaseInitializer() &&
6849 Context
.hasSameUnqualifiedType(
6850 Base
.getType(), QualType(Initializers
.back()->getBaseClass(), 0));
6855 SawLastInitializer
= false;
6858 // Add completions for virtual base classes.
6859 for (const auto &Base
: ClassDecl
->vbases()) {
6860 if (!InitializedBases
.insert(Context
.getCanonicalType(Base
.getType()))
6862 SawLastInitializer
=
6863 !Initializers
.empty() && Initializers
.back()->isBaseInitializer() &&
6864 Context
.hasSameUnqualifiedType(
6865 Base
.getType(), QualType(Initializers
.back()->getBaseClass(), 0));
6870 SawLastInitializer
= false;
6873 // Add completions for members.
6874 for (auto *Field
: ClassDecl
->fields()) {
6875 if (!InitializedFields
.insert(cast
<FieldDecl
>(Field
->getCanonicalDecl()))
6877 SawLastInitializer
= !Initializers
.empty() &&
6878 Initializers
.back()->isAnyMemberInitializer() &&
6879 Initializers
.back()->getAnyMember() == Field
;
6883 if (!Field
->getDeclName())
6887 SawLastInitializer
= false;
6889 Results
.ExitScope();
6891 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
6892 Results
.data(), Results
.size());
6895 /// Determine whether this scope denotes a namespace.
6896 static bool isNamespaceScope(Scope
*S
) {
6897 DeclContext
*DC
= S
->getEntity();
6901 return DC
->isFileContext();
6904 void Sema::CodeCompleteLambdaIntroducer(Scope
*S
, LambdaIntroducer
&Intro
,
6905 bool AfterAmpersand
) {
6906 ResultBuilder
Results(*this, CodeCompleter
->getAllocator(),
6907 CodeCompleter
->getCodeCompletionTUInfo(),
6908 CodeCompletionContext::CCC_Other
);
6909 Results
.EnterNewScope();
6911 // Note what has already been captured.
6912 llvm::SmallPtrSet
<IdentifierInfo
*, 4> Known
;
6913 bool IncludedThis
= false;
6914 for (const auto &C
: Intro
.Captures
) {
6915 if (C
.Kind
== LCK_This
) {
6916 IncludedThis
= true;
6923 // Look for other capturable variables.
6924 for (; S
&& !isNamespaceScope(S
); S
= S
->getParent()) {
6925 for (const auto *D
: S
->decls()) {
6926 const auto *Var
= dyn_cast
<VarDecl
>(D
);
6927 if (!Var
|| !Var
->hasLocalStorage() || Var
->hasAttr
<BlocksAttr
>())
6930 if (Known
.insert(Var
->getIdentifier()).second
)
6931 Results
.AddResult(CodeCompletionResult(Var
, CCP_LocalDeclaration
),
6932 CurContext
, nullptr, false);
6936 // Add 'this', if it would be valid.
6937 if (!IncludedThis
&& !AfterAmpersand
&& Intro
.Default
!= LCD_ByCopy
)
6938 addThisCompletion(*this, Results
);
6940 Results
.ExitScope();
6942 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
6943 Results
.data(), Results
.size());
6946 void Sema::CodeCompleteAfterFunctionEquals(Declarator
&D
) {
6947 if (!LangOpts
.CPlusPlus11
)
6949 ResultBuilder
Results(*this, CodeCompleter
->getAllocator(),
6950 CodeCompleter
->getCodeCompletionTUInfo(),
6951 CodeCompletionContext::CCC_Other
);
6952 auto ShouldAddDefault
= [&D
, this]() {
6953 if (!D
.isFunctionDeclarator())
6955 auto &Id
= D
.getName();
6956 if (Id
.getKind() == UnqualifiedIdKind::IK_DestructorName
)
6958 // FIXME(liuhui): Ideally, we should check the constructor parameter list to
6959 // verify that it is the default, copy or move constructor?
6960 if (Id
.getKind() == UnqualifiedIdKind::IK_ConstructorName
&&
6961 D
.getFunctionTypeInfo().NumParams
<= 1)
6963 if (Id
.getKind() == UnqualifiedIdKind::IK_OperatorFunctionId
) {
6964 auto Op
= Id
.OperatorFunctionId
.Operator
;
6965 // FIXME(liuhui): Ideally, we should check the function parameter list to
6966 // verify that it is the copy or move assignment?
6967 if (Op
== OverloadedOperatorKind::OO_Equal
)
6969 if (LangOpts
.CPlusPlus20
&&
6970 (Op
== OverloadedOperatorKind::OO_EqualEqual
||
6971 Op
== OverloadedOperatorKind::OO_ExclaimEqual
||
6972 Op
== OverloadedOperatorKind::OO_Less
||
6973 Op
== OverloadedOperatorKind::OO_LessEqual
||
6974 Op
== OverloadedOperatorKind::OO_Greater
||
6975 Op
== OverloadedOperatorKind::OO_GreaterEqual
||
6976 Op
== OverloadedOperatorKind::OO_Spaceship
))
6982 Results
.EnterNewScope();
6983 if (ShouldAddDefault())
6984 Results
.AddResult("default");
6985 // FIXME(liuhui): Ideally, we should only provide `delete` completion for the
6986 // first function declaration.
6987 Results
.AddResult("delete");
6988 Results
.ExitScope();
6989 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
6990 Results
.data(), Results
.size());
6993 /// Macro that optionally prepends an "@" to the string literal passed in via
6994 /// Keyword, depending on whether NeedAt is true or false.
6995 #define OBJC_AT_KEYWORD_NAME(NeedAt, Keyword) ((NeedAt) ? "@" Keyword : Keyword)
6997 static void AddObjCImplementationResults(const LangOptions
&LangOpts
,
6998 ResultBuilder
&Results
, bool NeedAt
) {
6999 typedef CodeCompletionResult Result
;
7000 // Since we have an implementation, we can end it.
7001 Results
.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt
, "end")));
7003 CodeCompletionBuilder
Builder(Results
.getAllocator(),
7004 Results
.getCodeCompletionTUInfo());
7005 if (LangOpts
.ObjC
) {
7007 Builder
.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt
, "dynamic"));
7008 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
7009 Builder
.AddPlaceholderChunk("property");
7010 Results
.AddResult(Result(Builder
.TakeString()));
7013 Builder
.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt
, "synthesize"));
7014 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
7015 Builder
.AddPlaceholderChunk("property");
7016 Results
.AddResult(Result(Builder
.TakeString()));
7020 static void AddObjCInterfaceResults(const LangOptions
&LangOpts
,
7021 ResultBuilder
&Results
, bool NeedAt
) {
7022 typedef CodeCompletionResult Result
;
7024 // Since we have an interface or protocol, we can end it.
7025 Results
.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt
, "end")));
7027 if (LangOpts
.ObjC
) {
7029 Results
.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt
, "property")));
7032 Results
.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt
, "required")));
7035 Results
.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt
, "optional")));
7039 static void AddObjCTopLevelResults(ResultBuilder
&Results
, bool NeedAt
) {
7040 typedef CodeCompletionResult Result
;
7041 CodeCompletionBuilder
Builder(Results
.getAllocator(),
7042 Results
.getCodeCompletionTUInfo());
7045 Builder
.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt
, "class"));
7046 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
7047 Builder
.AddPlaceholderChunk("name");
7048 Results
.AddResult(Result(Builder
.TakeString()));
7050 if (Results
.includeCodePatterns()) {
7052 // FIXME: Could introduce the whole pattern, including superclasses and
7054 Builder
.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt
, "interface"));
7055 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
7056 Builder
.AddPlaceholderChunk("class");
7057 Results
.AddResult(Result(Builder
.TakeString()));
7060 Builder
.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt
, "protocol"));
7061 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
7062 Builder
.AddPlaceholderChunk("protocol");
7063 Results
.AddResult(Result(Builder
.TakeString()));
7065 // @implementation name
7066 Builder
.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt
, "implementation"));
7067 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
7068 Builder
.AddPlaceholderChunk("class");
7069 Results
.AddResult(Result(Builder
.TakeString()));
7072 // @compatibility_alias name
7073 Builder
.AddTypedTextChunk(
7074 OBJC_AT_KEYWORD_NAME(NeedAt
, "compatibility_alias"));
7075 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
7076 Builder
.AddPlaceholderChunk("alias");
7077 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
7078 Builder
.AddPlaceholderChunk("class");
7079 Results
.AddResult(Result(Builder
.TakeString()));
7081 if (Results
.getSema().getLangOpts().Modules
) {
7083 Builder
.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt
, "import"));
7084 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
7085 Builder
.AddPlaceholderChunk("module");
7086 Results
.AddResult(Result(Builder
.TakeString()));
7090 void Sema::CodeCompleteObjCAtDirective(Scope
*S
) {
7091 ResultBuilder
Results(*this, CodeCompleter
->getAllocator(),
7092 CodeCompleter
->getCodeCompletionTUInfo(),
7093 CodeCompletionContext::CCC_Other
);
7094 Results
.EnterNewScope();
7095 if (isa
<ObjCImplDecl
>(CurContext
))
7096 AddObjCImplementationResults(getLangOpts(), Results
, false);
7097 else if (CurContext
->isObjCContainer())
7098 AddObjCInterfaceResults(getLangOpts(), Results
, false);
7100 AddObjCTopLevelResults(Results
, false);
7101 Results
.ExitScope();
7102 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
7103 Results
.data(), Results
.size());
7106 static void AddObjCExpressionResults(ResultBuilder
&Results
, bool NeedAt
) {
7107 typedef CodeCompletionResult Result
;
7108 CodeCompletionBuilder
Builder(Results
.getAllocator(),
7109 Results
.getCodeCompletionTUInfo());
7111 // @encode ( type-name )
7112 const char *EncodeType
= "char[]";
7113 if (Results
.getSema().getLangOpts().CPlusPlus
||
7114 Results
.getSema().getLangOpts().ConstStrings
)
7115 EncodeType
= "const char[]";
7116 Builder
.AddResultTypeChunk(EncodeType
);
7117 Builder
.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt
, "encode"));
7118 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
7119 Builder
.AddPlaceholderChunk("type-name");
7120 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
7121 Results
.AddResult(Result(Builder
.TakeString()));
7123 // @protocol ( protocol-name )
7124 Builder
.AddResultTypeChunk("Protocol *");
7125 Builder
.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt
, "protocol"));
7126 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
7127 Builder
.AddPlaceholderChunk("protocol-name");
7128 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
7129 Results
.AddResult(Result(Builder
.TakeString()));
7131 // @selector ( selector )
7132 Builder
.AddResultTypeChunk("SEL");
7133 Builder
.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt
, "selector"));
7134 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
7135 Builder
.AddPlaceholderChunk("selector");
7136 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
7137 Results
.AddResult(Result(Builder
.TakeString()));
7140 Builder
.AddResultTypeChunk("NSString *");
7141 Builder
.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt
, "\""));
7142 Builder
.AddPlaceholderChunk("string");
7143 Builder
.AddTextChunk("\"");
7144 Results
.AddResult(Result(Builder
.TakeString()));
7147 Builder
.AddResultTypeChunk("NSArray *");
7148 Builder
.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt
, "["));
7149 Builder
.AddPlaceholderChunk("objects, ...");
7150 Builder
.AddChunk(CodeCompletionString::CK_RightBracket
);
7151 Results
.AddResult(Result(Builder
.TakeString()));
7153 // @{key : object, ...}
7154 Builder
.AddResultTypeChunk("NSDictionary *");
7155 Builder
.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt
, "{"));
7156 Builder
.AddPlaceholderChunk("key");
7157 Builder
.AddChunk(CodeCompletionString::CK_Colon
);
7158 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
7159 Builder
.AddPlaceholderChunk("object, ...");
7160 Builder
.AddChunk(CodeCompletionString::CK_RightBrace
);
7161 Results
.AddResult(Result(Builder
.TakeString()));
7164 Builder
.AddResultTypeChunk("id");
7165 Builder
.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt
, "("));
7166 Builder
.AddPlaceholderChunk("expression");
7167 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
7168 Results
.AddResult(Result(Builder
.TakeString()));
7171 static void AddObjCStatementResults(ResultBuilder
&Results
, bool NeedAt
) {
7172 typedef CodeCompletionResult Result
;
7173 CodeCompletionBuilder
Builder(Results
.getAllocator(),
7174 Results
.getCodeCompletionTUInfo());
7176 if (Results
.includeCodePatterns()) {
7177 // @try { statements } @catch ( declaration ) { statements } @finally
7179 Builder
.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt
, "try"));
7180 Builder
.AddChunk(CodeCompletionString::CK_LeftBrace
);
7181 Builder
.AddPlaceholderChunk("statements");
7182 Builder
.AddChunk(CodeCompletionString::CK_RightBrace
);
7183 Builder
.AddTextChunk("@catch");
7184 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
7185 Builder
.AddPlaceholderChunk("parameter");
7186 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
7187 Builder
.AddChunk(CodeCompletionString::CK_LeftBrace
);
7188 Builder
.AddPlaceholderChunk("statements");
7189 Builder
.AddChunk(CodeCompletionString::CK_RightBrace
);
7190 Builder
.AddTextChunk("@finally");
7191 Builder
.AddChunk(CodeCompletionString::CK_LeftBrace
);
7192 Builder
.AddPlaceholderChunk("statements");
7193 Builder
.AddChunk(CodeCompletionString::CK_RightBrace
);
7194 Results
.AddResult(Result(Builder
.TakeString()));
7198 Builder
.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt
, "throw"));
7199 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
7200 Builder
.AddPlaceholderChunk("expression");
7201 Results
.AddResult(Result(Builder
.TakeString()));
7203 if (Results
.includeCodePatterns()) {
7204 // @synchronized ( expression ) { statements }
7205 Builder
.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt
, "synchronized"));
7206 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
7207 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
7208 Builder
.AddPlaceholderChunk("expression");
7209 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
7210 Builder
.AddChunk(CodeCompletionString::CK_LeftBrace
);
7211 Builder
.AddPlaceholderChunk("statements");
7212 Builder
.AddChunk(CodeCompletionString::CK_RightBrace
);
7213 Results
.AddResult(Result(Builder
.TakeString()));
7217 static void AddObjCVisibilityResults(const LangOptions
&LangOpts
,
7218 ResultBuilder
&Results
, bool NeedAt
) {
7219 typedef CodeCompletionResult Result
;
7220 Results
.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt
, "private")));
7221 Results
.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt
, "protected")));
7222 Results
.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt
, "public")));
7224 Results
.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt
, "package")));
7227 void Sema::CodeCompleteObjCAtVisibility(Scope
*S
) {
7228 ResultBuilder
Results(*this, CodeCompleter
->getAllocator(),
7229 CodeCompleter
->getCodeCompletionTUInfo(),
7230 CodeCompletionContext::CCC_Other
);
7231 Results
.EnterNewScope();
7232 AddObjCVisibilityResults(getLangOpts(), Results
, false);
7233 Results
.ExitScope();
7234 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
7235 Results
.data(), Results
.size());
7238 void Sema::CodeCompleteObjCAtStatement(Scope
*S
) {
7239 ResultBuilder
Results(*this, CodeCompleter
->getAllocator(),
7240 CodeCompleter
->getCodeCompletionTUInfo(),
7241 CodeCompletionContext::CCC_Other
);
7242 Results
.EnterNewScope();
7243 AddObjCStatementResults(Results
, false);
7244 AddObjCExpressionResults(Results
, false);
7245 Results
.ExitScope();
7246 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
7247 Results
.data(), Results
.size());
7250 void Sema::CodeCompleteObjCAtExpression(Scope
*S
) {
7251 ResultBuilder
Results(*this, CodeCompleter
->getAllocator(),
7252 CodeCompleter
->getCodeCompletionTUInfo(),
7253 CodeCompletionContext::CCC_Other
);
7254 Results
.EnterNewScope();
7255 AddObjCExpressionResults(Results
, false);
7256 Results
.ExitScope();
7257 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
7258 Results
.data(), Results
.size());
7261 /// Determine whether the addition of the given flag to an Objective-C
7262 /// property's attributes will cause a conflict.
7263 static bool ObjCPropertyFlagConflicts(unsigned Attributes
, unsigned NewFlag
) {
7264 // Check if we've already added this flag.
7265 if (Attributes
& NewFlag
)
7268 Attributes
|= NewFlag
;
7270 // Check for collisions with "readonly".
7271 if ((Attributes
& ObjCPropertyAttribute::kind_readonly
) &&
7272 (Attributes
& ObjCPropertyAttribute::kind_readwrite
))
7275 // Check for more than one of { assign, copy, retain, strong, weak }.
7276 unsigned AssignCopyRetMask
=
7278 (ObjCPropertyAttribute::kind_assign
|
7279 ObjCPropertyAttribute::kind_unsafe_unretained
|
7280 ObjCPropertyAttribute::kind_copy
| ObjCPropertyAttribute::kind_retain
|
7281 ObjCPropertyAttribute::kind_strong
| ObjCPropertyAttribute::kind_weak
);
7282 if (AssignCopyRetMask
&&
7283 AssignCopyRetMask
!= ObjCPropertyAttribute::kind_assign
&&
7284 AssignCopyRetMask
!= ObjCPropertyAttribute::kind_unsafe_unretained
&&
7285 AssignCopyRetMask
!= ObjCPropertyAttribute::kind_copy
&&
7286 AssignCopyRetMask
!= ObjCPropertyAttribute::kind_retain
&&
7287 AssignCopyRetMask
!= ObjCPropertyAttribute::kind_strong
&&
7288 AssignCopyRetMask
!= ObjCPropertyAttribute::kind_weak
)
7294 void Sema::CodeCompleteObjCPropertyFlags(Scope
*S
, ObjCDeclSpec
&ODS
) {
7298 unsigned Attributes
= ODS
.getPropertyAttributes();
7300 ResultBuilder
Results(*this, CodeCompleter
->getAllocator(),
7301 CodeCompleter
->getCodeCompletionTUInfo(),
7302 CodeCompletionContext::CCC_Other
);
7303 Results
.EnterNewScope();
7304 if (!ObjCPropertyFlagConflicts(Attributes
,
7305 ObjCPropertyAttribute::kind_readonly
))
7306 Results
.AddResult(CodeCompletionResult("readonly"));
7307 if (!ObjCPropertyFlagConflicts(Attributes
,
7308 ObjCPropertyAttribute::kind_assign
))
7309 Results
.AddResult(CodeCompletionResult("assign"));
7310 if (!ObjCPropertyFlagConflicts(Attributes
,
7311 ObjCPropertyAttribute::kind_unsafe_unretained
))
7312 Results
.AddResult(CodeCompletionResult("unsafe_unretained"));
7313 if (!ObjCPropertyFlagConflicts(Attributes
,
7314 ObjCPropertyAttribute::kind_readwrite
))
7315 Results
.AddResult(CodeCompletionResult("readwrite"));
7316 if (!ObjCPropertyFlagConflicts(Attributes
,
7317 ObjCPropertyAttribute::kind_retain
))
7318 Results
.AddResult(CodeCompletionResult("retain"));
7319 if (!ObjCPropertyFlagConflicts(Attributes
,
7320 ObjCPropertyAttribute::kind_strong
))
7321 Results
.AddResult(CodeCompletionResult("strong"));
7322 if (!ObjCPropertyFlagConflicts(Attributes
, ObjCPropertyAttribute::kind_copy
))
7323 Results
.AddResult(CodeCompletionResult("copy"));
7324 if (!ObjCPropertyFlagConflicts(Attributes
,
7325 ObjCPropertyAttribute::kind_nonatomic
))
7326 Results
.AddResult(CodeCompletionResult("nonatomic"));
7327 if (!ObjCPropertyFlagConflicts(Attributes
,
7328 ObjCPropertyAttribute::kind_atomic
))
7329 Results
.AddResult(CodeCompletionResult("atomic"));
7331 // Only suggest "weak" if we're compiling for ARC-with-weak-references or GC.
7332 if (getLangOpts().ObjCWeak
|| getLangOpts().getGC() != LangOptions::NonGC
)
7333 if (!ObjCPropertyFlagConflicts(Attributes
,
7334 ObjCPropertyAttribute::kind_weak
))
7335 Results
.AddResult(CodeCompletionResult("weak"));
7337 if (!ObjCPropertyFlagConflicts(Attributes
,
7338 ObjCPropertyAttribute::kind_setter
)) {
7339 CodeCompletionBuilder
Setter(Results
.getAllocator(),
7340 Results
.getCodeCompletionTUInfo());
7341 Setter
.AddTypedTextChunk("setter");
7342 Setter
.AddTextChunk("=");
7343 Setter
.AddPlaceholderChunk("method");
7344 Results
.AddResult(CodeCompletionResult(Setter
.TakeString()));
7346 if (!ObjCPropertyFlagConflicts(Attributes
,
7347 ObjCPropertyAttribute::kind_getter
)) {
7348 CodeCompletionBuilder
Getter(Results
.getAllocator(),
7349 Results
.getCodeCompletionTUInfo());
7350 Getter
.AddTypedTextChunk("getter");
7351 Getter
.AddTextChunk("=");
7352 Getter
.AddPlaceholderChunk("method");
7353 Results
.AddResult(CodeCompletionResult(Getter
.TakeString()));
7355 if (!ObjCPropertyFlagConflicts(Attributes
,
7356 ObjCPropertyAttribute::kind_nullability
)) {
7357 Results
.AddResult(CodeCompletionResult("nonnull"));
7358 Results
.AddResult(CodeCompletionResult("nullable"));
7359 Results
.AddResult(CodeCompletionResult("null_unspecified"));
7360 Results
.AddResult(CodeCompletionResult("null_resettable"));
7362 Results
.ExitScope();
7363 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
7364 Results
.data(), Results
.size());
7367 /// Describes the kind of Objective-C method that we want to find
7368 /// via code completion.
7369 enum ObjCMethodKind
{
7370 MK_Any
, ///< Any kind of method, provided it means other specified criteria.
7371 MK_ZeroArgSelector
, ///< Zero-argument (unary) selector.
7372 MK_OneArgSelector
///< One-argument selector.
7375 static bool isAcceptableObjCSelector(Selector Sel
, ObjCMethodKind WantKind
,
7376 ArrayRef
<IdentifierInfo
*> SelIdents
,
7377 bool AllowSameLength
= true) {
7378 unsigned NumSelIdents
= SelIdents
.size();
7379 if (NumSelIdents
> Sel
.getNumArgs())
7385 case MK_ZeroArgSelector
:
7386 return Sel
.isUnarySelector();
7387 case MK_OneArgSelector
:
7388 return Sel
.getNumArgs() == 1;
7391 if (!AllowSameLength
&& NumSelIdents
&& NumSelIdents
== Sel
.getNumArgs())
7394 for (unsigned I
= 0; I
!= NumSelIdents
; ++I
)
7395 if (SelIdents
[I
] != Sel
.getIdentifierInfoForSlot(I
))
7401 static bool isAcceptableObjCMethod(ObjCMethodDecl
*Method
,
7402 ObjCMethodKind WantKind
,
7403 ArrayRef
<IdentifierInfo
*> SelIdents
,
7404 bool AllowSameLength
= true) {
7405 return isAcceptableObjCSelector(Method
->getSelector(), WantKind
, SelIdents
,
7409 /// A set of selectors, which is used to avoid introducing multiple
7410 /// completions with the same selector into the result set.
7411 typedef llvm::SmallPtrSet
<Selector
, 16> VisitedSelectorSet
;
7413 /// Add all of the Objective-C methods in the given Objective-C
7414 /// container to the set of results.
7416 /// The container will be a class, protocol, category, or implementation of
7417 /// any of the above. This mether will recurse to include methods from
7418 /// the superclasses of classes along with their categories, protocols, and
7419 /// implementations.
7421 /// \param Container the container in which we'll look to find methods.
7423 /// \param WantInstanceMethods Whether to add instance methods (only); if
7424 /// false, this routine will add factory methods (only).
7426 /// \param CurContext the context in which we're performing the lookup that
7429 /// \param AllowSameLength Whether we allow a method to be added to the list
7430 /// when it has the same number of parameters as we have selector identifiers.
7432 /// \param Results the structure into which we'll add results.
7433 static void AddObjCMethods(ObjCContainerDecl
*Container
,
7434 bool WantInstanceMethods
, ObjCMethodKind WantKind
,
7435 ArrayRef
<IdentifierInfo
*> SelIdents
,
7436 DeclContext
*CurContext
,
7437 VisitedSelectorSet
&Selectors
, bool AllowSameLength
,
7438 ResultBuilder
&Results
, bool InOriginalClass
= true,
7439 bool IsRootClass
= false) {
7440 typedef CodeCompletionResult Result
;
7441 Container
= getContainerDef(Container
);
7442 ObjCInterfaceDecl
*IFace
= dyn_cast
<ObjCInterfaceDecl
>(Container
);
7443 IsRootClass
= IsRootClass
|| (IFace
&& !IFace
->getSuperClass());
7444 for (ObjCMethodDecl
*M
: Container
->methods()) {
7445 // The instance methods on the root class can be messaged via the
7447 if (M
->isInstanceMethod() == WantInstanceMethods
||
7448 (IsRootClass
&& !WantInstanceMethods
)) {
7449 // Check whether the selector identifiers we've been given are a
7450 // subset of the identifiers for this particular method.
7451 if (!isAcceptableObjCMethod(M
, WantKind
, SelIdents
, AllowSameLength
))
7454 if (!Selectors
.insert(M
->getSelector()).second
)
7457 Result R
= Result(M
, Results
.getBasePriority(M
), nullptr);
7458 R
.StartParameter
= SelIdents
.size();
7459 R
.AllParametersAreInformative
= (WantKind
!= MK_Any
);
7460 if (!InOriginalClass
)
7462 Results
.MaybeAddResult(R
, CurContext
);
7466 // Visit the protocols of protocols.
7467 if (const auto *Protocol
= dyn_cast
<ObjCProtocolDecl
>(Container
)) {
7468 if (Protocol
->hasDefinition()) {
7469 const ObjCList
<ObjCProtocolDecl
> &Protocols
=
7470 Protocol
->getReferencedProtocols();
7471 for (ObjCList
<ObjCProtocolDecl
>::iterator I
= Protocols
.begin(),
7472 E
= Protocols
.end();
7474 AddObjCMethods(*I
, WantInstanceMethods
, WantKind
, SelIdents
, CurContext
,
7475 Selectors
, AllowSameLength
, Results
, false, IsRootClass
);
7479 if (!IFace
|| !IFace
->hasDefinition())
7482 // Add methods in protocols.
7483 for (ObjCProtocolDecl
*I
: IFace
->protocols())
7484 AddObjCMethods(I
, WantInstanceMethods
, WantKind
, SelIdents
, CurContext
,
7485 Selectors
, AllowSameLength
, Results
, false, IsRootClass
);
7487 // Add methods in categories.
7488 for (ObjCCategoryDecl
*CatDecl
: IFace
->known_categories()) {
7489 AddObjCMethods(CatDecl
, WantInstanceMethods
, WantKind
, SelIdents
,
7490 CurContext
, Selectors
, AllowSameLength
, Results
,
7491 InOriginalClass
, IsRootClass
);
7493 // Add a categories protocol methods.
7494 const ObjCList
<ObjCProtocolDecl
> &Protocols
=
7495 CatDecl
->getReferencedProtocols();
7496 for (ObjCList
<ObjCProtocolDecl
>::iterator I
= Protocols
.begin(),
7497 E
= Protocols
.end();
7499 AddObjCMethods(*I
, WantInstanceMethods
, WantKind
, SelIdents
, CurContext
,
7500 Selectors
, AllowSameLength
, Results
, false, IsRootClass
);
7502 // Add methods in category implementations.
7503 if (ObjCCategoryImplDecl
*Impl
= CatDecl
->getImplementation())
7504 AddObjCMethods(Impl
, WantInstanceMethods
, WantKind
, SelIdents
, CurContext
,
7505 Selectors
, AllowSameLength
, Results
, InOriginalClass
,
7509 // Add methods in superclass.
7510 // Avoid passing in IsRootClass since root classes won't have super classes.
7511 if (IFace
->getSuperClass())
7512 AddObjCMethods(IFace
->getSuperClass(), WantInstanceMethods
, WantKind
,
7513 SelIdents
, CurContext
, Selectors
, AllowSameLength
, Results
,
7514 /*IsRootClass=*/false);
7516 // Add methods in our implementation, if any.
7517 if (ObjCImplementationDecl
*Impl
= IFace
->getImplementation())
7518 AddObjCMethods(Impl
, WantInstanceMethods
, WantKind
, SelIdents
, CurContext
,
7519 Selectors
, AllowSameLength
, Results
, InOriginalClass
,
7523 void Sema::CodeCompleteObjCPropertyGetter(Scope
*S
) {
7524 // Try to find the interface where getters might live.
7525 ObjCInterfaceDecl
*Class
= dyn_cast_or_null
<ObjCInterfaceDecl
>(CurContext
);
7527 if (ObjCCategoryDecl
*Category
=
7528 dyn_cast_or_null
<ObjCCategoryDecl
>(CurContext
))
7529 Class
= Category
->getClassInterface();
7535 // Find all of the potential getters.
7536 ResultBuilder
Results(*this, CodeCompleter
->getAllocator(),
7537 CodeCompleter
->getCodeCompletionTUInfo(),
7538 CodeCompletionContext::CCC_Other
);
7539 Results
.EnterNewScope();
7541 VisitedSelectorSet Selectors
;
7542 AddObjCMethods(Class
, true, MK_ZeroArgSelector
, None
, CurContext
, Selectors
,
7543 /*AllowSameLength=*/true, Results
);
7544 Results
.ExitScope();
7545 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
7546 Results
.data(), Results
.size());
7549 void Sema::CodeCompleteObjCPropertySetter(Scope
*S
) {
7550 // Try to find the interface where setters might live.
7551 ObjCInterfaceDecl
*Class
= dyn_cast_or_null
<ObjCInterfaceDecl
>(CurContext
);
7553 if (ObjCCategoryDecl
*Category
=
7554 dyn_cast_or_null
<ObjCCategoryDecl
>(CurContext
))
7555 Class
= Category
->getClassInterface();
7561 // Find all of the potential getters.
7562 ResultBuilder
Results(*this, CodeCompleter
->getAllocator(),
7563 CodeCompleter
->getCodeCompletionTUInfo(),
7564 CodeCompletionContext::CCC_Other
);
7565 Results
.EnterNewScope();
7567 VisitedSelectorSet Selectors
;
7568 AddObjCMethods(Class
, true, MK_OneArgSelector
, None
, CurContext
, Selectors
,
7569 /*AllowSameLength=*/true, Results
);
7571 Results
.ExitScope();
7572 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
7573 Results
.data(), Results
.size());
7576 void Sema::CodeCompleteObjCPassingType(Scope
*S
, ObjCDeclSpec
&DS
,
7578 ResultBuilder
Results(*this, CodeCompleter
->getAllocator(),
7579 CodeCompleter
->getCodeCompletionTUInfo(),
7580 CodeCompletionContext::CCC_Type
);
7581 Results
.EnterNewScope();
7583 // Add context-sensitive, Objective-C parameter-passing keywords.
7584 bool AddedInOut
= false;
7585 if ((DS
.getObjCDeclQualifier() &
7586 (ObjCDeclSpec::DQ_In
| ObjCDeclSpec::DQ_Inout
)) == 0) {
7587 Results
.AddResult("in");
7588 Results
.AddResult("inout");
7591 if ((DS
.getObjCDeclQualifier() &
7592 (ObjCDeclSpec::DQ_Out
| ObjCDeclSpec::DQ_Inout
)) == 0) {
7593 Results
.AddResult("out");
7595 Results
.AddResult("inout");
7597 if ((DS
.getObjCDeclQualifier() &
7598 (ObjCDeclSpec::DQ_Bycopy
| ObjCDeclSpec::DQ_Byref
|
7599 ObjCDeclSpec::DQ_Oneway
)) == 0) {
7600 Results
.AddResult("bycopy");
7601 Results
.AddResult("byref");
7602 Results
.AddResult("oneway");
7604 if ((DS
.getObjCDeclQualifier() & ObjCDeclSpec::DQ_CSNullability
) == 0) {
7605 Results
.AddResult("nonnull");
7606 Results
.AddResult("nullable");
7607 Results
.AddResult("null_unspecified");
7610 // If we're completing the return type of an Objective-C method and the
7611 // identifier IBAction refers to a macro, provide a completion item for
7613 // IBAction)<#selector#>:(id)sender
7614 if (DS
.getObjCDeclQualifier() == 0 && !IsParameter
&&
7615 PP
.isMacroDefined("IBAction")) {
7616 CodeCompletionBuilder
Builder(Results
.getAllocator(),
7617 Results
.getCodeCompletionTUInfo(),
7618 CCP_CodePattern
, CXAvailability_Available
);
7619 Builder
.AddTypedTextChunk("IBAction");
7620 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
7621 Builder
.AddPlaceholderChunk("selector");
7622 Builder
.AddChunk(CodeCompletionString::CK_Colon
);
7623 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
7624 Builder
.AddTextChunk("id");
7625 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
7626 Builder
.AddTextChunk("sender");
7627 Results
.AddResult(CodeCompletionResult(Builder
.TakeString()));
7630 // If we're completing the return type, provide 'instancetype'.
7632 Results
.AddResult(CodeCompletionResult("instancetype"));
7635 // Add various builtin type names and specifiers.
7636 AddOrdinaryNameResults(PCC_Type
, S
, *this, Results
);
7637 Results
.ExitScope();
7639 // Add the various type names
7640 Results
.setFilter(&ResultBuilder::IsOrdinaryNonValueName
);
7641 CodeCompletionDeclConsumer
Consumer(Results
, CurContext
);
7642 LookupVisibleDecls(S
, LookupOrdinaryName
, Consumer
,
7643 CodeCompleter
->includeGlobals(),
7644 CodeCompleter
->loadExternal());
7646 if (CodeCompleter
->includeMacros())
7647 AddMacroResults(PP
, Results
, CodeCompleter
->loadExternal(), false);
7649 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
7650 Results
.data(), Results
.size());
7653 /// When we have an expression with type "id", we may assume
7654 /// that it has some more-specific class type based on knowledge of
7655 /// common uses of Objective-C. This routine returns that class type,
7656 /// or NULL if no better result could be determined.
7657 static ObjCInterfaceDecl
*GetAssumedMessageSendExprType(Expr
*E
) {
7658 auto *Msg
= dyn_cast_or_null
<ObjCMessageExpr
>(E
);
7662 Selector Sel
= Msg
->getSelector();
7666 IdentifierInfo
*Id
= Sel
.getIdentifierInfoForSlot(0);
7670 ObjCMethodDecl
*Method
= Msg
->getMethodDecl();
7674 // Determine the class that we're sending the message to.
7675 ObjCInterfaceDecl
*IFace
= nullptr;
7676 switch (Msg
->getReceiverKind()) {
7677 case ObjCMessageExpr::Class
:
7678 if (const ObjCObjectType
*ObjType
=
7679 Msg
->getClassReceiver()->getAs
<ObjCObjectType
>())
7680 IFace
= ObjType
->getInterface();
7683 case ObjCMessageExpr::Instance
: {
7684 QualType T
= Msg
->getInstanceReceiver()->getType();
7685 if (const ObjCObjectPointerType
*Ptr
= T
->getAs
<ObjCObjectPointerType
>())
7686 IFace
= Ptr
->getInterfaceDecl();
7690 case ObjCMessageExpr::SuperInstance
:
7691 case ObjCMessageExpr::SuperClass
:
7698 ObjCInterfaceDecl
*Super
= IFace
->getSuperClass();
7699 if (Method
->isInstanceMethod())
7700 return llvm::StringSwitch
<ObjCInterfaceDecl
*>(Id
->getName())
7701 .Case("retain", IFace
)
7702 .Case("strong", IFace
)
7703 .Case("autorelease", IFace
)
7704 .Case("copy", IFace
)
7705 .Case("copyWithZone", IFace
)
7706 .Case("mutableCopy", IFace
)
7707 .Case("mutableCopyWithZone", IFace
)
7708 .Case("awakeFromCoder", IFace
)
7709 .Case("replacementObjectFromCoder", IFace
)
7710 .Case("class", IFace
)
7711 .Case("classForCoder", IFace
)
7712 .Case("superclass", Super
)
7715 return llvm::StringSwitch
<ObjCInterfaceDecl
*>(Id
->getName())
7717 .Case("alloc", IFace
)
7718 .Case("allocWithZone", IFace
)
7719 .Case("class", IFace
)
7720 .Case("superclass", Super
)
7724 // Add a special completion for a message send to "super", which fills in the
7725 // most likely case of forwarding all of our arguments to the superclass
7728 /// \param S The semantic analysis object.
7730 /// \param NeedSuperKeyword Whether we need to prefix this completion with
7731 /// the "super" keyword. Otherwise, we just need to provide the arguments.
7733 /// \param SelIdents The identifiers in the selector that have already been
7734 /// provided as arguments for a send to "super".
7736 /// \param Results The set of results to augment.
7738 /// \returns the Objective-C method declaration that would be invoked by
7739 /// this "super" completion. If NULL, no completion was added.
7740 static ObjCMethodDecl
*
7741 AddSuperSendCompletion(Sema
&S
, bool NeedSuperKeyword
,
7742 ArrayRef
<IdentifierInfo
*> SelIdents
,
7743 ResultBuilder
&Results
) {
7744 ObjCMethodDecl
*CurMethod
= S
.getCurMethodDecl();
7748 ObjCInterfaceDecl
*Class
= CurMethod
->getClassInterface();
7752 // Try to find a superclass method with the same selector.
7753 ObjCMethodDecl
*SuperMethod
= nullptr;
7754 while ((Class
= Class
->getSuperClass()) && !SuperMethod
) {
7755 // Check in the class
7756 SuperMethod
= Class
->getMethod(CurMethod
->getSelector(),
7757 CurMethod
->isInstanceMethod());
7759 // Check in categories or class extensions.
7761 for (const auto *Cat
: Class
->known_categories()) {
7762 if ((SuperMethod
= Cat
->getMethod(CurMethod
->getSelector(),
7763 CurMethod
->isInstanceMethod())))
7772 // Check whether the superclass method has the same signature.
7773 if (CurMethod
->param_size() != SuperMethod
->param_size() ||
7774 CurMethod
->isVariadic() != SuperMethod
->isVariadic())
7777 for (ObjCMethodDecl::param_iterator CurP
= CurMethod
->param_begin(),
7778 CurPEnd
= CurMethod
->param_end(),
7779 SuperP
= SuperMethod
->param_begin();
7780 CurP
!= CurPEnd
; ++CurP
, ++SuperP
) {
7781 // Make sure the parameter types are compatible.
7782 if (!S
.Context
.hasSameUnqualifiedType((*CurP
)->getType(),
7783 (*SuperP
)->getType()))
7786 // Make sure we have a parameter name to forward!
7787 if (!(*CurP
)->getIdentifier())
7791 // We have a superclass method. Now, form the send-to-super completion.
7792 CodeCompletionBuilder
Builder(Results
.getAllocator(),
7793 Results
.getCodeCompletionTUInfo());
7795 // Give this completion a return type.
7796 AddResultTypeChunk(S
.Context
, getCompletionPrintingPolicy(S
), SuperMethod
,
7797 Results
.getCompletionContext().getBaseType(), Builder
);
7799 // If we need the "super" keyword, add it (plus some spacing).
7800 if (NeedSuperKeyword
) {
7801 Builder
.AddTypedTextChunk("super");
7802 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
7805 Selector Sel
= CurMethod
->getSelector();
7806 if (Sel
.isUnarySelector()) {
7807 if (NeedSuperKeyword
)
7808 Builder
.AddTextChunk(
7809 Builder
.getAllocator().CopyString(Sel
.getNameForSlot(0)));
7811 Builder
.AddTypedTextChunk(
7812 Builder
.getAllocator().CopyString(Sel
.getNameForSlot(0)));
7814 ObjCMethodDecl::param_iterator CurP
= CurMethod
->param_begin();
7815 for (unsigned I
= 0, N
= Sel
.getNumArgs(); I
!= N
; ++I
, ++CurP
) {
7816 if (I
> SelIdents
.size())
7817 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
7819 if (I
< SelIdents
.size())
7820 Builder
.AddInformativeChunk(
7821 Builder
.getAllocator().CopyString(Sel
.getNameForSlot(I
) + ":"));
7822 else if (NeedSuperKeyword
|| I
> SelIdents
.size()) {
7823 Builder
.AddTextChunk(
7824 Builder
.getAllocator().CopyString(Sel
.getNameForSlot(I
) + ":"));
7825 Builder
.AddPlaceholderChunk(Builder
.getAllocator().CopyString(
7826 (*CurP
)->getIdentifier()->getName()));
7828 Builder
.AddTypedTextChunk(
7829 Builder
.getAllocator().CopyString(Sel
.getNameForSlot(I
) + ":"));
7830 Builder
.AddPlaceholderChunk(Builder
.getAllocator().CopyString(
7831 (*CurP
)->getIdentifier()->getName()));
7836 Results
.AddResult(CodeCompletionResult(Builder
.TakeString(), SuperMethod
,
7837 CCP_SuperCompletion
));
7841 void Sema::CodeCompleteObjCMessageReceiver(Scope
*S
) {
7842 typedef CodeCompletionResult Result
;
7843 ResultBuilder
Results(
7844 *this, CodeCompleter
->getAllocator(),
7845 CodeCompleter
->getCodeCompletionTUInfo(),
7846 CodeCompletionContext::CCC_ObjCMessageReceiver
,
7847 getLangOpts().CPlusPlus11
7848 ? &ResultBuilder::IsObjCMessageReceiverOrLambdaCapture
7849 : &ResultBuilder::IsObjCMessageReceiver
);
7851 CodeCompletionDeclConsumer
Consumer(Results
, CurContext
);
7852 Results
.EnterNewScope();
7853 LookupVisibleDecls(S
, LookupOrdinaryName
, Consumer
,
7854 CodeCompleter
->includeGlobals(),
7855 CodeCompleter
->loadExternal());
7857 // If we are in an Objective-C method inside a class that has a superclass,
7858 // add "super" as an option.
7859 if (ObjCMethodDecl
*Method
= getCurMethodDecl())
7860 if (ObjCInterfaceDecl
*Iface
= Method
->getClassInterface())
7861 if (Iface
->getSuperClass()) {
7862 Results
.AddResult(Result("super"));
7864 AddSuperSendCompletion(*this, /*NeedSuperKeyword=*/true, None
, Results
);
7867 if (getLangOpts().CPlusPlus11
)
7868 addThisCompletion(*this, Results
);
7870 Results
.ExitScope();
7872 if (CodeCompleter
->includeMacros())
7873 AddMacroResults(PP
, Results
, CodeCompleter
->loadExternal(), false);
7874 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
7875 Results
.data(), Results
.size());
7878 void Sema::CodeCompleteObjCSuperMessage(Scope
*S
, SourceLocation SuperLoc
,
7879 ArrayRef
<IdentifierInfo
*> SelIdents
,
7880 bool AtArgumentExpression
) {
7881 ObjCInterfaceDecl
*CDecl
= nullptr;
7882 if (ObjCMethodDecl
*CurMethod
= getCurMethodDecl()) {
7883 // Figure out which interface we're in.
7884 CDecl
= CurMethod
->getClassInterface();
7888 // Find the superclass of this class.
7889 CDecl
= CDecl
->getSuperClass();
7893 if (CurMethod
->isInstanceMethod()) {
7894 // We are inside an instance method, which means that the message
7895 // send [super ...] is actually calling an instance method on the
7897 return CodeCompleteObjCInstanceMessage(S
, nullptr, SelIdents
,
7898 AtArgumentExpression
, CDecl
);
7901 // Fall through to send to the superclass in CDecl.
7903 // "super" may be the name of a type or variable. Figure out which
7905 IdentifierInfo
*Super
= getSuperIdentifier();
7906 NamedDecl
*ND
= LookupSingleName(S
, Super
, SuperLoc
, LookupOrdinaryName
);
7907 if ((CDecl
= dyn_cast_or_null
<ObjCInterfaceDecl
>(ND
))) {
7908 // "super" names an interface. Use it.
7909 } else if (TypeDecl
*TD
= dyn_cast_or_null
<TypeDecl
>(ND
)) {
7910 if (const ObjCObjectType
*Iface
=
7911 Context
.getTypeDeclType(TD
)->getAs
<ObjCObjectType
>())
7912 CDecl
= Iface
->getInterface();
7913 } else if (ND
&& isa
<UnresolvedUsingTypenameDecl
>(ND
)) {
7914 // "super" names an unresolved type; we can't be more specific.
7916 // Assume that "super" names some kind of value and parse that way.
7918 SourceLocation TemplateKWLoc
;
7920 id
.setIdentifier(Super
, SuperLoc
);
7921 ExprResult SuperExpr
= ActOnIdExpression(S
, SS
, TemplateKWLoc
, id
,
7922 /*HasTrailingLParen=*/false,
7923 /*IsAddressOfOperand=*/false);
7924 return CodeCompleteObjCInstanceMessage(S
, (Expr
*)SuperExpr
.get(),
7925 SelIdents
, AtArgumentExpression
);
7931 ParsedType Receiver
;
7933 Receiver
= ParsedType::make(Context
.getObjCInterfaceType(CDecl
));
7934 return CodeCompleteObjCClassMessage(S
, Receiver
, SelIdents
,
7935 AtArgumentExpression
,
7939 /// Given a set of code-completion results for the argument of a message
7940 /// send, determine the preferred type (if any) for that argument expression.
7941 static QualType
getPreferredArgumentTypeForMessageSend(ResultBuilder
&Results
,
7942 unsigned NumSelIdents
) {
7943 typedef CodeCompletionResult Result
;
7944 ASTContext
&Context
= Results
.getSema().Context
;
7946 QualType PreferredType
;
7947 unsigned BestPriority
= CCP_Unlikely
* 2;
7948 Result
*ResultsData
= Results
.data();
7949 for (unsigned I
= 0, N
= Results
.size(); I
!= N
; ++I
) {
7950 Result
&R
= ResultsData
[I
];
7951 if (R
.Kind
== Result::RK_Declaration
&&
7952 isa
<ObjCMethodDecl
>(R
.Declaration
)) {
7953 if (R
.Priority
<= BestPriority
) {
7954 const ObjCMethodDecl
*Method
= cast
<ObjCMethodDecl
>(R
.Declaration
);
7955 if (NumSelIdents
<= Method
->param_size()) {
7956 QualType MyPreferredType
=
7957 Method
->parameters()[NumSelIdents
- 1]->getType();
7958 if (R
.Priority
< BestPriority
|| PreferredType
.isNull()) {
7959 BestPriority
= R
.Priority
;
7960 PreferredType
= MyPreferredType
;
7961 } else if (!Context
.hasSameUnqualifiedType(PreferredType
,
7963 PreferredType
= QualType();
7970 return PreferredType
;
7973 static void AddClassMessageCompletions(Sema
&SemaRef
, Scope
*S
,
7974 ParsedType Receiver
,
7975 ArrayRef
<IdentifierInfo
*> SelIdents
,
7976 bool AtArgumentExpression
, bool IsSuper
,
7977 ResultBuilder
&Results
) {
7978 typedef CodeCompletionResult Result
;
7979 ObjCInterfaceDecl
*CDecl
= nullptr;
7981 // If the given name refers to an interface type, retrieve the
7982 // corresponding declaration.
7984 QualType T
= SemaRef
.GetTypeFromParser(Receiver
, nullptr);
7986 if (const ObjCObjectType
*Interface
= T
->getAs
<ObjCObjectType
>())
7987 CDecl
= Interface
->getInterface();
7990 // Add all of the factory methods in this Objective-C class, its protocols,
7991 // superclasses, categories, implementation, etc.
7992 Results
.EnterNewScope();
7994 // If this is a send-to-super, try to add the special "super" send
7997 if (ObjCMethodDecl
*SuperMethod
=
7998 AddSuperSendCompletion(SemaRef
, false, SelIdents
, Results
))
7999 Results
.Ignore(SuperMethod
);
8002 // If we're inside an Objective-C method definition, prefer its selector to
8004 if (ObjCMethodDecl
*CurMethod
= SemaRef
.getCurMethodDecl())
8005 Results
.setPreferredSelector(CurMethod
->getSelector());
8007 VisitedSelectorSet Selectors
;
8009 AddObjCMethods(CDecl
, false, MK_Any
, SelIdents
, SemaRef
.CurContext
,
8010 Selectors
, AtArgumentExpression
, Results
);
8012 // We're messaging "id" as a type; provide all class/factory methods.
8014 // If we have an external source, load the entire class method
8015 // pool from the AST file.
8016 if (SemaRef
.getExternalSource()) {
8017 for (uint32_t I
= 0,
8018 N
= SemaRef
.getExternalSource()->GetNumExternalSelectors();
8020 Selector Sel
= SemaRef
.getExternalSource()->GetExternalSelector(I
);
8021 if (Sel
.isNull() || SemaRef
.MethodPool
.count(Sel
))
8024 SemaRef
.ReadMethodPool(Sel
);
8028 for (Sema::GlobalMethodPool::iterator M
= SemaRef
.MethodPool
.begin(),
8029 MEnd
= SemaRef
.MethodPool
.end();
8031 for (ObjCMethodList
*MethList
= &M
->second
.second
;
8032 MethList
&& MethList
->getMethod(); MethList
= MethList
->getNext()) {
8033 if (!isAcceptableObjCMethod(MethList
->getMethod(), MK_Any
, SelIdents
))
8036 Result
R(MethList
->getMethod(),
8037 Results
.getBasePriority(MethList
->getMethod()), nullptr);
8038 R
.StartParameter
= SelIdents
.size();
8039 R
.AllParametersAreInformative
= false;
8040 Results
.MaybeAddResult(R
, SemaRef
.CurContext
);
8045 Results
.ExitScope();
8048 void Sema::CodeCompleteObjCClassMessage(Scope
*S
, ParsedType Receiver
,
8049 ArrayRef
<IdentifierInfo
*> SelIdents
,
8050 bool AtArgumentExpression
,
8053 QualType T
= this->GetTypeFromParser(Receiver
);
8055 ResultBuilder
Results(
8056 *this, CodeCompleter
->getAllocator(),
8057 CodeCompleter
->getCodeCompletionTUInfo(),
8058 CodeCompletionContext(CodeCompletionContext::CCC_ObjCClassMessage
, T
,
8061 AddClassMessageCompletions(*this, S
, Receiver
, SelIdents
,
8062 AtArgumentExpression
, IsSuper
, Results
);
8064 // If we're actually at the argument expression (rather than prior to the
8065 // selector), we're actually performing code completion for an expression.
8066 // Determine whether we have a single, best method. If so, we can
8067 // code-complete the expression using the corresponding parameter type as
8068 // our preferred type, improving completion results.
8069 if (AtArgumentExpression
) {
8070 QualType PreferredType
=
8071 getPreferredArgumentTypeForMessageSend(Results
, SelIdents
.size());
8072 if (PreferredType
.isNull())
8073 CodeCompleteOrdinaryName(S
, PCC_Expression
);
8075 CodeCompleteExpression(S
, PreferredType
);
8079 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
8080 Results
.data(), Results
.size());
8083 void Sema::CodeCompleteObjCInstanceMessage(Scope
*S
, Expr
*Receiver
,
8084 ArrayRef
<IdentifierInfo
*> SelIdents
,
8085 bool AtArgumentExpression
,
8086 ObjCInterfaceDecl
*Super
) {
8087 typedef CodeCompletionResult Result
;
8089 Expr
*RecExpr
= static_cast<Expr
*>(Receiver
);
8091 // If necessary, apply function/array conversion to the receiver.
8092 // C99 6.7.5.3p[7,8].
8094 ExprResult Conv
= DefaultFunctionArrayLvalueConversion(RecExpr
);
8095 if (Conv
.isInvalid()) // conversion failed. bail.
8097 RecExpr
= Conv
.get();
8099 QualType ReceiverType
= RecExpr
8100 ? RecExpr
->getType()
8101 : Super
? Context
.getObjCObjectPointerType(
8102 Context
.getObjCInterfaceType(Super
))
8103 : Context
.getObjCIdType();
8105 // If we're messaging an expression with type "id" or "Class", check
8106 // whether we know something special about the receiver that allows
8107 // us to assume a more-specific receiver type.
8108 if (ReceiverType
->isObjCIdType() || ReceiverType
->isObjCClassType()) {
8109 if (ObjCInterfaceDecl
*IFace
= GetAssumedMessageSendExprType(RecExpr
)) {
8110 if (ReceiverType
->isObjCClassType())
8111 return CodeCompleteObjCClassMessage(
8112 S
, ParsedType::make(Context
.getObjCInterfaceType(IFace
)), SelIdents
,
8113 AtArgumentExpression
, Super
);
8116 Context
.getObjCObjectPointerType(Context
.getObjCInterfaceType(IFace
));
8118 } else if (RecExpr
&& getLangOpts().CPlusPlus
) {
8119 ExprResult Conv
= PerformContextuallyConvertToObjCPointer(RecExpr
);
8120 if (Conv
.isUsable()) {
8121 RecExpr
= Conv
.get();
8122 ReceiverType
= RecExpr
->getType();
8126 // Build the set of methods we can see.
8127 ResultBuilder
Results(
8128 *this, CodeCompleter
->getAllocator(),
8129 CodeCompleter
->getCodeCompletionTUInfo(),
8130 CodeCompletionContext(CodeCompletionContext::CCC_ObjCInstanceMessage
,
8131 ReceiverType
, SelIdents
));
8133 Results
.EnterNewScope();
8135 // If this is a send-to-super, try to add the special "super" send
8138 if (ObjCMethodDecl
*SuperMethod
=
8139 AddSuperSendCompletion(*this, false, SelIdents
, Results
))
8140 Results
.Ignore(SuperMethod
);
8143 // If we're inside an Objective-C method definition, prefer its selector to
8145 if (ObjCMethodDecl
*CurMethod
= getCurMethodDecl())
8146 Results
.setPreferredSelector(CurMethod
->getSelector());
8148 // Keep track of the selectors we've already added.
8149 VisitedSelectorSet Selectors
;
8151 // Handle messages to Class. This really isn't a message to an instance
8152 // method, so we treat it the same way we would treat a message send to a
8154 if (ReceiverType
->isObjCClassType() ||
8155 ReceiverType
->isObjCQualifiedClassType()) {
8156 if (ObjCMethodDecl
*CurMethod
= getCurMethodDecl()) {
8157 if (ObjCInterfaceDecl
*ClassDecl
= CurMethod
->getClassInterface())
8158 AddObjCMethods(ClassDecl
, false, MK_Any
, SelIdents
, CurContext
,
8159 Selectors
, AtArgumentExpression
, Results
);
8162 // Handle messages to a qualified ID ("id<foo>").
8163 else if (const ObjCObjectPointerType
*QualID
=
8164 ReceiverType
->getAsObjCQualifiedIdType()) {
8165 // Search protocols for instance methods.
8166 for (auto *I
: QualID
->quals())
8167 AddObjCMethods(I
, true, MK_Any
, SelIdents
, CurContext
, Selectors
,
8168 AtArgumentExpression
, Results
);
8170 // Handle messages to a pointer to interface type.
8171 else if (const ObjCObjectPointerType
*IFacePtr
=
8172 ReceiverType
->getAsObjCInterfacePointerType()) {
8173 // Search the class, its superclasses, etc., for instance methods.
8174 AddObjCMethods(IFacePtr
->getInterfaceDecl(), true, MK_Any
, SelIdents
,
8175 CurContext
, Selectors
, AtArgumentExpression
, Results
);
8177 // Search protocols for instance methods.
8178 for (auto *I
: IFacePtr
->quals())
8179 AddObjCMethods(I
, true, MK_Any
, SelIdents
, CurContext
, Selectors
,
8180 AtArgumentExpression
, Results
);
8182 // Handle messages to "id".
8183 else if (ReceiverType
->isObjCIdType()) {
8184 // We're messaging "id", so provide all instance methods we know
8185 // about as code-completion results.
8187 // If we have an external source, load the entire class method
8188 // pool from the AST file.
8189 if (ExternalSource
) {
8190 for (uint32_t I
= 0, N
= ExternalSource
->GetNumExternalSelectors();
8192 Selector Sel
= ExternalSource
->GetExternalSelector(I
);
8193 if (Sel
.isNull() || MethodPool
.count(Sel
))
8196 ReadMethodPool(Sel
);
8200 for (GlobalMethodPool::iterator M
= MethodPool
.begin(),
8201 MEnd
= MethodPool
.end();
8203 for (ObjCMethodList
*MethList
= &M
->second
.first
;
8204 MethList
&& MethList
->getMethod(); MethList
= MethList
->getNext()) {
8205 if (!isAcceptableObjCMethod(MethList
->getMethod(), MK_Any
, SelIdents
))
8208 if (!Selectors
.insert(MethList
->getMethod()->getSelector()).second
)
8211 Result
R(MethList
->getMethod(),
8212 Results
.getBasePriority(MethList
->getMethod()), nullptr);
8213 R
.StartParameter
= SelIdents
.size();
8214 R
.AllParametersAreInformative
= false;
8215 Results
.MaybeAddResult(R
, CurContext
);
8219 Results
.ExitScope();
8221 // If we're actually at the argument expression (rather than prior to the
8222 // selector), we're actually performing code completion for an expression.
8223 // Determine whether we have a single, best method. If so, we can
8224 // code-complete the expression using the corresponding parameter type as
8225 // our preferred type, improving completion results.
8226 if (AtArgumentExpression
) {
8227 QualType PreferredType
=
8228 getPreferredArgumentTypeForMessageSend(Results
, SelIdents
.size());
8229 if (PreferredType
.isNull())
8230 CodeCompleteOrdinaryName(S
, PCC_Expression
);
8232 CodeCompleteExpression(S
, PreferredType
);
8236 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
8237 Results
.data(), Results
.size());
8240 void Sema::CodeCompleteObjCForCollection(Scope
*S
,
8241 DeclGroupPtrTy IterationVar
) {
8242 CodeCompleteExpressionData Data
;
8243 Data
.ObjCCollection
= true;
8245 if (IterationVar
.getAsOpaquePtr()) {
8246 DeclGroupRef DG
= IterationVar
.get();
8247 for (DeclGroupRef::iterator I
= DG
.begin(), End
= DG
.end(); I
!= End
; ++I
) {
8249 Data
.IgnoreDecls
.push_back(*I
);
8253 CodeCompleteExpression(S
, Data
);
8256 void Sema::CodeCompleteObjCSelector(Scope
*S
,
8257 ArrayRef
<IdentifierInfo
*> SelIdents
) {
8258 // If we have an external source, load the entire class method
8259 // pool from the AST file.
8260 if (ExternalSource
) {
8261 for (uint32_t I
= 0, N
= ExternalSource
->GetNumExternalSelectors(); I
!= N
;
8263 Selector Sel
= ExternalSource
->GetExternalSelector(I
);
8264 if (Sel
.isNull() || MethodPool
.count(Sel
))
8267 ReadMethodPool(Sel
);
8271 ResultBuilder
Results(*this, CodeCompleter
->getAllocator(),
8272 CodeCompleter
->getCodeCompletionTUInfo(),
8273 CodeCompletionContext::CCC_SelectorName
);
8274 Results
.EnterNewScope();
8275 for (GlobalMethodPool::iterator M
= MethodPool
.begin(),
8276 MEnd
= MethodPool
.end();
8279 Selector Sel
= M
->first
;
8280 if (!isAcceptableObjCSelector(Sel
, MK_Any
, SelIdents
))
8283 CodeCompletionBuilder
Builder(Results
.getAllocator(),
8284 Results
.getCodeCompletionTUInfo());
8285 if (Sel
.isUnarySelector()) {
8286 Builder
.AddTypedTextChunk(
8287 Builder
.getAllocator().CopyString(Sel
.getNameForSlot(0)));
8288 Results
.AddResult(Builder
.TakeString());
8292 std::string Accumulator
;
8293 for (unsigned I
= 0, N
= Sel
.getNumArgs(); I
!= N
; ++I
) {
8294 if (I
== SelIdents
.size()) {
8295 if (!Accumulator
.empty()) {
8296 Builder
.AddInformativeChunk(
8297 Builder
.getAllocator().CopyString(Accumulator
));
8298 Accumulator
.clear();
8302 Accumulator
+= Sel
.getNameForSlot(I
);
8305 Builder
.AddTypedTextChunk(Builder
.getAllocator().CopyString(Accumulator
));
8306 Results
.AddResult(Builder
.TakeString());
8308 Results
.ExitScope();
8310 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
8311 Results
.data(), Results
.size());
8314 /// Add all of the protocol declarations that we find in the given
8315 /// (translation unit) context.
8316 static void AddProtocolResults(DeclContext
*Ctx
, DeclContext
*CurContext
,
8317 bool OnlyForwardDeclarations
,
8318 ResultBuilder
&Results
) {
8319 typedef CodeCompletionResult Result
;
8321 for (const auto *D
: Ctx
->decls()) {
8322 // Record any protocols we find.
8323 if (const auto *Proto
= dyn_cast
<ObjCProtocolDecl
>(D
))
8324 if (!OnlyForwardDeclarations
|| !Proto
->hasDefinition())
8326 Result(Proto
, Results
.getBasePriority(Proto
), nullptr), CurContext
,
8331 void Sema::CodeCompleteObjCProtocolReferences(
8332 ArrayRef
<IdentifierLocPair
> Protocols
) {
8333 ResultBuilder
Results(*this, CodeCompleter
->getAllocator(),
8334 CodeCompleter
->getCodeCompletionTUInfo(),
8335 CodeCompletionContext::CCC_ObjCProtocolName
);
8337 if (CodeCompleter
->includeGlobals()) {
8338 Results
.EnterNewScope();
8340 // Tell the result set to ignore all of the protocols we have
8342 // FIXME: This doesn't work when caching code-completion results.
8343 for (const IdentifierLocPair
&Pair
: Protocols
)
8344 if (ObjCProtocolDecl
*Protocol
= LookupProtocol(Pair
.first
, Pair
.second
))
8345 Results
.Ignore(Protocol
);
8347 // Add all protocols.
8348 AddProtocolResults(Context
.getTranslationUnitDecl(), CurContext
, false,
8351 Results
.ExitScope();
8354 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
8355 Results
.data(), Results
.size());
8358 void Sema::CodeCompleteObjCProtocolDecl(Scope
*) {
8359 ResultBuilder
Results(*this, CodeCompleter
->getAllocator(),
8360 CodeCompleter
->getCodeCompletionTUInfo(),
8361 CodeCompletionContext::CCC_ObjCProtocolName
);
8363 if (CodeCompleter
->includeGlobals()) {
8364 Results
.EnterNewScope();
8366 // Add all protocols.
8367 AddProtocolResults(Context
.getTranslationUnitDecl(), CurContext
, true,
8370 Results
.ExitScope();
8373 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
8374 Results
.data(), Results
.size());
8377 /// Add all of the Objective-C interface declarations that we find in
8378 /// the given (translation unit) context.
8379 static void AddInterfaceResults(DeclContext
*Ctx
, DeclContext
*CurContext
,
8380 bool OnlyForwardDeclarations
,
8381 bool OnlyUnimplemented
,
8382 ResultBuilder
&Results
) {
8383 typedef CodeCompletionResult Result
;
8385 for (const auto *D
: Ctx
->decls()) {
8386 // Record any interfaces we find.
8387 if (const auto *Class
= dyn_cast
<ObjCInterfaceDecl
>(D
))
8388 if ((!OnlyForwardDeclarations
|| !Class
->hasDefinition()) &&
8389 (!OnlyUnimplemented
|| !Class
->getImplementation()))
8391 Result(Class
, Results
.getBasePriority(Class
), nullptr), CurContext
,
8396 void Sema::CodeCompleteObjCInterfaceDecl(Scope
*S
) {
8397 ResultBuilder
Results(*this, CodeCompleter
->getAllocator(),
8398 CodeCompleter
->getCodeCompletionTUInfo(),
8399 CodeCompletionContext::CCC_ObjCInterfaceName
);
8400 Results
.EnterNewScope();
8402 if (CodeCompleter
->includeGlobals()) {
8404 AddInterfaceResults(Context
.getTranslationUnitDecl(), CurContext
, false,
8408 Results
.ExitScope();
8410 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
8411 Results
.data(), Results
.size());
8414 void Sema::CodeCompleteObjCSuperclass(Scope
*S
, IdentifierInfo
*ClassName
,
8415 SourceLocation ClassNameLoc
) {
8416 ResultBuilder
Results(*this, CodeCompleter
->getAllocator(),
8417 CodeCompleter
->getCodeCompletionTUInfo(),
8418 CodeCompletionContext::CCC_ObjCInterfaceName
);
8419 Results
.EnterNewScope();
8421 // Make sure that we ignore the class we're currently defining.
8422 NamedDecl
*CurClass
=
8423 LookupSingleName(TUScope
, ClassName
, ClassNameLoc
, LookupOrdinaryName
);
8424 if (CurClass
&& isa
<ObjCInterfaceDecl
>(CurClass
))
8425 Results
.Ignore(CurClass
);
8427 if (CodeCompleter
->includeGlobals()) {
8429 AddInterfaceResults(Context
.getTranslationUnitDecl(), CurContext
, false,
8433 Results
.ExitScope();
8435 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
8436 Results
.data(), Results
.size());
8439 void Sema::CodeCompleteObjCImplementationDecl(Scope
*S
) {
8440 ResultBuilder
Results(*this, CodeCompleter
->getAllocator(),
8441 CodeCompleter
->getCodeCompletionTUInfo(),
8442 CodeCompletionContext::CCC_ObjCImplementation
);
8443 Results
.EnterNewScope();
8445 if (CodeCompleter
->includeGlobals()) {
8446 // Add all unimplemented classes.
8447 AddInterfaceResults(Context
.getTranslationUnitDecl(), CurContext
, false,
8451 Results
.ExitScope();
8453 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
8454 Results
.data(), Results
.size());
8457 void Sema::CodeCompleteObjCInterfaceCategory(Scope
*S
,
8458 IdentifierInfo
*ClassName
,
8459 SourceLocation ClassNameLoc
) {
8460 typedef CodeCompletionResult Result
;
8462 ResultBuilder
Results(*this, CodeCompleter
->getAllocator(),
8463 CodeCompleter
->getCodeCompletionTUInfo(),
8464 CodeCompletionContext::CCC_ObjCCategoryName
);
8466 // Ignore any categories we find that have already been implemented by this
8468 llvm::SmallPtrSet
<IdentifierInfo
*, 16> CategoryNames
;
8469 NamedDecl
*CurClass
=
8470 LookupSingleName(TUScope
, ClassName
, ClassNameLoc
, LookupOrdinaryName
);
8471 if (ObjCInterfaceDecl
*Class
=
8472 dyn_cast_or_null
<ObjCInterfaceDecl
>(CurClass
)) {
8473 for (const auto *Cat
: Class
->visible_categories())
8474 CategoryNames
.insert(Cat
->getIdentifier());
8477 // Add all of the categories we know about.
8478 Results
.EnterNewScope();
8479 TranslationUnitDecl
*TU
= Context
.getTranslationUnitDecl();
8480 for (const auto *D
: TU
->decls())
8481 if (const auto *Category
= dyn_cast
<ObjCCategoryDecl
>(D
))
8482 if (CategoryNames
.insert(Category
->getIdentifier()).second
)
8484 Result(Category
, Results
.getBasePriority(Category
), nullptr),
8485 CurContext
, nullptr, false);
8486 Results
.ExitScope();
8488 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
8489 Results
.data(), Results
.size());
8492 void Sema::CodeCompleteObjCImplementationCategory(Scope
*S
,
8493 IdentifierInfo
*ClassName
,
8494 SourceLocation ClassNameLoc
) {
8495 typedef CodeCompletionResult Result
;
8497 // Find the corresponding interface. If we couldn't find the interface, the
8498 // program itself is ill-formed. However, we'll try to be helpful still by
8499 // providing the list of all of the categories we know about.
8500 NamedDecl
*CurClass
=
8501 LookupSingleName(TUScope
, ClassName
, ClassNameLoc
, LookupOrdinaryName
);
8502 ObjCInterfaceDecl
*Class
= dyn_cast_or_null
<ObjCInterfaceDecl
>(CurClass
);
8504 return CodeCompleteObjCInterfaceCategory(S
, ClassName
, ClassNameLoc
);
8506 ResultBuilder
Results(*this, CodeCompleter
->getAllocator(),
8507 CodeCompleter
->getCodeCompletionTUInfo(),
8508 CodeCompletionContext::CCC_ObjCCategoryName
);
8510 // Add all of the categories that have have corresponding interface
8511 // declarations in this class and any of its superclasses, except for
8512 // already-implemented categories in the class itself.
8513 llvm::SmallPtrSet
<IdentifierInfo
*, 16> CategoryNames
;
8514 Results
.EnterNewScope();
8515 bool IgnoreImplemented
= true;
8517 for (const auto *Cat
: Class
->visible_categories()) {
8518 if ((!IgnoreImplemented
|| !Cat
->getImplementation()) &&
8519 CategoryNames
.insert(Cat
->getIdentifier()).second
)
8520 Results
.AddResult(Result(Cat
, Results
.getBasePriority(Cat
), nullptr),
8521 CurContext
, nullptr, false);
8524 Class
= Class
->getSuperClass();
8525 IgnoreImplemented
= false;
8527 Results
.ExitScope();
8529 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
8530 Results
.data(), Results
.size());
8533 void Sema::CodeCompleteObjCPropertyDefinition(Scope
*S
) {
8534 CodeCompletionContext
CCContext(CodeCompletionContext::CCC_Other
);
8535 ResultBuilder
Results(*this, CodeCompleter
->getAllocator(),
8536 CodeCompleter
->getCodeCompletionTUInfo(), CCContext
);
8538 // Figure out where this @synthesize lives.
8539 ObjCContainerDecl
*Container
=
8540 dyn_cast_or_null
<ObjCContainerDecl
>(CurContext
);
8541 if (!Container
|| (!isa
<ObjCImplementationDecl
>(Container
) &&
8542 !isa
<ObjCCategoryImplDecl
>(Container
)))
8545 // Ignore any properties that have already been implemented.
8546 Container
= getContainerDef(Container
);
8547 for (const auto *D
: Container
->decls())
8548 if (const auto *PropertyImpl
= dyn_cast
<ObjCPropertyImplDecl
>(D
))
8549 Results
.Ignore(PropertyImpl
->getPropertyDecl());
8551 // Add any properties that we find.
8552 AddedPropertiesSet AddedProperties
;
8553 Results
.EnterNewScope();
8554 if (ObjCImplementationDecl
*ClassImpl
=
8555 dyn_cast
<ObjCImplementationDecl
>(Container
))
8556 AddObjCProperties(CCContext
, ClassImpl
->getClassInterface(), false,
8557 /*AllowNullaryMethods=*/false, CurContext
,
8558 AddedProperties
, Results
);
8560 AddObjCProperties(CCContext
,
8561 cast
<ObjCCategoryImplDecl
>(Container
)->getCategoryDecl(),
8562 false, /*AllowNullaryMethods=*/false, CurContext
,
8563 AddedProperties
, Results
);
8564 Results
.ExitScope();
8566 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
8567 Results
.data(), Results
.size());
8570 void Sema::CodeCompleteObjCPropertySynthesizeIvar(
8571 Scope
*S
, IdentifierInfo
*PropertyName
) {
8572 typedef CodeCompletionResult Result
;
8573 ResultBuilder
Results(*this, CodeCompleter
->getAllocator(),
8574 CodeCompleter
->getCodeCompletionTUInfo(),
8575 CodeCompletionContext::CCC_Other
);
8577 // Figure out where this @synthesize lives.
8578 ObjCContainerDecl
*Container
=
8579 dyn_cast_or_null
<ObjCContainerDecl
>(CurContext
);
8580 if (!Container
|| (!isa
<ObjCImplementationDecl
>(Container
) &&
8581 !isa
<ObjCCategoryImplDecl
>(Container
)))
8584 // Figure out which interface we're looking into.
8585 ObjCInterfaceDecl
*Class
= nullptr;
8586 if (ObjCImplementationDecl
*ClassImpl
=
8587 dyn_cast
<ObjCImplementationDecl
>(Container
))
8588 Class
= ClassImpl
->getClassInterface();
8590 Class
= cast
<ObjCCategoryImplDecl
>(Container
)
8592 ->getClassInterface();
8594 // Determine the type of the property we're synthesizing.
8595 QualType PropertyType
= Context
.getObjCIdType();
8597 if (ObjCPropertyDecl
*Property
= Class
->FindPropertyDeclaration(
8598 PropertyName
, ObjCPropertyQueryKind::OBJC_PR_query_instance
)) {
8600 Property
->getType().getNonReferenceType().getUnqualifiedType();
8602 // Give preference to ivars
8603 Results
.setPreferredType(PropertyType
);
8607 // Add all of the instance variables in this class and its superclasses.
8608 Results
.EnterNewScope();
8609 bool SawSimilarlyNamedIvar
= false;
8610 std::string NameWithPrefix
;
8611 NameWithPrefix
+= '_';
8612 NameWithPrefix
+= PropertyName
->getName();
8613 std::string NameWithSuffix
= PropertyName
->getName().str();
8614 NameWithSuffix
+= '_';
8615 for (; Class
; Class
= Class
->getSuperClass()) {
8616 for (ObjCIvarDecl
*Ivar
= Class
->all_declared_ivar_begin(); Ivar
;
8617 Ivar
= Ivar
->getNextIvar()) {
8618 Results
.AddResult(Result(Ivar
, Results
.getBasePriority(Ivar
), nullptr),
8619 CurContext
, nullptr, false);
8621 // Determine whether we've seen an ivar with a name similar to the
8623 if ((PropertyName
== Ivar
->getIdentifier() ||
8624 NameWithPrefix
== Ivar
->getName() ||
8625 NameWithSuffix
== Ivar
->getName())) {
8626 SawSimilarlyNamedIvar
= true;
8628 // Reduce the priority of this result by one, to give it a slight
8629 // advantage over other results whose names don't match so closely.
8630 if (Results
.size() &&
8631 Results
.data()[Results
.size() - 1].Kind
==
8632 CodeCompletionResult::RK_Declaration
&&
8633 Results
.data()[Results
.size() - 1].Declaration
== Ivar
)
8634 Results
.data()[Results
.size() - 1].Priority
--;
8639 if (!SawSimilarlyNamedIvar
) {
8640 // Create ivar result _propName, that the user can use to synthesize
8641 // an ivar of the appropriate type.
8642 unsigned Priority
= CCP_MemberDeclaration
+ 1;
8643 typedef CodeCompletionResult Result
;
8644 CodeCompletionAllocator
&Allocator
= Results
.getAllocator();
8645 CodeCompletionBuilder
Builder(Allocator
, Results
.getCodeCompletionTUInfo(),
8646 Priority
, CXAvailability_Available
);
8648 PrintingPolicy Policy
= getCompletionPrintingPolicy(*this);
8649 Builder
.AddResultTypeChunk(
8650 GetCompletionTypeString(PropertyType
, Context
, Policy
, Allocator
));
8651 Builder
.AddTypedTextChunk(Allocator
.CopyString(NameWithPrefix
));
8653 Result(Builder
.TakeString(), Priority
, CXCursor_ObjCIvarDecl
));
8656 Results
.ExitScope();
8658 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
8659 Results
.data(), Results
.size());
8662 // Mapping from selectors to the methods that implement that selector, along
8663 // with the "in original class" flag.
8664 typedef llvm::DenseMap
<Selector
,
8665 llvm::PointerIntPair
<ObjCMethodDecl
*, 1, bool>>
8668 /// Find all of the methods that reside in the given container
8669 /// (and its superclasses, protocols, etc.) that meet the given
8670 /// criteria. Insert those methods into the map of known methods,
8671 /// indexed by selector so they can be easily found.
8672 static void FindImplementableMethods(ASTContext
&Context
,
8673 ObjCContainerDecl
*Container
,
8674 Optional
<bool> WantInstanceMethods
,
8675 QualType ReturnType
,
8676 KnownMethodsMap
&KnownMethods
,
8677 bool InOriginalClass
= true) {
8678 if (ObjCInterfaceDecl
*IFace
= dyn_cast
<ObjCInterfaceDecl
>(Container
)) {
8679 // Make sure we have a definition; that's what we'll walk.
8680 if (!IFace
->hasDefinition())
8683 IFace
= IFace
->getDefinition();
8686 const ObjCList
<ObjCProtocolDecl
> &Protocols
=
8687 IFace
->getReferencedProtocols();
8688 for (ObjCList
<ObjCProtocolDecl
>::iterator I
= Protocols
.begin(),
8689 E
= Protocols
.end();
8691 FindImplementableMethods(Context
, *I
, WantInstanceMethods
, ReturnType
,
8692 KnownMethods
, InOriginalClass
);
8694 // Add methods from any class extensions and categories.
8695 for (auto *Cat
: IFace
->visible_categories()) {
8696 FindImplementableMethods(Context
, Cat
, WantInstanceMethods
, ReturnType
,
8697 KnownMethods
, false);
8700 // Visit the superclass.
8701 if (IFace
->getSuperClass())
8702 FindImplementableMethods(Context
, IFace
->getSuperClass(),
8703 WantInstanceMethods
, ReturnType
, KnownMethods
,
8707 if (ObjCCategoryDecl
*Category
= dyn_cast
<ObjCCategoryDecl
>(Container
)) {
8708 // Recurse into protocols.
8709 const ObjCList
<ObjCProtocolDecl
> &Protocols
=
8710 Category
->getReferencedProtocols();
8711 for (ObjCList
<ObjCProtocolDecl
>::iterator I
= Protocols
.begin(),
8712 E
= Protocols
.end();
8714 FindImplementableMethods(Context
, *I
, WantInstanceMethods
, ReturnType
,
8715 KnownMethods
, InOriginalClass
);
8717 // If this category is the original class, jump to the interface.
8718 if (InOriginalClass
&& Category
->getClassInterface())
8719 FindImplementableMethods(Context
, Category
->getClassInterface(),
8720 WantInstanceMethods
, ReturnType
, KnownMethods
,
8724 if (ObjCProtocolDecl
*Protocol
= dyn_cast
<ObjCProtocolDecl
>(Container
)) {
8725 // Make sure we have a definition; that's what we'll walk.
8726 if (!Protocol
->hasDefinition())
8728 Protocol
= Protocol
->getDefinition();
8729 Container
= Protocol
;
8731 // Recurse into protocols.
8732 const ObjCList
<ObjCProtocolDecl
> &Protocols
=
8733 Protocol
->getReferencedProtocols();
8734 for (ObjCList
<ObjCProtocolDecl
>::iterator I
= Protocols
.begin(),
8735 E
= Protocols
.end();
8737 FindImplementableMethods(Context
, *I
, WantInstanceMethods
, ReturnType
,
8738 KnownMethods
, false);
8741 // Add methods in this container. This operation occurs last because
8742 // we want the methods from this container to override any methods
8743 // we've previously seen with the same selector.
8744 for (auto *M
: Container
->methods()) {
8745 if (!WantInstanceMethods
|| M
->isInstanceMethod() == *WantInstanceMethods
) {
8746 if (!ReturnType
.isNull() &&
8747 !Context
.hasSameUnqualifiedType(ReturnType
, M
->getReturnType()))
8750 KnownMethods
[M
->getSelector()] =
8751 KnownMethodsMap::mapped_type(M
, InOriginalClass
);
8756 /// Add the parenthesized return or parameter type chunk to a code
8757 /// completion string.
8758 static void AddObjCPassingTypeChunk(QualType Type
, unsigned ObjCDeclQuals
,
8759 ASTContext
&Context
,
8760 const PrintingPolicy
&Policy
,
8761 CodeCompletionBuilder
&Builder
) {
8762 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
8763 std::string Quals
= formatObjCParamQualifiers(ObjCDeclQuals
, Type
);
8765 Builder
.AddTextChunk(Builder
.getAllocator().CopyString(Quals
));
8766 Builder
.AddTextChunk(
8767 GetCompletionTypeString(Type
, Context
, Policy
, Builder
.getAllocator()));
8768 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
8771 /// Determine whether the given class is or inherits from a class by
8773 static bool InheritsFromClassNamed(ObjCInterfaceDecl
*Class
, StringRef Name
) {
8777 if (Class
->getIdentifier() && Class
->getIdentifier()->getName() == Name
)
8780 return InheritsFromClassNamed(Class
->getSuperClass(), Name
);
8783 /// Add code completions for Objective-C Key-Value Coding (KVC) and
8784 /// Key-Value Observing (KVO).
8785 static void AddObjCKeyValueCompletions(ObjCPropertyDecl
*Property
,
8786 bool IsInstanceMethod
,
8787 QualType ReturnType
, ASTContext
&Context
,
8788 VisitedSelectorSet
&KnownSelectors
,
8789 ResultBuilder
&Results
) {
8790 IdentifierInfo
*PropName
= Property
->getIdentifier();
8791 if (!PropName
|| PropName
->getLength() == 0)
8794 PrintingPolicy Policy
= getCompletionPrintingPolicy(Results
.getSema());
8796 // Builder that will create each code completion.
8797 typedef CodeCompletionResult Result
;
8798 CodeCompletionAllocator
&Allocator
= Results
.getAllocator();
8799 CodeCompletionBuilder
Builder(Allocator
, Results
.getCodeCompletionTUInfo());
8801 // The selector table.
8802 SelectorTable
&Selectors
= Context
.Selectors
;
8804 // The property name, copied into the code completion allocation region
8807 CodeCompletionAllocator
&Allocator
;
8809 const char *CopiedKey
;
8811 KeyHolder(CodeCompletionAllocator
&Allocator
, StringRef Key
)
8812 : Allocator(Allocator
), Key(Key
), CopiedKey(nullptr) {}
8814 operator const char *() {
8818 return CopiedKey
= Allocator
.CopyString(Key
);
8820 } Key(Allocator
, PropName
->getName());
8822 // The uppercased name of the property name.
8823 std::string UpperKey
= std::string(PropName
->getName());
8824 if (!UpperKey
.empty())
8825 UpperKey
[0] = toUppercase(UpperKey
[0]);
8827 bool ReturnTypeMatchesProperty
=
8828 ReturnType
.isNull() ||
8829 Context
.hasSameUnqualifiedType(ReturnType
.getNonReferenceType(),
8830 Property
->getType());
8831 bool ReturnTypeMatchesVoid
= ReturnType
.isNull() || ReturnType
->isVoidType();
8833 // Add the normal accessor -(type)key.
8834 if (IsInstanceMethod
&&
8835 KnownSelectors
.insert(Selectors
.getNullarySelector(PropName
)).second
&&
8836 ReturnTypeMatchesProperty
&& !Property
->getGetterMethodDecl()) {
8837 if (ReturnType
.isNull())
8838 AddObjCPassingTypeChunk(Property
->getType(), /*Quals=*/0, Context
, Policy
,
8841 Builder
.AddTypedTextChunk(Key
);
8842 Results
.AddResult(Result(Builder
.TakeString(), CCP_CodePattern
,
8843 CXCursor_ObjCInstanceMethodDecl
));
8846 // If we have an integral or boolean property (or the user has provided
8847 // an integral or boolean return type), add the accessor -(type)isKey.
8848 if (IsInstanceMethod
&&
8849 ((!ReturnType
.isNull() &&
8850 (ReturnType
->isIntegerType() || ReturnType
->isBooleanType())) ||
8851 (ReturnType
.isNull() && (Property
->getType()->isIntegerType() ||
8852 Property
->getType()->isBooleanType())))) {
8853 std::string SelectorName
= (Twine("is") + UpperKey
).str();
8854 IdentifierInfo
*SelectorId
= &Context
.Idents
.get(SelectorName
);
8855 if (KnownSelectors
.insert(Selectors
.getNullarySelector(SelectorId
))
8857 if (ReturnType
.isNull()) {
8858 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
8859 Builder
.AddTextChunk("BOOL");
8860 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
8863 Builder
.AddTypedTextChunk(Allocator
.CopyString(SelectorId
->getName()));
8864 Results
.AddResult(Result(Builder
.TakeString(), CCP_CodePattern
,
8865 CXCursor_ObjCInstanceMethodDecl
));
8869 // Add the normal mutator.
8870 if (IsInstanceMethod
&& ReturnTypeMatchesVoid
&&
8871 !Property
->getSetterMethodDecl()) {
8872 std::string SelectorName
= (Twine("set") + UpperKey
).str();
8873 IdentifierInfo
*SelectorId
= &Context
.Idents
.get(SelectorName
);
8874 if (KnownSelectors
.insert(Selectors
.getUnarySelector(SelectorId
)).second
) {
8875 if (ReturnType
.isNull()) {
8876 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
8877 Builder
.AddTextChunk("void");
8878 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
8881 Builder
.AddTypedTextChunk(
8882 Allocator
.CopyString(SelectorId
->getName() + ":"));
8883 AddObjCPassingTypeChunk(Property
->getType(), /*Quals=*/0, Context
, Policy
,
8885 Builder
.AddTextChunk(Key
);
8886 Results
.AddResult(Result(Builder
.TakeString(), CCP_CodePattern
,
8887 CXCursor_ObjCInstanceMethodDecl
));
8891 // Indexed and unordered accessors
8892 unsigned IndexedGetterPriority
= CCP_CodePattern
;
8893 unsigned IndexedSetterPriority
= CCP_CodePattern
;
8894 unsigned UnorderedGetterPriority
= CCP_CodePattern
;
8895 unsigned UnorderedSetterPriority
= CCP_CodePattern
;
8896 if (const auto *ObjCPointer
=
8897 Property
->getType()->getAs
<ObjCObjectPointerType
>()) {
8898 if (ObjCInterfaceDecl
*IFace
= ObjCPointer
->getInterfaceDecl()) {
8899 // If this interface type is not provably derived from a known
8900 // collection, penalize the corresponding completions.
8901 if (!InheritsFromClassNamed(IFace
, "NSMutableArray")) {
8902 IndexedSetterPriority
+= CCD_ProbablyNotObjCCollection
;
8903 if (!InheritsFromClassNamed(IFace
, "NSArray"))
8904 IndexedGetterPriority
+= CCD_ProbablyNotObjCCollection
;
8907 if (!InheritsFromClassNamed(IFace
, "NSMutableSet")) {
8908 UnorderedSetterPriority
+= CCD_ProbablyNotObjCCollection
;
8909 if (!InheritsFromClassNamed(IFace
, "NSSet"))
8910 UnorderedGetterPriority
+= CCD_ProbablyNotObjCCollection
;
8914 IndexedGetterPriority
+= CCD_ProbablyNotObjCCollection
;
8915 IndexedSetterPriority
+= CCD_ProbablyNotObjCCollection
;
8916 UnorderedGetterPriority
+= CCD_ProbablyNotObjCCollection
;
8917 UnorderedSetterPriority
+= CCD_ProbablyNotObjCCollection
;
8920 // Add -(NSUInteger)countOf<key>
8921 if (IsInstanceMethod
&&
8922 (ReturnType
.isNull() || ReturnType
->isIntegerType())) {
8923 std::string SelectorName
= (Twine("countOf") + UpperKey
).str();
8924 IdentifierInfo
*SelectorId
= &Context
.Idents
.get(SelectorName
);
8925 if (KnownSelectors
.insert(Selectors
.getNullarySelector(SelectorId
))
8927 if (ReturnType
.isNull()) {
8928 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
8929 Builder
.AddTextChunk("NSUInteger");
8930 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
8933 Builder
.AddTypedTextChunk(Allocator
.CopyString(SelectorId
->getName()));
8935 Result(Builder
.TakeString(),
8936 std::min(IndexedGetterPriority
, UnorderedGetterPriority
),
8937 CXCursor_ObjCInstanceMethodDecl
));
8942 // Add -(id)objectInKeyAtIndex:(NSUInteger)index
8943 if (IsInstanceMethod
&&
8944 (ReturnType
.isNull() || ReturnType
->isObjCObjectPointerType())) {
8945 std::string SelectorName
= (Twine("objectIn") + UpperKey
+ "AtIndex").str();
8946 IdentifierInfo
*SelectorId
= &Context
.Idents
.get(SelectorName
);
8947 if (KnownSelectors
.insert(Selectors
.getUnarySelector(SelectorId
)).second
) {
8948 if (ReturnType
.isNull()) {
8949 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
8950 Builder
.AddTextChunk("id");
8951 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
8954 Builder
.AddTypedTextChunk(Allocator
.CopyString(SelectorName
+ ":"));
8955 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
8956 Builder
.AddTextChunk("NSUInteger");
8957 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
8958 Builder
.AddTextChunk("index");
8959 Results
.AddResult(Result(Builder
.TakeString(), IndexedGetterPriority
,
8960 CXCursor_ObjCInstanceMethodDecl
));
8964 // Add -(NSArray *)keyAtIndexes:(NSIndexSet *)indexes
8965 if (IsInstanceMethod
&&
8966 (ReturnType
.isNull() ||
8967 (ReturnType
->isObjCObjectPointerType() &&
8968 ReturnType
->castAs
<ObjCObjectPointerType
>()->getInterfaceDecl() &&
8969 ReturnType
->castAs
<ObjCObjectPointerType
>()
8970 ->getInterfaceDecl()
8971 ->getName() == "NSArray"))) {
8972 std::string SelectorName
= (Twine(Property
->getName()) + "AtIndexes").str();
8973 IdentifierInfo
*SelectorId
= &Context
.Idents
.get(SelectorName
);
8974 if (KnownSelectors
.insert(Selectors
.getUnarySelector(SelectorId
)).second
) {
8975 if (ReturnType
.isNull()) {
8976 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
8977 Builder
.AddTextChunk("NSArray *");
8978 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
8981 Builder
.AddTypedTextChunk(Allocator
.CopyString(SelectorName
+ ":"));
8982 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
8983 Builder
.AddTextChunk("NSIndexSet *");
8984 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
8985 Builder
.AddTextChunk("indexes");
8986 Results
.AddResult(Result(Builder
.TakeString(), IndexedGetterPriority
,
8987 CXCursor_ObjCInstanceMethodDecl
));
8991 // Add -(void)getKey:(type **)buffer range:(NSRange)inRange
8992 if (IsInstanceMethod
&& ReturnTypeMatchesVoid
) {
8993 std::string SelectorName
= (Twine("get") + UpperKey
).str();
8994 IdentifierInfo
*SelectorIds
[2] = {&Context
.Idents
.get(SelectorName
),
8995 &Context
.Idents
.get("range")};
8997 if (KnownSelectors
.insert(Selectors
.getSelector(2, SelectorIds
)).second
) {
8998 if (ReturnType
.isNull()) {
8999 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9000 Builder
.AddTextChunk("void");
9001 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9004 Builder
.AddTypedTextChunk(Allocator
.CopyString(SelectorName
+ ":"));
9005 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9006 Builder
.AddPlaceholderChunk("object-type");
9007 Builder
.AddTextChunk(" **");
9008 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9009 Builder
.AddTextChunk("buffer");
9010 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
9011 Builder
.AddTypedTextChunk("range:");
9012 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9013 Builder
.AddTextChunk("NSRange");
9014 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9015 Builder
.AddTextChunk("inRange");
9016 Results
.AddResult(Result(Builder
.TakeString(), IndexedGetterPriority
,
9017 CXCursor_ObjCInstanceMethodDecl
));
9021 // Mutable indexed accessors
9023 // - (void)insertObject:(type *)object inKeyAtIndex:(NSUInteger)index
9024 if (IsInstanceMethod
&& ReturnTypeMatchesVoid
) {
9025 std::string SelectorName
= (Twine("in") + UpperKey
+ "AtIndex").str();
9026 IdentifierInfo
*SelectorIds
[2] = {&Context
.Idents
.get("insertObject"),
9027 &Context
.Idents
.get(SelectorName
)};
9029 if (KnownSelectors
.insert(Selectors
.getSelector(2, SelectorIds
)).second
) {
9030 if (ReturnType
.isNull()) {
9031 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9032 Builder
.AddTextChunk("void");
9033 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9036 Builder
.AddTypedTextChunk("insertObject:");
9037 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9038 Builder
.AddPlaceholderChunk("object-type");
9039 Builder
.AddTextChunk(" *");
9040 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9041 Builder
.AddTextChunk("object");
9042 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
9043 Builder
.AddTypedTextChunk(Allocator
.CopyString(SelectorName
+ ":"));
9044 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9045 Builder
.AddPlaceholderChunk("NSUInteger");
9046 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9047 Builder
.AddTextChunk("index");
9048 Results
.AddResult(Result(Builder
.TakeString(), IndexedSetterPriority
,
9049 CXCursor_ObjCInstanceMethodDecl
));
9053 // - (void)insertKey:(NSArray *)array atIndexes:(NSIndexSet *)indexes
9054 if (IsInstanceMethod
&& ReturnTypeMatchesVoid
) {
9055 std::string SelectorName
= (Twine("insert") + UpperKey
).str();
9056 IdentifierInfo
*SelectorIds
[2] = {&Context
.Idents
.get(SelectorName
),
9057 &Context
.Idents
.get("atIndexes")};
9059 if (KnownSelectors
.insert(Selectors
.getSelector(2, SelectorIds
)).second
) {
9060 if (ReturnType
.isNull()) {
9061 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9062 Builder
.AddTextChunk("void");
9063 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9066 Builder
.AddTypedTextChunk(Allocator
.CopyString(SelectorName
+ ":"));
9067 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9068 Builder
.AddTextChunk("NSArray *");
9069 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9070 Builder
.AddTextChunk("array");
9071 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
9072 Builder
.AddTypedTextChunk("atIndexes:");
9073 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9074 Builder
.AddPlaceholderChunk("NSIndexSet *");
9075 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9076 Builder
.AddTextChunk("indexes");
9077 Results
.AddResult(Result(Builder
.TakeString(), IndexedSetterPriority
,
9078 CXCursor_ObjCInstanceMethodDecl
));
9082 // -(void)removeObjectFromKeyAtIndex:(NSUInteger)index
9083 if (IsInstanceMethod
&& ReturnTypeMatchesVoid
) {
9084 std::string SelectorName
=
9085 (Twine("removeObjectFrom") + UpperKey
+ "AtIndex").str();
9086 IdentifierInfo
*SelectorId
= &Context
.Idents
.get(SelectorName
);
9087 if (KnownSelectors
.insert(Selectors
.getUnarySelector(SelectorId
)).second
) {
9088 if (ReturnType
.isNull()) {
9089 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9090 Builder
.AddTextChunk("void");
9091 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9094 Builder
.AddTypedTextChunk(Allocator
.CopyString(SelectorName
+ ":"));
9095 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9096 Builder
.AddTextChunk("NSUInteger");
9097 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9098 Builder
.AddTextChunk("index");
9099 Results
.AddResult(Result(Builder
.TakeString(), IndexedSetterPriority
,
9100 CXCursor_ObjCInstanceMethodDecl
));
9104 // -(void)removeKeyAtIndexes:(NSIndexSet *)indexes
9105 if (IsInstanceMethod
&& ReturnTypeMatchesVoid
) {
9106 std::string SelectorName
= (Twine("remove") + UpperKey
+ "AtIndexes").str();
9107 IdentifierInfo
*SelectorId
= &Context
.Idents
.get(SelectorName
);
9108 if (KnownSelectors
.insert(Selectors
.getUnarySelector(SelectorId
)).second
) {
9109 if (ReturnType
.isNull()) {
9110 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9111 Builder
.AddTextChunk("void");
9112 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9115 Builder
.AddTypedTextChunk(Allocator
.CopyString(SelectorName
+ ":"));
9116 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9117 Builder
.AddTextChunk("NSIndexSet *");
9118 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9119 Builder
.AddTextChunk("indexes");
9120 Results
.AddResult(Result(Builder
.TakeString(), IndexedSetterPriority
,
9121 CXCursor_ObjCInstanceMethodDecl
));
9125 // - (void)replaceObjectInKeyAtIndex:(NSUInteger)index withObject:(id)object
9126 if (IsInstanceMethod
&& ReturnTypeMatchesVoid
) {
9127 std::string SelectorName
=
9128 (Twine("replaceObjectIn") + UpperKey
+ "AtIndex").str();
9129 IdentifierInfo
*SelectorIds
[2] = {&Context
.Idents
.get(SelectorName
),
9130 &Context
.Idents
.get("withObject")};
9132 if (KnownSelectors
.insert(Selectors
.getSelector(2, SelectorIds
)).second
) {
9133 if (ReturnType
.isNull()) {
9134 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9135 Builder
.AddTextChunk("void");
9136 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9139 Builder
.AddTypedTextChunk(Allocator
.CopyString(SelectorName
+ ":"));
9140 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9141 Builder
.AddPlaceholderChunk("NSUInteger");
9142 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9143 Builder
.AddTextChunk("index");
9144 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
9145 Builder
.AddTypedTextChunk("withObject:");
9146 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9147 Builder
.AddTextChunk("id");
9148 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9149 Builder
.AddTextChunk("object");
9150 Results
.AddResult(Result(Builder
.TakeString(), IndexedSetterPriority
,
9151 CXCursor_ObjCInstanceMethodDecl
));
9155 // - (void)replaceKeyAtIndexes:(NSIndexSet *)indexes withKey:(NSArray *)array
9156 if (IsInstanceMethod
&& ReturnTypeMatchesVoid
) {
9157 std::string SelectorName1
=
9158 (Twine("replace") + UpperKey
+ "AtIndexes").str();
9159 std::string SelectorName2
= (Twine("with") + UpperKey
).str();
9160 IdentifierInfo
*SelectorIds
[2] = {&Context
.Idents
.get(SelectorName1
),
9161 &Context
.Idents
.get(SelectorName2
)};
9163 if (KnownSelectors
.insert(Selectors
.getSelector(2, SelectorIds
)).second
) {
9164 if (ReturnType
.isNull()) {
9165 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9166 Builder
.AddTextChunk("void");
9167 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9170 Builder
.AddTypedTextChunk(Allocator
.CopyString(SelectorName1
+ ":"));
9171 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9172 Builder
.AddPlaceholderChunk("NSIndexSet *");
9173 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9174 Builder
.AddTextChunk("indexes");
9175 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
9176 Builder
.AddTypedTextChunk(Allocator
.CopyString(SelectorName2
+ ":"));
9177 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9178 Builder
.AddTextChunk("NSArray *");
9179 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9180 Builder
.AddTextChunk("array");
9181 Results
.AddResult(Result(Builder
.TakeString(), IndexedSetterPriority
,
9182 CXCursor_ObjCInstanceMethodDecl
));
9186 // Unordered getters
9187 // - (NSEnumerator *)enumeratorOfKey
9188 if (IsInstanceMethod
&&
9189 (ReturnType
.isNull() ||
9190 (ReturnType
->isObjCObjectPointerType() &&
9191 ReturnType
->castAs
<ObjCObjectPointerType
>()->getInterfaceDecl() &&
9192 ReturnType
->castAs
<ObjCObjectPointerType
>()
9193 ->getInterfaceDecl()
9194 ->getName() == "NSEnumerator"))) {
9195 std::string SelectorName
= (Twine("enumeratorOf") + UpperKey
).str();
9196 IdentifierInfo
*SelectorId
= &Context
.Idents
.get(SelectorName
);
9197 if (KnownSelectors
.insert(Selectors
.getNullarySelector(SelectorId
))
9199 if (ReturnType
.isNull()) {
9200 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9201 Builder
.AddTextChunk("NSEnumerator *");
9202 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9205 Builder
.AddTypedTextChunk(Allocator
.CopyString(SelectorName
));
9206 Results
.AddResult(Result(Builder
.TakeString(), UnorderedGetterPriority
,
9207 CXCursor_ObjCInstanceMethodDecl
));
9211 // - (type *)memberOfKey:(type *)object
9212 if (IsInstanceMethod
&&
9213 (ReturnType
.isNull() || ReturnType
->isObjCObjectPointerType())) {
9214 std::string SelectorName
= (Twine("memberOf") + UpperKey
).str();
9215 IdentifierInfo
*SelectorId
= &Context
.Idents
.get(SelectorName
);
9216 if (KnownSelectors
.insert(Selectors
.getUnarySelector(SelectorId
)).second
) {
9217 if (ReturnType
.isNull()) {
9218 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9219 Builder
.AddPlaceholderChunk("object-type");
9220 Builder
.AddTextChunk(" *");
9221 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9224 Builder
.AddTypedTextChunk(Allocator
.CopyString(SelectorName
+ ":"));
9225 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9226 if (ReturnType
.isNull()) {
9227 Builder
.AddPlaceholderChunk("object-type");
9228 Builder
.AddTextChunk(" *");
9230 Builder
.AddTextChunk(GetCompletionTypeString(
9231 ReturnType
, Context
, Policy
, Builder
.getAllocator()));
9233 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9234 Builder
.AddTextChunk("object");
9235 Results
.AddResult(Result(Builder
.TakeString(), UnorderedGetterPriority
,
9236 CXCursor_ObjCInstanceMethodDecl
));
9240 // Mutable unordered accessors
9241 // - (void)addKeyObject:(type *)object
9242 if (IsInstanceMethod
&& ReturnTypeMatchesVoid
) {
9243 std::string SelectorName
=
9244 (Twine("add") + UpperKey
+ Twine("Object")).str();
9245 IdentifierInfo
*SelectorId
= &Context
.Idents
.get(SelectorName
);
9246 if (KnownSelectors
.insert(Selectors
.getUnarySelector(SelectorId
)).second
) {
9247 if (ReturnType
.isNull()) {
9248 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9249 Builder
.AddTextChunk("void");
9250 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9253 Builder
.AddTypedTextChunk(Allocator
.CopyString(SelectorName
+ ":"));
9254 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9255 Builder
.AddPlaceholderChunk("object-type");
9256 Builder
.AddTextChunk(" *");
9257 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9258 Builder
.AddTextChunk("object");
9259 Results
.AddResult(Result(Builder
.TakeString(), UnorderedSetterPriority
,
9260 CXCursor_ObjCInstanceMethodDecl
));
9264 // - (void)addKey:(NSSet *)objects
9265 if (IsInstanceMethod
&& ReturnTypeMatchesVoid
) {
9266 std::string SelectorName
= (Twine("add") + UpperKey
).str();
9267 IdentifierInfo
*SelectorId
= &Context
.Idents
.get(SelectorName
);
9268 if (KnownSelectors
.insert(Selectors
.getUnarySelector(SelectorId
)).second
) {
9269 if (ReturnType
.isNull()) {
9270 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9271 Builder
.AddTextChunk("void");
9272 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9275 Builder
.AddTypedTextChunk(Allocator
.CopyString(SelectorName
+ ":"));
9276 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9277 Builder
.AddTextChunk("NSSet *");
9278 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9279 Builder
.AddTextChunk("objects");
9280 Results
.AddResult(Result(Builder
.TakeString(), UnorderedSetterPriority
,
9281 CXCursor_ObjCInstanceMethodDecl
));
9285 // - (void)removeKeyObject:(type *)object
9286 if (IsInstanceMethod
&& ReturnTypeMatchesVoid
) {
9287 std::string SelectorName
=
9288 (Twine("remove") + UpperKey
+ Twine("Object")).str();
9289 IdentifierInfo
*SelectorId
= &Context
.Idents
.get(SelectorName
);
9290 if (KnownSelectors
.insert(Selectors
.getUnarySelector(SelectorId
)).second
) {
9291 if (ReturnType
.isNull()) {
9292 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9293 Builder
.AddTextChunk("void");
9294 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9297 Builder
.AddTypedTextChunk(Allocator
.CopyString(SelectorName
+ ":"));
9298 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9299 Builder
.AddPlaceholderChunk("object-type");
9300 Builder
.AddTextChunk(" *");
9301 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9302 Builder
.AddTextChunk("object");
9303 Results
.AddResult(Result(Builder
.TakeString(), UnorderedSetterPriority
,
9304 CXCursor_ObjCInstanceMethodDecl
));
9308 // - (void)removeKey:(NSSet *)objects
9309 if (IsInstanceMethod
&& ReturnTypeMatchesVoid
) {
9310 std::string SelectorName
= (Twine("remove") + UpperKey
).str();
9311 IdentifierInfo
*SelectorId
= &Context
.Idents
.get(SelectorName
);
9312 if (KnownSelectors
.insert(Selectors
.getUnarySelector(SelectorId
)).second
) {
9313 if (ReturnType
.isNull()) {
9314 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9315 Builder
.AddTextChunk("void");
9316 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9319 Builder
.AddTypedTextChunk(Allocator
.CopyString(SelectorName
+ ":"));
9320 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9321 Builder
.AddTextChunk("NSSet *");
9322 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9323 Builder
.AddTextChunk("objects");
9324 Results
.AddResult(Result(Builder
.TakeString(), UnorderedSetterPriority
,
9325 CXCursor_ObjCInstanceMethodDecl
));
9329 // - (void)intersectKey:(NSSet *)objects
9330 if (IsInstanceMethod
&& ReturnTypeMatchesVoid
) {
9331 std::string SelectorName
= (Twine("intersect") + UpperKey
).str();
9332 IdentifierInfo
*SelectorId
= &Context
.Idents
.get(SelectorName
);
9333 if (KnownSelectors
.insert(Selectors
.getUnarySelector(SelectorId
)).second
) {
9334 if (ReturnType
.isNull()) {
9335 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9336 Builder
.AddTextChunk("void");
9337 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9340 Builder
.AddTypedTextChunk(Allocator
.CopyString(SelectorName
+ ":"));
9341 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9342 Builder
.AddTextChunk("NSSet *");
9343 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9344 Builder
.AddTextChunk("objects");
9345 Results
.AddResult(Result(Builder
.TakeString(), UnorderedSetterPriority
,
9346 CXCursor_ObjCInstanceMethodDecl
));
9350 // Key-Value Observing
9351 // + (NSSet *)keyPathsForValuesAffectingKey
9352 if (!IsInstanceMethod
&&
9353 (ReturnType
.isNull() ||
9354 (ReturnType
->isObjCObjectPointerType() &&
9355 ReturnType
->castAs
<ObjCObjectPointerType
>()->getInterfaceDecl() &&
9356 ReturnType
->castAs
<ObjCObjectPointerType
>()
9357 ->getInterfaceDecl()
9358 ->getName() == "NSSet"))) {
9359 std::string SelectorName
=
9360 (Twine("keyPathsForValuesAffecting") + UpperKey
).str();
9361 IdentifierInfo
*SelectorId
= &Context
.Idents
.get(SelectorName
);
9362 if (KnownSelectors
.insert(Selectors
.getNullarySelector(SelectorId
))
9364 if (ReturnType
.isNull()) {
9365 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9366 Builder
.AddTextChunk("NSSet<NSString *> *");
9367 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9370 Builder
.AddTypedTextChunk(Allocator
.CopyString(SelectorName
));
9371 Results
.AddResult(Result(Builder
.TakeString(), CCP_CodePattern
,
9372 CXCursor_ObjCClassMethodDecl
));
9376 // + (BOOL)automaticallyNotifiesObserversForKey
9377 if (!IsInstanceMethod
&&
9378 (ReturnType
.isNull() || ReturnType
->isIntegerType() ||
9379 ReturnType
->isBooleanType())) {
9380 std::string SelectorName
=
9381 (Twine("automaticallyNotifiesObserversOf") + UpperKey
).str();
9382 IdentifierInfo
*SelectorId
= &Context
.Idents
.get(SelectorName
);
9383 if (KnownSelectors
.insert(Selectors
.getNullarySelector(SelectorId
))
9385 if (ReturnType
.isNull()) {
9386 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9387 Builder
.AddTextChunk("BOOL");
9388 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9391 Builder
.AddTypedTextChunk(Allocator
.CopyString(SelectorName
));
9392 Results
.AddResult(Result(Builder
.TakeString(), CCP_CodePattern
,
9393 CXCursor_ObjCClassMethodDecl
));
9398 void Sema::CodeCompleteObjCMethodDecl(Scope
*S
, Optional
<bool> IsInstanceMethod
,
9399 ParsedType ReturnTy
) {
9400 // Determine the return type of the method we're declaring, if
9402 QualType ReturnType
= GetTypeFromParser(ReturnTy
);
9403 Decl
*IDecl
= nullptr;
9404 if (CurContext
->isObjCContainer()) {
9405 ObjCContainerDecl
*OCD
= dyn_cast
<ObjCContainerDecl
>(CurContext
);
9408 // Determine where we should start searching for methods.
9409 ObjCContainerDecl
*SearchDecl
= nullptr;
9410 bool IsInImplementation
= false;
9411 if (Decl
*D
= IDecl
) {
9412 if (ObjCImplementationDecl
*Impl
= dyn_cast
<ObjCImplementationDecl
>(D
)) {
9413 SearchDecl
= Impl
->getClassInterface();
9414 IsInImplementation
= true;
9415 } else if (ObjCCategoryImplDecl
*CatImpl
=
9416 dyn_cast
<ObjCCategoryImplDecl
>(D
)) {
9417 SearchDecl
= CatImpl
->getCategoryDecl();
9418 IsInImplementation
= true;
9420 SearchDecl
= dyn_cast
<ObjCContainerDecl
>(D
);
9423 if (!SearchDecl
&& S
) {
9424 if (DeclContext
*DC
= S
->getEntity())
9425 SearchDecl
= dyn_cast
<ObjCContainerDecl
>(DC
);
9429 HandleCodeCompleteResults(this, CodeCompleter
,
9430 CodeCompletionContext::CCC_Other
, nullptr, 0);
9434 // Find all of the methods that we could declare/implement here.
9435 KnownMethodsMap KnownMethods
;
9436 FindImplementableMethods(Context
, SearchDecl
, IsInstanceMethod
, ReturnType
,
9439 // Add declarations or definitions for each of the known methods.
9440 typedef CodeCompletionResult Result
;
9441 ResultBuilder
Results(*this, CodeCompleter
->getAllocator(),
9442 CodeCompleter
->getCodeCompletionTUInfo(),
9443 CodeCompletionContext::CCC_Other
);
9444 Results
.EnterNewScope();
9445 PrintingPolicy Policy
= getCompletionPrintingPolicy(*this);
9446 for (KnownMethodsMap::iterator M
= KnownMethods
.begin(),
9447 MEnd
= KnownMethods
.end();
9449 ObjCMethodDecl
*Method
= M
->second
.getPointer();
9450 CodeCompletionBuilder
Builder(Results
.getAllocator(),
9451 Results
.getCodeCompletionTUInfo());
9453 // Add the '-'/'+' prefix if it wasn't provided yet.
9454 if (!IsInstanceMethod
) {
9455 Builder
.AddTextChunk(Method
->isInstanceMethod() ? "-" : "+");
9456 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
9459 // If the result type was not already provided, add it to the
9460 // pattern as (type).
9461 if (ReturnType
.isNull()) {
9462 QualType ResTy
= Method
->getSendResultType().stripObjCKindOfType(Context
);
9463 AttributedType::stripOuterNullability(ResTy
);
9464 AddObjCPassingTypeChunk(ResTy
, Method
->getObjCDeclQualifier(), Context
,
9468 Selector Sel
= Method
->getSelector();
9470 if (Sel
.isUnarySelector()) {
9471 // Unary selectors have no arguments.
9472 Builder
.AddTypedTextChunk(
9473 Builder
.getAllocator().CopyString(Sel
.getNameForSlot(0)));
9475 // Add all parameters to the pattern.
9477 for (ObjCMethodDecl::param_iterator P
= Method
->param_begin(),
9478 PEnd
= Method
->param_end();
9479 P
!= PEnd
; (void)++P
, ++I
) {
9480 // Add the part of the selector name.
9482 Builder
.AddTypedTextChunk(
9483 Builder
.getAllocator().CopyString(Sel
.getNameForSlot(I
) + ":"));
9484 else if (I
< Sel
.getNumArgs()) {
9485 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
9486 Builder
.AddTypedTextChunk(
9487 Builder
.getAllocator().CopyString(Sel
.getNameForSlot(I
) + ":"));
9491 // Add the parameter type.
9493 if ((*P
)->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability
)
9494 ParamType
= (*P
)->getType();
9496 ParamType
= (*P
)->getOriginalType();
9497 ParamType
= ParamType
.substObjCTypeArgs(
9498 Context
, {}, ObjCSubstitutionContext::Parameter
);
9499 AttributedType::stripOuterNullability(ParamType
);
9500 AddObjCPassingTypeChunk(ParamType
, (*P
)->getObjCDeclQualifier(),
9501 Context
, Policy
, Builder
);
9503 if (IdentifierInfo
*Id
= (*P
)->getIdentifier())
9504 Builder
.AddTextChunk(
9505 Builder
.getAllocator().CopyString(Id
->getName()));
9509 if (Method
->isVariadic()) {
9510 if (Method
->param_size() > 0)
9511 Builder
.AddChunk(CodeCompletionString::CK_Comma
);
9512 Builder
.AddTextChunk("...");
9515 if (IsInImplementation
&& Results
.includeCodePatterns()) {
9516 // We will be defining the method here, so add a compound statement.
9517 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
9518 Builder
.AddChunk(CodeCompletionString::CK_LeftBrace
);
9519 Builder
.AddChunk(CodeCompletionString::CK_VerticalSpace
);
9520 if (!Method
->getReturnType()->isVoidType()) {
9521 // If the result type is not void, add a return clause.
9522 Builder
.AddTextChunk("return");
9523 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
9524 Builder
.AddPlaceholderChunk("expression");
9525 Builder
.AddChunk(CodeCompletionString::CK_SemiColon
);
9527 Builder
.AddPlaceholderChunk("statements");
9529 Builder
.AddChunk(CodeCompletionString::CK_VerticalSpace
);
9530 Builder
.AddChunk(CodeCompletionString::CK_RightBrace
);
9533 unsigned Priority
= CCP_CodePattern
;
9534 auto R
= Result(Builder
.TakeString(), Method
, Priority
);
9535 if (!M
->second
.getInt())
9537 Results
.AddResult(std::move(R
));
9540 // Add Key-Value-Coding and Key-Value-Observing accessor methods for all of
9541 // the properties in this class and its categories.
9542 if (Context
.getLangOpts().ObjC
) {
9543 SmallVector
<ObjCContainerDecl
*, 4> Containers
;
9544 Containers
.push_back(SearchDecl
);
9546 VisitedSelectorSet KnownSelectors
;
9547 for (KnownMethodsMap::iterator M
= KnownMethods
.begin(),
9548 MEnd
= KnownMethods
.end();
9550 KnownSelectors
.insert(M
->first
);
9552 ObjCInterfaceDecl
*IFace
= dyn_cast
<ObjCInterfaceDecl
>(SearchDecl
);
9554 if (ObjCCategoryDecl
*Category
= dyn_cast
<ObjCCategoryDecl
>(SearchDecl
))
9555 IFace
= Category
->getClassInterface();
9558 llvm::append_range(Containers
, IFace
->visible_categories());
9560 if (IsInstanceMethod
) {
9561 for (unsigned I
= 0, N
= Containers
.size(); I
!= N
; ++I
)
9562 for (auto *P
: Containers
[I
]->instance_properties())
9563 AddObjCKeyValueCompletions(P
, *IsInstanceMethod
, ReturnType
, Context
,
9564 KnownSelectors
, Results
);
9568 Results
.ExitScope();
9570 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
9571 Results
.data(), Results
.size());
9574 void Sema::CodeCompleteObjCMethodDeclSelector(
9575 Scope
*S
, bool IsInstanceMethod
, bool AtParameterName
, ParsedType ReturnTy
,
9576 ArrayRef
<IdentifierInfo
*> SelIdents
) {
9577 // If we have an external source, load the entire class method
9578 // pool from the AST file.
9579 if (ExternalSource
) {
9580 for (uint32_t I
= 0, N
= ExternalSource
->GetNumExternalSelectors(); I
!= N
;
9582 Selector Sel
= ExternalSource
->GetExternalSelector(I
);
9583 if (Sel
.isNull() || MethodPool
.count(Sel
))
9586 ReadMethodPool(Sel
);
9590 // Build the set of methods we can see.
9591 typedef CodeCompletionResult Result
;
9592 ResultBuilder
Results(*this, CodeCompleter
->getAllocator(),
9593 CodeCompleter
->getCodeCompletionTUInfo(),
9594 CodeCompletionContext::CCC_Other
);
9597 Results
.setPreferredType(GetTypeFromParser(ReturnTy
).getNonReferenceType());
9599 Results
.EnterNewScope();
9600 for (GlobalMethodPool::iterator M
= MethodPool
.begin(),
9601 MEnd
= MethodPool
.end();
9603 for (ObjCMethodList
*MethList
= IsInstanceMethod
? &M
->second
.first
9604 : &M
->second
.second
;
9605 MethList
&& MethList
->getMethod(); MethList
= MethList
->getNext()) {
9606 if (!isAcceptableObjCMethod(MethList
->getMethod(), MK_Any
, SelIdents
))
9609 if (AtParameterName
) {
9610 // Suggest parameter names we've seen before.
9611 unsigned NumSelIdents
= SelIdents
.size();
9613 NumSelIdents
<= MethList
->getMethod()->param_size()) {
9614 ParmVarDecl
*Param
=
9615 MethList
->getMethod()->parameters()[NumSelIdents
- 1];
9616 if (Param
->getIdentifier()) {
9617 CodeCompletionBuilder
Builder(Results
.getAllocator(),
9618 Results
.getCodeCompletionTUInfo());
9619 Builder
.AddTypedTextChunk(Builder
.getAllocator().CopyString(
9620 Param
->getIdentifier()->getName()));
9621 Results
.AddResult(Builder
.TakeString());
9628 Result
R(MethList
->getMethod(),
9629 Results
.getBasePriority(MethList
->getMethod()), nullptr);
9630 R
.StartParameter
= SelIdents
.size();
9631 R
.AllParametersAreInformative
= false;
9632 R
.DeclaringEntity
= true;
9633 Results
.MaybeAddResult(R
, CurContext
);
9637 Results
.ExitScope();
9639 if (!AtParameterName
&& !SelIdents
.empty() &&
9640 SelIdents
.front()->getName().startswith("init")) {
9641 for (const auto &M
: PP
.macros()) {
9642 if (M
.first
->getName() != "NS_DESIGNATED_INITIALIZER")
9644 Results
.EnterNewScope();
9645 CodeCompletionBuilder
Builder(Results
.getAllocator(),
9646 Results
.getCodeCompletionTUInfo());
9647 Builder
.AddTypedTextChunk(
9648 Builder
.getAllocator().CopyString(M
.first
->getName()));
9649 Results
.AddResult(CodeCompletionResult(Builder
.TakeString(), CCP_Macro
,
9650 CXCursor_MacroDefinition
));
9651 Results
.ExitScope();
9655 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
9656 Results
.data(), Results
.size());
9659 void Sema::CodeCompletePreprocessorDirective(bool InConditional
) {
9660 ResultBuilder
Results(*this, CodeCompleter
->getAllocator(),
9661 CodeCompleter
->getCodeCompletionTUInfo(),
9662 CodeCompletionContext::CCC_PreprocessorDirective
);
9663 Results
.EnterNewScope();
9666 CodeCompletionBuilder
Builder(Results
.getAllocator(),
9667 Results
.getCodeCompletionTUInfo());
9668 Builder
.AddTypedTextChunk("if");
9669 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
9670 Builder
.AddPlaceholderChunk("condition");
9671 Results
.AddResult(Builder
.TakeString());
9674 Builder
.AddTypedTextChunk("ifdef");
9675 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
9676 Builder
.AddPlaceholderChunk("macro");
9677 Results
.AddResult(Builder
.TakeString());
9680 Builder
.AddTypedTextChunk("ifndef");
9681 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
9682 Builder
.AddPlaceholderChunk("macro");
9683 Results
.AddResult(Builder
.TakeString());
9685 if (InConditional
) {
9686 // #elif <condition>
9687 Builder
.AddTypedTextChunk("elif");
9688 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
9689 Builder
.AddPlaceholderChunk("condition");
9690 Results
.AddResult(Builder
.TakeString());
9693 Builder
.AddTypedTextChunk("elifdef");
9694 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
9695 Builder
.AddPlaceholderChunk("macro");
9696 Results
.AddResult(Builder
.TakeString());
9698 // #elifndef <macro>
9699 Builder
.AddTypedTextChunk("elifndef");
9700 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
9701 Builder
.AddPlaceholderChunk("macro");
9702 Results
.AddResult(Builder
.TakeString());
9705 Builder
.AddTypedTextChunk("else");
9706 Results
.AddResult(Builder
.TakeString());
9709 Builder
.AddTypedTextChunk("endif");
9710 Results
.AddResult(Builder
.TakeString());
9713 // #include "header"
9714 Builder
.AddTypedTextChunk("include");
9715 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
9716 Builder
.AddTextChunk("\"");
9717 Builder
.AddPlaceholderChunk("header");
9718 Builder
.AddTextChunk("\"");
9719 Results
.AddResult(Builder
.TakeString());
9721 // #include <header>
9722 Builder
.AddTypedTextChunk("include");
9723 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
9724 Builder
.AddTextChunk("<");
9725 Builder
.AddPlaceholderChunk("header");
9726 Builder
.AddTextChunk(">");
9727 Results
.AddResult(Builder
.TakeString());
9730 Builder
.AddTypedTextChunk("define");
9731 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
9732 Builder
.AddPlaceholderChunk("macro");
9733 Results
.AddResult(Builder
.TakeString());
9735 // #define <macro>(<args>)
9736 Builder
.AddTypedTextChunk("define");
9737 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
9738 Builder
.AddPlaceholderChunk("macro");
9739 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9740 Builder
.AddPlaceholderChunk("args");
9741 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9742 Results
.AddResult(Builder
.TakeString());
9745 Builder
.AddTypedTextChunk("undef");
9746 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
9747 Builder
.AddPlaceholderChunk("macro");
9748 Results
.AddResult(Builder
.TakeString());
9751 Builder
.AddTypedTextChunk("line");
9752 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
9753 Builder
.AddPlaceholderChunk("number");
9754 Results
.AddResult(Builder
.TakeString());
9756 // #line <number> "filename"
9757 Builder
.AddTypedTextChunk("line");
9758 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
9759 Builder
.AddPlaceholderChunk("number");
9760 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
9761 Builder
.AddTextChunk("\"");
9762 Builder
.AddPlaceholderChunk("filename");
9763 Builder
.AddTextChunk("\"");
9764 Results
.AddResult(Builder
.TakeString());
9767 Builder
.AddTypedTextChunk("error");
9768 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
9769 Builder
.AddPlaceholderChunk("message");
9770 Results
.AddResult(Builder
.TakeString());
9772 // #pragma <arguments>
9773 Builder
.AddTypedTextChunk("pragma");
9774 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
9775 Builder
.AddPlaceholderChunk("arguments");
9776 Results
.AddResult(Builder
.TakeString());
9778 if (getLangOpts().ObjC
) {
9780 Builder
.AddTypedTextChunk("import");
9781 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
9782 Builder
.AddTextChunk("\"");
9783 Builder
.AddPlaceholderChunk("header");
9784 Builder
.AddTextChunk("\"");
9785 Results
.AddResult(Builder
.TakeString());
9788 Builder
.AddTypedTextChunk("import");
9789 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
9790 Builder
.AddTextChunk("<");
9791 Builder
.AddPlaceholderChunk("header");
9792 Builder
.AddTextChunk(">");
9793 Results
.AddResult(Builder
.TakeString());
9796 // #include_next "header"
9797 Builder
.AddTypedTextChunk("include_next");
9798 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
9799 Builder
.AddTextChunk("\"");
9800 Builder
.AddPlaceholderChunk("header");
9801 Builder
.AddTextChunk("\"");
9802 Results
.AddResult(Builder
.TakeString());
9804 // #include_next <header>
9805 Builder
.AddTypedTextChunk("include_next");
9806 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
9807 Builder
.AddTextChunk("<");
9808 Builder
.AddPlaceholderChunk("header");
9809 Builder
.AddTextChunk(">");
9810 Results
.AddResult(Builder
.TakeString());
9812 // #warning <message>
9813 Builder
.AddTypedTextChunk("warning");
9814 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
9815 Builder
.AddPlaceholderChunk("message");
9816 Results
.AddResult(Builder
.TakeString());
9818 // Note: #ident and #sccs are such crazy anachronisms that we don't provide
9819 // completions for them. And __include_macros is a Clang-internal extension
9820 // that we don't want to encourage anyone to use.
9822 // FIXME: we don't support #assert or #unassert, so don't suggest them.
9823 Results
.ExitScope();
9825 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
9826 Results
.data(), Results
.size());
9829 void Sema::CodeCompleteInPreprocessorConditionalExclusion(Scope
*S
) {
9830 CodeCompleteOrdinaryName(S
, S
->getFnParent() ? Sema::PCC_RecoveryInFunction
9831 : Sema::PCC_Namespace
);
9834 void Sema::CodeCompletePreprocessorMacroName(bool IsDefinition
) {
9835 ResultBuilder
Results(*this, CodeCompleter
->getAllocator(),
9836 CodeCompleter
->getCodeCompletionTUInfo(),
9837 IsDefinition
? CodeCompletionContext::CCC_MacroName
9838 : CodeCompletionContext::CCC_MacroNameUse
);
9839 if (!IsDefinition
&& CodeCompleter
->includeMacros()) {
9840 // Add just the names of macros, not their arguments.
9841 CodeCompletionBuilder
Builder(Results
.getAllocator(),
9842 Results
.getCodeCompletionTUInfo());
9843 Results
.EnterNewScope();
9844 for (Preprocessor::macro_iterator M
= PP
.macro_begin(),
9845 MEnd
= PP
.macro_end();
9847 Builder
.AddTypedTextChunk(
9848 Builder
.getAllocator().CopyString(M
->first
->getName()));
9849 Results
.AddResult(CodeCompletionResult(
9850 Builder
.TakeString(), CCP_CodePattern
, CXCursor_MacroDefinition
));
9852 Results
.ExitScope();
9853 } else if (IsDefinition
) {
9854 // FIXME: Can we detect when the user just wrote an include guard above?
9857 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
9858 Results
.data(), Results
.size());
9861 void Sema::CodeCompletePreprocessorExpression() {
9862 ResultBuilder
Results(*this, CodeCompleter
->getAllocator(),
9863 CodeCompleter
->getCodeCompletionTUInfo(),
9864 CodeCompletionContext::CCC_PreprocessorExpression
);
9866 if (CodeCompleter
->includeMacros())
9867 AddMacroResults(PP
, Results
, CodeCompleter
->loadExternal(), true);
9869 // defined (<macro>)
9870 Results
.EnterNewScope();
9871 CodeCompletionBuilder
Builder(Results
.getAllocator(),
9872 Results
.getCodeCompletionTUInfo());
9873 Builder
.AddTypedTextChunk("defined");
9874 Builder
.AddChunk(CodeCompletionString::CK_HorizontalSpace
);
9875 Builder
.AddChunk(CodeCompletionString::CK_LeftParen
);
9876 Builder
.AddPlaceholderChunk("macro");
9877 Builder
.AddChunk(CodeCompletionString::CK_RightParen
);
9878 Results
.AddResult(Builder
.TakeString());
9879 Results
.ExitScope();
9881 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
9882 Results
.data(), Results
.size());
9885 void Sema::CodeCompletePreprocessorMacroArgument(Scope
*S
,
9886 IdentifierInfo
*Macro
,
9887 MacroInfo
*MacroInfo
,
9888 unsigned Argument
) {
9889 // FIXME: In the future, we could provide "overload" results, much like we
9890 // do for function calls.
9892 // Now just ignore this. There will be another code-completion callback
9893 // for the expanded tokens.
9896 // This handles completion inside an #include filename, e.g. #include <foo/ba
9897 // We look for the directory "foo" under each directory on the include path,
9898 // list its files, and reassemble the appropriate #include.
9899 void Sema::CodeCompleteIncludedFile(llvm::StringRef Dir
, bool Angled
) {
9900 // RelDir should use /, but unescaped \ is possible on windows!
9901 // Our completions will normalize to / for simplicity, this case is rare.
9902 std::string RelDir
= llvm::sys::path::convert_to_slash(Dir
);
9903 // We need the native slashes for the actual file system interactions.
9904 SmallString
<128> NativeRelDir
= StringRef(RelDir
);
9905 llvm::sys::path::native(NativeRelDir
);
9906 llvm::vfs::FileSystem
&FS
=
9907 getSourceManager().getFileManager().getVirtualFileSystem();
9909 ResultBuilder
Results(*this, CodeCompleter
->getAllocator(),
9910 CodeCompleter
->getCodeCompletionTUInfo(),
9911 CodeCompletionContext::CCC_IncludedFile
);
9912 llvm::DenseSet
<StringRef
> SeenResults
; // To deduplicate results.
9914 // Helper: adds one file or directory completion result.
9915 auto AddCompletion
= [&](StringRef Filename
, bool IsDirectory
) {
9916 SmallString
<64> TypedChunk
= Filename
;
9917 // Directory completion is up to the slash, e.g. <sys/
9918 TypedChunk
.push_back(IsDirectory
? '/' : Angled
? '>' : '"');
9919 auto R
= SeenResults
.insert(TypedChunk
);
9920 if (R
.second
) { // New completion
9921 const char *InternedTyped
= Results
.getAllocator().CopyString(TypedChunk
);
9922 *R
.first
= InternedTyped
; // Avoid dangling StringRef.
9923 CodeCompletionBuilder
Builder(CodeCompleter
->getAllocator(),
9924 CodeCompleter
->getCodeCompletionTUInfo());
9925 Builder
.AddTypedTextChunk(InternedTyped
);
9926 // The result is a "Pattern", which is pretty opaque.
9927 // We may want to include the real filename to allow smart ranking.
9928 Results
.AddResult(CodeCompletionResult(Builder
.TakeString()));
9932 // Helper: scans IncludeDir for nice files, and adds results for each.
9933 auto AddFilesFromIncludeDir
= [&](StringRef IncludeDir
,
9935 DirectoryLookup::LookupType_t LookupType
) {
9936 llvm::SmallString
<128> Dir
= IncludeDir
;
9937 if (!NativeRelDir
.empty()) {
9938 if (LookupType
== DirectoryLookup::LT_Framework
) {
9939 // For a framework dir, #include <Foo/Bar/> actually maps to
9940 // a path of Foo.framework/Headers/Bar/.
9941 auto Begin
= llvm::sys::path::begin(NativeRelDir
);
9942 auto End
= llvm::sys::path::end(NativeRelDir
);
9944 llvm::sys::path::append(Dir
, *Begin
+ ".framework", "Headers");
9945 llvm::sys::path::append(Dir
, ++Begin
, End
);
9947 llvm::sys::path::append(Dir
, NativeRelDir
);
9951 const StringRef
&Dirname
= llvm::sys::path::filename(Dir
);
9952 const bool isQt
= Dirname
.startswith("Qt") || Dirname
== "ActiveQt";
9953 const bool ExtensionlessHeaders
=
9954 IsSystem
|| isQt
|| Dir
.endswith(".framework/Headers");
9957 for (auto It
= FS
.dir_begin(Dir
, EC
);
9958 !EC
&& It
!= llvm::vfs::directory_iterator(); It
.increment(EC
)) {
9959 if (++Count
== 2500) // If we happen to hit a huge directory,
9960 break; // bail out early so we're not too slow.
9961 StringRef Filename
= llvm::sys::path::filename(It
->path());
9963 // To know whether a symlink should be treated as file or a directory, we
9964 // have to stat it. This should be cheap enough as there shouldn't be many
9966 llvm::sys::fs::file_type Type
= It
->type();
9967 if (Type
== llvm::sys::fs::file_type::symlink_file
) {
9968 if (auto FileStatus
= FS
.status(It
->path()))
9969 Type
= FileStatus
->getType();
9972 case llvm::sys::fs::file_type::directory_file
:
9973 // All entries in a framework directory must have a ".framework" suffix,
9974 // but the suffix does not appear in the source code's include/import.
9975 if (LookupType
== DirectoryLookup::LT_Framework
&&
9976 NativeRelDir
.empty() && !Filename
.consume_back(".framework"))
9979 AddCompletion(Filename
, /*IsDirectory=*/true);
9981 case llvm::sys::fs::file_type::regular_file
: {
9982 // Only files that really look like headers. (Except in special dirs).
9983 // Header extensions from Types.def, which we can't depend on here.
9984 const bool IsHeader
= Filename
.endswith_insensitive(".h") ||
9985 Filename
.endswith_insensitive(".hh") ||
9986 Filename
.endswith_insensitive(".hpp") ||
9987 Filename
.endswith_insensitive(".inc") ||
9988 (ExtensionlessHeaders
&& !Filename
.contains('.'));
9991 AddCompletion(Filename
, /*IsDirectory=*/false);
10000 // Helper: adds results relative to IncludeDir, if possible.
10001 auto AddFilesFromDirLookup
= [&](const DirectoryLookup
&IncludeDir
,
10003 switch (IncludeDir
.getLookupType()) {
10004 case DirectoryLookup::LT_HeaderMap
:
10005 // header maps are not (currently) enumerable.
10007 case DirectoryLookup::LT_NormalDir
:
10008 AddFilesFromIncludeDir(IncludeDir
.getDir()->getName(), IsSystem
,
10009 DirectoryLookup::LT_NormalDir
);
10011 case DirectoryLookup::LT_Framework
:
10012 AddFilesFromIncludeDir(IncludeDir
.getFrameworkDir()->getName(), IsSystem
,
10013 DirectoryLookup::LT_Framework
);
10018 // Finally with all our helpers, we can scan the include path.
10019 // Do this in standard order so deduplication keeps the right file.
10020 // (In case we decide to add more details to the results later).
10021 const auto &S
= PP
.getHeaderSearchInfo();
10022 using llvm::make_range
;
10024 // The current directory is on the include path for "quoted" includes.
10025 const FileEntry
*CurFile
= PP
.getCurrentFileLexer()->getFileEntry();
10026 if (CurFile
&& CurFile
->getDir())
10027 AddFilesFromIncludeDir(CurFile
->getDir()->getName(), false,
10028 DirectoryLookup::LT_NormalDir
);
10029 for (const auto &D
: make_range(S
.quoted_dir_begin(), S
.quoted_dir_end()))
10030 AddFilesFromDirLookup(D
, false);
10032 for (const auto &D
: make_range(S
.angled_dir_begin(), S
.angled_dir_end()))
10033 AddFilesFromDirLookup(D
, false);
10034 for (const auto &D
: make_range(S
.system_dir_begin(), S
.system_dir_end()))
10035 AddFilesFromDirLookup(D
, true);
10037 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
10038 Results
.data(), Results
.size());
10041 void Sema::CodeCompleteNaturalLanguage() {
10042 HandleCodeCompleteResults(this, CodeCompleter
,
10043 CodeCompletionContext::CCC_NaturalLanguage
, nullptr,
10047 void Sema::CodeCompleteAvailabilityPlatformName() {
10048 ResultBuilder
Results(*this, CodeCompleter
->getAllocator(),
10049 CodeCompleter
->getCodeCompletionTUInfo(),
10050 CodeCompletionContext::CCC_Other
);
10051 Results
.EnterNewScope();
10052 static const char *Platforms
[] = {"macOS", "iOS", "watchOS", "tvOS"};
10053 for (const char *Platform
: llvm::makeArrayRef(Platforms
)) {
10054 Results
.AddResult(CodeCompletionResult(Platform
));
10055 Results
.AddResult(CodeCompletionResult(Results
.getAllocator().CopyString(
10056 Twine(Platform
) + "ApplicationExtension")));
10058 Results
.ExitScope();
10059 HandleCodeCompleteResults(this, CodeCompleter
, Results
.getCompletionContext(),
10060 Results
.data(), Results
.size());
10063 void Sema::GatherGlobalCodeCompletions(
10064 CodeCompletionAllocator
&Allocator
, CodeCompletionTUInfo
&CCTUInfo
,
10065 SmallVectorImpl
<CodeCompletionResult
> &Results
) {
10066 ResultBuilder
Builder(*this, Allocator
, CCTUInfo
,
10067 CodeCompletionContext::CCC_Recovery
);
10068 if (!CodeCompleter
|| CodeCompleter
->includeGlobals()) {
10069 CodeCompletionDeclConsumer
Consumer(Builder
,
10070 Context
.getTranslationUnitDecl());
10071 LookupVisibleDecls(Context
.getTranslationUnitDecl(), LookupAnyName
,
10073 !CodeCompleter
|| CodeCompleter
->loadExternal());
10076 if (!CodeCompleter
|| CodeCompleter
->includeMacros())
10077 AddMacroResults(PP
, Builder
,
10078 !CodeCompleter
|| CodeCompleter
->loadExternal(), true);
10081 Results
.insert(Results
.end(), Builder
.data(),
10082 Builder
.data() + Builder
.size());