1 //===---------------- SemaCodeComplete.cpp - Code Completion ----*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the code-completion semantic actions.
12 //===----------------------------------------------------------------------===//
13 #include "clang/Sema/SemaInternal.h"
14 #include "clang/AST/DeclObjC.h"
15 #include "clang/AST/ExprCXX.h"
16 #include "clang/AST/ExprObjC.h"
17 #include "clang/Basic/CharInfo.h"
18 #include "clang/Lex/HeaderSearch.h"
19 #include "clang/Lex/MacroInfo.h"
20 #include "clang/Lex/Preprocessor.h"
21 #include "clang/Sema/CodeCompleteConsumer.h"
22 #include "clang/Sema/Lookup.h"
23 #include "clang/Sema/Overload.h"
24 #include "clang/Sema/Scope.h"
25 #include "clang/Sema/ScopeInfo.h"
26 #include "llvm/ADT/DenseSet.h"
27 #include "llvm/ADT/SmallBitVector.h"
28 #include "llvm/ADT/SmallPtrSet.h"
29 #include "llvm/ADT/SmallString.h"
30 #include "llvm/ADT/StringExtras.h"
31 #include "llvm/ADT/StringSwitch.h"
32 #include "llvm/ADT/Twine.h"
37 using namespace clang;
41 /// \brief A container of code-completion results.
44 /// \brief The type of a name-lookup filter, which can be provided to the
45 /// name-lookup routines to specify which declarations should be included in
46 /// the result set (when it returns true) and which declarations should be
47 /// filtered out (returns false).
48 typedef bool (ResultBuilder::*LookupFilter)(const NamedDecl *) const;
50 typedef CodeCompletionResult Result;
53 /// \brief The actual results we have found.
54 std::vector<Result> Results;
56 /// \brief A record of all of the declarations we have found and placed
57 /// into the result set, used to ensure that no declaration ever gets into
58 /// the result set twice.
59 llvm::SmallPtrSet<const Decl*, 16> AllDeclsFound;
61 typedef std::pair<const NamedDecl *, unsigned> DeclIndexPair;
63 /// \brief An entry in the shadow map, which is optimized to store
64 /// a single (declaration, index) mapping (the common case) but
65 /// can also store a list of (declaration, index) mappings.
66 class ShadowMapEntry {
67 typedef SmallVector<DeclIndexPair, 4> DeclIndexPairVector;
69 /// \brief Contains either the solitary NamedDecl * or a vector
70 /// of (declaration, index) pairs.
71 llvm::PointerUnion<const NamedDecl *, DeclIndexPairVector*> DeclOrVector;
73 /// \brief When the entry contains a single declaration, this is
74 /// the index associated with that entry.
75 unsigned SingleDeclIndex;
78 ShadowMapEntry() : DeclOrVector(), SingleDeclIndex(0) { }
80 void Add(const NamedDecl *ND, unsigned Index) {
81 if (DeclOrVector.isNull()) {
82 // 0 - > 1 elements: just set the single element information.
84 SingleDeclIndex = Index;
88 if (const NamedDecl *PrevND =
89 DeclOrVector.dyn_cast<const NamedDecl *>()) {
90 // 1 -> 2 elements: create the vector of results and push in the
91 // existing declaration.
92 DeclIndexPairVector *Vec = new DeclIndexPairVector;
93 Vec->push_back(DeclIndexPair(PrevND, SingleDeclIndex));
97 // Add the new element to the end of the vector.
98 DeclOrVector.get<DeclIndexPairVector*>()->push_back(
99 DeclIndexPair(ND, Index));
103 if (DeclIndexPairVector *Vec
104 = DeclOrVector.dyn_cast<DeclIndexPairVector *>()) {
106 DeclOrVector = ((NamedDecl *)nullptr);
112 iterator begin() const;
113 iterator end() const;
116 /// \brief A mapping from declaration names to the declarations that have
117 /// this name within a particular scope and their index within the list of
119 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
121 /// \brief The semantic analysis object for which results are being
125 /// \brief The allocator used to allocate new code-completion strings.
126 CodeCompletionAllocator &Allocator;
128 CodeCompletionTUInfo &CCTUInfo;
130 /// \brief If non-NULL, a filter function used to remove any code-completion
131 /// results that are not desirable.
134 /// \brief Whether we should allow declarations as
135 /// nested-name-specifiers that would otherwise be filtered out.
136 bool AllowNestedNameSpecifiers;
138 /// \brief If set, the type that we would prefer our resulting value
139 /// declarations to have.
141 /// Closely matching the preferred type gives a boost to a result's
143 CanQualType PreferredType;
145 /// \brief A list of shadow maps, which is used to model name hiding at
146 /// different levels of, e.g., the inheritance hierarchy.
147 std::list<ShadowMap> ShadowMaps;
149 /// \brief If we're potentially referring to a C++ member function, the set
150 /// of qualifiers applied to the object type.
151 Qualifiers ObjectTypeQualifiers;
153 /// \brief Whether the \p ObjectTypeQualifiers field is active.
154 bool HasObjectTypeQualifiers;
156 /// \brief The selector that we prefer.
157 Selector PreferredSelector;
159 /// \brief The completion context in which we are gathering results.
160 CodeCompletionContext CompletionContext;
162 /// \brief If we are in an instance method definition, the \@implementation
164 ObjCImplementationDecl *ObjCImplementation;
166 void AdjustResultPriorityForDecl(Result &R);
168 void MaybeAddConstructorResults(Result R);
171 explicit ResultBuilder(Sema &SemaRef, CodeCompletionAllocator &Allocator,
172 CodeCompletionTUInfo &CCTUInfo,
173 const CodeCompletionContext &CompletionContext,
174 LookupFilter Filter = nullptr)
175 : SemaRef(SemaRef), Allocator(Allocator), CCTUInfo(CCTUInfo),
177 AllowNestedNameSpecifiers(false), HasObjectTypeQualifiers(false),
178 CompletionContext(CompletionContext),
179 ObjCImplementation(nullptr)
181 // If this is an Objective-C instance method definition, dig out the
182 // corresponding implementation.
183 switch (CompletionContext.getKind()) {
184 case CodeCompletionContext::CCC_Expression:
185 case CodeCompletionContext::CCC_ObjCMessageReceiver:
186 case CodeCompletionContext::CCC_ParenthesizedExpression:
187 case CodeCompletionContext::CCC_Statement:
188 case CodeCompletionContext::CCC_Recovery:
189 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl())
190 if (Method->isInstanceMethod())
191 if (ObjCInterfaceDecl *Interface = Method->getClassInterface())
192 ObjCImplementation = Interface->getImplementation();
200 /// \brief Determine the priority for a reference to the given declaration.
201 unsigned getBasePriority(const NamedDecl *D);
203 /// \brief Whether we should include code patterns in the completion
205 bool includeCodePatterns() const {
206 return SemaRef.CodeCompleter &&
207 SemaRef.CodeCompleter->includeCodePatterns();
210 /// \brief Set the filter used for code-completion results.
211 void setFilter(LookupFilter Filter) {
212 this->Filter = Filter;
215 Result *data() { return Results.empty()? nullptr : &Results.front(); }
216 unsigned size() const { return Results.size(); }
217 bool empty() const { return Results.empty(); }
219 /// \brief Specify the preferred type.
220 void setPreferredType(QualType T) {
221 PreferredType = SemaRef.Context.getCanonicalType(T);
224 /// \brief Set the cv-qualifiers on the object type, for us in filtering
225 /// calls to member functions.
227 /// When there are qualifiers in this set, they will be used to filter
228 /// out member functions that aren't available (because there will be a
229 /// cv-qualifier mismatch) or prefer functions with an exact qualifier
231 void setObjectTypeQualifiers(Qualifiers Quals) {
232 ObjectTypeQualifiers = Quals;
233 HasObjectTypeQualifiers = true;
236 /// \brief Set the preferred selector.
238 /// When an Objective-C method declaration result is added, and that
239 /// method's selector matches this preferred selector, we give that method
240 /// a slight priority boost.
241 void setPreferredSelector(Selector Sel) {
242 PreferredSelector = Sel;
245 /// \brief Retrieve the code-completion context for which results are
247 const CodeCompletionContext &getCompletionContext() const {
248 return CompletionContext;
251 /// \brief Specify whether nested-name-specifiers are allowed.
252 void allowNestedNameSpecifiers(bool Allow = true) {
253 AllowNestedNameSpecifiers = Allow;
256 /// \brief Return the semantic analysis object for which we are collecting
257 /// code completion results.
258 Sema &getSema() const { return SemaRef; }
260 /// \brief Retrieve the allocator used to allocate code completion strings.
261 CodeCompletionAllocator &getAllocator() const { return Allocator; }
263 CodeCompletionTUInfo &getCodeCompletionTUInfo() const { return CCTUInfo; }
265 /// \brief Determine whether the given declaration is at all interesting
266 /// as a code-completion result.
268 /// \param ND the declaration that we are inspecting.
270 /// \param AsNestedNameSpecifier will be set true if this declaration is
271 /// only interesting when it is a nested-name-specifier.
272 bool isInterestingDecl(const NamedDecl *ND,
273 bool &AsNestedNameSpecifier) const;
275 /// \brief Check whether the result is hidden by the Hiding declaration.
277 /// \returns true if the result is hidden and cannot be found, false if
278 /// the hidden result could still be found. When false, \p R may be
279 /// modified to describe how the result can be found (e.g., via extra
281 bool CheckHiddenResult(Result &R, DeclContext *CurContext,
282 const NamedDecl *Hiding);
284 /// \brief Add a new result to this result set (if it isn't already in one
285 /// of the shadow maps), or replace an existing result (for, e.g., a
288 /// \param R the result to add (if it is unique).
290 /// \param CurContext the context in which this result will be named.
291 void MaybeAddResult(Result R, DeclContext *CurContext = nullptr);
293 /// \brief Add a new result to this result set, where we already know
294 /// the hiding declaration (if any).
296 /// \param R the result to add (if it is unique).
298 /// \param CurContext the context in which this result will be named.
300 /// \param Hiding the declaration that hides the result.
302 /// \param InBaseClass whether the result was found in a base
303 /// class of the searched context.
304 void AddResult(Result R, DeclContext *CurContext, NamedDecl *Hiding,
307 /// \brief Add a new non-declaration result to this result set.
308 void AddResult(Result R);
310 /// \brief Enter into a new scope.
311 void EnterNewScope();
313 /// \brief Exit from the current scope.
316 /// \brief Ignore this declaration, if it is seen again.
317 void Ignore(const Decl *D) { AllDeclsFound.insert(D->getCanonicalDecl()); }
319 /// \name Name lookup predicates
321 /// These predicates can be passed to the name lookup functions to filter the
322 /// results of name lookup. All of the predicates have the same type, so that
325 bool IsOrdinaryName(const NamedDecl *ND) const;
326 bool IsOrdinaryNonTypeName(const NamedDecl *ND) const;
327 bool IsIntegralConstantValue(const NamedDecl *ND) const;
328 bool IsOrdinaryNonValueName(const NamedDecl *ND) const;
329 bool IsNestedNameSpecifier(const NamedDecl *ND) const;
330 bool IsEnum(const NamedDecl *ND) const;
331 bool IsClassOrStruct(const NamedDecl *ND) const;
332 bool IsUnion(const NamedDecl *ND) const;
333 bool IsNamespace(const NamedDecl *ND) const;
334 bool IsNamespaceOrAlias(const NamedDecl *ND) const;
335 bool IsType(const NamedDecl *ND) const;
336 bool IsMember(const NamedDecl *ND) const;
337 bool IsObjCIvar(const NamedDecl *ND) const;
338 bool IsObjCMessageReceiver(const NamedDecl *ND) const;
339 bool IsObjCMessageReceiverOrLambdaCapture(const NamedDecl *ND) const;
340 bool IsObjCCollection(const NamedDecl *ND) const;
341 bool IsImpossibleToSatisfy(const NamedDecl *ND) const;
346 class ResultBuilder::ShadowMapEntry::iterator {
347 llvm::PointerUnion<const NamedDecl *, const DeclIndexPair *> DeclOrIterator;
348 unsigned SingleDeclIndex;
351 typedef DeclIndexPair value_type;
352 typedef value_type reference;
353 typedef std::ptrdiff_t difference_type;
354 typedef std::input_iterator_tag iterator_category;
360 pointer(const DeclIndexPair &Value) : Value(Value) { }
362 const DeclIndexPair *operator->() const {
367 iterator() : DeclOrIterator((NamedDecl *)nullptr), SingleDeclIndex(0) {}
369 iterator(const NamedDecl *SingleDecl, unsigned Index)
370 : DeclOrIterator(SingleDecl), SingleDeclIndex(Index) { }
372 iterator(const DeclIndexPair *Iterator)
373 : DeclOrIterator(Iterator), SingleDeclIndex(0) { }
375 iterator &operator++() {
376 if (DeclOrIterator.is<const NamedDecl *>()) {
377 DeclOrIterator = (NamedDecl *)nullptr;
382 const DeclIndexPair *I = DeclOrIterator.get<const DeclIndexPair*>();
388 /*iterator operator++(int) {
394 reference operator*() const {
395 if (const NamedDecl *ND = DeclOrIterator.dyn_cast<const NamedDecl *>())
396 return reference(ND, SingleDeclIndex);
398 return *DeclOrIterator.get<const DeclIndexPair*>();
401 pointer operator->() const {
402 return pointer(**this);
405 friend bool operator==(const iterator &X, const iterator &Y) {
406 return X.DeclOrIterator.getOpaqueValue()
407 == Y.DeclOrIterator.getOpaqueValue() &&
408 X.SingleDeclIndex == Y.SingleDeclIndex;
411 friend bool operator!=(const iterator &X, const iterator &Y) {
416 ResultBuilder::ShadowMapEntry::iterator
417 ResultBuilder::ShadowMapEntry::begin() const {
418 if (DeclOrVector.isNull())
421 if (const NamedDecl *ND = DeclOrVector.dyn_cast<const NamedDecl *>())
422 return iterator(ND, SingleDeclIndex);
424 return iterator(DeclOrVector.get<DeclIndexPairVector *>()->begin());
427 ResultBuilder::ShadowMapEntry::iterator
428 ResultBuilder::ShadowMapEntry::end() const {
429 if (DeclOrVector.is<const NamedDecl *>() || DeclOrVector.isNull())
432 return iterator(DeclOrVector.get<DeclIndexPairVector *>()->end());
435 /// \brief Compute the qualification required to get from the current context
436 /// (\p CurContext) to the target context (\p TargetContext).
438 /// \param Context the AST context in which the qualification will be used.
440 /// \param CurContext the context where an entity is being named, which is
441 /// typically based on the current scope.
443 /// \param TargetContext the context in which the named entity actually
446 /// \returns a nested name specifier that refers into the target context, or
447 /// NULL if no qualification is needed.
448 static NestedNameSpecifier *
449 getRequiredQualification(ASTContext &Context,
450 const DeclContext *CurContext,
451 const DeclContext *TargetContext) {
452 SmallVector<const DeclContext *, 4> TargetParents;
454 for (const DeclContext *CommonAncestor = TargetContext;
455 CommonAncestor && !CommonAncestor->Encloses(CurContext);
456 CommonAncestor = CommonAncestor->getLookupParent()) {
457 if (CommonAncestor->isTransparentContext() ||
458 CommonAncestor->isFunctionOrMethod())
461 TargetParents.push_back(CommonAncestor);
464 NestedNameSpecifier *Result = nullptr;
465 while (!TargetParents.empty()) {
466 const DeclContext *Parent = TargetParents.pop_back_val();
468 if (const NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Parent)) {
469 if (!Namespace->getIdentifier())
472 Result = NestedNameSpecifier::Create(Context, Result, Namespace);
474 else if (const TagDecl *TD = dyn_cast<TagDecl>(Parent))
475 Result = NestedNameSpecifier::Create(Context, Result,
477 Context.getTypeDeclType(TD).getTypePtr());
482 /// Determine whether \p Id is a name reserved for the implementation (C99
483 /// 7.1.3, C++ [lib.global.names]).
484 static bool isReservedName(const IdentifierInfo *Id,
485 bool doubleUnderscoreOnly = false) {
486 if (Id->getLength() < 2)
488 const char *Name = Id->getNameStart();
489 return Name[0] == '_' &&
490 (Name[1] == '_' || (Name[1] >= 'A' && Name[1] <= 'Z' &&
491 !doubleUnderscoreOnly));
494 // Some declarations have reserved names that we don't want to ever show.
495 // Filter out names reserved for the implementation if they come from a
497 static bool shouldIgnoreDueToReservedName(const NamedDecl *ND, Sema &SemaRef) {
498 const IdentifierInfo *Id = ND->getIdentifier();
502 // Ignore reserved names for compiler provided decls.
503 if (isReservedName(Id) && ND->getLocation().isInvalid())
506 // For system headers ignore only double-underscore names.
507 // This allows for system headers providing private symbols with a single
509 if (isReservedName(Id, /*doubleUnderscoreOnly=*/true) &&
510 SemaRef.SourceMgr.isInSystemHeader(
511 SemaRef.SourceMgr.getSpellingLoc(ND->getLocation())))
517 bool ResultBuilder::isInterestingDecl(const NamedDecl *ND,
518 bool &AsNestedNameSpecifier) const {
519 AsNestedNameSpecifier = false;
522 ND = ND->getUnderlyingDecl();
524 // Skip unnamed entities.
525 if (!ND->getDeclName())
528 // Friend declarations and declarations introduced due to friends are never
530 if (ND->getFriendObjectKind() == Decl::FOK_Undeclared)
533 // Class template (partial) specializations are never added as results.
534 if (isa<ClassTemplateSpecializationDecl>(ND) ||
535 isa<ClassTemplatePartialSpecializationDecl>(ND))
538 // Using declarations themselves are never added as results.
539 if (isa<UsingDecl>(ND))
542 if (shouldIgnoreDueToReservedName(ND, SemaRef))
545 if (Filter == &ResultBuilder::IsNestedNameSpecifier ||
546 (isa<NamespaceDecl>(ND) &&
547 Filter != &ResultBuilder::IsNamespace &&
548 Filter != &ResultBuilder::IsNamespaceOrAlias &&
550 AsNestedNameSpecifier = true;
552 // Filter out any unwanted results.
553 if (Filter && !(this->*Filter)(Named)) {
554 // Check whether it is interesting as a nested-name-specifier.
555 if (AllowNestedNameSpecifiers && SemaRef.getLangOpts().CPlusPlus &&
556 IsNestedNameSpecifier(ND) &&
557 (Filter != &ResultBuilder::IsMember ||
558 (isa<CXXRecordDecl>(ND) &&
559 cast<CXXRecordDecl>(ND)->isInjectedClassName()))) {
560 AsNestedNameSpecifier = true;
566 // ... then it must be interesting!
570 bool ResultBuilder::CheckHiddenResult(Result &R, DeclContext *CurContext,
571 const NamedDecl *Hiding) {
572 // In C, there is no way to refer to a hidden name.
573 // FIXME: This isn't true; we can find a tag name hidden by an ordinary
574 // name if we introduce the tag type.
575 if (!SemaRef.getLangOpts().CPlusPlus)
578 const DeclContext *HiddenCtx =
579 R.Declaration->getDeclContext()->getRedeclContext();
581 // There is no way to qualify a name declared in a function or method.
582 if (HiddenCtx->isFunctionOrMethod())
585 if (HiddenCtx == Hiding->getDeclContext()->getRedeclContext())
588 // We can refer to the result with the appropriate qualification. Do it.
590 R.QualifierIsInformative = false;
593 R.Qualifier = getRequiredQualification(SemaRef.Context,
595 R.Declaration->getDeclContext());
599 /// \brief A simplified classification of types used to determine whether two
600 /// types are "similar enough" when adjusting priorities.
601 SimplifiedTypeClass clang::getSimplifiedTypeClass(CanQualType T) {
602 switch (T->getTypeClass()) {
604 switch (cast<BuiltinType>(T)->getKind()) {
605 case BuiltinType::Void:
608 case BuiltinType::NullPtr:
611 case BuiltinType::Overload:
612 case BuiltinType::Dependent:
615 case BuiltinType::ObjCId:
616 case BuiltinType::ObjCClass:
617 case BuiltinType::ObjCSel:
618 return STC_ObjectiveC;
621 return STC_Arithmetic;
625 return STC_Arithmetic;
630 case Type::BlockPointer:
633 case Type::LValueReference:
634 case Type::RValueReference:
635 return getSimplifiedTypeClass(T->getAs<ReferenceType>()->getPointeeType());
637 case Type::ConstantArray:
638 case Type::IncompleteArray:
639 case Type::VariableArray:
640 case Type::DependentSizedArray:
643 case Type::DependentSizedExtVector:
645 case Type::ExtVector:
646 return STC_Arithmetic;
648 case Type::FunctionProto:
649 case Type::FunctionNoProto:
656 return STC_Arithmetic;
658 case Type::ObjCObject:
659 case Type::ObjCInterface:
660 case Type::ObjCObjectPointer:
661 return STC_ObjectiveC;
668 /// \brief Get the type that a given expression will have if this declaration
669 /// is used as an expression in its "typical" code-completion form.
670 QualType clang::getDeclUsageType(ASTContext &C, const NamedDecl *ND) {
671 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
673 if (const TypeDecl *Type = dyn_cast<TypeDecl>(ND))
674 return C.getTypeDeclType(Type);
675 if (const ObjCInterfaceDecl *Iface = dyn_cast<ObjCInterfaceDecl>(ND))
676 return C.getObjCInterfaceType(Iface);
679 if (const FunctionDecl *Function = ND->getAsFunction())
680 T = Function->getCallResultType();
681 else if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND))
682 T = Method->getSendResultType();
683 else if (const EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND))
684 T = C.getTypeDeclType(cast<EnumDecl>(Enumerator->getDeclContext()));
685 else if (const ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND))
686 T = Property->getType();
687 else if (const ValueDecl *Value = dyn_cast<ValueDecl>(ND))
688 T = Value->getType();
692 // Dig through references, function pointers, and block pointers to
693 // get down to the likely type of an expression when the entity is
696 if (const ReferenceType *Ref = T->getAs<ReferenceType>()) {
697 T = Ref->getPointeeType();
701 if (const PointerType *Pointer = T->getAs<PointerType>()) {
702 if (Pointer->getPointeeType()->isFunctionType()) {
703 T = Pointer->getPointeeType();
710 if (const BlockPointerType *Block = T->getAs<BlockPointerType>()) {
711 T = Block->getPointeeType();
715 if (const FunctionType *Function = T->getAs<FunctionType>()) {
716 T = Function->getReturnType();
726 unsigned ResultBuilder::getBasePriority(const NamedDecl *ND) {
730 // Context-based decisions.
731 const DeclContext *LexicalDC = ND->getLexicalDeclContext();
732 if (LexicalDC->isFunctionOrMethod()) {
733 // _cmd is relatively rare
734 if (const ImplicitParamDecl *ImplicitParam =
735 dyn_cast<ImplicitParamDecl>(ND))
736 if (ImplicitParam->getIdentifier() &&
737 ImplicitParam->getIdentifier()->isStr("_cmd"))
740 return CCP_LocalDeclaration;
743 const DeclContext *DC = ND->getDeclContext()->getRedeclContext();
744 if (DC->isRecord() || isa<ObjCContainerDecl>(DC))
745 return CCP_MemberDeclaration;
747 // Content-based decisions.
748 if (isa<EnumConstantDecl>(ND))
751 // Use CCP_Type for type declarations unless we're in a statement, Objective-C
752 // message receiver, or parenthesized expression context. There, it's as
753 // likely that the user will want to write a type as other declarations.
754 if ((isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) &&
755 !(CompletionContext.getKind() == CodeCompletionContext::CCC_Statement ||
756 CompletionContext.getKind()
757 == CodeCompletionContext::CCC_ObjCMessageReceiver ||
758 CompletionContext.getKind()
759 == CodeCompletionContext::CCC_ParenthesizedExpression))
762 return CCP_Declaration;
765 void ResultBuilder::AdjustResultPriorityForDecl(Result &R) {
766 // If this is an Objective-C method declaration whose selector matches our
767 // preferred selector, give it a priority boost.
768 if (!PreferredSelector.isNull())
769 if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(R.Declaration))
770 if (PreferredSelector == Method->getSelector())
771 R.Priority += CCD_SelectorMatch;
773 // If we have a preferred type, adjust the priority for results with exactly-
774 // matching or nearly-matching types.
775 if (!PreferredType.isNull()) {
776 QualType T = getDeclUsageType(SemaRef.Context, R.Declaration);
778 CanQualType TC = SemaRef.Context.getCanonicalType(T);
779 // Check for exactly-matching types (modulo qualifiers).
780 if (SemaRef.Context.hasSameUnqualifiedType(PreferredType, TC))
781 R.Priority /= CCF_ExactTypeMatch;
782 // Check for nearly-matching types, based on classification of each.
783 else if ((getSimplifiedTypeClass(PreferredType)
784 == getSimplifiedTypeClass(TC)) &&
785 !(PreferredType->isEnumeralType() && TC->isEnumeralType()))
786 R.Priority /= CCF_SimilarTypeMatch;
791 void ResultBuilder::MaybeAddConstructorResults(Result R) {
792 if (!SemaRef.getLangOpts().CPlusPlus || !R.Declaration ||
793 !CompletionContext.wantConstructorResults())
796 ASTContext &Context = SemaRef.Context;
797 const NamedDecl *D = R.Declaration;
798 const CXXRecordDecl *Record = nullptr;
799 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D))
800 Record = ClassTemplate->getTemplatedDecl();
801 else if ((Record = dyn_cast<CXXRecordDecl>(D))) {
802 // Skip specializations and partial specializations.
803 if (isa<ClassTemplateSpecializationDecl>(Record))
806 // There are no constructors here.
810 Record = Record->getDefinition();
815 QualType RecordTy = Context.getTypeDeclType(Record);
816 DeclarationName ConstructorName
817 = Context.DeclarationNames.getCXXConstructorName(
818 Context.getCanonicalType(RecordTy));
819 DeclContext::lookup_result Ctors = Record->lookup(ConstructorName);
820 for (DeclContext::lookup_iterator I = Ctors.begin(),
824 R.CursorKind = getCursorKindForDecl(R.Declaration);
825 Results.push_back(R);
829 void ResultBuilder::MaybeAddResult(Result R, DeclContext *CurContext) {
830 assert(!ShadowMaps.empty() && "Must enter into a results scope");
832 if (R.Kind != Result::RK_Declaration) {
833 // For non-declaration results, just add the result.
834 Results.push_back(R);
838 // Look through using declarations.
839 if (const UsingShadowDecl *Using =
840 dyn_cast<UsingShadowDecl>(R.Declaration)) {
841 MaybeAddResult(Result(Using->getTargetDecl(),
842 getBasePriority(Using->getTargetDecl()),
848 const Decl *CanonDecl = R.Declaration->getCanonicalDecl();
849 unsigned IDNS = CanonDecl->getIdentifierNamespace();
851 bool AsNestedNameSpecifier = false;
852 if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
855 // C++ constructors are never found by name lookup.
856 if (isa<CXXConstructorDecl>(R.Declaration))
859 ShadowMap &SMap = ShadowMaps.back();
860 ShadowMapEntry::iterator I, IEnd;
861 ShadowMap::iterator NamePos = SMap.find(R.Declaration->getDeclName());
862 if (NamePos != SMap.end()) {
863 I = NamePos->second.begin();
864 IEnd = NamePos->second.end();
867 for (; I != IEnd; ++I) {
868 const NamedDecl *ND = I->first;
869 unsigned Index = I->second;
870 if (ND->getCanonicalDecl() == CanonDecl) {
871 // This is a redeclaration. Always pick the newer declaration.
872 Results[Index].Declaration = R.Declaration;
879 // This is a new declaration in this scope. However, check whether this
880 // declaration name is hidden by a similarly-named declaration in an outer
882 std::list<ShadowMap>::iterator SM, SMEnd = ShadowMaps.end();
884 for (SM = ShadowMaps.begin(); SM != SMEnd; ++SM) {
885 ShadowMapEntry::iterator I, IEnd;
886 ShadowMap::iterator NamePos = SM->find(R.Declaration->getDeclName());
887 if (NamePos != SM->end()) {
888 I = NamePos->second.begin();
889 IEnd = NamePos->second.end();
891 for (; I != IEnd; ++I) {
892 // A tag declaration does not hide a non-tag declaration.
893 if (I->first->hasTagIdentifierNamespace() &&
894 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
895 Decl::IDNS_LocalExtern | Decl::IDNS_ObjCProtocol)))
898 // Protocols are in distinct namespaces from everything else.
899 if (((I->first->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
900 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
901 I->first->getIdentifierNamespace() != IDNS)
904 // The newly-added result is hidden by an entry in the shadow map.
905 if (CheckHiddenResult(R, CurContext, I->first))
912 // Make sure that any given declaration only shows up in the result set once.
913 if (!AllDeclsFound.insert(CanonDecl).second)
916 // If the filter is for nested-name-specifiers, then this result starts a
917 // nested-name-specifier.
918 if (AsNestedNameSpecifier) {
919 R.StartsNestedNameSpecifier = true;
920 R.Priority = CCP_NestedNameSpecifier;
922 AdjustResultPriorityForDecl(R);
924 // If this result is supposed to have an informative qualifier, add one.
925 if (R.QualifierIsInformative && !R.Qualifier &&
926 !R.StartsNestedNameSpecifier) {
927 const DeclContext *Ctx = R.Declaration->getDeclContext();
928 if (const NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
929 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, nullptr,
931 else if (const TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
932 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, nullptr,
933 false, SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
935 R.QualifierIsInformative = false;
938 // Insert this result into the set of results and into the current shadow
940 SMap[R.Declaration->getDeclName()].Add(R.Declaration, Results.size());
941 Results.push_back(R);
943 if (!AsNestedNameSpecifier)
944 MaybeAddConstructorResults(R);
947 void ResultBuilder::AddResult(Result R, DeclContext *CurContext,
948 NamedDecl *Hiding, bool InBaseClass = false) {
949 if (R.Kind != Result::RK_Declaration) {
950 // For non-declaration results, just add the result.
951 Results.push_back(R);
955 // Look through using declarations.
956 if (const UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
957 AddResult(Result(Using->getTargetDecl(),
958 getBasePriority(Using->getTargetDecl()),
964 bool AsNestedNameSpecifier = false;
965 if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
968 // C++ constructors are never found by name lookup.
969 if (isa<CXXConstructorDecl>(R.Declaration))
972 if (Hiding && CheckHiddenResult(R, CurContext, Hiding))
975 // Make sure that any given declaration only shows up in the result set once.
976 if (!AllDeclsFound.insert(R.Declaration->getCanonicalDecl()).second)
979 // If the filter is for nested-name-specifiers, then this result starts a
980 // nested-name-specifier.
981 if (AsNestedNameSpecifier) {
982 R.StartsNestedNameSpecifier = true;
983 R.Priority = CCP_NestedNameSpecifier;
985 else if (Filter == &ResultBuilder::IsMember && !R.Qualifier && InBaseClass &&
986 isa<CXXRecordDecl>(R.Declaration->getDeclContext()
987 ->getRedeclContext()))
988 R.QualifierIsInformative = true;
990 // If this result is supposed to have an informative qualifier, add one.
991 if (R.QualifierIsInformative && !R.Qualifier &&
992 !R.StartsNestedNameSpecifier) {
993 const DeclContext *Ctx = R.Declaration->getDeclContext();
994 if (const NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
995 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, nullptr,
997 else if (const TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
998 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, nullptr, false,
999 SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
1001 R.QualifierIsInformative = false;
1004 // Adjust the priority if this result comes from a base class.
1006 R.Priority += CCD_InBaseClass;
1008 AdjustResultPriorityForDecl(R);
1010 if (HasObjectTypeQualifiers)
1011 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(R.Declaration))
1012 if (Method->isInstance()) {
1013 Qualifiers MethodQuals
1014 = Qualifiers::fromCVRMask(Method->getTypeQualifiers());
1015 if (ObjectTypeQualifiers == MethodQuals)
1016 R.Priority += CCD_ObjectQualifierMatch;
1017 else if (ObjectTypeQualifiers - MethodQuals) {
1018 // The method cannot be invoked, because doing so would drop
1024 // Insert this result into the set of results.
1025 Results.push_back(R);
1027 if (!AsNestedNameSpecifier)
1028 MaybeAddConstructorResults(R);
1031 void ResultBuilder::AddResult(Result R) {
1032 assert(R.Kind != Result::RK_Declaration &&
1033 "Declaration results need more context");
1034 Results.push_back(R);
1037 /// \brief Enter into a new scope.
1038 void ResultBuilder::EnterNewScope() { ShadowMaps.emplace_back(); }
1040 /// \brief Exit from the current scope.
1041 void ResultBuilder::ExitScope() {
1042 for (ShadowMap::iterator E = ShadowMaps.back().begin(),
1043 EEnd = ShadowMaps.back().end();
1046 E->second.Destroy();
1048 ShadowMaps.pop_back();
1051 /// \brief Determines whether this given declaration will be found by
1052 /// ordinary name lookup.
1053 bool ResultBuilder::IsOrdinaryName(const NamedDecl *ND) const {
1054 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
1056 // If name lookup finds a local extern declaration, then we are in a
1057 // context where it behaves like an ordinary name.
1058 unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_LocalExtern;
1059 if (SemaRef.getLangOpts().CPlusPlus)
1060 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
1061 else if (SemaRef.getLangOpts().ObjC1) {
1062 if (isa<ObjCIvarDecl>(ND))
1066 return ND->getIdentifierNamespace() & IDNS;
1069 /// \brief Determines whether this given declaration will be found by
1070 /// ordinary name lookup but is not a type name.
1071 bool ResultBuilder::IsOrdinaryNonTypeName(const NamedDecl *ND) const {
1072 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
1073 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND))
1076 unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_LocalExtern;
1077 if (SemaRef.getLangOpts().CPlusPlus)
1078 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
1079 else if (SemaRef.getLangOpts().ObjC1) {
1080 if (isa<ObjCIvarDecl>(ND))
1084 return ND->getIdentifierNamespace() & IDNS;
1087 bool ResultBuilder::IsIntegralConstantValue(const NamedDecl *ND) const {
1088 if (!IsOrdinaryNonTypeName(ND))
1091 if (const ValueDecl *VD = dyn_cast<ValueDecl>(ND->getUnderlyingDecl()))
1092 if (VD->getType()->isIntegralOrEnumerationType())
1098 /// \brief Determines whether this given declaration will be found by
1099 /// ordinary name lookup.
1100 bool ResultBuilder::IsOrdinaryNonValueName(const NamedDecl *ND) const {
1101 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
1103 unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_LocalExtern;
1104 if (SemaRef.getLangOpts().CPlusPlus)
1105 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace;
1107 return (ND->getIdentifierNamespace() & IDNS) &&
1108 !isa<ValueDecl>(ND) && !isa<FunctionTemplateDecl>(ND) &&
1109 !isa<ObjCPropertyDecl>(ND);
1112 /// \brief Determines whether the given declaration is suitable as the
1113 /// start of a C++ nested-name-specifier, e.g., a class or namespace.
1114 bool ResultBuilder::IsNestedNameSpecifier(const NamedDecl *ND) const {
1115 // Allow us to find class templates, too.
1116 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
1117 ND = ClassTemplate->getTemplatedDecl();
1119 return SemaRef.isAcceptableNestedNameSpecifier(ND);
1122 /// \brief Determines whether the given declaration is an enumeration.
1123 bool ResultBuilder::IsEnum(const NamedDecl *ND) const {
1124 return isa<EnumDecl>(ND);
1127 /// \brief Determines whether the given declaration is a class or struct.
1128 bool ResultBuilder::IsClassOrStruct(const NamedDecl *ND) const {
1129 // Allow us to find class templates, too.
1130 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
1131 ND = ClassTemplate->getTemplatedDecl();
1133 // For purposes of this check, interfaces match too.
1134 if (const RecordDecl *RD = dyn_cast<RecordDecl>(ND))
1135 return RD->getTagKind() == TTK_Class ||
1136 RD->getTagKind() == TTK_Struct ||
1137 RD->getTagKind() == TTK_Interface;
1142 /// \brief Determines whether the given declaration is a union.
1143 bool ResultBuilder::IsUnion(const NamedDecl *ND) const {
1144 // Allow us to find class templates, too.
1145 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
1146 ND = ClassTemplate->getTemplatedDecl();
1148 if (const RecordDecl *RD = dyn_cast<RecordDecl>(ND))
1149 return RD->getTagKind() == TTK_Union;
1154 /// \brief Determines whether the given declaration is a namespace.
1155 bool ResultBuilder::IsNamespace(const NamedDecl *ND) const {
1156 return isa<NamespaceDecl>(ND);
1159 /// \brief Determines whether the given declaration is a namespace or
1160 /// namespace alias.
1161 bool ResultBuilder::IsNamespaceOrAlias(const NamedDecl *ND) const {
1162 return isa<NamespaceDecl>(ND->getUnderlyingDecl());
1165 /// \brief Determines whether the given declaration is a type.
1166 bool ResultBuilder::IsType(const NamedDecl *ND) const {
1167 ND = ND->getUnderlyingDecl();
1168 return isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
1171 /// \brief Determines which members of a class should be visible via
1172 /// "." or "->". Only value declarations, nested name specifiers, and
1173 /// using declarations thereof should show up.
1174 bool ResultBuilder::IsMember(const NamedDecl *ND) const {
1175 ND = ND->getUnderlyingDecl();
1176 return isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND) ||
1177 isa<ObjCPropertyDecl>(ND);
1180 static bool isObjCReceiverType(ASTContext &C, QualType T) {
1181 T = C.getCanonicalType(T);
1182 switch (T->getTypeClass()) {
1183 case Type::ObjCObject:
1184 case Type::ObjCInterface:
1185 case Type::ObjCObjectPointer:
1189 switch (cast<BuiltinType>(T)->getKind()) {
1190 case BuiltinType::ObjCId:
1191 case BuiltinType::ObjCClass:
1192 case BuiltinType::ObjCSel:
1204 if (!C.getLangOpts().CPlusPlus)
1207 // FIXME: We could perform more analysis here to determine whether a
1208 // particular class type has any conversions to Objective-C types. For now,
1209 // just accept all class types.
1210 return T->isDependentType() || T->isRecordType();
1213 bool ResultBuilder::IsObjCMessageReceiver(const NamedDecl *ND) const {
1214 QualType T = getDeclUsageType(SemaRef.Context, ND);
1218 T = SemaRef.Context.getBaseElementType(T);
1219 return isObjCReceiverType(SemaRef.Context, T);
1222 bool ResultBuilder::IsObjCMessageReceiverOrLambdaCapture(const NamedDecl *ND) const {
1223 if (IsObjCMessageReceiver(ND))
1226 const VarDecl *Var = dyn_cast<VarDecl>(ND);
1230 return Var->hasLocalStorage() && !Var->hasAttr<BlocksAttr>();
1233 bool ResultBuilder::IsObjCCollection(const NamedDecl *ND) const {
1234 if ((SemaRef.getLangOpts().CPlusPlus && !IsOrdinaryName(ND)) ||
1235 (!SemaRef.getLangOpts().CPlusPlus && !IsOrdinaryNonTypeName(ND)))
1238 QualType T = getDeclUsageType(SemaRef.Context, ND);
1242 T = SemaRef.Context.getBaseElementType(T);
1243 return T->isObjCObjectType() || T->isObjCObjectPointerType() ||
1244 T->isObjCIdType() ||
1245 (SemaRef.getLangOpts().CPlusPlus && T->isRecordType());
1248 bool ResultBuilder::IsImpossibleToSatisfy(const NamedDecl *ND) const {
1252 /// \brief Determines whether the given declaration is an Objective-C
1253 /// instance variable.
1254 bool ResultBuilder::IsObjCIvar(const NamedDecl *ND) const {
1255 return isa<ObjCIvarDecl>(ND);
1259 /// \brief Visible declaration consumer that adds a code-completion result
1260 /// for each visible declaration.
1261 class CodeCompletionDeclConsumer : public VisibleDeclConsumer {
1262 ResultBuilder &Results;
1263 DeclContext *CurContext;
1266 CodeCompletionDeclConsumer(ResultBuilder &Results, DeclContext *CurContext)
1267 : Results(Results), CurContext(CurContext) { }
1269 void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
1270 bool InBaseClass) override {
1271 bool Accessible = true;
1273 Accessible = Results.getSema().IsSimplyAccessible(ND, Ctx);
1275 ResultBuilder::Result Result(ND, Results.getBasePriority(ND), nullptr,
1277 Results.AddResult(Result, CurContext, Hiding, InBaseClass);
1282 /// \brief Add type specifiers for the current language as keyword results.
1283 static void AddTypeSpecifierResults(const LangOptions &LangOpts,
1284 ResultBuilder &Results) {
1285 typedef CodeCompletionResult Result;
1286 Results.AddResult(Result("short", CCP_Type));
1287 Results.AddResult(Result("long", CCP_Type));
1288 Results.AddResult(Result("signed", CCP_Type));
1289 Results.AddResult(Result("unsigned", CCP_Type));
1290 Results.AddResult(Result("void", CCP_Type));
1291 Results.AddResult(Result("char", CCP_Type));
1292 Results.AddResult(Result("int", CCP_Type));
1293 Results.AddResult(Result("float", CCP_Type));
1294 Results.AddResult(Result("double", CCP_Type));
1295 Results.AddResult(Result("enum", CCP_Type));
1296 Results.AddResult(Result("struct", CCP_Type));
1297 Results.AddResult(Result("union", CCP_Type));
1298 Results.AddResult(Result("const", CCP_Type));
1299 Results.AddResult(Result("volatile", CCP_Type));
1303 Results.AddResult(Result("_Complex", CCP_Type));
1304 Results.AddResult(Result("_Imaginary", CCP_Type));
1305 Results.AddResult(Result("_Bool", CCP_Type));
1306 Results.AddResult(Result("restrict", CCP_Type));
1309 CodeCompletionBuilder Builder(Results.getAllocator(),
1310 Results.getCodeCompletionTUInfo());
1311 if (LangOpts.CPlusPlus) {
1313 Results.AddResult(Result("bool", CCP_Type +
1314 (LangOpts.ObjC1? CCD_bool_in_ObjC : 0)));
1315 Results.AddResult(Result("class", CCP_Type));
1316 Results.AddResult(Result("wchar_t", CCP_Type));
1318 // typename qualified-id
1319 Builder.AddTypedTextChunk("typename");
1320 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1321 Builder.AddPlaceholderChunk("qualifier");
1322 Builder.AddTextChunk("::");
1323 Builder.AddPlaceholderChunk("name");
1324 Results.AddResult(Result(Builder.TakeString()));
1326 if (LangOpts.CPlusPlus11) {
1327 Results.AddResult(Result("auto", CCP_Type));
1328 Results.AddResult(Result("char16_t", CCP_Type));
1329 Results.AddResult(Result("char32_t", CCP_Type));
1331 Builder.AddTypedTextChunk("decltype");
1332 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1333 Builder.AddPlaceholderChunk("expression");
1334 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1335 Results.AddResult(Result(Builder.TakeString()));
1338 Results.AddResult(Result("__auto_type", CCP_Type));
1341 if (LangOpts.GNUMode) {
1342 // FIXME: Enable when we actually support decimal floating point.
1343 // Results.AddResult(Result("_Decimal32"));
1344 // Results.AddResult(Result("_Decimal64"));
1345 // Results.AddResult(Result("_Decimal128"));
1347 Builder.AddTypedTextChunk("typeof");
1348 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1349 Builder.AddPlaceholderChunk("expression");
1350 Results.AddResult(Result(Builder.TakeString()));
1352 Builder.AddTypedTextChunk("typeof");
1353 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1354 Builder.AddPlaceholderChunk("type");
1355 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1356 Results.AddResult(Result(Builder.TakeString()));
1360 Results.AddResult(Result("_Nonnull", CCP_Type));
1361 Results.AddResult(Result("_Null_unspecified", CCP_Type));
1362 Results.AddResult(Result("_Nullable", CCP_Type));
1365 static void AddStorageSpecifiers(Sema::ParserCompletionContext CCC,
1366 const LangOptions &LangOpts,
1367 ResultBuilder &Results) {
1368 typedef CodeCompletionResult Result;
1369 // Note: we don't suggest either "auto" or "register", because both
1370 // are pointless as storage specifiers. Elsewhere, we suggest "auto"
1371 // in C++0x as a type specifier.
1372 Results.AddResult(Result("extern"));
1373 Results.AddResult(Result("static"));
1375 if (LangOpts.CPlusPlus11) {
1376 CodeCompletionAllocator &Allocator = Results.getAllocator();
1377 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
1380 Builder.AddTypedTextChunk("alignas");
1381 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1382 Builder.AddPlaceholderChunk("expression");
1383 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1384 Results.AddResult(Result(Builder.TakeString()));
1386 Results.AddResult(Result("constexpr"));
1387 Results.AddResult(Result("thread_local"));
1391 static void AddFunctionSpecifiers(Sema::ParserCompletionContext CCC,
1392 const LangOptions &LangOpts,
1393 ResultBuilder &Results) {
1394 typedef CodeCompletionResult Result;
1396 case Sema::PCC_Class:
1397 case Sema::PCC_MemberTemplate:
1398 if (LangOpts.CPlusPlus) {
1399 Results.AddResult(Result("explicit"));
1400 Results.AddResult(Result("friend"));
1401 Results.AddResult(Result("mutable"));
1402 Results.AddResult(Result("virtual"));
1406 case Sema::PCC_ObjCInterface:
1407 case Sema::PCC_ObjCImplementation:
1408 case Sema::PCC_Namespace:
1409 case Sema::PCC_Template:
1410 if (LangOpts.CPlusPlus || LangOpts.C99)
1411 Results.AddResult(Result("inline"));
1414 case Sema::PCC_ObjCInstanceVariableList:
1415 case Sema::PCC_Expression:
1416 case Sema::PCC_Statement:
1417 case Sema::PCC_ForInit:
1418 case Sema::PCC_Condition:
1419 case Sema::PCC_RecoveryInFunction:
1420 case Sema::PCC_Type:
1421 case Sema::PCC_ParenthesizedExpression:
1422 case Sema::PCC_LocalDeclarationSpecifiers:
1427 static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt);
1428 static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt);
1429 static void AddObjCVisibilityResults(const LangOptions &LangOpts,
1430 ResultBuilder &Results,
1432 static void AddObjCImplementationResults(const LangOptions &LangOpts,
1433 ResultBuilder &Results,
1435 static void AddObjCInterfaceResults(const LangOptions &LangOpts,
1436 ResultBuilder &Results,
1438 static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt);
1440 static void AddTypedefResult(ResultBuilder &Results) {
1441 CodeCompletionBuilder Builder(Results.getAllocator(),
1442 Results.getCodeCompletionTUInfo());
1443 Builder.AddTypedTextChunk("typedef");
1444 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1445 Builder.AddPlaceholderChunk("type");
1446 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1447 Builder.AddPlaceholderChunk("name");
1448 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
1451 static bool WantTypesInContext(Sema::ParserCompletionContext CCC,
1452 const LangOptions &LangOpts) {
1454 case Sema::PCC_Namespace:
1455 case Sema::PCC_Class:
1456 case Sema::PCC_ObjCInstanceVariableList:
1457 case Sema::PCC_Template:
1458 case Sema::PCC_MemberTemplate:
1459 case Sema::PCC_Statement:
1460 case Sema::PCC_RecoveryInFunction:
1461 case Sema::PCC_Type:
1462 case Sema::PCC_ParenthesizedExpression:
1463 case Sema::PCC_LocalDeclarationSpecifiers:
1466 case Sema::PCC_Expression:
1467 case Sema::PCC_Condition:
1468 return LangOpts.CPlusPlus;
1470 case Sema::PCC_ObjCInterface:
1471 case Sema::PCC_ObjCImplementation:
1474 case Sema::PCC_ForInit:
1475 return LangOpts.CPlusPlus || LangOpts.ObjC1 || LangOpts.C99;
1478 llvm_unreachable("Invalid ParserCompletionContext!");
1481 static PrintingPolicy getCompletionPrintingPolicy(const ASTContext &Context,
1482 const Preprocessor &PP) {
1483 PrintingPolicy Policy = Sema::getPrintingPolicy(Context, PP);
1484 Policy.AnonymousTagLocations = false;
1485 Policy.SuppressStrongLifetime = true;
1486 Policy.SuppressUnwrittenScope = true;
1490 /// \brief Retrieve a printing policy suitable for code completion.
1491 static PrintingPolicy getCompletionPrintingPolicy(Sema &S) {
1492 return getCompletionPrintingPolicy(S.Context, S.PP);
1495 /// \brief Retrieve the string representation of the given type as a string
1496 /// that has the appropriate lifetime for code completion.
1498 /// This routine provides a fast path where we provide constant strings for
1499 /// common type names.
1500 static const char *GetCompletionTypeString(QualType T,
1501 ASTContext &Context,
1502 const PrintingPolicy &Policy,
1503 CodeCompletionAllocator &Allocator) {
1504 if (!T.getLocalQualifiers()) {
1505 // Built-in type names are constant strings.
1506 if (const BuiltinType *BT = dyn_cast<BuiltinType>(T))
1507 return BT->getNameAsCString(Policy);
1509 // Anonymous tag types are constant strings.
1510 if (const TagType *TagT = dyn_cast<TagType>(T))
1511 if (TagDecl *Tag = TagT->getDecl())
1512 if (!Tag->hasNameForLinkage()) {
1513 switch (Tag->getTagKind()) {
1514 case TTK_Struct: return "struct <anonymous>";
1515 case TTK_Interface: return "__interface <anonymous>";
1516 case TTK_Class: return "class <anonymous>";
1517 case TTK_Union: return "union <anonymous>";
1518 case TTK_Enum: return "enum <anonymous>";
1523 // Slow path: format the type as a string.
1525 T.getAsStringInternal(Result, Policy);
1526 return Allocator.CopyString(Result);
1529 /// \brief Add a completion for "this", if we're in a member function.
1530 static void addThisCompletion(Sema &S, ResultBuilder &Results) {
1531 QualType ThisTy = S.getCurrentThisType();
1532 if (ThisTy.isNull())
1535 CodeCompletionAllocator &Allocator = Results.getAllocator();
1536 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
1537 PrintingPolicy Policy = getCompletionPrintingPolicy(S);
1538 Builder.AddResultTypeChunk(GetCompletionTypeString(ThisTy,
1542 Builder.AddTypedTextChunk("this");
1543 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
1546 static void AddStaticAssertResult(CodeCompletionBuilder &Builder,
1547 ResultBuilder &Results,
1548 const LangOptions &LangOpts) {
1549 if (!LangOpts.CPlusPlus11)
1552 Builder.AddTypedTextChunk("static_assert");
1553 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1554 Builder.AddPlaceholderChunk("expression");
1555 Builder.AddChunk(CodeCompletionString::CK_Comma);
1556 Builder.AddPlaceholderChunk("message");
1557 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1558 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
1561 /// \brief Add language constructs that show up for "ordinary" names.
1562 static void AddOrdinaryNameResults(Sema::ParserCompletionContext CCC,
1565 ResultBuilder &Results) {
1566 CodeCompletionAllocator &Allocator = Results.getAllocator();
1567 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
1569 typedef CodeCompletionResult Result;
1571 case Sema::PCC_Namespace:
1572 if (SemaRef.getLangOpts().CPlusPlus) {
1573 if (Results.includeCodePatterns()) {
1574 // namespace <identifier> { declarations }
1575 Builder.AddTypedTextChunk("namespace");
1576 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1577 Builder.AddPlaceholderChunk("identifier");
1578 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1579 Builder.AddPlaceholderChunk("declarations");
1580 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1581 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1582 Results.AddResult(Result(Builder.TakeString()));
1585 // namespace identifier = identifier ;
1586 Builder.AddTypedTextChunk("namespace");
1587 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1588 Builder.AddPlaceholderChunk("name");
1589 Builder.AddChunk(CodeCompletionString::CK_Equal);
1590 Builder.AddPlaceholderChunk("namespace");
1591 Results.AddResult(Result(Builder.TakeString()));
1594 Builder.AddTypedTextChunk("using");
1595 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1596 Builder.AddTextChunk("namespace");
1597 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1598 Builder.AddPlaceholderChunk("identifier");
1599 Results.AddResult(Result(Builder.TakeString()));
1601 // asm(string-literal)
1602 Builder.AddTypedTextChunk("asm");
1603 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1604 Builder.AddPlaceholderChunk("string-literal");
1605 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1606 Results.AddResult(Result(Builder.TakeString()));
1608 if (Results.includeCodePatterns()) {
1609 // Explicit template instantiation
1610 Builder.AddTypedTextChunk("template");
1611 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1612 Builder.AddPlaceholderChunk("declaration");
1613 Results.AddResult(Result(Builder.TakeString()));
1617 if (SemaRef.getLangOpts().ObjC1)
1618 AddObjCTopLevelResults(Results, true);
1620 AddTypedefResult(Results);
1623 case Sema::PCC_Class:
1624 if (SemaRef.getLangOpts().CPlusPlus) {
1625 // Using declaration
1626 Builder.AddTypedTextChunk("using");
1627 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1628 Builder.AddPlaceholderChunk("qualifier");
1629 Builder.AddTextChunk("::");
1630 Builder.AddPlaceholderChunk("name");
1631 Results.AddResult(Result(Builder.TakeString()));
1633 // using typename qualifier::name (only in a dependent context)
1634 if (SemaRef.CurContext->isDependentContext()) {
1635 Builder.AddTypedTextChunk("using");
1636 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1637 Builder.AddTextChunk("typename");
1638 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1639 Builder.AddPlaceholderChunk("qualifier");
1640 Builder.AddTextChunk("::");
1641 Builder.AddPlaceholderChunk("name");
1642 Results.AddResult(Result(Builder.TakeString()));
1645 AddStaticAssertResult(Builder, Results, SemaRef.getLangOpts());
1647 if (CCC == Sema::PCC_Class) {
1648 AddTypedefResult(Results);
1651 Builder.AddTypedTextChunk("public");
1652 if (Results.includeCodePatterns())
1653 Builder.AddChunk(CodeCompletionString::CK_Colon);
1654 Results.AddResult(Result(Builder.TakeString()));
1657 Builder.AddTypedTextChunk("protected");
1658 if (Results.includeCodePatterns())
1659 Builder.AddChunk(CodeCompletionString::CK_Colon);
1660 Results.AddResult(Result(Builder.TakeString()));
1663 Builder.AddTypedTextChunk("private");
1664 if (Results.includeCodePatterns())
1665 Builder.AddChunk(CodeCompletionString::CK_Colon);
1666 Results.AddResult(Result(Builder.TakeString()));
1671 case Sema::PCC_Template:
1672 case Sema::PCC_MemberTemplate:
1673 if (SemaRef.getLangOpts().CPlusPlus && Results.includeCodePatterns()) {
1674 // template < parameters >
1675 Builder.AddTypedTextChunk("template");
1676 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1677 Builder.AddPlaceholderChunk("parameters");
1678 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1679 Results.AddResult(Result(Builder.TakeString()));
1682 AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
1683 AddFunctionSpecifiers(CCC, SemaRef.getLangOpts(), Results);
1686 case Sema::PCC_ObjCInterface:
1687 AddObjCInterfaceResults(SemaRef.getLangOpts(), Results, true);
1688 AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
1689 AddFunctionSpecifiers(CCC, SemaRef.getLangOpts(), Results);
1692 case Sema::PCC_ObjCImplementation:
1693 AddObjCImplementationResults(SemaRef.getLangOpts(), Results, true);
1694 AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
1695 AddFunctionSpecifiers(CCC, SemaRef.getLangOpts(), Results);
1698 case Sema::PCC_ObjCInstanceVariableList:
1699 AddObjCVisibilityResults(SemaRef.getLangOpts(), Results, true);
1702 case Sema::PCC_RecoveryInFunction:
1703 case Sema::PCC_Statement: {
1704 AddTypedefResult(Results);
1706 if (SemaRef.getLangOpts().CPlusPlus && Results.includeCodePatterns() &&
1707 SemaRef.getLangOpts().CXXExceptions) {
1708 Builder.AddTypedTextChunk("try");
1709 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1710 Builder.AddPlaceholderChunk("statements");
1711 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1712 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1713 Builder.AddTextChunk("catch");
1714 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1715 Builder.AddPlaceholderChunk("declaration");
1716 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1717 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1718 Builder.AddPlaceholderChunk("statements");
1719 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1720 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1721 Results.AddResult(Result(Builder.TakeString()));
1723 if (SemaRef.getLangOpts().ObjC1)
1724 AddObjCStatementResults(Results, true);
1726 if (Results.includeCodePatterns()) {
1727 // if (condition) { statements }
1728 Builder.AddTypedTextChunk("if");
1729 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1730 if (SemaRef.getLangOpts().CPlusPlus)
1731 Builder.AddPlaceholderChunk("condition");
1733 Builder.AddPlaceholderChunk("expression");
1734 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1735 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1736 Builder.AddPlaceholderChunk("statements");
1737 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1738 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1739 Results.AddResult(Result(Builder.TakeString()));
1741 // switch (condition) { }
1742 Builder.AddTypedTextChunk("switch");
1743 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1744 if (SemaRef.getLangOpts().CPlusPlus)
1745 Builder.AddPlaceholderChunk("condition");
1747 Builder.AddPlaceholderChunk("expression");
1748 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1749 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1750 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1751 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1752 Results.AddResult(Result(Builder.TakeString()));
1755 // Switch-specific statements.
1756 if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
1758 Builder.AddTypedTextChunk("case");
1759 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1760 Builder.AddPlaceholderChunk("expression");
1761 Builder.AddChunk(CodeCompletionString::CK_Colon);
1762 Results.AddResult(Result(Builder.TakeString()));
1765 Builder.AddTypedTextChunk("default");
1766 Builder.AddChunk(CodeCompletionString::CK_Colon);
1767 Results.AddResult(Result(Builder.TakeString()));
1770 if (Results.includeCodePatterns()) {
1771 /// while (condition) { statements }
1772 Builder.AddTypedTextChunk("while");
1773 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1774 if (SemaRef.getLangOpts().CPlusPlus)
1775 Builder.AddPlaceholderChunk("condition");
1777 Builder.AddPlaceholderChunk("expression");
1778 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1779 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1780 Builder.AddPlaceholderChunk("statements");
1781 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1782 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1783 Results.AddResult(Result(Builder.TakeString()));
1785 // do { statements } while ( expression );
1786 Builder.AddTypedTextChunk("do");
1787 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1788 Builder.AddPlaceholderChunk("statements");
1789 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1790 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1791 Builder.AddTextChunk("while");
1792 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1793 Builder.AddPlaceholderChunk("expression");
1794 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1795 Results.AddResult(Result(Builder.TakeString()));
1797 // for ( for-init-statement ; condition ; expression ) { statements }
1798 Builder.AddTypedTextChunk("for");
1799 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1800 if (SemaRef.getLangOpts().CPlusPlus || SemaRef.getLangOpts().C99)
1801 Builder.AddPlaceholderChunk("init-statement");
1803 Builder.AddPlaceholderChunk("init-expression");
1804 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
1805 Builder.AddPlaceholderChunk("condition");
1806 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
1807 Builder.AddPlaceholderChunk("inc-expression");
1808 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1809 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1810 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1811 Builder.AddPlaceholderChunk("statements");
1812 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1813 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1814 Results.AddResult(Result(Builder.TakeString()));
1817 if (S->getContinueParent()) {
1819 Builder.AddTypedTextChunk("continue");
1820 Results.AddResult(Result(Builder.TakeString()));
1823 if (S->getBreakParent()) {
1825 Builder.AddTypedTextChunk("break");
1826 Results.AddResult(Result(Builder.TakeString()));
1829 // "return expression ;" or "return ;", depending on whether we
1830 // know the function is void or not.
1831 bool isVoid = false;
1832 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(SemaRef.CurContext))
1833 isVoid = Function->getReturnType()->isVoidType();
1834 else if (ObjCMethodDecl *Method
1835 = dyn_cast<ObjCMethodDecl>(SemaRef.CurContext))
1836 isVoid = Method->getReturnType()->isVoidType();
1837 else if (SemaRef.getCurBlock() &&
1838 !SemaRef.getCurBlock()->ReturnType.isNull())
1839 isVoid = SemaRef.getCurBlock()->ReturnType->isVoidType();
1840 Builder.AddTypedTextChunk("return");
1842 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1843 Builder.AddPlaceholderChunk("expression");
1845 Results.AddResult(Result(Builder.TakeString()));
1847 // goto identifier ;
1848 Builder.AddTypedTextChunk("goto");
1849 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1850 Builder.AddPlaceholderChunk("label");
1851 Results.AddResult(Result(Builder.TakeString()));
1854 Builder.AddTypedTextChunk("using");
1855 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1856 Builder.AddTextChunk("namespace");
1857 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1858 Builder.AddPlaceholderChunk("identifier");
1859 Results.AddResult(Result(Builder.TakeString()));
1861 AddStaticAssertResult(Builder, Results, SemaRef.getLangOpts());
1865 // Fall through (for statement expressions).
1866 case Sema::PCC_ForInit:
1867 case Sema::PCC_Condition:
1868 AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
1869 // Fall through: conditions and statements can have expressions.
1872 case Sema::PCC_ParenthesizedExpression:
1873 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
1874 CCC == Sema::PCC_ParenthesizedExpression) {
1875 // (__bridge <type>)<expression>
1876 Builder.AddTypedTextChunk("__bridge");
1877 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1878 Builder.AddPlaceholderChunk("type");
1879 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1880 Builder.AddPlaceholderChunk("expression");
1881 Results.AddResult(Result(Builder.TakeString()));
1883 // (__bridge_transfer <Objective-C type>)<expression>
1884 Builder.AddTypedTextChunk("__bridge_transfer");
1885 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1886 Builder.AddPlaceholderChunk("Objective-C type");
1887 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1888 Builder.AddPlaceholderChunk("expression");
1889 Results.AddResult(Result(Builder.TakeString()));
1891 // (__bridge_retained <CF type>)<expression>
1892 Builder.AddTypedTextChunk("__bridge_retained");
1893 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1894 Builder.AddPlaceholderChunk("CF type");
1895 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1896 Builder.AddPlaceholderChunk("expression");
1897 Results.AddResult(Result(Builder.TakeString()));
1902 case Sema::PCC_Expression: {
1903 if (SemaRef.getLangOpts().CPlusPlus) {
1904 // 'this', if we're in a non-static member function.
1905 addThisCompletion(SemaRef, Results);
1908 Builder.AddResultTypeChunk("bool");
1909 Builder.AddTypedTextChunk("true");
1910 Results.AddResult(Result(Builder.TakeString()));
1913 Builder.AddResultTypeChunk("bool");
1914 Builder.AddTypedTextChunk("false");
1915 Results.AddResult(Result(Builder.TakeString()));
1917 if (SemaRef.getLangOpts().RTTI) {
1918 // dynamic_cast < type-id > ( expression )
1919 Builder.AddTypedTextChunk("dynamic_cast");
1920 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1921 Builder.AddPlaceholderChunk("type");
1922 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1923 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1924 Builder.AddPlaceholderChunk("expression");
1925 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1926 Results.AddResult(Result(Builder.TakeString()));
1929 // static_cast < type-id > ( expression )
1930 Builder.AddTypedTextChunk("static_cast");
1931 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1932 Builder.AddPlaceholderChunk("type");
1933 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1934 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1935 Builder.AddPlaceholderChunk("expression");
1936 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1937 Results.AddResult(Result(Builder.TakeString()));
1939 // reinterpret_cast < type-id > ( expression )
1940 Builder.AddTypedTextChunk("reinterpret_cast");
1941 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1942 Builder.AddPlaceholderChunk("type");
1943 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1944 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1945 Builder.AddPlaceholderChunk("expression");
1946 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1947 Results.AddResult(Result(Builder.TakeString()));
1949 // const_cast < type-id > ( expression )
1950 Builder.AddTypedTextChunk("const_cast");
1951 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1952 Builder.AddPlaceholderChunk("type");
1953 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1954 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1955 Builder.AddPlaceholderChunk("expression");
1956 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1957 Results.AddResult(Result(Builder.TakeString()));
1959 if (SemaRef.getLangOpts().RTTI) {
1960 // typeid ( expression-or-type )
1961 Builder.AddResultTypeChunk("std::type_info");
1962 Builder.AddTypedTextChunk("typeid");
1963 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1964 Builder.AddPlaceholderChunk("expression-or-type");
1965 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1966 Results.AddResult(Result(Builder.TakeString()));
1970 Builder.AddTypedTextChunk("new");
1971 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1972 Builder.AddPlaceholderChunk("type");
1973 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1974 Builder.AddPlaceholderChunk("expressions");
1975 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1976 Results.AddResult(Result(Builder.TakeString()));
1978 // new T [ ] ( ... )
1979 Builder.AddTypedTextChunk("new");
1980 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1981 Builder.AddPlaceholderChunk("type");
1982 Builder.AddChunk(CodeCompletionString::CK_LeftBracket);
1983 Builder.AddPlaceholderChunk("size");
1984 Builder.AddChunk(CodeCompletionString::CK_RightBracket);
1985 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1986 Builder.AddPlaceholderChunk("expressions");
1987 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1988 Results.AddResult(Result(Builder.TakeString()));
1990 // delete expression
1991 Builder.AddResultTypeChunk("void");
1992 Builder.AddTypedTextChunk("delete");
1993 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1994 Builder.AddPlaceholderChunk("expression");
1995 Results.AddResult(Result(Builder.TakeString()));
1997 // delete [] expression
1998 Builder.AddResultTypeChunk("void");
1999 Builder.AddTypedTextChunk("delete");
2000 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2001 Builder.AddChunk(CodeCompletionString::CK_LeftBracket);
2002 Builder.AddChunk(CodeCompletionString::CK_RightBracket);
2003 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2004 Builder.AddPlaceholderChunk("expression");
2005 Results.AddResult(Result(Builder.TakeString()));
2007 if (SemaRef.getLangOpts().CXXExceptions) {
2009 Builder.AddResultTypeChunk("void");
2010 Builder.AddTypedTextChunk("throw");
2011 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2012 Builder.AddPlaceholderChunk("expression");
2013 Results.AddResult(Result(Builder.TakeString()));
2018 if (SemaRef.getLangOpts().CPlusPlus11) {
2020 Builder.AddResultTypeChunk("std::nullptr_t");
2021 Builder.AddTypedTextChunk("nullptr");
2022 Results.AddResult(Result(Builder.TakeString()));
2025 Builder.AddResultTypeChunk("size_t");
2026 Builder.AddTypedTextChunk("alignof");
2027 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2028 Builder.AddPlaceholderChunk("type");
2029 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2030 Results.AddResult(Result(Builder.TakeString()));
2033 Builder.AddResultTypeChunk("bool");
2034 Builder.AddTypedTextChunk("noexcept");
2035 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2036 Builder.AddPlaceholderChunk("expression");
2037 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2038 Results.AddResult(Result(Builder.TakeString()));
2040 // sizeof... expression
2041 Builder.AddResultTypeChunk("size_t");
2042 Builder.AddTypedTextChunk("sizeof...");
2043 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2044 Builder.AddPlaceholderChunk("parameter-pack");
2045 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2046 Results.AddResult(Result(Builder.TakeString()));
2050 if (SemaRef.getLangOpts().ObjC1) {
2051 // Add "super", if we're in an Objective-C class with a superclass.
2052 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
2053 // The interface can be NULL.
2054 if (ObjCInterfaceDecl *ID = Method->getClassInterface())
2055 if (ID->getSuperClass()) {
2056 std::string SuperType;
2057 SuperType = ID->getSuperClass()->getNameAsString();
2058 if (Method->isInstanceMethod())
2061 Builder.AddResultTypeChunk(Allocator.CopyString(SuperType));
2062 Builder.AddTypedTextChunk("super");
2063 Results.AddResult(Result(Builder.TakeString()));
2067 AddObjCExpressionResults(Results, true);
2070 if (SemaRef.getLangOpts().C11) {
2072 Builder.AddResultTypeChunk("size_t");
2073 if (SemaRef.PP.isMacroDefined("alignof"))
2074 Builder.AddTypedTextChunk("alignof");
2076 Builder.AddTypedTextChunk("_Alignof");
2077 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2078 Builder.AddPlaceholderChunk("type");
2079 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2080 Results.AddResult(Result(Builder.TakeString()));
2083 // sizeof expression
2084 Builder.AddResultTypeChunk("size_t");
2085 Builder.AddTypedTextChunk("sizeof");
2086 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2087 Builder.AddPlaceholderChunk("expression-or-type");
2088 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2089 Results.AddResult(Result(Builder.TakeString()));
2093 case Sema::PCC_Type:
2094 case Sema::PCC_LocalDeclarationSpecifiers:
2098 if (WantTypesInContext(CCC, SemaRef.getLangOpts()))
2099 AddTypeSpecifierResults(SemaRef.getLangOpts(), Results);
2101 if (SemaRef.getLangOpts().CPlusPlus && CCC != Sema::PCC_Type)
2102 Results.AddResult(Result("operator"));
2105 /// \brief If the given declaration has an associated type, add it as a result
2107 static void AddResultTypeChunk(ASTContext &Context,
2108 const PrintingPolicy &Policy,
2109 const NamedDecl *ND,
2111 CodeCompletionBuilder &Result) {
2115 // Skip constructors and conversion functions, which have their return types
2116 // built into their names.
2117 if (isa<CXXConstructorDecl>(ND) || isa<CXXConversionDecl>(ND))
2120 // Determine the type of the declaration (if it has a type).
2122 if (const FunctionDecl *Function = ND->getAsFunction())
2123 T = Function->getReturnType();
2124 else if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND)) {
2125 if (!BaseType.isNull())
2126 T = Method->getSendResultType(BaseType);
2128 T = Method->getReturnType();
2129 } else if (const EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND))
2130 T = Context.getTypeDeclType(cast<TypeDecl>(Enumerator->getDeclContext()));
2131 else if (isa<UnresolvedUsingValueDecl>(ND)) {
2132 /* Do nothing: ignore unresolved using declarations*/
2133 } else if (const ObjCIvarDecl *Ivar = dyn_cast<ObjCIvarDecl>(ND)) {
2134 if (!BaseType.isNull())
2135 T = Ivar->getUsageType(BaseType);
2137 T = Ivar->getType();
2138 } else if (const ValueDecl *Value = dyn_cast<ValueDecl>(ND)) {
2139 T = Value->getType();
2140 } else if (const ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND)) {
2141 if (!BaseType.isNull())
2142 T = Property->getUsageType(BaseType);
2144 T = Property->getType();
2147 if (T.isNull() || Context.hasSameType(T, Context.DependentTy))
2150 Result.AddResultTypeChunk(GetCompletionTypeString(T, Context, Policy,
2151 Result.getAllocator()));
2154 static void MaybeAddSentinel(Preprocessor &PP,
2155 const NamedDecl *FunctionOrMethod,
2156 CodeCompletionBuilder &Result) {
2157 if (SentinelAttr *Sentinel = FunctionOrMethod->getAttr<SentinelAttr>())
2158 if (Sentinel->getSentinel() == 0) {
2159 if (PP.getLangOpts().ObjC1 && PP.isMacroDefined("nil"))
2160 Result.AddTextChunk(", nil");
2161 else if (PP.isMacroDefined("NULL"))
2162 Result.AddTextChunk(", NULL");
2164 Result.AddTextChunk(", (void*)0");
2168 static std::string formatObjCParamQualifiers(unsigned ObjCQuals,
2171 if (ObjCQuals & Decl::OBJC_TQ_In)
2173 else if (ObjCQuals & Decl::OBJC_TQ_Inout)
2175 else if (ObjCQuals & Decl::OBJC_TQ_Out)
2177 if (ObjCQuals & Decl::OBJC_TQ_Bycopy)
2178 Result += "bycopy ";
2179 else if (ObjCQuals & Decl::OBJC_TQ_Byref)
2181 if (ObjCQuals & Decl::OBJC_TQ_Oneway)
2182 Result += "oneway ";
2183 if (ObjCQuals & Decl::OBJC_TQ_CSNullability) {
2184 if (auto nullability = AttributedType::stripOuterNullability(Type)) {
2185 switch (*nullability) {
2186 case NullabilityKind::NonNull:
2187 Result += "nonnull ";
2190 case NullabilityKind::Nullable:
2191 Result += "nullable ";
2194 case NullabilityKind::Unspecified:
2195 Result += "null_unspecified ";
2203 /// \brief Tries to find the most appropriate type location for an Objective-C
2204 /// block placeholder.
2206 /// This function ignores things like typedefs and qualifiers in order to
2207 /// present the most relevant and accurate block placeholders in code completion
2209 static void findTypeLocationForBlockDecl(const TypeSourceInfo *TSInfo,
2210 FunctionTypeLoc &Block,
2211 FunctionProtoTypeLoc &BlockProto,
2212 bool SuppressBlock = false) {
2215 TypeLoc TL = TSInfo->getTypeLoc().getUnqualifiedLoc();
2217 // Look through typedefs.
2218 if (!SuppressBlock) {
2219 if (TypedefTypeLoc TypedefTL = TL.getAs<TypedefTypeLoc>()) {
2220 if (TypeSourceInfo *InnerTSInfo =
2221 TypedefTL.getTypedefNameDecl()->getTypeSourceInfo()) {
2222 TL = InnerTSInfo->getTypeLoc().getUnqualifiedLoc();
2227 // Look through qualified types
2228 if (QualifiedTypeLoc QualifiedTL = TL.getAs<QualifiedTypeLoc>()) {
2229 TL = QualifiedTL.getUnqualifiedLoc();
2233 if (AttributedTypeLoc AttrTL = TL.getAs<AttributedTypeLoc>()) {
2234 TL = AttrTL.getModifiedLoc();
2239 // Try to get the function prototype behind the block pointer type,
2241 if (BlockPointerTypeLoc BlockPtr = TL.getAs<BlockPointerTypeLoc>()) {
2242 TL = BlockPtr.getPointeeLoc().IgnoreParens();
2243 Block = TL.getAs<FunctionTypeLoc>();
2244 BlockProto = TL.getAs<FunctionProtoTypeLoc>();
2251 formatBlockPlaceholder(const PrintingPolicy &Policy, const NamedDecl *BlockDecl,
2252 FunctionTypeLoc &Block, FunctionProtoTypeLoc &BlockProto,
2253 bool SuppressBlockName = false,
2254 bool SuppressBlock = false,
2255 Optional<ArrayRef<QualType>> ObjCSubsts = None);
2257 static std::string FormatFunctionParameter(const PrintingPolicy &Policy,
2258 const ParmVarDecl *Param,
2259 bool SuppressName = false,
2260 bool SuppressBlock = false,
2261 Optional<ArrayRef<QualType>> ObjCSubsts = None) {
2262 bool ObjCMethodParam = isa<ObjCMethodDecl>(Param->getDeclContext());
2263 if (Param->getType()->isDependentType() ||
2264 !Param->getType()->isBlockPointerType()) {
2265 // The argument for a dependent or non-block parameter is a placeholder
2266 // containing that parameter's type.
2269 if (Param->getIdentifier() && !ObjCMethodParam && !SuppressName)
2270 Result = Param->getIdentifier()->getName();
2272 QualType Type = Param->getType();
2274 Type = Type.substObjCTypeArgs(Param->getASTContext(), *ObjCSubsts,
2275 ObjCSubstitutionContext::Parameter);
2276 if (ObjCMethodParam) {
2277 Result = "(" + formatObjCParamQualifiers(Param->getObjCDeclQualifier(),
2279 Result += Type.getAsString(Policy) + ")";
2280 if (Param->getIdentifier() && !SuppressName)
2281 Result += Param->getIdentifier()->getName();
2283 Type.getAsStringInternal(Result, Policy);
2288 // The argument for a block pointer parameter is a block literal with
2289 // the appropriate type.
2290 FunctionTypeLoc Block;
2291 FunctionProtoTypeLoc BlockProto;
2292 findTypeLocationForBlockDecl(Param->getTypeSourceInfo(), Block, BlockProto,
2294 // Try to retrieve the block type information from the property if this is a
2295 // parameter in a setter.
2296 if (!Block && ObjCMethodParam &&
2297 cast<ObjCMethodDecl>(Param->getDeclContext())->isPropertyAccessor()) {
2298 if (const auto *PD = cast<ObjCMethodDecl>(Param->getDeclContext())
2299 ->findPropertyDecl(/*CheckOverrides=*/false))
2300 findTypeLocationForBlockDecl(PD->getTypeSourceInfo(), Block, BlockProto,
2305 // We were unable to find a FunctionProtoTypeLoc with parameter names
2306 // for the block; just use the parameter type as a placeholder.
2308 if (!ObjCMethodParam && Param->getIdentifier())
2309 Result = Param->getIdentifier()->getName();
2311 QualType Type = Param->getType().getUnqualifiedType();
2313 if (ObjCMethodParam) {
2314 Result = Type.getAsString(Policy);
2316 formatObjCParamQualifiers(Param->getObjCDeclQualifier(), Type);
2318 Result = "(" + Quals + " " + Result + ")";
2319 if (Result.back() != ')')
2321 if (Param->getIdentifier())
2322 Result += Param->getIdentifier()->getName();
2324 Type.getAsStringInternal(Result, Policy);
2330 // We have the function prototype behind the block pointer type, as it was
2331 // written in the source.
2332 return formatBlockPlaceholder(Policy, Param, Block, BlockProto,
2333 /*SuppressBlockName=*/false, SuppressBlock,
2337 /// \brief Returns a placeholder string that corresponds to an Objective-C block
2340 /// \param BlockDecl A declaration with an Objective-C block type.
2342 /// \param Block The most relevant type location for that block type.
2344 /// \param SuppressBlockName Determines wether or not the name of the block
2345 /// declaration is included in the resulting string.
2347 formatBlockPlaceholder(const PrintingPolicy &Policy, const NamedDecl *BlockDecl,
2348 FunctionTypeLoc &Block, FunctionProtoTypeLoc &BlockProto,
2349 bool SuppressBlockName, bool SuppressBlock,
2350 Optional<ArrayRef<QualType>> ObjCSubsts) {
2352 QualType ResultType = Block.getTypePtr()->getReturnType();
2355 ResultType.substObjCTypeArgs(BlockDecl->getASTContext(), *ObjCSubsts,
2356 ObjCSubstitutionContext::Result);
2357 if (!ResultType->isVoidType() || SuppressBlock)
2358 ResultType.getAsStringInternal(Result, Policy);
2360 // Format the parameter list.
2362 if (!BlockProto || Block.getNumParams() == 0) {
2363 if (BlockProto && BlockProto.getTypePtr()->isVariadic())
2369 for (unsigned I = 0, N = Block.getNumParams(); I != N; ++I) {
2372 Params += FormatFunctionParameter(Policy, Block.getParam(I),
2373 /*SuppressName=*/false,
2374 /*SuppressBlock=*/true, ObjCSubsts);
2376 if (I == N - 1 && BlockProto.getTypePtr()->isVariadic())
2382 if (SuppressBlock) {
2383 // Format as a parameter.
2384 Result = Result + " (^";
2385 if (!SuppressBlockName && BlockDecl->getIdentifier())
2386 Result += BlockDecl->getIdentifier()->getName();
2390 // Format as a block literal argument.
2391 Result = '^' + Result;
2394 if (!SuppressBlockName && BlockDecl->getIdentifier())
2395 Result += BlockDecl->getIdentifier()->getName();
2401 /// \brief Add function parameter chunks to the given code completion string.
2402 static void AddFunctionParameterChunks(Preprocessor &PP,
2403 const PrintingPolicy &Policy,
2404 const FunctionDecl *Function,
2405 CodeCompletionBuilder &Result,
2407 bool InOptional = false) {
2408 bool FirstParameter = true;
2410 for (unsigned P = Start, N = Function->getNumParams(); P != N; ++P) {
2411 const ParmVarDecl *Param = Function->getParamDecl(P);
2413 if (Param->hasDefaultArg() && !InOptional) {
2414 // When we see an optional default argument, put that argument and
2415 // the remaining default arguments into a new, optional string.
2416 CodeCompletionBuilder Opt(Result.getAllocator(),
2417 Result.getCodeCompletionTUInfo());
2418 if (!FirstParameter)
2419 Opt.AddChunk(CodeCompletionString::CK_Comma);
2420 AddFunctionParameterChunks(PP, Policy, Function, Opt, P, true);
2421 Result.AddOptionalChunk(Opt.TakeString());
2426 FirstParameter = false;
2428 Result.AddChunk(CodeCompletionString::CK_Comma);
2432 // Format the placeholder string.
2433 std::string PlaceholderStr = FormatFunctionParameter(Policy, Param);
2435 if (Function->isVariadic() && P == N - 1)
2436 PlaceholderStr += ", ...";
2438 // Add the placeholder string.
2439 Result.AddPlaceholderChunk(
2440 Result.getAllocator().CopyString(PlaceholderStr));
2443 if (const FunctionProtoType *Proto
2444 = Function->getType()->getAs<FunctionProtoType>())
2445 if (Proto->isVariadic()) {
2446 if (Proto->getNumParams() == 0)
2447 Result.AddPlaceholderChunk("...");
2449 MaybeAddSentinel(PP, Function, Result);
2453 /// \brief Add template parameter chunks to the given code completion string.
2454 static void AddTemplateParameterChunks(ASTContext &Context,
2455 const PrintingPolicy &Policy,
2456 const TemplateDecl *Template,
2457 CodeCompletionBuilder &Result,
2458 unsigned MaxParameters = 0,
2460 bool InDefaultArg = false) {
2461 bool FirstParameter = true;
2463 // Prefer to take the template parameter names from the first declaration of
2465 Template = cast<TemplateDecl>(Template->getCanonicalDecl());
2467 TemplateParameterList *Params = Template->getTemplateParameters();
2468 TemplateParameterList::iterator PEnd = Params->end();
2470 PEnd = Params->begin() + MaxParameters;
2471 for (TemplateParameterList::iterator P = Params->begin() + Start;
2473 bool HasDefaultArg = false;
2474 std::string PlaceholderStr;
2475 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
2476 if (TTP->wasDeclaredWithTypename())
2477 PlaceholderStr = "typename";
2479 PlaceholderStr = "class";
2481 if (TTP->getIdentifier()) {
2482 PlaceholderStr += ' ';
2483 PlaceholderStr += TTP->getIdentifier()->getName();
2486 HasDefaultArg = TTP->hasDefaultArgument();
2487 } else if (NonTypeTemplateParmDecl *NTTP
2488 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
2489 if (NTTP->getIdentifier())
2490 PlaceholderStr = NTTP->getIdentifier()->getName();
2491 NTTP->getType().getAsStringInternal(PlaceholderStr, Policy);
2492 HasDefaultArg = NTTP->hasDefaultArgument();
2494 assert(isa<TemplateTemplateParmDecl>(*P));
2495 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
2497 // Since putting the template argument list into the placeholder would
2498 // be very, very long, we just use an abbreviation.
2499 PlaceholderStr = "template<...> class";
2500 if (TTP->getIdentifier()) {
2501 PlaceholderStr += ' ';
2502 PlaceholderStr += TTP->getIdentifier()->getName();
2505 HasDefaultArg = TTP->hasDefaultArgument();
2508 if (HasDefaultArg && !InDefaultArg) {
2509 // When we see an optional default argument, put that argument and
2510 // the remaining default arguments into a new, optional string.
2511 CodeCompletionBuilder Opt(Result.getAllocator(),
2512 Result.getCodeCompletionTUInfo());
2513 if (!FirstParameter)
2514 Opt.AddChunk(CodeCompletionString::CK_Comma);
2515 AddTemplateParameterChunks(Context, Policy, Template, Opt, MaxParameters,
2516 P - Params->begin(), true);
2517 Result.AddOptionalChunk(Opt.TakeString());
2521 InDefaultArg = false;
2524 FirstParameter = false;
2526 Result.AddChunk(CodeCompletionString::CK_Comma);
2528 // Add the placeholder string.
2529 Result.AddPlaceholderChunk(
2530 Result.getAllocator().CopyString(PlaceholderStr));
2534 /// \brief Add a qualifier to the given code-completion string, if the
2535 /// provided nested-name-specifier is non-NULL.
2537 AddQualifierToCompletionString(CodeCompletionBuilder &Result,
2538 NestedNameSpecifier *Qualifier,
2539 bool QualifierIsInformative,
2540 ASTContext &Context,
2541 const PrintingPolicy &Policy) {
2545 std::string PrintedNNS;
2547 llvm::raw_string_ostream OS(PrintedNNS);
2548 Qualifier->print(OS, Policy);
2550 if (QualifierIsInformative)
2551 Result.AddInformativeChunk(Result.getAllocator().CopyString(PrintedNNS));
2553 Result.AddTextChunk(Result.getAllocator().CopyString(PrintedNNS));
2557 AddFunctionTypeQualsToCompletionString(CodeCompletionBuilder &Result,
2558 const FunctionDecl *Function) {
2559 const FunctionProtoType *Proto
2560 = Function->getType()->getAs<FunctionProtoType>();
2561 if (!Proto || !Proto->getTypeQuals())
2564 // FIXME: Add ref-qualifier!
2566 // Handle single qualifiers without copying
2567 if (Proto->getTypeQuals() == Qualifiers::Const) {
2568 Result.AddInformativeChunk(" const");
2572 if (Proto->getTypeQuals() == Qualifiers::Volatile) {
2573 Result.AddInformativeChunk(" volatile");
2577 if (Proto->getTypeQuals() == Qualifiers::Restrict) {
2578 Result.AddInformativeChunk(" restrict");
2582 // Handle multiple qualifiers.
2583 std::string QualsStr;
2584 if (Proto->isConst())
2585 QualsStr += " const";
2586 if (Proto->isVolatile())
2587 QualsStr += " volatile";
2588 if (Proto->isRestrict())
2589 QualsStr += " restrict";
2590 Result.AddInformativeChunk(Result.getAllocator().CopyString(QualsStr));
2593 /// \brief Add the name of the given declaration
2594 static void AddTypedNameChunk(ASTContext &Context, const PrintingPolicy &Policy,
2595 const NamedDecl *ND,
2596 CodeCompletionBuilder &Result) {
2597 DeclarationName Name = ND->getDeclName();
2601 switch (Name.getNameKind()) {
2602 case DeclarationName::CXXOperatorName: {
2603 const char *OperatorName = nullptr;
2604 switch (Name.getCXXOverloadedOperator()) {
2606 case OO_Conditional:
2607 case NUM_OVERLOADED_OPERATORS:
2608 OperatorName = "operator";
2611 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2612 case OO_##Name: OperatorName = "operator" Spelling; break;
2613 #define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
2614 #include "clang/Basic/OperatorKinds.def"
2616 case OO_New: OperatorName = "operator new"; break;
2617 case OO_Delete: OperatorName = "operator delete"; break;
2618 case OO_Array_New: OperatorName = "operator new[]"; break;
2619 case OO_Array_Delete: OperatorName = "operator delete[]"; break;
2620 case OO_Call: OperatorName = "operator()"; break;
2621 case OO_Subscript: OperatorName = "operator[]"; break;
2623 Result.AddTypedTextChunk(OperatorName);
2627 case DeclarationName::Identifier:
2628 case DeclarationName::CXXConversionFunctionName:
2629 case DeclarationName::CXXDestructorName:
2630 case DeclarationName::CXXLiteralOperatorName:
2631 Result.AddTypedTextChunk(
2632 Result.getAllocator().CopyString(ND->getNameAsString()));
2635 case DeclarationName::CXXDeductionGuideName:
2636 case DeclarationName::CXXUsingDirective:
2637 case DeclarationName::ObjCZeroArgSelector:
2638 case DeclarationName::ObjCOneArgSelector:
2639 case DeclarationName::ObjCMultiArgSelector:
2642 case DeclarationName::CXXConstructorName: {
2643 CXXRecordDecl *Record = nullptr;
2644 QualType Ty = Name.getCXXNameType();
2645 if (const RecordType *RecordTy = Ty->getAs<RecordType>())
2646 Record = cast<CXXRecordDecl>(RecordTy->getDecl());
2647 else if (const InjectedClassNameType *InjectedTy
2648 = Ty->getAs<InjectedClassNameType>())
2649 Record = InjectedTy->getDecl();
2651 Result.AddTypedTextChunk(
2652 Result.getAllocator().CopyString(ND->getNameAsString()));
2656 Result.AddTypedTextChunk(
2657 Result.getAllocator().CopyString(Record->getNameAsString()));
2658 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) {
2659 Result.AddChunk(CodeCompletionString::CK_LeftAngle);
2660 AddTemplateParameterChunks(Context, Policy, Template, Result);
2661 Result.AddChunk(CodeCompletionString::CK_RightAngle);
2668 CodeCompletionString *CodeCompletionResult::CreateCodeCompletionString(Sema &S,
2669 const CodeCompletionContext &CCContext,
2670 CodeCompletionAllocator &Allocator,
2671 CodeCompletionTUInfo &CCTUInfo,
2672 bool IncludeBriefComments) {
2673 return CreateCodeCompletionString(S.Context, S.PP, CCContext, Allocator,
2674 CCTUInfo, IncludeBriefComments);
2677 /// \brief If possible, create a new code completion string for the given
2680 /// \returns Either a new, heap-allocated code completion string describing
2681 /// how to use this result, or NULL to indicate that the string or name of the
2682 /// result is all that is needed.
2683 CodeCompletionString *
2684 CodeCompletionResult::CreateCodeCompletionString(ASTContext &Ctx,
2686 const CodeCompletionContext &CCContext,
2687 CodeCompletionAllocator &Allocator,
2688 CodeCompletionTUInfo &CCTUInfo,
2689 bool IncludeBriefComments) {
2690 CodeCompletionBuilder Result(Allocator, CCTUInfo, Priority, Availability);
2692 PrintingPolicy Policy = getCompletionPrintingPolicy(Ctx, PP);
2693 if (Kind == RK_Pattern) {
2694 Pattern->Priority = Priority;
2695 Pattern->Availability = Availability;
2698 Result.addParentContext(Declaration->getDeclContext());
2699 Pattern->ParentName = Result.getParentName();
2700 // Provide code completion comment for self.GetterName where
2701 // GetterName is the getter method for a property with name
2702 // different from the property name (declared via a property
2703 // getter attribute.
2704 const NamedDecl *ND = Declaration;
2705 if (const ObjCMethodDecl *M = dyn_cast<ObjCMethodDecl>(ND))
2706 if (M->isPropertyAccessor())
2707 if (const ObjCPropertyDecl *PDecl = M->findPropertyDecl())
2708 if (PDecl->getGetterName() == M->getSelector() &&
2709 PDecl->getIdentifier() != M->getIdentifier()) {
2710 if (const RawComment *RC =
2711 Ctx.getRawCommentForAnyRedecl(M)) {
2712 Result.addBriefComment(RC->getBriefText(Ctx));
2713 Pattern->BriefComment = Result.getBriefComment();
2715 else if (const RawComment *RC =
2716 Ctx.getRawCommentForAnyRedecl(PDecl)) {
2717 Result.addBriefComment(RC->getBriefText(Ctx));
2718 Pattern->BriefComment = Result.getBriefComment();
2726 if (Kind == RK_Keyword) {
2727 Result.AddTypedTextChunk(Keyword);
2728 return Result.TakeString();
2731 if (Kind == RK_Macro) {
2732 const MacroInfo *MI = PP.getMacroInfo(Macro);
2733 Result.AddTypedTextChunk(
2734 Result.getAllocator().CopyString(Macro->getName()));
2736 if (!MI || !MI->isFunctionLike())
2737 return Result.TakeString();
2739 // Format a function-like macro with placeholders for the arguments.
2740 Result.AddChunk(CodeCompletionString::CK_LeftParen);
2741 MacroInfo::arg_iterator A = MI->arg_begin(), AEnd = MI->arg_end();
2743 // C99 variadic macros add __VA_ARGS__ at the end. Skip it.
2744 if (MI->isC99Varargs()) {
2748 Result.AddPlaceholderChunk("...");
2752 for (MacroInfo::arg_iterator A = MI->arg_begin(); A != AEnd; ++A) {
2753 if (A != MI->arg_begin())
2754 Result.AddChunk(CodeCompletionString::CK_Comma);
2756 if (MI->isVariadic() && (A+1) == AEnd) {
2757 SmallString<32> Arg = (*A)->getName();
2758 if (MI->isC99Varargs())
2762 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
2766 // Non-variadic macros are simple.
2767 Result.AddPlaceholderChunk(
2768 Result.getAllocator().CopyString((*A)->getName()));
2770 Result.AddChunk(CodeCompletionString::CK_RightParen);
2771 return Result.TakeString();
2774 assert(Kind == RK_Declaration && "Missed a result kind?");
2775 const NamedDecl *ND = Declaration;
2776 Result.addParentContext(ND->getDeclContext());
2778 if (IncludeBriefComments) {
2779 // Add documentation comment, if it exists.
2780 if (const RawComment *RC = Ctx.getRawCommentForAnyRedecl(ND)) {
2781 Result.addBriefComment(RC->getBriefText(Ctx));
2783 else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
2784 if (OMD->isPropertyAccessor())
2785 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
2786 if (const RawComment *RC = Ctx.getRawCommentForAnyRedecl(PDecl))
2787 Result.addBriefComment(RC->getBriefText(Ctx));
2790 if (StartsNestedNameSpecifier) {
2791 Result.AddTypedTextChunk(
2792 Result.getAllocator().CopyString(ND->getNameAsString()));
2793 Result.AddTextChunk("::");
2794 return Result.TakeString();
2797 for (const auto *I : ND->specific_attrs<AnnotateAttr>())
2798 Result.AddAnnotation(Result.getAllocator().CopyString(I->getAnnotation()));
2800 AddResultTypeChunk(Ctx, Policy, ND, CCContext.getBaseType(), Result);
2802 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(ND)) {
2803 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2805 AddTypedNameChunk(Ctx, Policy, ND, Result);
2806 Result.AddChunk(CodeCompletionString::CK_LeftParen);
2807 AddFunctionParameterChunks(PP, Policy, Function, Result);
2808 Result.AddChunk(CodeCompletionString::CK_RightParen);
2809 AddFunctionTypeQualsToCompletionString(Result, Function);
2810 return Result.TakeString();
2813 if (const FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND)) {
2814 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2816 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
2817 AddTypedNameChunk(Ctx, Policy, Function, Result);
2819 // Figure out which template parameters are deduced (or have default
2821 llvm::SmallBitVector Deduced;
2822 Sema::MarkDeducedTemplateParameters(Ctx, FunTmpl, Deduced);
2823 unsigned LastDeducibleArgument;
2824 for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0;
2825 --LastDeducibleArgument) {
2826 if (!Deduced[LastDeducibleArgument - 1]) {
2827 // C++0x: Figure out if the template argument has a default. If so,
2828 // the user doesn't need to type this argument.
2829 // FIXME: We need to abstract template parameters better!
2830 bool HasDefaultArg = false;
2831 NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam(
2832 LastDeducibleArgument - 1);
2833 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2834 HasDefaultArg = TTP->hasDefaultArgument();
2835 else if (NonTypeTemplateParmDecl *NTTP
2836 = dyn_cast<NonTypeTemplateParmDecl>(Param))
2837 HasDefaultArg = NTTP->hasDefaultArgument();
2839 assert(isa<TemplateTemplateParmDecl>(Param));
2841 = cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument();
2849 if (LastDeducibleArgument) {
2850 // Some of the function template arguments cannot be deduced from a
2851 // function call, so we introduce an explicit template argument list
2852 // containing all of the arguments up to the first deducible argument.
2853 Result.AddChunk(CodeCompletionString::CK_LeftAngle);
2854 AddTemplateParameterChunks(Ctx, Policy, FunTmpl, Result,
2855 LastDeducibleArgument);
2856 Result.AddChunk(CodeCompletionString::CK_RightAngle);
2859 // Add the function parameters
2860 Result.AddChunk(CodeCompletionString::CK_LeftParen);
2861 AddFunctionParameterChunks(PP, Policy, Function, Result);
2862 Result.AddChunk(CodeCompletionString::CK_RightParen);
2863 AddFunctionTypeQualsToCompletionString(Result, Function);
2864 return Result.TakeString();
2867 if (const TemplateDecl *Template = dyn_cast<TemplateDecl>(ND)) {
2868 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2870 Result.AddTypedTextChunk(
2871 Result.getAllocator().CopyString(Template->getNameAsString()));
2872 Result.AddChunk(CodeCompletionString::CK_LeftAngle);
2873 AddTemplateParameterChunks(Ctx, Policy, Template, Result);
2874 Result.AddChunk(CodeCompletionString::CK_RightAngle);
2875 return Result.TakeString();
2878 if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND)) {
2879 Selector Sel = Method->getSelector();
2880 if (Sel.isUnarySelector()) {
2881 Result.AddTypedTextChunk(Result.getAllocator().CopyString(
2882 Sel.getNameForSlot(0)));
2883 return Result.TakeString();
2886 std::string SelName = Sel.getNameForSlot(0).str();
2888 if (StartParameter == 0)
2889 Result.AddTypedTextChunk(Result.getAllocator().CopyString(SelName));
2891 Result.AddInformativeChunk(Result.getAllocator().CopyString(SelName));
2893 // If there is only one parameter, and we're past it, add an empty
2894 // typed-text chunk since there is nothing to type.
2895 if (Method->param_size() == 1)
2896 Result.AddTypedTextChunk("");
2899 for (ObjCMethodDecl::param_const_iterator P = Method->param_begin(),
2900 PEnd = Method->param_end();
2901 P != PEnd; (void)++P, ++Idx) {
2903 std::string Keyword;
2904 if (Idx > StartParameter)
2905 Result.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2906 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(Idx))
2907 Keyword += II->getName();
2909 if (Idx < StartParameter || AllParametersAreInformative)
2910 Result.AddInformativeChunk(Result.getAllocator().CopyString(Keyword));
2912 Result.AddTypedTextChunk(Result.getAllocator().CopyString(Keyword));
2915 // If we're before the starting parameter, skip the placeholder.
2916 if (Idx < StartParameter)
2920 QualType ParamType = (*P)->getType();
2921 Optional<ArrayRef<QualType>> ObjCSubsts;
2922 if (!CCContext.getBaseType().isNull())
2923 ObjCSubsts = CCContext.getBaseType()->getObjCSubstitutions(Method);
2925 if (ParamType->isBlockPointerType() && !DeclaringEntity)
2926 Arg = FormatFunctionParameter(Policy, *P, true,
2927 /*SuppressBlock=*/false,
2931 ParamType = ParamType.substObjCTypeArgs(Ctx, *ObjCSubsts,
2932 ObjCSubstitutionContext::Parameter);
2933 Arg = "(" + formatObjCParamQualifiers((*P)->getObjCDeclQualifier(),
2935 Arg += ParamType.getAsString(Policy) + ")";
2936 if (IdentifierInfo *II = (*P)->getIdentifier())
2937 if (DeclaringEntity || AllParametersAreInformative)
2938 Arg += II->getName();
2941 if (Method->isVariadic() && (P + 1) == PEnd)
2944 if (DeclaringEntity)
2945 Result.AddTextChunk(Result.getAllocator().CopyString(Arg));
2946 else if (AllParametersAreInformative)
2947 Result.AddInformativeChunk(Result.getAllocator().CopyString(Arg));
2949 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
2952 if (Method->isVariadic()) {
2953 if (Method->param_size() == 0) {
2954 if (DeclaringEntity)
2955 Result.AddTextChunk(", ...");
2956 else if (AllParametersAreInformative)
2957 Result.AddInformativeChunk(", ...");
2959 Result.AddPlaceholderChunk(", ...");
2962 MaybeAddSentinel(PP, Method, Result);
2965 return Result.TakeString();
2969 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2972 Result.AddTypedTextChunk(
2973 Result.getAllocator().CopyString(ND->getNameAsString()));
2974 return Result.TakeString();
2977 /// \brief Add function overload parameter chunks to the given code completion
2979 static void AddOverloadParameterChunks(ASTContext &Context,
2980 const PrintingPolicy &Policy,
2981 const FunctionDecl *Function,
2982 const FunctionProtoType *Prototype,
2983 CodeCompletionBuilder &Result,
2984 unsigned CurrentArg,
2986 bool InOptional = false) {
2987 bool FirstParameter = true;
2988 unsigned NumParams = Function ? Function->getNumParams()
2989 : Prototype->getNumParams();
2991 for (unsigned P = Start; P != NumParams; ++P) {
2992 if (Function && Function->getParamDecl(P)->hasDefaultArg() && !InOptional) {
2993 // When we see an optional default argument, put that argument and
2994 // the remaining default arguments into a new, optional string.
2995 CodeCompletionBuilder Opt(Result.getAllocator(),
2996 Result.getCodeCompletionTUInfo());
2997 if (!FirstParameter)
2998 Opt.AddChunk(CodeCompletionString::CK_Comma);
2999 // Optional sections are nested.
3000 AddOverloadParameterChunks(Context, Policy, Function, Prototype, Opt,
3001 CurrentArg, P, /*InOptional=*/true);
3002 Result.AddOptionalChunk(Opt.TakeString());
3007 FirstParameter = false;
3009 Result.AddChunk(CodeCompletionString::CK_Comma);
3013 // Format the placeholder string.
3014 std::string Placeholder;
3016 Placeholder = FormatFunctionParameter(Policy, Function->getParamDecl(P));
3018 Placeholder = Prototype->getParamType(P).getAsString(Policy);
3020 if (P == CurrentArg)
3021 Result.AddCurrentParameterChunk(
3022 Result.getAllocator().CopyString(Placeholder));
3024 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Placeholder));
3027 if (Prototype && Prototype->isVariadic()) {
3028 CodeCompletionBuilder Opt(Result.getAllocator(),
3029 Result.getCodeCompletionTUInfo());
3030 if (!FirstParameter)
3031 Opt.AddChunk(CodeCompletionString::CK_Comma);
3033 if (CurrentArg < NumParams)
3034 Opt.AddPlaceholderChunk("...");
3036 Opt.AddCurrentParameterChunk("...");
3038 Result.AddOptionalChunk(Opt.TakeString());
3042 CodeCompletionString *
3043 CodeCompleteConsumer::OverloadCandidate::CreateSignatureString(
3044 unsigned CurrentArg, Sema &S,
3045 CodeCompletionAllocator &Allocator,
3046 CodeCompletionTUInfo &CCTUInfo,
3047 bool IncludeBriefComments) const {
3048 PrintingPolicy Policy = getCompletionPrintingPolicy(S);
3050 // FIXME: Set priority, availability appropriately.
3051 CodeCompletionBuilder Result(Allocator,CCTUInfo, 1, CXAvailability_Available);
3052 FunctionDecl *FDecl = getFunction();
3053 const FunctionProtoType *Proto
3054 = dyn_cast<FunctionProtoType>(getFunctionType());
3055 if (!FDecl && !Proto) {
3056 // Function without a prototype. Just give the return type and a
3057 // highlighted ellipsis.
3058 const FunctionType *FT = getFunctionType();
3059 Result.AddResultTypeChunk(Result.getAllocator().CopyString(
3060 FT->getReturnType().getAsString(Policy)));
3061 Result.AddChunk(CodeCompletionString::CK_LeftParen);
3062 Result.AddChunk(CodeCompletionString::CK_CurrentParameter, "...");
3063 Result.AddChunk(CodeCompletionString::CK_RightParen);
3064 return Result.TakeString();
3068 if (IncludeBriefComments && CurrentArg < FDecl->getNumParams())
3069 if (auto RC = S.getASTContext().getRawCommentForAnyRedecl(
3070 FDecl->getParamDecl(CurrentArg)))
3071 Result.addBriefComment(RC->getBriefText(S.getASTContext()));
3072 AddResultTypeChunk(S.Context, Policy, FDecl, QualType(), Result);
3073 Result.AddTextChunk(
3074 Result.getAllocator().CopyString(FDecl->getNameAsString()));
3076 Result.AddResultTypeChunk(
3077 Result.getAllocator().CopyString(
3078 Proto->getReturnType().getAsString(Policy)));
3081 Result.AddChunk(CodeCompletionString::CK_LeftParen);
3082 AddOverloadParameterChunks(S.getASTContext(), Policy, FDecl, Proto, Result,
3084 Result.AddChunk(CodeCompletionString::CK_RightParen);
3086 return Result.TakeString();
3089 unsigned clang::getMacroUsagePriority(StringRef MacroName,
3090 const LangOptions &LangOpts,
3091 bool PreferredTypeIsPointer) {
3092 unsigned Priority = CCP_Macro;
3094 // Treat the "nil", "Nil" and "NULL" macros as null pointer constants.
3095 if (MacroName.equals("nil") || MacroName.equals("NULL") ||
3096 MacroName.equals("Nil")) {
3097 Priority = CCP_Constant;
3098 if (PreferredTypeIsPointer)
3099 Priority = Priority / CCF_SimilarTypeMatch;
3101 // Treat "YES", "NO", "true", and "false" as constants.
3102 else if (MacroName.equals("YES") || MacroName.equals("NO") ||
3103 MacroName.equals("true") || MacroName.equals("false"))
3104 Priority = CCP_Constant;
3105 // Treat "bool" as a type.
3106 else if (MacroName.equals("bool"))
3107 Priority = CCP_Type + (LangOpts.ObjC1? CCD_bool_in_ObjC : 0);
3113 CXCursorKind clang::getCursorKindForDecl(const Decl *D) {
3115 return CXCursor_UnexposedDecl;
3117 switch (D->getKind()) {
3118 case Decl::Enum: return CXCursor_EnumDecl;
3119 case Decl::EnumConstant: return CXCursor_EnumConstantDecl;
3120 case Decl::Field: return CXCursor_FieldDecl;
3121 case Decl::Function:
3122 return CXCursor_FunctionDecl;
3123 case Decl::ObjCCategory: return CXCursor_ObjCCategoryDecl;
3124 case Decl::ObjCCategoryImpl: return CXCursor_ObjCCategoryImplDecl;
3125 case Decl::ObjCImplementation: return CXCursor_ObjCImplementationDecl;
3127 case Decl::ObjCInterface: return CXCursor_ObjCInterfaceDecl;
3128 case Decl::ObjCIvar: return CXCursor_ObjCIvarDecl;
3129 case Decl::ObjCMethod:
3130 return cast<ObjCMethodDecl>(D)->isInstanceMethod()
3131 ? CXCursor_ObjCInstanceMethodDecl : CXCursor_ObjCClassMethodDecl;
3132 case Decl::CXXMethod: return CXCursor_CXXMethod;
3133 case Decl::CXXConstructor: return CXCursor_Constructor;
3134 case Decl::CXXDestructor: return CXCursor_Destructor;
3135 case Decl::CXXConversion: return CXCursor_ConversionFunction;
3136 case Decl::ObjCProperty: return CXCursor_ObjCPropertyDecl;
3137 case Decl::ObjCProtocol: return CXCursor_ObjCProtocolDecl;
3138 case Decl::ParmVar: return CXCursor_ParmDecl;
3139 case Decl::Typedef: return CXCursor_TypedefDecl;
3140 case Decl::TypeAlias: return CXCursor_TypeAliasDecl;
3141 case Decl::TypeAliasTemplate: return CXCursor_TypeAliasTemplateDecl;
3142 case Decl::Var: return CXCursor_VarDecl;
3143 case Decl::Namespace: return CXCursor_Namespace;
3144 case Decl::NamespaceAlias: return CXCursor_NamespaceAlias;
3145 case Decl::TemplateTypeParm: return CXCursor_TemplateTypeParameter;
3146 case Decl::NonTypeTemplateParm:return CXCursor_NonTypeTemplateParameter;
3147 case Decl::TemplateTemplateParm:return CXCursor_TemplateTemplateParameter;
3148 case Decl::FunctionTemplate: return CXCursor_FunctionTemplate;
3149 case Decl::ClassTemplate: return CXCursor_ClassTemplate;
3150 case Decl::AccessSpec: return CXCursor_CXXAccessSpecifier;
3151 case Decl::ClassTemplatePartialSpecialization:
3152 return CXCursor_ClassTemplatePartialSpecialization;
3153 case Decl::UsingDirective: return CXCursor_UsingDirective;
3154 case Decl::StaticAssert: return CXCursor_StaticAssert;
3155 case Decl::Friend: return CXCursor_FriendDecl;
3156 case Decl::TranslationUnit: return CXCursor_TranslationUnit;
3159 case Decl::UnresolvedUsingValue:
3160 case Decl::UnresolvedUsingTypename:
3161 return CXCursor_UsingDeclaration;
3163 case Decl::ObjCPropertyImpl:
3164 switch (cast<ObjCPropertyImplDecl>(D)->getPropertyImplementation()) {
3165 case ObjCPropertyImplDecl::Dynamic:
3166 return CXCursor_ObjCDynamicDecl;
3168 case ObjCPropertyImplDecl::Synthesize:
3169 return CXCursor_ObjCSynthesizeDecl;
3173 return CXCursor_ModuleImportDecl;
3175 case Decl::ObjCTypeParam: return CXCursor_TemplateTypeParameter;
3178 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
3179 switch (TD->getTagKind()) {
3180 case TTK_Interface: // fall through
3181 case TTK_Struct: return CXCursor_StructDecl;
3182 case TTK_Class: return CXCursor_ClassDecl;
3183 case TTK_Union: return CXCursor_UnionDecl;
3184 case TTK_Enum: return CXCursor_EnumDecl;
3189 return CXCursor_UnexposedDecl;
3192 static void AddMacroResults(Preprocessor &PP, ResultBuilder &Results,
3193 bool IncludeUndefined,
3194 bool TargetTypeIsPointer = false) {
3195 typedef CodeCompletionResult Result;
3197 Results.EnterNewScope();
3199 for (Preprocessor::macro_iterator M = PP.macro_begin(),
3200 MEnd = PP.macro_end();
3202 auto MD = PP.getMacroDefinition(M->first);
3203 if (IncludeUndefined || MD) {
3204 if (MacroInfo *MI = MD.getMacroInfo())
3205 if (MI->isUsedForHeaderGuard())
3208 Results.AddResult(Result(M->first,
3209 getMacroUsagePriority(M->first->getName(),
3211 TargetTypeIsPointer)));
3215 Results.ExitScope();
3219 static void AddPrettyFunctionResults(const LangOptions &LangOpts,
3220 ResultBuilder &Results) {
3221 typedef CodeCompletionResult Result;
3223 Results.EnterNewScope();
3225 Results.AddResult(Result("__PRETTY_FUNCTION__", CCP_Constant));
3226 Results.AddResult(Result("__FUNCTION__", CCP_Constant));
3227 if (LangOpts.C99 || LangOpts.CPlusPlus11)
3228 Results.AddResult(Result("__func__", CCP_Constant));
3229 Results.ExitScope();
3232 static void HandleCodeCompleteResults(Sema *S,
3233 CodeCompleteConsumer *CodeCompleter,
3234 CodeCompletionContext Context,
3235 CodeCompletionResult *Results,
3236 unsigned NumResults) {
3238 CodeCompleter->ProcessCodeCompleteResults(*S, Context, Results, NumResults);
3241 static enum CodeCompletionContext::Kind mapCodeCompletionContext(Sema &S,
3242 Sema::ParserCompletionContext PCC) {
3244 case Sema::PCC_Namespace:
3245 return CodeCompletionContext::CCC_TopLevel;
3247 case Sema::PCC_Class:
3248 return CodeCompletionContext::CCC_ClassStructUnion;
3250 case Sema::PCC_ObjCInterface:
3251 return CodeCompletionContext::CCC_ObjCInterface;
3253 case Sema::PCC_ObjCImplementation:
3254 return CodeCompletionContext::CCC_ObjCImplementation;
3256 case Sema::PCC_ObjCInstanceVariableList:
3257 return CodeCompletionContext::CCC_ObjCIvarList;
3259 case Sema::PCC_Template:
3260 case Sema::PCC_MemberTemplate:
3261 if (S.CurContext->isFileContext())
3262 return CodeCompletionContext::CCC_TopLevel;
3263 if (S.CurContext->isRecord())
3264 return CodeCompletionContext::CCC_ClassStructUnion;
3265 return CodeCompletionContext::CCC_Other;
3267 case Sema::PCC_RecoveryInFunction:
3268 return CodeCompletionContext::CCC_Recovery;
3270 case Sema::PCC_ForInit:
3271 if (S.getLangOpts().CPlusPlus || S.getLangOpts().C99 ||
3272 S.getLangOpts().ObjC1)
3273 return CodeCompletionContext::CCC_ParenthesizedExpression;
3275 return CodeCompletionContext::CCC_Expression;
3277 case Sema::PCC_Expression:
3278 case Sema::PCC_Condition:
3279 return CodeCompletionContext::CCC_Expression;
3281 case Sema::PCC_Statement:
3282 return CodeCompletionContext::CCC_Statement;
3284 case Sema::PCC_Type:
3285 return CodeCompletionContext::CCC_Type;
3287 case Sema::PCC_ParenthesizedExpression:
3288 return CodeCompletionContext::CCC_ParenthesizedExpression;
3290 case Sema::PCC_LocalDeclarationSpecifiers:
3291 return CodeCompletionContext::CCC_Type;
3294 llvm_unreachable("Invalid ParserCompletionContext!");
3297 /// \brief If we're in a C++ virtual member function, add completion results
3298 /// that invoke the functions we override, since it's common to invoke the
3299 /// overridden function as well as adding new functionality.
3301 /// \param S The semantic analysis object for which we are generating results.
3303 /// \param InContext This context in which the nested-name-specifier preceding
3304 /// the code-completion point
3305 static void MaybeAddOverrideCalls(Sema &S, DeclContext *InContext,
3306 ResultBuilder &Results) {
3307 // Look through blocks.
3308 DeclContext *CurContext = S.CurContext;
3309 while (isa<BlockDecl>(CurContext))
3310 CurContext = CurContext->getParent();
3313 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(CurContext);
3314 if (!Method || !Method->isVirtual())
3317 // We need to have names for all of the parameters, if we're going to
3318 // generate a forwarding call.
3319 for (auto P : Method->parameters())
3320 if (!P->getDeclName())
3323 PrintingPolicy Policy = getCompletionPrintingPolicy(S);
3324 for (CXXMethodDecl::method_iterator M = Method->begin_overridden_methods(),
3325 MEnd = Method->end_overridden_methods();
3327 CodeCompletionBuilder Builder(Results.getAllocator(),
3328 Results.getCodeCompletionTUInfo());
3329 const CXXMethodDecl *Overridden = *M;
3330 if (Overridden->getCanonicalDecl() == Method->getCanonicalDecl())
3333 // If we need a nested-name-specifier, add one now.
3335 NestedNameSpecifier *NNS
3336 = getRequiredQualification(S.Context, CurContext,
3337 Overridden->getDeclContext());
3340 llvm::raw_string_ostream OS(Str);
3341 NNS->print(OS, Policy);
3342 Builder.AddTextChunk(Results.getAllocator().CopyString(OS.str()));
3344 } else if (!InContext->Equals(Overridden->getDeclContext()))
3347 Builder.AddTypedTextChunk(Results.getAllocator().CopyString(
3348 Overridden->getNameAsString()));
3349 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
3350 bool FirstParam = true;
3351 for (auto P : Method->parameters()) {
3355 Builder.AddChunk(CodeCompletionString::CK_Comma);
3357 Builder.AddPlaceholderChunk(
3358 Results.getAllocator().CopyString(P->getIdentifier()->getName()));
3360 Builder.AddChunk(CodeCompletionString::CK_RightParen);
3361 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
3362 CCP_SuperCompletion,
3364 CXAvailability_Available,
3366 Results.Ignore(Overridden);
3370 void Sema::CodeCompleteModuleImport(SourceLocation ImportLoc,
3371 ModuleIdPath Path) {
3372 typedef CodeCompletionResult Result;
3373 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3374 CodeCompleter->getCodeCompletionTUInfo(),
3375 CodeCompletionContext::CCC_Other);
3376 Results.EnterNewScope();
3378 CodeCompletionAllocator &Allocator = Results.getAllocator();
3379 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
3380 typedef CodeCompletionResult Result;
3382 // Enumerate all top-level modules.
3383 SmallVector<Module *, 8> Modules;
3384 PP.getHeaderSearchInfo().collectAllModules(Modules);
3385 for (unsigned I = 0, N = Modules.size(); I != N; ++I) {
3386 Builder.AddTypedTextChunk(
3387 Builder.getAllocator().CopyString(Modules[I]->Name));
3388 Results.AddResult(Result(Builder.TakeString(),
3390 CXCursor_ModuleImportDecl,
3391 Modules[I]->isAvailable()
3392 ? CXAvailability_Available
3393 : CXAvailability_NotAvailable));
3395 } else if (getLangOpts().Modules) {
3396 // Load the named module.
3397 Module *Mod = PP.getModuleLoader().loadModule(ImportLoc, Path,
3399 /*IsInclusionDirective=*/false);
3400 // Enumerate submodules.
3402 for (Module::submodule_iterator Sub = Mod->submodule_begin(),
3403 SubEnd = Mod->submodule_end();
3404 Sub != SubEnd; ++Sub) {
3406 Builder.AddTypedTextChunk(
3407 Builder.getAllocator().CopyString((*Sub)->Name));
3408 Results.AddResult(Result(Builder.TakeString(),
3410 CXCursor_ModuleImportDecl,
3411 (*Sub)->isAvailable()
3412 ? CXAvailability_Available
3413 : CXAvailability_NotAvailable));
3417 Results.ExitScope();
3418 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
3419 Results.data(),Results.size());
3422 void Sema::CodeCompleteOrdinaryName(Scope *S,
3423 ParserCompletionContext CompletionContext) {
3424 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3425 CodeCompleter->getCodeCompletionTUInfo(),
3426 mapCodeCompletionContext(*this, CompletionContext));
3427 Results.EnterNewScope();
3429 // Determine how to filter results, e.g., so that the names of
3430 // values (functions, enumerators, function templates, etc.) are
3431 // only allowed where we can have an expression.
3432 switch (CompletionContext) {
3435 case PCC_ObjCInterface:
3436 case PCC_ObjCImplementation:
3437 case PCC_ObjCInstanceVariableList:
3439 case PCC_MemberTemplate:
3441 case PCC_LocalDeclarationSpecifiers:
3442 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
3446 case PCC_ParenthesizedExpression:
3447 case PCC_Expression:
3450 if (WantTypesInContext(CompletionContext, getLangOpts()))
3451 Results.setFilter(&ResultBuilder::IsOrdinaryName);
3453 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
3455 if (getLangOpts().CPlusPlus)
3456 MaybeAddOverrideCalls(*this, /*InContext=*/nullptr, Results);
3459 case PCC_RecoveryInFunction:
3464 // If we are in a C++ non-static member function, check the qualifiers on
3465 // the member function to filter/prioritize the results list.
3466 if (CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext))
3467 if (CurMethod->isInstance())
3468 Results.setObjectTypeQualifiers(
3469 Qualifiers::fromCVRMask(CurMethod->getTypeQualifiers()));
3471 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3472 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3473 CodeCompleter->includeGlobals());
3475 AddOrdinaryNameResults(CompletionContext, S, *this, Results);
3476 Results.ExitScope();
3478 switch (CompletionContext) {
3479 case PCC_ParenthesizedExpression:
3480 case PCC_Expression:
3482 case PCC_RecoveryInFunction:
3483 if (S->getFnParent())
3484 AddPrettyFunctionResults(getLangOpts(), Results);
3489 case PCC_ObjCInterface:
3490 case PCC_ObjCImplementation:
3491 case PCC_ObjCInstanceVariableList:
3493 case PCC_MemberTemplate:
3497 case PCC_LocalDeclarationSpecifiers:
3501 if (CodeCompleter->includeMacros())
3502 AddMacroResults(PP, Results, false);
3504 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
3505 Results.data(),Results.size());
3508 static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
3509 ParsedType Receiver,
3510 ArrayRef<IdentifierInfo *> SelIdents,
3511 bool AtArgumentExpression,
3513 ResultBuilder &Results);
3515 void Sema::CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
3516 bool AllowNonIdentifiers,
3517 bool AllowNestedNameSpecifiers) {
3518 typedef CodeCompletionResult Result;
3519 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3520 CodeCompleter->getCodeCompletionTUInfo(),
3521 AllowNestedNameSpecifiers
3522 ? CodeCompletionContext::CCC_PotentiallyQualifiedName
3523 : CodeCompletionContext::CCC_Name);
3524 Results.EnterNewScope();
3526 // Type qualifiers can come after names.
3527 Results.AddResult(Result("const"));
3528 Results.AddResult(Result("volatile"));
3529 if (getLangOpts().C99)
3530 Results.AddResult(Result("restrict"));
3532 if (getLangOpts().CPlusPlus) {
3533 if (getLangOpts().CPlusPlus11 &&
3534 (DS.getTypeSpecType() == DeclSpec::TST_class ||
3535 DS.getTypeSpecType() == DeclSpec::TST_struct))
3536 Results.AddResult("final");
3538 if (AllowNonIdentifiers) {
3539 Results.AddResult(Result("operator"));
3542 // Add nested-name-specifiers.
3543 if (AllowNestedNameSpecifiers) {
3544 Results.allowNestedNameSpecifiers();
3545 Results.setFilter(&ResultBuilder::IsImpossibleToSatisfy);
3546 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3547 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer,
3548 CodeCompleter->includeGlobals());
3549 Results.setFilter(nullptr);
3552 Results.ExitScope();
3554 // If we're in a context where we might have an expression (rather than a
3555 // declaration), and what we've seen so far is an Objective-C type that could
3556 // be a receiver of a class message, this may be a class message send with
3557 // the initial opening bracket '[' missing. Add appropriate completions.
3558 if (AllowNonIdentifiers && !AllowNestedNameSpecifiers &&
3559 DS.getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier &&
3560 DS.getTypeSpecType() == DeclSpec::TST_typename &&
3561 DS.getTypeSpecComplex() == DeclSpec::TSC_unspecified &&
3562 DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
3563 !DS.isTypeAltiVecVector() &&
3565 (S->getFlags() & Scope::DeclScope) != 0 &&
3566 (S->getFlags() & (Scope::ClassScope | Scope::TemplateParamScope |
3567 Scope::FunctionPrototypeScope |
3568 Scope::AtCatchScope)) == 0) {
3569 ParsedType T = DS.getRepAsType();
3570 if (!T.get().isNull() && T.get()->isObjCObjectOrInterfaceType())
3571 AddClassMessageCompletions(*this, S, T, None, false, false, Results);
3574 // Note that we intentionally suppress macro results here, since we do not
3575 // encourage using macros to produce the names of entities.
3577 HandleCodeCompleteResults(this, CodeCompleter,
3578 Results.getCompletionContext(),
3579 Results.data(), Results.size());
3582 struct Sema::CodeCompleteExpressionData {
3583 CodeCompleteExpressionData(QualType PreferredType = QualType())
3584 : PreferredType(PreferredType), IntegralConstantExpression(false),
3585 ObjCCollection(false) { }
3587 QualType PreferredType;
3588 bool IntegralConstantExpression;
3589 bool ObjCCollection;
3590 SmallVector<Decl *, 4> IgnoreDecls;
3593 /// \brief Perform code-completion in an expression context when we know what
3594 /// type we're looking for.
3595 void Sema::CodeCompleteExpression(Scope *S,
3596 const CodeCompleteExpressionData &Data) {
3597 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3598 CodeCompleter->getCodeCompletionTUInfo(),
3599 CodeCompletionContext::CCC_Expression);
3600 if (Data.ObjCCollection)
3601 Results.setFilter(&ResultBuilder::IsObjCCollection);
3602 else if (Data.IntegralConstantExpression)
3603 Results.setFilter(&ResultBuilder::IsIntegralConstantValue);
3604 else if (WantTypesInContext(PCC_Expression, getLangOpts()))
3605 Results.setFilter(&ResultBuilder::IsOrdinaryName);
3607 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
3609 if (!Data.PreferredType.isNull())
3610 Results.setPreferredType(Data.PreferredType.getNonReferenceType());
3612 // Ignore any declarations that we were told that we don't care about.
3613 for (unsigned I = 0, N = Data.IgnoreDecls.size(); I != N; ++I)
3614 Results.Ignore(Data.IgnoreDecls[I]);
3616 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3617 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3618 CodeCompleter->includeGlobals());
3620 Results.EnterNewScope();
3621 AddOrdinaryNameResults(PCC_Expression, S, *this, Results);
3622 Results.ExitScope();
3624 bool PreferredTypeIsPointer = false;
3625 if (!Data.PreferredType.isNull())
3626 PreferredTypeIsPointer = Data.PreferredType->isAnyPointerType()
3627 || Data.PreferredType->isMemberPointerType()
3628 || Data.PreferredType->isBlockPointerType();
3630 if (S->getFnParent() &&
3631 !Data.ObjCCollection &&
3632 !Data.IntegralConstantExpression)
3633 AddPrettyFunctionResults(getLangOpts(), Results);
3635 if (CodeCompleter->includeMacros())
3636 AddMacroResults(PP, Results, false, PreferredTypeIsPointer);
3637 HandleCodeCompleteResults(this, CodeCompleter,
3638 CodeCompletionContext(CodeCompletionContext::CCC_Expression,
3639 Data.PreferredType),
3640 Results.data(),Results.size());
3643 void Sema::CodeCompletePostfixExpression(Scope *S, ExprResult E) {
3645 CodeCompleteOrdinaryName(S, PCC_RecoveryInFunction);
3646 else if (getLangOpts().ObjC1)
3647 CodeCompleteObjCInstanceMessage(S, E.get(), None, false);
3650 /// \brief The set of properties that have already been added, referenced by
3652 typedef llvm::SmallPtrSet<IdentifierInfo*, 16> AddedPropertiesSet;
3654 /// \brief Retrieve the container definition, if any?
3655 static ObjCContainerDecl *getContainerDef(ObjCContainerDecl *Container) {
3656 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
3657 if (Interface->hasDefinition())
3658 return Interface->getDefinition();
3663 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
3664 if (Protocol->hasDefinition())
3665 return Protocol->getDefinition();
3672 /// \brief Adds a block invocation code completion result for the given block
3673 /// declaration \p BD.
3674 static void AddObjCBlockCall(ASTContext &Context, const PrintingPolicy &Policy,
3675 CodeCompletionBuilder &Builder,
3676 const NamedDecl *BD,
3677 const FunctionTypeLoc &BlockLoc,
3678 const FunctionProtoTypeLoc &BlockProtoLoc) {
3679 Builder.AddResultTypeChunk(
3680 GetCompletionTypeString(BlockLoc.getReturnLoc().getType(), Context,
3681 Policy, Builder.getAllocator()));
3683 AddTypedNameChunk(Context, Policy, BD, Builder);
3684 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
3686 if (BlockProtoLoc && BlockProtoLoc.getTypePtr()->isVariadic()) {
3687 Builder.AddPlaceholderChunk("...");
3689 for (unsigned I = 0, N = BlockLoc.getNumParams(); I != N; ++I) {
3691 Builder.AddChunk(CodeCompletionString::CK_Comma);
3693 // Format the placeholder string.
3694 std::string PlaceholderStr =
3695 FormatFunctionParameter(Policy, BlockLoc.getParam(I));
3697 if (I == N - 1 && BlockProtoLoc &&
3698 BlockProtoLoc.getTypePtr()->isVariadic())
3699 PlaceholderStr += ", ...";
3701 // Add the placeholder string.
3702 Builder.AddPlaceholderChunk(
3703 Builder.getAllocator().CopyString(PlaceholderStr));
3707 Builder.AddChunk(CodeCompletionString::CK_RightParen);
3710 static void AddObjCProperties(
3711 const CodeCompletionContext &CCContext, ObjCContainerDecl *Container,
3712 bool AllowCategories, bool AllowNullaryMethods, DeclContext *CurContext,
3713 AddedPropertiesSet &AddedProperties, ResultBuilder &Results,
3714 bool IsBaseExprStatement = false, bool IsClassProperty = false) {
3715 typedef CodeCompletionResult Result;
3717 // Retrieve the definition.
3718 Container = getContainerDef(Container);
3720 // Add properties in this container.
3721 const auto AddProperty = [&](const ObjCPropertyDecl *P) {
3722 if (!AddedProperties.insert(P->getIdentifier()).second)
3725 // FIXME: Provide block invocation completion for non-statement
3727 if (!P->getType().getTypePtr()->isBlockPointerType() ||
3728 !IsBaseExprStatement) {
3729 Results.MaybeAddResult(Result(P, Results.getBasePriority(P), nullptr),
3734 // Block setter and invocation completion is provided only when we are able
3735 // to find the FunctionProtoTypeLoc with parameter names for the block.
3736 FunctionTypeLoc BlockLoc;
3737 FunctionProtoTypeLoc BlockProtoLoc;
3738 findTypeLocationForBlockDecl(P->getTypeSourceInfo(), BlockLoc,
3741 Results.MaybeAddResult(Result(P, Results.getBasePriority(P), nullptr),
3746 // The default completion result for block properties should be the block
3747 // invocation completion when the base expression is a statement.
3748 CodeCompletionBuilder Builder(Results.getAllocator(),
3749 Results.getCodeCompletionTUInfo());
3750 AddObjCBlockCall(Container->getASTContext(),
3751 getCompletionPrintingPolicy(Results.getSema()), Builder, P,
3752 BlockLoc, BlockProtoLoc);
3753 Results.MaybeAddResult(
3754 Result(Builder.TakeString(), P, Results.getBasePriority(P)),
3757 // Provide additional block setter completion iff the base expression is a
3758 // statement and the block property is mutable.
3759 if (!P->isReadOnly()) {
3760 CodeCompletionBuilder Builder(Results.getAllocator(),
3761 Results.getCodeCompletionTUInfo());
3762 AddResultTypeChunk(Container->getASTContext(),
3763 getCompletionPrintingPolicy(Results.getSema()), P,
3764 CCContext.getBaseType(), Builder);
3765 Builder.AddTypedTextChunk(
3766 Results.getAllocator().CopyString(P->getName()));
3767 Builder.AddChunk(CodeCompletionString::CK_Equal);
3769 std::string PlaceholderStr = formatBlockPlaceholder(
3770 getCompletionPrintingPolicy(Results.getSema()), P, BlockLoc,
3771 BlockProtoLoc, /*SuppressBlockName=*/true);
3772 // Add the placeholder string.
3773 Builder.AddPlaceholderChunk(
3774 Builder.getAllocator().CopyString(PlaceholderStr));
3776 // When completing blocks properties that return void the default
3777 // property completion result should show up before the setter,
3778 // otherwise the setter completion should show up before the default
3779 // property completion, as we normally want to use the result of the
3781 Results.MaybeAddResult(
3782 Result(Builder.TakeString(), P,
3783 Results.getBasePriority(P) +
3784 (BlockLoc.getTypePtr()->getReturnType()->isVoidType()
3785 ? CCD_BlockPropertySetter
3786 : -CCD_BlockPropertySetter)),
3791 if (IsClassProperty) {
3792 for (const auto *P : Container->class_properties())
3795 for (const auto *P : Container->instance_properties())
3799 // Add nullary methods or implicit class properties
3800 if (AllowNullaryMethods) {
3801 ASTContext &Context = Container->getASTContext();
3802 PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema());
3803 // Adds a method result
3804 const auto AddMethod = [&](const ObjCMethodDecl *M) {
3805 IdentifierInfo *Name = M->getSelector().getIdentifierInfoForSlot(0);
3808 if (!AddedProperties.insert(Name).second)
3810 CodeCompletionBuilder Builder(Results.getAllocator(),
3811 Results.getCodeCompletionTUInfo());
3812 AddResultTypeChunk(Context, Policy, M, CCContext.getBaseType(), Builder);
3813 Builder.AddTypedTextChunk(
3814 Results.getAllocator().CopyString(Name->getName()));
3815 Results.MaybeAddResult(
3816 Result(Builder.TakeString(), M,
3817 CCP_MemberDeclaration + CCD_MethodAsProperty),
3821 if (IsClassProperty) {
3822 for (const auto *M : Container->methods()) {
3823 // Gather the class method that can be used as implicit property
3824 // getters. Methods with arguments or methods that return void aren't
3825 // added to the results as they can't be used as a getter.
3826 if (!M->getSelector().isUnarySelector() ||
3827 M->getReturnType()->isVoidType() || M->isInstanceMethod())
3832 for (auto *M : Container->methods()) {
3833 if (M->getSelector().isUnarySelector())
3839 // Add properties in referenced protocols.
3840 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
3841 for (auto *P : Protocol->protocols())
3842 AddObjCProperties(CCContext, P, AllowCategories, AllowNullaryMethods,
3843 CurContext, AddedProperties, Results,
3844 IsBaseExprStatement, IsClassProperty);
3845 } else if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)){
3846 if (AllowCategories) {
3847 // Look through categories.
3848 for (auto *Cat : IFace->known_categories())
3849 AddObjCProperties(CCContext, Cat, AllowCategories, AllowNullaryMethods,
3850 CurContext, AddedProperties, Results,
3851 IsBaseExprStatement, IsClassProperty);
3854 // Look through protocols.
3855 for (auto *I : IFace->all_referenced_protocols())
3856 AddObjCProperties(CCContext, I, AllowCategories, AllowNullaryMethods,
3857 CurContext, AddedProperties, Results,
3858 IsBaseExprStatement, IsClassProperty);
3860 // Look in the superclass.
3861 if (IFace->getSuperClass())
3862 AddObjCProperties(CCContext, IFace->getSuperClass(), AllowCategories,
3863 AllowNullaryMethods, CurContext, AddedProperties,
3864 Results, IsBaseExprStatement, IsClassProperty);
3865 } else if (const ObjCCategoryDecl *Category
3866 = dyn_cast<ObjCCategoryDecl>(Container)) {
3867 // Look through protocols.
3868 for (auto *P : Category->protocols())
3869 AddObjCProperties(CCContext, P, AllowCategories, AllowNullaryMethods,
3870 CurContext, AddedProperties, Results,
3871 IsBaseExprStatement, IsClassProperty);
3875 static void AddRecordMembersCompletionResults(Sema &SemaRef,
3876 ResultBuilder &Results, Scope *S,
3879 // Indicate that we are performing a member access, and the cv-qualifiers
3880 // for the base object type.
3881 Results.setObjectTypeQualifiers(BaseType.getQualifiers());
3883 // Access to a C/C++ class, struct, or union.
3884 Results.allowNestedNameSpecifiers();
3885 CodeCompletionDeclConsumer Consumer(Results, SemaRef.CurContext);
3886 SemaRef.LookupVisibleDecls(RD, Sema::LookupMemberName, Consumer,
3887 SemaRef.CodeCompleter->includeGlobals(),
3888 /*IncludeDependentBases=*/true);
3890 if (SemaRef.getLangOpts().CPlusPlus) {
3891 if (!Results.empty()) {
3892 // The "template" keyword can follow "->" or "." in the grammar.
3893 // However, we only want to suggest the template keyword if something
3895 bool IsDependent = BaseType->isDependentType();
3897 for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent())
3898 if (DeclContext *Ctx = DepScope->getEntity()) {
3899 IsDependent = Ctx->isDependentContext();
3905 Results.AddResult(CodeCompletionResult("template"));
3910 void Sema::CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base,
3911 SourceLocation OpLoc, bool IsArrow,
3912 bool IsBaseExprStatement) {
3913 if (!Base || !CodeCompleter)
3916 ExprResult ConvertedBase = PerformMemberExprBaseConversion(Base, IsArrow);
3917 if (ConvertedBase.isInvalid())
3919 Base = ConvertedBase.get();
3921 QualType BaseType = Base->getType();
3924 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
3925 BaseType = Ptr->getPointeeType();
3926 else if (BaseType->isObjCObjectPointerType())
3932 enum CodeCompletionContext::Kind contextKind;
3935 contextKind = CodeCompletionContext::CCC_ArrowMemberAccess;
3938 if (BaseType->isObjCObjectPointerType() ||
3939 BaseType->isObjCObjectOrInterfaceType()) {
3940 contextKind = CodeCompletionContext::CCC_ObjCPropertyAccess;
3943 contextKind = CodeCompletionContext::CCC_DotMemberAccess;
3947 CodeCompletionContext CCContext(contextKind, BaseType);
3948 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3949 CodeCompleter->getCodeCompletionTUInfo(),
3951 &ResultBuilder::IsMember);
3952 Results.EnterNewScope();
3953 if (const RecordType *Record = BaseType->getAs<RecordType>()) {
3954 AddRecordMembersCompletionResults(*this, Results, S, BaseType,
3956 } else if (const auto *TST = BaseType->getAs<TemplateSpecializationType>()) {
3957 TemplateName TN = TST->getTemplateName();
3958 if (const auto *TD =
3959 dyn_cast_or_null<ClassTemplateDecl>(TN.getAsTemplateDecl())) {
3960 CXXRecordDecl *RD = TD->getTemplatedDecl();
3961 AddRecordMembersCompletionResults(*this, Results, S, BaseType, RD);
3963 } else if (const auto *ICNT = BaseType->getAs<InjectedClassNameType>()) {
3964 if (auto *RD = ICNT->getDecl())
3965 AddRecordMembersCompletionResults(*this, Results, S, BaseType, RD);
3966 } else if (!IsArrow && BaseType->isObjCObjectPointerType()) {
3967 // Objective-C property reference.
3968 AddedPropertiesSet AddedProperties;
3970 if (const ObjCObjectPointerType *ObjCPtr =
3971 BaseType->getAsObjCInterfacePointerType()) {
3972 // Add property results based on our interface.
3973 assert(ObjCPtr && "Non-NULL pointer guaranteed above!");
3974 AddObjCProperties(CCContext, ObjCPtr->getInterfaceDecl(), true,
3975 /*AllowNullaryMethods=*/true, CurContext,
3976 AddedProperties, Results, IsBaseExprStatement);
3979 // Add properties from the protocols in a qualified interface.
3980 for (auto *I : BaseType->getAs<ObjCObjectPointerType>()->quals())
3981 AddObjCProperties(CCContext, I, true, /*AllowNullaryMethods=*/true,
3982 CurContext, AddedProperties, Results,
3983 IsBaseExprStatement);
3984 } else if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
3985 (!IsArrow && BaseType->isObjCObjectType())) {
3986 // Objective-C instance variable access.
3987 ObjCInterfaceDecl *Class = nullptr;
3988 if (const ObjCObjectPointerType *ObjCPtr
3989 = BaseType->getAs<ObjCObjectPointerType>())
3990 Class = ObjCPtr->getInterfaceDecl();
3992 Class = BaseType->getAs<ObjCObjectType>()->getInterface();
3994 // Add all ivars from this class and its superclasses.
3996 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3997 Results.setFilter(&ResultBuilder::IsObjCIvar);
3998 LookupVisibleDecls(Class, LookupMemberName, Consumer,
3999 CodeCompleter->includeGlobals());
4003 // FIXME: How do we cope with isa?
4005 Results.ExitScope();
4007 // Hand off the results found for code completion.
4008 HandleCodeCompleteResults(this, CodeCompleter,
4009 Results.getCompletionContext(),
4010 Results.data(),Results.size());
4013 void Sema::CodeCompleteObjCClassPropertyRefExpr(Scope *S,
4014 IdentifierInfo &ClassName,
4015 SourceLocation ClassNameLoc,
4016 bool IsBaseExprStatement) {
4017 IdentifierInfo *ClassNamePtr = &ClassName;
4018 ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(ClassNamePtr, ClassNameLoc);
4021 CodeCompletionContext CCContext(
4022 CodeCompletionContext::CCC_ObjCPropertyAccess);
4023 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4024 CodeCompleter->getCodeCompletionTUInfo(), CCContext,
4025 &ResultBuilder::IsMember);
4026 Results.EnterNewScope();
4027 AddedPropertiesSet AddedProperties;
4028 AddObjCProperties(CCContext, IFace, true,
4029 /*AllowNullaryMethods=*/true, CurContext, AddedProperties,
4030 Results, IsBaseExprStatement,
4031 /*IsClassProperty=*/true);
4032 Results.ExitScope();
4033 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4034 Results.data(), Results.size());
4037 void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) {
4041 ResultBuilder::LookupFilter Filter = nullptr;
4042 enum CodeCompletionContext::Kind ContextKind
4043 = CodeCompletionContext::CCC_Other;
4044 switch ((DeclSpec::TST)TagSpec) {
4045 case DeclSpec::TST_enum:
4046 Filter = &ResultBuilder::IsEnum;
4047 ContextKind = CodeCompletionContext::CCC_EnumTag;
4050 case DeclSpec::TST_union:
4051 Filter = &ResultBuilder::IsUnion;
4052 ContextKind = CodeCompletionContext::CCC_UnionTag;
4055 case DeclSpec::TST_struct:
4056 case DeclSpec::TST_class:
4057 case DeclSpec::TST_interface:
4058 Filter = &ResultBuilder::IsClassOrStruct;
4059 ContextKind = CodeCompletionContext::CCC_ClassOrStructTag;
4063 llvm_unreachable("Unknown type specifier kind in CodeCompleteTag");
4066 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4067 CodeCompleter->getCodeCompletionTUInfo(), ContextKind);
4068 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4070 // First pass: look for tags.
4071 Results.setFilter(Filter);
4072 LookupVisibleDecls(S, LookupTagName, Consumer,
4073 CodeCompleter->includeGlobals());
4075 if (CodeCompleter->includeGlobals()) {
4076 // Second pass: look for nested name specifiers.
4077 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
4078 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer);
4081 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4082 Results.data(),Results.size());
4085 static void AddTypeQualifierResults(DeclSpec &DS, ResultBuilder &Results,
4086 const LangOptions &LangOpts) {
4087 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_const))
4088 Results.AddResult("const");
4089 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_volatile))
4090 Results.AddResult("volatile");
4091 if (LangOpts.C99 && !(DS.getTypeQualifiers() & DeclSpec::TQ_restrict))
4092 Results.AddResult("restrict");
4093 if (LangOpts.C11 && !(DS.getTypeQualifiers() & DeclSpec::TQ_atomic))
4094 Results.AddResult("_Atomic");
4095 if (LangOpts.MSVCCompat && !(DS.getTypeQualifiers() & DeclSpec::TQ_unaligned))
4096 Results.AddResult("__unaligned");
4099 void Sema::CodeCompleteTypeQualifiers(DeclSpec &DS) {
4100 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4101 CodeCompleter->getCodeCompletionTUInfo(),
4102 CodeCompletionContext::CCC_TypeQualifiers);
4103 Results.EnterNewScope();
4104 AddTypeQualifierResults(DS, Results, LangOpts);
4105 Results.ExitScope();
4106 HandleCodeCompleteResults(this, CodeCompleter,
4107 Results.getCompletionContext(),
4108 Results.data(), Results.size());
4111 void Sema::CodeCompleteFunctionQualifiers(DeclSpec &DS, Declarator &D,
4112 const VirtSpecifiers *VS) {
4113 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4114 CodeCompleter->getCodeCompletionTUInfo(),
4115 CodeCompletionContext::CCC_TypeQualifiers);
4116 Results.EnterNewScope();
4117 AddTypeQualifierResults(DS, Results, LangOpts);
4118 if (LangOpts.CPlusPlus11) {
4119 Results.AddResult("noexcept");
4120 if (D.getContext() == Declarator::MemberContext && !D.isCtorOrDtor() &&
4121 !D.isStaticMember()) {
4122 if (!VS || !VS->isFinalSpecified())
4123 Results.AddResult("final");
4124 if (!VS || !VS->isOverrideSpecified())
4125 Results.AddResult("override");
4128 Results.ExitScope();
4129 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4130 Results.data(), Results.size());
4133 void Sema::CodeCompleteBracketDeclarator(Scope *S) {
4134 CodeCompleteExpression(S, QualType(getASTContext().getSizeType()));
4137 void Sema::CodeCompleteCase(Scope *S) {
4138 if (getCurFunction()->SwitchStack.empty() || !CodeCompleter)
4141 SwitchStmt *Switch = getCurFunction()->SwitchStack.back();
4142 QualType type = Switch->getCond()->IgnoreImplicit()->getType();
4143 if (!type->isEnumeralType()) {
4144 CodeCompleteExpressionData Data(type);
4145 Data.IntegralConstantExpression = true;
4146 CodeCompleteExpression(S, Data);
4150 // Code-complete the cases of a switch statement over an enumeration type
4151 // by providing the list of
4152 EnumDecl *Enum = type->castAs<EnumType>()->getDecl();
4153 if (EnumDecl *Def = Enum->getDefinition())
4156 // Determine which enumerators we have already seen in the switch statement.
4157 // FIXME: Ideally, we would also be able to look *past* the code-completion
4158 // token, in case we are code-completing in the middle of the switch and not
4159 // at the end. However, we aren't able to do so at the moment.
4160 llvm::SmallPtrSet<EnumConstantDecl *, 8> EnumeratorsSeen;
4161 NestedNameSpecifier *Qualifier = nullptr;
4162 for (SwitchCase *SC = Switch->getSwitchCaseList(); SC;
4163 SC = SC->getNextSwitchCase()) {
4164 CaseStmt *Case = dyn_cast<CaseStmt>(SC);
4168 Expr *CaseVal = Case->getLHS()->IgnoreParenCasts();
4169 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseVal))
4170 if (EnumConstantDecl *Enumerator
4171 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
4172 // We look into the AST of the case statement to determine which
4173 // enumerator was named. Alternatively, we could compute the value of
4174 // the integral constant expression, then compare it against the
4175 // values of each enumerator. However, value-based approach would not
4176 // work as well with C++ templates where enumerators declared within a
4177 // template are type- and value-dependent.
4178 EnumeratorsSeen.insert(Enumerator);
4180 // If this is a qualified-id, keep track of the nested-name-specifier
4181 // so that we can reproduce it as part of code completion, e.g.,
4183 // switch (TagD.getKind()) {
4184 // case TagDecl::TK_enum:
4188 // At the XXX, our completions are TagDecl::TK_union,
4189 // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
4190 // TK_struct, and TK_class.
4191 Qualifier = DRE->getQualifier();
4195 if (getLangOpts().CPlusPlus && !Qualifier && EnumeratorsSeen.empty()) {
4196 // If there are no prior enumerators in C++, check whether we have to
4197 // qualify the names of the enumerators that we suggest, because they
4198 // may not be visible in this scope.
4199 Qualifier = getRequiredQualification(Context, CurContext, Enum);
4202 // Add any enumerators that have not yet been mentioned.
4203 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4204 CodeCompleter->getCodeCompletionTUInfo(),
4205 CodeCompletionContext::CCC_Expression);
4206 Results.EnterNewScope();
4207 for (auto *E : Enum->enumerators()) {
4208 if (EnumeratorsSeen.count(E))
4211 CodeCompletionResult R(E, CCP_EnumInCase, Qualifier);
4212 Results.AddResult(R, CurContext, nullptr, false);
4214 Results.ExitScope();
4216 //We need to make sure we're setting the right context,
4217 //so only say we include macros if the code completer says we do
4218 enum CodeCompletionContext::Kind kind = CodeCompletionContext::CCC_Other;
4219 if (CodeCompleter->includeMacros()) {
4220 AddMacroResults(PP, Results, false);
4221 kind = CodeCompletionContext::CCC_OtherWithMacros;
4224 HandleCodeCompleteResults(this, CodeCompleter,
4226 Results.data(),Results.size());
4229 static bool anyNullArguments(ArrayRef<Expr *> Args) {
4230 if (Args.size() && !Args.data())
4233 for (unsigned I = 0; I != Args.size(); ++I)
4240 typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate;
4242 static void mergeCandidatesWithResults(Sema &SemaRef,
4243 SmallVectorImpl<ResultCandidate> &Results,
4244 OverloadCandidateSet &CandidateSet,
4245 SourceLocation Loc) {
4246 if (!CandidateSet.empty()) {
4247 // Sort the overload candidate set by placing the best overloads first.
4249 CandidateSet.begin(), CandidateSet.end(),
4250 [&](const OverloadCandidate &X, const OverloadCandidate &Y) {
4251 return isBetterOverloadCandidate(SemaRef, X, Y, Loc);
4254 // Add the remaining viable overload candidates as code-completion results.
4255 for (auto &Candidate : CandidateSet)
4256 if (Candidate.Viable)
4257 Results.push_back(ResultCandidate(Candidate.Function));
4261 /// \brief Get the type of the Nth parameter from a given set of overload
4263 static QualType getParamType(Sema &SemaRef,
4264 ArrayRef<ResultCandidate> Candidates,
4267 // Given the overloads 'Candidates' for a function call matching all arguments
4268 // up to N, return the type of the Nth parameter if it is the same for all
4269 // overload candidates.
4271 for (auto &Candidate : Candidates) {
4272 if (auto FType = Candidate.getFunctionType())
4273 if (auto Proto = dyn_cast<FunctionProtoType>(FType))
4274 if (N < Proto->getNumParams()) {
4275 if (ParamType.isNull())
4276 ParamType = Proto->getParamType(N);
4277 else if (!SemaRef.Context.hasSameUnqualifiedType(
4278 ParamType.getNonReferenceType(),
4279 Proto->getParamType(N).getNonReferenceType()))
4280 // Otherwise return a default-constructed QualType.
4288 static void CodeCompleteOverloadResults(Sema &SemaRef, Scope *S,
4289 MutableArrayRef<ResultCandidate> Candidates,
4290 unsigned CurrentArg,
4291 bool CompleteExpressionWithCurrentArg = true) {
4293 if (CompleteExpressionWithCurrentArg)
4294 ParamType = getParamType(SemaRef, Candidates, CurrentArg);
4296 if (ParamType.isNull())
4297 SemaRef.CodeCompleteOrdinaryName(S, Sema::PCC_Expression);
4299 SemaRef.CodeCompleteExpression(S, ParamType);
4301 if (!Candidates.empty())
4302 SemaRef.CodeCompleter->ProcessOverloadCandidates(SemaRef, CurrentArg,
4307 void Sema::CodeCompleteCall(Scope *S, Expr *Fn, ArrayRef<Expr *> Args) {
4311 // When we're code-completing for a call, we fall back to ordinary
4312 // name code-completion whenever we can't produce specific
4313 // results. We may want to revisit this strategy in the future,
4314 // e.g., by merging the two kinds of results.
4316 // FIXME: Provide support for variadic template functions.
4318 // Ignore type-dependent call expressions entirely.
4319 if (!Fn || Fn->isTypeDependent() || anyNullArguments(Args) ||
4320 Expr::hasAnyTypeDependentArguments(Args)) {
4321 CodeCompleteOrdinaryName(S, PCC_Expression);
4325 // Build an overload candidate set based on the functions we find.
4326 SourceLocation Loc = Fn->getExprLoc();
4327 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
4329 SmallVector<ResultCandidate, 8> Results;
4331 Expr *NakedFn = Fn->IgnoreParenCasts();
4332 if (auto ULE = dyn_cast<UnresolvedLookupExpr>(NakedFn))
4333 AddOverloadedCallCandidates(ULE, Args, CandidateSet,
4334 /*PartialOverloading=*/true);
4335 else if (auto UME = dyn_cast<UnresolvedMemberExpr>(NakedFn)) {
4336 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
4337 if (UME->hasExplicitTemplateArgs()) {
4338 UME->copyTemplateArgumentsInto(TemplateArgsBuffer);
4339 TemplateArgs = &TemplateArgsBuffer;
4342 // Add the base as first argument (use a nullptr if the base is implicit).
4343 SmallVector<Expr *, 12> ArgExprs(
4344 1, UME->isImplicitAccess() ? nullptr : UME->getBase());
4345 ArgExprs.append(Args.begin(), Args.end());
4346 UnresolvedSet<8> Decls;
4347 Decls.append(UME->decls_begin(), UME->decls_end());
4348 AddFunctionCandidates(Decls, ArgExprs, CandidateSet, TemplateArgs,
4349 /*SuppressUsedConversions=*/false,
4350 /*PartialOverloading=*/true);
4352 FunctionDecl *FD = nullptr;
4353 if (auto MCE = dyn_cast<MemberExpr>(NakedFn))
4354 FD = dyn_cast<FunctionDecl>(MCE->getMemberDecl());
4355 else if (auto DRE = dyn_cast<DeclRefExpr>(NakedFn))
4356 FD = dyn_cast<FunctionDecl>(DRE->getDecl());
4357 if (FD) { // We check whether it's a resolved function declaration.
4358 if (!getLangOpts().CPlusPlus ||
4359 !FD->getType()->getAs<FunctionProtoType>())
4360 Results.push_back(ResultCandidate(FD));
4362 AddOverloadCandidate(FD, DeclAccessPair::make(FD, FD->getAccess()),
4364 /*SuppressUsedConversions=*/false,
4365 /*PartialOverloading=*/true);
4367 } else if (auto DC = NakedFn->getType()->getAsCXXRecordDecl()) {
4368 // If expression's type is CXXRecordDecl, it may overload the function
4369 // call operator, so we check if it does and add them as candidates.
4370 // A complete type is needed to lookup for member function call operators.
4371 if (isCompleteType(Loc, NakedFn->getType())) {
4372 DeclarationName OpName = Context.DeclarationNames
4373 .getCXXOperatorName(OO_Call);
4374 LookupResult R(*this, OpName, Loc, LookupOrdinaryName);
4375 LookupQualifiedName(R, DC);
4376 R.suppressDiagnostics();
4377 SmallVector<Expr *, 12> ArgExprs(1, NakedFn);
4378 ArgExprs.append(Args.begin(), Args.end());
4379 AddFunctionCandidates(R.asUnresolvedSet(), ArgExprs, CandidateSet,
4380 /*ExplicitArgs=*/nullptr,
4381 /*SuppressUsedConversions=*/false,
4382 /*PartialOverloading=*/true);
4385 // Lastly we check whether expression's type is function pointer or
4387 QualType T = NakedFn->getType();
4388 if (!T->getPointeeType().isNull())
4389 T = T->getPointeeType();
4391 if (auto FP = T->getAs<FunctionProtoType>()) {
4392 if (!TooManyArguments(FP->getNumParams(), Args.size(),
4393 /*PartialOverloading=*/true) ||
4395 Results.push_back(ResultCandidate(FP));
4396 } else if (auto FT = T->getAs<FunctionType>())
4397 // No prototype and declaration, it may be a K & R style function.
4398 Results.push_back(ResultCandidate(FT));
4402 mergeCandidatesWithResults(*this, Results, CandidateSet, Loc);
4403 CodeCompleteOverloadResults(*this, S, Results, Args.size(),
4404 !CandidateSet.empty());
4407 void Sema::CodeCompleteConstructor(Scope *S, QualType Type, SourceLocation Loc,
4408 ArrayRef<Expr *> Args) {
4412 // A complete type is needed to lookup for constructors.
4413 if (!isCompleteType(Loc, Type))
4416 CXXRecordDecl *RD = Type->getAsCXXRecordDecl();
4418 CodeCompleteExpression(S, Type);
4422 // FIXME: Provide support for member initializers.
4423 // FIXME: Provide support for variadic template constructors.
4425 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
4427 for (auto C : LookupConstructors(RD)) {
4428 if (auto FD = dyn_cast<FunctionDecl>(C)) {
4429 AddOverloadCandidate(FD, DeclAccessPair::make(FD, C->getAccess()),
4431 /*SuppressUsedConversions=*/false,
4432 /*PartialOverloading=*/true);
4433 } else if (auto FTD = dyn_cast<FunctionTemplateDecl>(C)) {
4434 AddTemplateOverloadCandidate(FTD,
4435 DeclAccessPair::make(FTD, C->getAccess()),
4436 /*ExplicitTemplateArgs=*/nullptr,
4438 /*SuppressUsedConversions=*/false,
4439 /*PartialOverloading=*/true);
4443 SmallVector<ResultCandidate, 8> Results;
4444 mergeCandidatesWithResults(*this, Results, CandidateSet, Loc);
4445 CodeCompleteOverloadResults(*this, S, Results, Args.size());
4448 void Sema::CodeCompleteInitializer(Scope *S, Decl *D) {
4449 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
4451 CodeCompleteOrdinaryName(S, PCC_Expression);
4455 CodeCompleteExpression(S, VD->getType());
4458 void Sema::CodeCompleteReturn(Scope *S) {
4459 QualType ResultType;
4460 if (isa<BlockDecl>(CurContext)) {
4461 if (BlockScopeInfo *BSI = getCurBlock())
4462 ResultType = BSI->ReturnType;
4463 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(CurContext))
4464 ResultType = Function->getReturnType();
4465 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(CurContext))
4466 ResultType = Method->getReturnType();
4468 if (ResultType.isNull())
4469 CodeCompleteOrdinaryName(S, PCC_Expression);
4471 CodeCompleteExpression(S, ResultType);
4474 void Sema::CodeCompleteAfterIf(Scope *S) {
4475 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4476 CodeCompleter->getCodeCompletionTUInfo(),
4477 mapCodeCompletionContext(*this, PCC_Statement));
4478 Results.setFilter(&ResultBuilder::IsOrdinaryName);
4479 Results.EnterNewScope();
4481 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4482 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4483 CodeCompleter->includeGlobals());
4485 AddOrdinaryNameResults(PCC_Statement, S, *this, Results);
4488 CodeCompletionBuilder Builder(Results.getAllocator(),
4489 Results.getCodeCompletionTUInfo());
4490 Builder.AddTypedTextChunk("else");
4491 if (Results.includeCodePatterns()) {
4492 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4493 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4494 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
4495 Builder.AddPlaceholderChunk("statements");
4496 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
4497 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4499 Results.AddResult(Builder.TakeString());
4502 Builder.AddTypedTextChunk("else");
4503 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4504 Builder.AddTextChunk("if");
4505 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4506 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4507 if (getLangOpts().CPlusPlus)
4508 Builder.AddPlaceholderChunk("condition");
4510 Builder.AddPlaceholderChunk("expression");
4511 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4512 if (Results.includeCodePatterns()) {
4513 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4514 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4515 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
4516 Builder.AddPlaceholderChunk("statements");
4517 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
4518 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4520 Results.AddResult(Builder.TakeString());
4522 Results.ExitScope();
4524 if (S->getFnParent())
4525 AddPrettyFunctionResults(getLangOpts(), Results);
4527 if (CodeCompleter->includeMacros())
4528 AddMacroResults(PP, Results, false);
4530 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4531 Results.data(),Results.size());
4534 void Sema::CodeCompleteAssignmentRHS(Scope *S, Expr *LHS) {
4536 CodeCompleteExpression(S, static_cast<Expr *>(LHS)->getType());
4538 CodeCompleteOrdinaryName(S, PCC_Expression);
4541 void Sema::CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
4542 bool EnteringContext) {
4543 if (!SS.getScopeRep() || !CodeCompleter)
4546 DeclContext *Ctx = computeDeclContext(SS, EnteringContext);
4550 // Try to instantiate any non-dependent declaration contexts before
4552 if (!isDependentScopeSpecifier(SS) && RequireCompleteDeclContext(SS, Ctx))
4555 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4556 CodeCompleter->getCodeCompletionTUInfo(),
4557 CodeCompletionContext::CCC_Name);
4558 Results.EnterNewScope();
4560 // The "template" keyword can follow "::" in the grammar, but only
4561 // put it into the grammar if the nested-name-specifier is dependent.
4562 NestedNameSpecifier *NNS = SS.getScopeRep();
4563 if (!Results.empty() && NNS->isDependent())
4564 Results.AddResult("template");
4566 // Add calls to overridden virtual functions, if there are any.
4568 // FIXME: This isn't wonderful, because we don't know whether we're actually
4569 // in a context that permits expressions. This is a general issue with
4570 // qualified-id completions.
4571 if (!EnteringContext)
4572 MaybeAddOverrideCalls(*this, Ctx, Results);
4573 Results.ExitScope();
4575 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4576 LookupVisibleDecls(Ctx, LookupOrdinaryName, Consumer);
4578 HandleCodeCompleteResults(this, CodeCompleter,
4579 Results.getCompletionContext(),
4580 Results.data(),Results.size());
4583 void Sema::CodeCompleteUsing(Scope *S) {
4587 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4588 CodeCompleter->getCodeCompletionTUInfo(),
4589 CodeCompletionContext::CCC_PotentiallyQualifiedName,
4590 &ResultBuilder::IsNestedNameSpecifier);
4591 Results.EnterNewScope();
4593 // If we aren't in class scope, we could see the "namespace" keyword.
4594 if (!S->isClassScope())
4595 Results.AddResult(CodeCompletionResult("namespace"));
4597 // After "using", we can see anything that would start a
4598 // nested-name-specifier.
4599 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4600 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4601 CodeCompleter->includeGlobals());
4602 Results.ExitScope();
4604 HandleCodeCompleteResults(this, CodeCompleter,
4605 CodeCompletionContext::CCC_PotentiallyQualifiedName,
4606 Results.data(),Results.size());
4609 void Sema::CodeCompleteUsingDirective(Scope *S) {
4613 // After "using namespace", we expect to see a namespace name or namespace
4615 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4616 CodeCompleter->getCodeCompletionTUInfo(),
4617 CodeCompletionContext::CCC_Namespace,
4618 &ResultBuilder::IsNamespaceOrAlias);
4619 Results.EnterNewScope();
4620 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4621 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4622 CodeCompleter->includeGlobals());
4623 Results.ExitScope();
4624 HandleCodeCompleteResults(this, CodeCompleter,
4625 CodeCompletionContext::CCC_Namespace,
4626 Results.data(),Results.size());
4629 void Sema::CodeCompleteNamespaceDecl(Scope *S) {
4633 DeclContext *Ctx = S->getEntity();
4634 if (!S->getParent())
4635 Ctx = Context.getTranslationUnitDecl();
4637 bool SuppressedGlobalResults
4638 = Ctx && !CodeCompleter->includeGlobals() && isa<TranslationUnitDecl>(Ctx);
4640 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4641 CodeCompleter->getCodeCompletionTUInfo(),
4642 SuppressedGlobalResults
4643 ? CodeCompletionContext::CCC_Namespace
4644 : CodeCompletionContext::CCC_Other,
4645 &ResultBuilder::IsNamespace);
4647 if (Ctx && Ctx->isFileContext() && !SuppressedGlobalResults) {
4648 // We only want to see those namespaces that have already been defined
4649 // within this scope, because its likely that the user is creating an
4650 // extended namespace declaration. Keep track of the most recent
4651 // definition of each namespace.
4652 std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest;
4653 for (DeclContext::specific_decl_iterator<NamespaceDecl>
4654 NS(Ctx->decls_begin()), NSEnd(Ctx->decls_end());
4656 OrigToLatest[NS->getOriginalNamespace()] = *NS;
4658 // Add the most recent definition (or extended definition) of each
4659 // namespace to the list of results.
4660 Results.EnterNewScope();
4661 for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator
4662 NS = OrigToLatest.begin(),
4663 NSEnd = OrigToLatest.end();
4665 Results.AddResult(CodeCompletionResult(
4666 NS->second, Results.getBasePriority(NS->second),
4668 CurContext, nullptr, false);
4669 Results.ExitScope();
4672 HandleCodeCompleteResults(this, CodeCompleter,
4673 Results.getCompletionContext(),
4674 Results.data(),Results.size());
4677 void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) {
4681 // After "namespace", we expect to see a namespace or alias.
4682 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4683 CodeCompleter->getCodeCompletionTUInfo(),
4684 CodeCompletionContext::CCC_Namespace,
4685 &ResultBuilder::IsNamespaceOrAlias);
4686 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4687 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4688 CodeCompleter->includeGlobals());
4689 HandleCodeCompleteResults(this, CodeCompleter,
4690 Results.getCompletionContext(),
4691 Results.data(),Results.size());
4694 void Sema::CodeCompleteOperatorName(Scope *S) {
4698 typedef CodeCompletionResult Result;
4699 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4700 CodeCompleter->getCodeCompletionTUInfo(),
4701 CodeCompletionContext::CCC_Type,
4702 &ResultBuilder::IsType);
4703 Results.EnterNewScope();
4705 // Add the names of overloadable operators.
4706 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
4707 if (std::strcmp(Spelling, "?")) \
4708 Results.AddResult(Result(Spelling));
4709 #include "clang/Basic/OperatorKinds.def"
4711 // Add any type names visible from the current scope
4712 Results.allowNestedNameSpecifiers();
4713 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4714 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4715 CodeCompleter->includeGlobals());
4717 // Add any type specifiers
4718 AddTypeSpecifierResults(getLangOpts(), Results);
4719 Results.ExitScope();
4721 HandleCodeCompleteResults(this, CodeCompleter,
4722 CodeCompletionContext::CCC_Type,
4723 Results.data(),Results.size());
4726 void Sema::CodeCompleteConstructorInitializer(
4728 ArrayRef <CXXCtorInitializer *> Initializers) {
4732 AdjustDeclIfTemplate(ConstructorD);
4734 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ConstructorD);
4738 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4739 CodeCompleter->getCodeCompletionTUInfo(),
4740 CodeCompletionContext::CCC_PotentiallyQualifiedName);
4741 Results.EnterNewScope();
4743 // Fill in any already-initialized fields or base classes.
4744 llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields;
4745 llvm::SmallPtrSet<CanQualType, 4> InitializedBases;
4746 for (unsigned I = 0, E = Initializers.size(); I != E; ++I) {
4747 if (Initializers[I]->isBaseInitializer())
4748 InitializedBases.insert(
4749 Context.getCanonicalType(QualType(Initializers[I]->getBaseClass(), 0)));
4751 InitializedFields.insert(cast<FieldDecl>(
4752 Initializers[I]->getAnyMember()));
4755 // Add completions for base classes.
4756 CodeCompletionBuilder Builder(Results.getAllocator(),
4757 Results.getCodeCompletionTUInfo());
4758 PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
4759 bool SawLastInitializer = Initializers.empty();
4760 CXXRecordDecl *ClassDecl = Constructor->getParent();
4761 for (const auto &Base : ClassDecl->bases()) {
4762 if (!InitializedBases.insert(Context.getCanonicalType(Base.getType()))
4765 = !Initializers.empty() &&
4766 Initializers.back()->isBaseInitializer() &&
4767 Context.hasSameUnqualifiedType(Base.getType(),
4768 QualType(Initializers.back()->getBaseClass(), 0));
4772 Builder.AddTypedTextChunk(
4773 Results.getAllocator().CopyString(
4774 Base.getType().getAsString(Policy)));
4775 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4776 Builder.AddPlaceholderChunk("args");
4777 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4778 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
4779 SawLastInitializer? CCP_NextInitializer
4780 : CCP_MemberDeclaration));
4781 SawLastInitializer = false;
4784 // Add completions for virtual base classes.
4785 for (const auto &Base : ClassDecl->vbases()) {
4786 if (!InitializedBases.insert(Context.getCanonicalType(Base.getType()))
4789 = !Initializers.empty() &&
4790 Initializers.back()->isBaseInitializer() &&
4791 Context.hasSameUnqualifiedType(Base.getType(),
4792 QualType(Initializers.back()->getBaseClass(), 0));
4796 Builder.AddTypedTextChunk(
4797 Builder.getAllocator().CopyString(
4798 Base.getType().getAsString(Policy)));
4799 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4800 Builder.AddPlaceholderChunk("args");
4801 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4802 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
4803 SawLastInitializer? CCP_NextInitializer
4804 : CCP_MemberDeclaration));
4805 SawLastInitializer = false;
4808 // Add completions for members.
4809 for (auto *Field : ClassDecl->fields()) {
4810 if (!InitializedFields.insert(cast<FieldDecl>(Field->getCanonicalDecl()))
4813 = !Initializers.empty() &&
4814 Initializers.back()->isAnyMemberInitializer() &&
4815 Initializers.back()->getAnyMember() == Field;
4819 if (!Field->getDeclName())
4822 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
4823 Field->getIdentifier()->getName()));
4824 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4825 Builder.AddPlaceholderChunk("args");
4826 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4827 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
4828 SawLastInitializer? CCP_NextInitializer
4829 : CCP_MemberDeclaration,
4831 CXAvailability_Available,
4833 SawLastInitializer = false;
4835 Results.ExitScope();
4837 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4838 Results.data(), Results.size());
4841 /// \brief Determine whether this scope denotes a namespace.
4842 static bool isNamespaceScope(Scope *S) {
4843 DeclContext *DC = S->getEntity();
4847 return DC->isFileContext();
4850 void Sema::CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro,
4851 bool AfterAmpersand) {
4852 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4853 CodeCompleter->getCodeCompletionTUInfo(),
4854 CodeCompletionContext::CCC_Other);
4855 Results.EnterNewScope();
4857 // Note what has already been captured.
4858 llvm::SmallPtrSet<IdentifierInfo *, 4> Known;
4859 bool IncludedThis = false;
4860 for (const auto &C : Intro.Captures) {
4861 if (C.Kind == LCK_This) {
4862 IncludedThis = true;
4869 // Look for other capturable variables.
4870 for (; S && !isNamespaceScope(S); S = S->getParent()) {
4871 for (const auto *D : S->decls()) {
4872 const auto *Var = dyn_cast<VarDecl>(D);
4874 !Var->hasLocalStorage() ||
4875 Var->hasAttr<BlocksAttr>())
4878 if (Known.insert(Var->getIdentifier()).second)
4879 Results.AddResult(CodeCompletionResult(Var, CCP_LocalDeclaration),
4880 CurContext, nullptr, false);
4884 // Add 'this', if it would be valid.
4885 if (!IncludedThis && !AfterAmpersand && Intro.Default != LCD_ByCopy)
4886 addThisCompletion(*this, Results);
4888 Results.ExitScope();
4890 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4891 Results.data(), Results.size());
4894 /// Macro that optionally prepends an "@" to the string literal passed in via
4895 /// Keyword, depending on whether NeedAt is true or false.
4896 #define OBJC_AT_KEYWORD_NAME(NeedAt,Keyword) ((NeedAt)? "@" Keyword : Keyword)
4898 static void AddObjCImplementationResults(const LangOptions &LangOpts,
4899 ResultBuilder &Results,
4901 typedef CodeCompletionResult Result;
4902 // Since we have an implementation, we can end it.
4903 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"end")));
4905 CodeCompletionBuilder Builder(Results.getAllocator(),
4906 Results.getCodeCompletionTUInfo());
4907 if (LangOpts.ObjC2) {
4909 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"dynamic"));
4910 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4911 Builder.AddPlaceholderChunk("property");
4912 Results.AddResult(Result(Builder.TakeString()));
4915 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"synthesize"));
4916 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4917 Builder.AddPlaceholderChunk("property");
4918 Results.AddResult(Result(Builder.TakeString()));
4922 static void AddObjCInterfaceResults(const LangOptions &LangOpts,
4923 ResultBuilder &Results,
4925 typedef CodeCompletionResult Result;
4927 // Since we have an interface or protocol, we can end it.
4928 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"end")));
4930 if (LangOpts.ObjC2) {
4932 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"property")));
4935 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"required")));
4938 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"optional")));
4942 static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt) {
4943 typedef CodeCompletionResult Result;
4944 CodeCompletionBuilder Builder(Results.getAllocator(),
4945 Results.getCodeCompletionTUInfo());
4948 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"class"));
4949 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4950 Builder.AddPlaceholderChunk("name");
4951 Results.AddResult(Result(Builder.TakeString()));
4953 if (Results.includeCodePatterns()) {
4955 // FIXME: Could introduce the whole pattern, including superclasses and
4957 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"interface"));
4958 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4959 Builder.AddPlaceholderChunk("class");
4960 Results.AddResult(Result(Builder.TakeString()));
4963 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"protocol"));
4964 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4965 Builder.AddPlaceholderChunk("protocol");
4966 Results.AddResult(Result(Builder.TakeString()));
4968 // @implementation name
4969 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"implementation"));
4970 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4971 Builder.AddPlaceholderChunk("class");
4972 Results.AddResult(Result(Builder.TakeString()));
4975 // @compatibility_alias name
4976 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"compatibility_alias"));
4977 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4978 Builder.AddPlaceholderChunk("alias");
4979 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4980 Builder.AddPlaceholderChunk("class");
4981 Results.AddResult(Result(Builder.TakeString()));
4983 if (Results.getSema().getLangOpts().Modules) {
4985 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "import"));
4986 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4987 Builder.AddPlaceholderChunk("module");
4988 Results.AddResult(Result(Builder.TakeString()));
4992 void Sema::CodeCompleteObjCAtDirective(Scope *S) {
4993 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4994 CodeCompleter->getCodeCompletionTUInfo(),
4995 CodeCompletionContext::CCC_Other);
4996 Results.EnterNewScope();
4997 if (isa<ObjCImplDecl>(CurContext))
4998 AddObjCImplementationResults(getLangOpts(), Results, false);
4999 else if (CurContext->isObjCContainer())
5000 AddObjCInterfaceResults(getLangOpts(), Results, false);
5002 AddObjCTopLevelResults(Results, false);
5003 Results.ExitScope();
5004 HandleCodeCompleteResults(this, CodeCompleter,
5005 CodeCompletionContext::CCC_Other,
5006 Results.data(),Results.size());
5009 static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt) {
5010 typedef CodeCompletionResult Result;
5011 CodeCompletionBuilder Builder(Results.getAllocator(),
5012 Results.getCodeCompletionTUInfo());
5014 // @encode ( type-name )
5015 const char *EncodeType = "char[]";
5016 if (Results.getSema().getLangOpts().CPlusPlus ||
5017 Results.getSema().getLangOpts().ConstStrings)
5018 EncodeType = "const char[]";
5019 Builder.AddResultTypeChunk(EncodeType);
5020 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"encode"));
5021 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5022 Builder.AddPlaceholderChunk("type-name");
5023 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5024 Results.AddResult(Result(Builder.TakeString()));
5026 // @protocol ( protocol-name )
5027 Builder.AddResultTypeChunk("Protocol *");
5028 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"protocol"));
5029 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5030 Builder.AddPlaceholderChunk("protocol-name");
5031 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5032 Results.AddResult(Result(Builder.TakeString()));
5034 // @selector ( selector )
5035 Builder.AddResultTypeChunk("SEL");
5036 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"selector"));
5037 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5038 Builder.AddPlaceholderChunk("selector");
5039 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5040 Results.AddResult(Result(Builder.TakeString()));
5043 Builder.AddResultTypeChunk("NSString *");
5044 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"\""));
5045 Builder.AddPlaceholderChunk("string");
5046 Builder.AddTextChunk("\"");
5047 Results.AddResult(Result(Builder.TakeString()));
5050 Builder.AddResultTypeChunk("NSArray *");
5051 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"["));
5052 Builder.AddPlaceholderChunk("objects, ...");
5053 Builder.AddChunk(CodeCompletionString::CK_RightBracket);
5054 Results.AddResult(Result(Builder.TakeString()));
5056 // @{key : object, ...}
5057 Builder.AddResultTypeChunk("NSDictionary *");
5058 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"{"));
5059 Builder.AddPlaceholderChunk("key");
5060 Builder.AddChunk(CodeCompletionString::CK_Colon);
5061 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5062 Builder.AddPlaceholderChunk("object, ...");
5063 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
5064 Results.AddResult(Result(Builder.TakeString()));
5067 Builder.AddResultTypeChunk("id");
5068 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "("));
5069 Builder.AddPlaceholderChunk("expression");
5070 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5071 Results.AddResult(Result(Builder.TakeString()));
5074 static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt) {
5075 typedef CodeCompletionResult Result;
5076 CodeCompletionBuilder Builder(Results.getAllocator(),
5077 Results.getCodeCompletionTUInfo());
5079 if (Results.includeCodePatterns()) {
5080 // @try { statements } @catch ( declaration ) { statements } @finally
5082 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"try"));
5083 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
5084 Builder.AddPlaceholderChunk("statements");
5085 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
5086 Builder.AddTextChunk("@catch");
5087 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5088 Builder.AddPlaceholderChunk("parameter");
5089 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5090 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
5091 Builder.AddPlaceholderChunk("statements");
5092 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
5093 Builder.AddTextChunk("@finally");
5094 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
5095 Builder.AddPlaceholderChunk("statements");
5096 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
5097 Results.AddResult(Result(Builder.TakeString()));
5101 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"throw"));
5102 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5103 Builder.AddPlaceholderChunk("expression");
5104 Results.AddResult(Result(Builder.TakeString()));
5106 if (Results.includeCodePatterns()) {
5107 // @synchronized ( expression ) { statements }
5108 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"synchronized"));
5109 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5110 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5111 Builder.AddPlaceholderChunk("expression");
5112 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5113 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
5114 Builder.AddPlaceholderChunk("statements");
5115 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
5116 Results.AddResult(Result(Builder.TakeString()));
5120 static void AddObjCVisibilityResults(const LangOptions &LangOpts,
5121 ResultBuilder &Results,
5123 typedef CodeCompletionResult Result;
5124 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"private")));
5125 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"protected")));
5126 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"public")));
5128 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"package")));
5131 void Sema::CodeCompleteObjCAtVisibility(Scope *S) {
5132 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5133 CodeCompleter->getCodeCompletionTUInfo(),
5134 CodeCompletionContext::CCC_Other);
5135 Results.EnterNewScope();
5136 AddObjCVisibilityResults(getLangOpts(), Results, false);
5137 Results.ExitScope();
5138 HandleCodeCompleteResults(this, CodeCompleter,
5139 CodeCompletionContext::CCC_Other,
5140 Results.data(),Results.size());
5143 void Sema::CodeCompleteObjCAtStatement(Scope *S) {
5144 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5145 CodeCompleter->getCodeCompletionTUInfo(),
5146 CodeCompletionContext::CCC_Other);
5147 Results.EnterNewScope();
5148 AddObjCStatementResults(Results, false);
5149 AddObjCExpressionResults(Results, false);
5150 Results.ExitScope();
5151 HandleCodeCompleteResults(this, CodeCompleter,
5152 CodeCompletionContext::CCC_Other,
5153 Results.data(),Results.size());
5156 void Sema::CodeCompleteObjCAtExpression(Scope *S) {
5157 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5158 CodeCompleter->getCodeCompletionTUInfo(),
5159 CodeCompletionContext::CCC_Other);
5160 Results.EnterNewScope();
5161 AddObjCExpressionResults(Results, false);
5162 Results.ExitScope();
5163 HandleCodeCompleteResults(this, CodeCompleter,
5164 CodeCompletionContext::CCC_Other,
5165 Results.data(),Results.size());
5168 /// \brief Determine whether the addition of the given flag to an Objective-C
5169 /// property's attributes will cause a conflict.
5170 static bool ObjCPropertyFlagConflicts(unsigned Attributes, unsigned NewFlag) {
5171 // Check if we've already added this flag.
5172 if (Attributes & NewFlag)
5175 Attributes |= NewFlag;
5177 // Check for collisions with "readonly".
5178 if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
5179 (Attributes & ObjCDeclSpec::DQ_PR_readwrite))
5182 // Check for more than one of { assign, copy, retain, strong, weak }.
5183 unsigned AssignCopyRetMask = Attributes & (ObjCDeclSpec::DQ_PR_assign |
5184 ObjCDeclSpec::DQ_PR_unsafe_unretained |
5185 ObjCDeclSpec::DQ_PR_copy |
5186 ObjCDeclSpec::DQ_PR_retain |
5187 ObjCDeclSpec::DQ_PR_strong |
5188 ObjCDeclSpec::DQ_PR_weak);
5189 if (AssignCopyRetMask &&
5190 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_assign &&
5191 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_unsafe_unretained &&
5192 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_copy &&
5193 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_retain &&
5194 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_strong &&
5195 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_weak)
5201 void Sema::CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS) {
5205 unsigned Attributes = ODS.getPropertyAttributes();
5207 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5208 CodeCompleter->getCodeCompletionTUInfo(),
5209 CodeCompletionContext::CCC_Other);
5210 Results.EnterNewScope();
5211 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readonly))
5212 Results.AddResult(CodeCompletionResult("readonly"));
5213 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_assign))
5214 Results.AddResult(CodeCompletionResult("assign"));
5215 if (!ObjCPropertyFlagConflicts(Attributes,
5216 ObjCDeclSpec::DQ_PR_unsafe_unretained))
5217 Results.AddResult(CodeCompletionResult("unsafe_unretained"));
5218 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readwrite))
5219 Results.AddResult(CodeCompletionResult("readwrite"));
5220 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_retain))
5221 Results.AddResult(CodeCompletionResult("retain"));
5222 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_strong))
5223 Results.AddResult(CodeCompletionResult("strong"));
5224 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_copy))
5225 Results.AddResult(CodeCompletionResult("copy"));
5226 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nonatomic))
5227 Results.AddResult(CodeCompletionResult("nonatomic"));
5228 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_atomic))
5229 Results.AddResult(CodeCompletionResult("atomic"));
5231 // Only suggest "weak" if we're compiling for ARC-with-weak-references or GC.
5232 if (getLangOpts().ObjCWeak || getLangOpts().getGC() != LangOptions::NonGC)
5233 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_weak))
5234 Results.AddResult(CodeCompletionResult("weak"));
5236 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_setter)) {
5237 CodeCompletionBuilder Setter(Results.getAllocator(),
5238 Results.getCodeCompletionTUInfo());
5239 Setter.AddTypedTextChunk("setter");
5240 Setter.AddTextChunk("=");
5241 Setter.AddPlaceholderChunk("method");
5242 Results.AddResult(CodeCompletionResult(Setter.TakeString()));
5244 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_getter)) {
5245 CodeCompletionBuilder Getter(Results.getAllocator(),
5246 Results.getCodeCompletionTUInfo());
5247 Getter.AddTypedTextChunk("getter");
5248 Getter.AddTextChunk("=");
5249 Getter.AddPlaceholderChunk("method");
5250 Results.AddResult(CodeCompletionResult(Getter.TakeString()));
5252 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nullability)) {
5253 Results.AddResult(CodeCompletionResult("nonnull"));
5254 Results.AddResult(CodeCompletionResult("nullable"));
5255 Results.AddResult(CodeCompletionResult("null_unspecified"));
5256 Results.AddResult(CodeCompletionResult("null_resettable"));
5258 Results.ExitScope();
5259 HandleCodeCompleteResults(this, CodeCompleter,
5260 CodeCompletionContext::CCC_Other,
5261 Results.data(),Results.size());
5264 /// \brief Describes the kind of Objective-C method that we want to find
5265 /// via code completion.
5266 enum ObjCMethodKind {
5267 MK_Any, ///< Any kind of method, provided it means other specified criteria.
5268 MK_ZeroArgSelector, ///< Zero-argument (unary) selector.
5269 MK_OneArgSelector ///< One-argument selector.
5272 static bool isAcceptableObjCSelector(Selector Sel,
5273 ObjCMethodKind WantKind,
5274 ArrayRef<IdentifierInfo *> SelIdents,
5275 bool AllowSameLength = true) {
5276 unsigned NumSelIdents = SelIdents.size();
5277 if (NumSelIdents > Sel.getNumArgs())
5282 case MK_ZeroArgSelector: return Sel.isUnarySelector();
5283 case MK_OneArgSelector: return Sel.getNumArgs() == 1;
5286 if (!AllowSameLength && NumSelIdents && NumSelIdents == Sel.getNumArgs())
5289 for (unsigned I = 0; I != NumSelIdents; ++I)
5290 if (SelIdents[I] != Sel.getIdentifierInfoForSlot(I))
5296 static bool isAcceptableObjCMethod(ObjCMethodDecl *Method,
5297 ObjCMethodKind WantKind,
5298 ArrayRef<IdentifierInfo *> SelIdents,
5299 bool AllowSameLength = true) {
5300 return isAcceptableObjCSelector(Method->getSelector(), WantKind, SelIdents,
5305 /// \brief A set of selectors, which is used to avoid introducing multiple
5306 /// completions with the same selector into the result set.
5307 typedef llvm::SmallPtrSet<Selector, 16> VisitedSelectorSet;
5310 /// \brief Add all of the Objective-C methods in the given Objective-C
5311 /// container to the set of results.
5313 /// The container will be a class, protocol, category, or implementation of
5314 /// any of the above. This mether will recurse to include methods from
5315 /// the superclasses of classes along with their categories, protocols, and
5316 /// implementations.
5318 /// \param Container the container in which we'll look to find methods.
5320 /// \param WantInstanceMethods Whether to add instance methods (only); if
5321 /// false, this routine will add factory methods (only).
5323 /// \param CurContext the context in which we're performing the lookup that
5326 /// \param AllowSameLength Whether we allow a method to be added to the list
5327 /// when it has the same number of parameters as we have selector identifiers.
5329 /// \param Results the structure into which we'll add results.
5330 static void AddObjCMethods(ObjCContainerDecl *Container,
5331 bool WantInstanceMethods, ObjCMethodKind WantKind,
5332 ArrayRef<IdentifierInfo *> SelIdents,
5333 DeclContext *CurContext,
5334 VisitedSelectorSet &Selectors, bool AllowSameLength,
5335 ResultBuilder &Results, bool InOriginalClass = true,
5336 bool IsRootClass = false) {
5337 typedef CodeCompletionResult Result;
5338 Container = getContainerDef(Container);
5339 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container);
5340 IsRootClass = IsRootClass || (IFace && !IFace->getSuperClass());
5341 for (auto *M : Container->methods()) {
5342 // The instance methods on the root class can be messaged via the
5344 if (M->isInstanceMethod() == WantInstanceMethods ||
5345 (IsRootClass && !WantInstanceMethods)) {
5346 // Check whether the selector identifiers we've been given are a
5347 // subset of the identifiers for this particular method.
5348 if (!isAcceptableObjCMethod(M, WantKind, SelIdents, AllowSameLength))
5351 if (!Selectors.insert(M->getSelector()).second)
5354 Result R = Result(M, Results.getBasePriority(M), nullptr);
5355 R.StartParameter = SelIdents.size();
5356 R.AllParametersAreInformative = (WantKind != MK_Any);
5357 if (!InOriginalClass)
5358 R.Priority += CCD_InBaseClass;
5359 Results.MaybeAddResult(R, CurContext);
5363 // Visit the protocols of protocols.
5364 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
5365 if (Protocol->hasDefinition()) {
5366 const ObjCList<ObjCProtocolDecl> &Protocols
5367 = Protocol->getReferencedProtocols();
5368 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
5369 E = Protocols.end();
5371 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, CurContext,
5372 Selectors, AllowSameLength, Results, false, IsRootClass);
5376 if (!IFace || !IFace->hasDefinition())
5379 // Add methods in protocols.
5380 for (auto *I : IFace->protocols())
5381 AddObjCMethods(I, WantInstanceMethods, WantKind, SelIdents, CurContext,
5382 Selectors, AllowSameLength, Results, false, IsRootClass);
5384 // Add methods in categories.
5385 for (auto *CatDecl : IFace->known_categories()) {
5386 AddObjCMethods(CatDecl, WantInstanceMethods, WantKind, SelIdents,
5387 CurContext, Selectors, AllowSameLength, Results,
5388 InOriginalClass, IsRootClass);
5390 // Add a categories protocol methods.
5391 const ObjCList<ObjCProtocolDecl> &Protocols
5392 = CatDecl->getReferencedProtocols();
5393 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
5394 E = Protocols.end();
5396 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, CurContext,
5397 Selectors, AllowSameLength, Results, false, IsRootClass);
5399 // Add methods in category implementations.
5400 if (ObjCCategoryImplDecl *Impl = CatDecl->getImplementation())
5401 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents, CurContext,
5402 Selectors, AllowSameLength, Results, InOriginalClass,
5406 // Add methods in superclass.
5407 // Avoid passing in IsRootClass since root classes won't have super classes.
5408 if (IFace->getSuperClass())
5409 AddObjCMethods(IFace->getSuperClass(), WantInstanceMethods, WantKind,
5410 SelIdents, CurContext, Selectors, AllowSameLength, Results,
5411 /*IsRootClass=*/false);
5413 // Add methods in our implementation, if any.
5414 if (ObjCImplementationDecl *Impl = IFace->getImplementation())
5415 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents, CurContext,
5416 Selectors, AllowSameLength, Results, InOriginalClass,
5421 void Sema::CodeCompleteObjCPropertyGetter(Scope *S) {
5422 // Try to find the interface where getters might live.
5423 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext);
5425 if (ObjCCategoryDecl *Category
5426 = dyn_cast_or_null<ObjCCategoryDecl>(CurContext))
5427 Class = Category->getClassInterface();
5433 // Find all of the potential getters.
5434 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5435 CodeCompleter->getCodeCompletionTUInfo(),
5436 CodeCompletionContext::CCC_Other);
5437 Results.EnterNewScope();
5439 VisitedSelectorSet Selectors;
5440 AddObjCMethods(Class, true, MK_ZeroArgSelector, None, CurContext, Selectors,
5441 /*AllowSameLength=*/true, Results);
5442 Results.ExitScope();
5443 HandleCodeCompleteResults(this, CodeCompleter,
5444 CodeCompletionContext::CCC_Other,
5445 Results.data(),Results.size());
5448 void Sema::CodeCompleteObjCPropertySetter(Scope *S) {
5449 // Try to find the interface where setters might live.
5450 ObjCInterfaceDecl *Class
5451 = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext);
5453 if (ObjCCategoryDecl *Category
5454 = dyn_cast_or_null<ObjCCategoryDecl>(CurContext))
5455 Class = Category->getClassInterface();
5461 // Find all of the potential getters.
5462 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5463 CodeCompleter->getCodeCompletionTUInfo(),
5464 CodeCompletionContext::CCC_Other);
5465 Results.EnterNewScope();
5467 VisitedSelectorSet Selectors;
5468 AddObjCMethods(Class, true, MK_OneArgSelector, None, CurContext,
5469 Selectors, /*AllowSameLength=*/true, Results);
5471 Results.ExitScope();
5472 HandleCodeCompleteResults(this, CodeCompleter,
5473 CodeCompletionContext::CCC_Other,
5474 Results.data(),Results.size());
5477 void Sema::CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
5479 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5480 CodeCompleter->getCodeCompletionTUInfo(),
5481 CodeCompletionContext::CCC_Type);
5482 Results.EnterNewScope();
5484 // Add context-sensitive, Objective-C parameter-passing keywords.
5485 bool AddedInOut = false;
5486 if ((DS.getObjCDeclQualifier() &
5487 (ObjCDeclSpec::DQ_In | ObjCDeclSpec::DQ_Inout)) == 0) {
5488 Results.AddResult("in");
5489 Results.AddResult("inout");
5492 if ((DS.getObjCDeclQualifier() &
5493 (ObjCDeclSpec::DQ_Out | ObjCDeclSpec::DQ_Inout)) == 0) {
5494 Results.AddResult("out");
5496 Results.AddResult("inout");
5498 if ((DS.getObjCDeclQualifier() &
5499 (ObjCDeclSpec::DQ_Bycopy | ObjCDeclSpec::DQ_Byref |
5500 ObjCDeclSpec::DQ_Oneway)) == 0) {
5501 Results.AddResult("bycopy");
5502 Results.AddResult("byref");
5503 Results.AddResult("oneway");
5505 if ((DS.getObjCDeclQualifier() & ObjCDeclSpec::DQ_CSNullability) == 0) {
5506 Results.AddResult("nonnull");
5507 Results.AddResult("nullable");
5508 Results.AddResult("null_unspecified");
5511 // If we're completing the return type of an Objective-C method and the
5512 // identifier IBAction refers to a macro, provide a completion item for
5514 // IBAction)<#selector#>:(id)sender
5515 if (DS.getObjCDeclQualifier() == 0 && !IsParameter &&
5516 PP.isMacroDefined("IBAction")) {
5517 CodeCompletionBuilder Builder(Results.getAllocator(),
5518 Results.getCodeCompletionTUInfo(),
5519 CCP_CodePattern, CXAvailability_Available);
5520 Builder.AddTypedTextChunk("IBAction");
5521 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5522 Builder.AddPlaceholderChunk("selector");
5523 Builder.AddChunk(CodeCompletionString::CK_Colon);
5524 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5525 Builder.AddTextChunk("id");
5526 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5527 Builder.AddTextChunk("sender");
5528 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
5531 // If we're completing the return type, provide 'instancetype'.
5533 Results.AddResult(CodeCompletionResult("instancetype"));
5536 // Add various builtin type names and specifiers.
5537 AddOrdinaryNameResults(PCC_Type, S, *this, Results);
5538 Results.ExitScope();
5540 // Add the various type names
5541 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
5542 CodeCompletionDeclConsumer Consumer(Results, CurContext);
5543 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
5544 CodeCompleter->includeGlobals());
5546 if (CodeCompleter->includeMacros())
5547 AddMacroResults(PP, Results, false);
5549 HandleCodeCompleteResults(this, CodeCompleter,
5550 CodeCompletionContext::CCC_Type,
5551 Results.data(), Results.size());
5554 /// \brief When we have an expression with type "id", we may assume
5555 /// that it has some more-specific class type based on knowledge of
5556 /// common uses of Objective-C. This routine returns that class type,
5557 /// or NULL if no better result could be determined.
5558 static ObjCInterfaceDecl *GetAssumedMessageSendExprType(Expr *E) {
5559 ObjCMessageExpr *Msg = dyn_cast_or_null<ObjCMessageExpr>(E);
5563 Selector Sel = Msg->getSelector();
5567 IdentifierInfo *Id = Sel.getIdentifierInfoForSlot(0);
5571 ObjCMethodDecl *Method = Msg->getMethodDecl();
5575 // Determine the class that we're sending the message to.
5576 ObjCInterfaceDecl *IFace = nullptr;
5577 switch (Msg->getReceiverKind()) {
5578 case ObjCMessageExpr::Class:
5579 if (const ObjCObjectType *ObjType
5580 = Msg->getClassReceiver()->getAs<ObjCObjectType>())
5581 IFace = ObjType->getInterface();
5584 case ObjCMessageExpr::Instance: {
5585 QualType T = Msg->getInstanceReceiver()->getType();
5586 if (const ObjCObjectPointerType *Ptr = T->getAs<ObjCObjectPointerType>())
5587 IFace = Ptr->getInterfaceDecl();
5591 case ObjCMessageExpr::SuperInstance:
5592 case ObjCMessageExpr::SuperClass:
5599 ObjCInterfaceDecl *Super = IFace->getSuperClass();
5600 if (Method->isInstanceMethod())
5601 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
5602 .Case("retain", IFace)
5603 .Case("strong", IFace)
5604 .Case("autorelease", IFace)
5605 .Case("copy", IFace)
5606 .Case("copyWithZone", IFace)
5607 .Case("mutableCopy", IFace)
5608 .Case("mutableCopyWithZone", IFace)
5609 .Case("awakeFromCoder", IFace)
5610 .Case("replacementObjectFromCoder", IFace)
5611 .Case("class", IFace)
5612 .Case("classForCoder", IFace)
5613 .Case("superclass", Super)
5616 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
5618 .Case("alloc", IFace)
5619 .Case("allocWithZone", IFace)
5620 .Case("class", IFace)
5621 .Case("superclass", Super)
5625 // Add a special completion for a message send to "super", which fills in the
5626 // most likely case of forwarding all of our arguments to the superclass
5629 /// \param S The semantic analysis object.
5631 /// \param NeedSuperKeyword Whether we need to prefix this completion with
5632 /// the "super" keyword. Otherwise, we just need to provide the arguments.
5634 /// \param SelIdents The identifiers in the selector that have already been
5635 /// provided as arguments for a send to "super".
5637 /// \param Results The set of results to augment.
5639 /// \returns the Objective-C method declaration that would be invoked by
5640 /// this "super" completion. If NULL, no completion was added.
5641 static ObjCMethodDecl *AddSuperSendCompletion(
5642 Sema &S, bool NeedSuperKeyword,
5643 ArrayRef<IdentifierInfo *> SelIdents,
5644 ResultBuilder &Results) {
5645 ObjCMethodDecl *CurMethod = S.getCurMethodDecl();
5649 ObjCInterfaceDecl *Class = CurMethod->getClassInterface();
5653 // Try to find a superclass method with the same selector.
5654 ObjCMethodDecl *SuperMethod = nullptr;
5655 while ((Class = Class->getSuperClass()) && !SuperMethod) {
5656 // Check in the class
5657 SuperMethod = Class->getMethod(CurMethod->getSelector(),
5658 CurMethod->isInstanceMethod());
5660 // Check in categories or class extensions.
5662 for (const auto *Cat : Class->known_categories()) {
5663 if ((SuperMethod = Cat->getMethod(CurMethod->getSelector(),
5664 CurMethod->isInstanceMethod())))
5673 // Check whether the superclass method has the same signature.
5674 if (CurMethod->param_size() != SuperMethod->param_size() ||
5675 CurMethod->isVariadic() != SuperMethod->isVariadic())
5678 for (ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin(),
5679 CurPEnd = CurMethod->param_end(),
5680 SuperP = SuperMethod->param_begin();
5681 CurP != CurPEnd; ++CurP, ++SuperP) {
5682 // Make sure the parameter types are compatible.
5683 if (!S.Context.hasSameUnqualifiedType((*CurP)->getType(),
5684 (*SuperP)->getType()))
5687 // Make sure we have a parameter name to forward!
5688 if (!(*CurP)->getIdentifier())
5692 // We have a superclass method. Now, form the send-to-super completion.
5693 CodeCompletionBuilder Builder(Results.getAllocator(),
5694 Results.getCodeCompletionTUInfo());
5696 // Give this completion a return type.
5697 AddResultTypeChunk(S.Context, getCompletionPrintingPolicy(S), SuperMethod,
5698 Results.getCompletionContext().getBaseType(),
5701 // If we need the "super" keyword, add it (plus some spacing).
5702 if (NeedSuperKeyword) {
5703 Builder.AddTypedTextChunk("super");
5704 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5707 Selector Sel = CurMethod->getSelector();
5708 if (Sel.isUnarySelector()) {
5709 if (NeedSuperKeyword)
5710 Builder.AddTextChunk(Builder.getAllocator().CopyString(
5711 Sel.getNameForSlot(0)));
5713 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
5714 Sel.getNameForSlot(0)));
5716 ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin();
5717 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I, ++CurP) {
5718 if (I > SelIdents.size())
5719 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5721 if (I < SelIdents.size())
5722 Builder.AddInformativeChunk(
5723 Builder.getAllocator().CopyString(
5724 Sel.getNameForSlot(I) + ":"));
5725 else if (NeedSuperKeyword || I > SelIdents.size()) {
5726 Builder.AddTextChunk(
5727 Builder.getAllocator().CopyString(
5728 Sel.getNameForSlot(I) + ":"));
5729 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
5730 (*CurP)->getIdentifier()->getName()));
5732 Builder.AddTypedTextChunk(
5733 Builder.getAllocator().CopyString(
5734 Sel.getNameForSlot(I) + ":"));
5735 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
5736 (*CurP)->getIdentifier()->getName()));
5741 Results.AddResult(CodeCompletionResult(Builder.TakeString(), SuperMethod,
5742 CCP_SuperCompletion));
5746 void Sema::CodeCompleteObjCMessageReceiver(Scope *S) {
5747 typedef CodeCompletionResult Result;
5748 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5749 CodeCompleter->getCodeCompletionTUInfo(),
5750 CodeCompletionContext::CCC_ObjCMessageReceiver,
5751 getLangOpts().CPlusPlus11
5752 ? &ResultBuilder::IsObjCMessageReceiverOrLambdaCapture
5753 : &ResultBuilder::IsObjCMessageReceiver);
5755 CodeCompletionDeclConsumer Consumer(Results, CurContext);
5756 Results.EnterNewScope();
5757 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
5758 CodeCompleter->includeGlobals());
5760 // If we are in an Objective-C method inside a class that has a superclass,
5761 // add "super" as an option.
5762 if (ObjCMethodDecl *Method = getCurMethodDecl())
5763 if (ObjCInterfaceDecl *Iface = Method->getClassInterface())
5764 if (Iface->getSuperClass()) {
5765 Results.AddResult(Result("super"));
5767 AddSuperSendCompletion(*this, /*NeedSuperKeyword=*/true, None, Results);
5770 if (getLangOpts().CPlusPlus11)
5771 addThisCompletion(*this, Results);
5773 Results.ExitScope();
5775 if (CodeCompleter->includeMacros())
5776 AddMacroResults(PP, Results, false);
5777 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
5778 Results.data(), Results.size());
5782 void Sema::CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
5783 ArrayRef<IdentifierInfo *> SelIdents,
5784 bool AtArgumentExpression) {
5785 ObjCInterfaceDecl *CDecl = nullptr;
5786 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
5787 // Figure out which interface we're in.
5788 CDecl = CurMethod->getClassInterface();
5792 // Find the superclass of this class.
5793 CDecl = CDecl->getSuperClass();
5797 if (CurMethod->isInstanceMethod()) {
5798 // We are inside an instance method, which means that the message
5799 // send [super ...] is actually calling an instance method on the
5801 return CodeCompleteObjCInstanceMessage(S, nullptr, SelIdents,
5802 AtArgumentExpression,
5806 // Fall through to send to the superclass in CDecl.
5808 // "super" may be the name of a type or variable. Figure out which
5810 IdentifierInfo *Super = getSuperIdentifier();
5811 NamedDecl *ND = LookupSingleName(S, Super, SuperLoc,
5812 LookupOrdinaryName);
5813 if ((CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(ND))) {
5814 // "super" names an interface. Use it.
5815 } else if (TypeDecl *TD = dyn_cast_or_null<TypeDecl>(ND)) {
5816 if (const ObjCObjectType *Iface
5817 = Context.getTypeDeclType(TD)->getAs<ObjCObjectType>())
5818 CDecl = Iface->getInterface();
5819 } else if (ND && isa<UnresolvedUsingTypenameDecl>(ND)) {
5820 // "super" names an unresolved type; we can't be more specific.
5822 // Assume that "super" names some kind of value and parse that way.
5824 SourceLocation TemplateKWLoc;
5826 id.setIdentifier(Super, SuperLoc);
5827 ExprResult SuperExpr = ActOnIdExpression(S, SS, TemplateKWLoc, id,
5829 return CodeCompleteObjCInstanceMessage(S, (Expr *)SuperExpr.get(),
5831 AtArgumentExpression);
5837 ParsedType Receiver;
5839 Receiver = ParsedType::make(Context.getObjCInterfaceType(CDecl));
5840 return CodeCompleteObjCClassMessage(S, Receiver, SelIdents,
5841 AtArgumentExpression,
5845 /// \brief Given a set of code-completion results for the argument of a message
5846 /// send, determine the preferred type (if any) for that argument expression.
5847 static QualType getPreferredArgumentTypeForMessageSend(ResultBuilder &Results,
5848 unsigned NumSelIdents) {
5849 typedef CodeCompletionResult Result;
5850 ASTContext &Context = Results.getSema().Context;
5852 QualType PreferredType;
5853 unsigned BestPriority = CCP_Unlikely * 2;
5854 Result *ResultsData = Results.data();
5855 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
5856 Result &R = ResultsData[I];
5857 if (R.Kind == Result::RK_Declaration &&
5858 isa<ObjCMethodDecl>(R.Declaration)) {
5859 if (R.Priority <= BestPriority) {
5860 const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(R.Declaration);
5861 if (NumSelIdents <= Method->param_size()) {
5862 QualType MyPreferredType = Method->parameters()[NumSelIdents - 1]
5864 if (R.Priority < BestPriority || PreferredType.isNull()) {
5865 BestPriority = R.Priority;
5866 PreferredType = MyPreferredType;
5867 } else if (!Context.hasSameUnqualifiedType(PreferredType,
5869 PreferredType = QualType();
5876 return PreferredType;
5879 static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
5880 ParsedType Receiver,
5881 ArrayRef<IdentifierInfo *> SelIdents,
5882 bool AtArgumentExpression,
5884 ResultBuilder &Results) {
5885 typedef CodeCompletionResult Result;
5886 ObjCInterfaceDecl *CDecl = nullptr;
5888 // If the given name refers to an interface type, retrieve the
5889 // corresponding declaration.
5891 QualType T = SemaRef.GetTypeFromParser(Receiver, nullptr);
5893 if (const ObjCObjectType *Interface = T->getAs<ObjCObjectType>())
5894 CDecl = Interface->getInterface();
5897 // Add all of the factory methods in this Objective-C class, its protocols,
5898 // superclasses, categories, implementation, etc.
5899 Results.EnterNewScope();
5901 // If this is a send-to-super, try to add the special "super" send
5904 if (ObjCMethodDecl *SuperMethod
5905 = AddSuperSendCompletion(SemaRef, false, SelIdents, Results))
5906 Results.Ignore(SuperMethod);
5909 // If we're inside an Objective-C method definition, prefer its selector to
5911 if (ObjCMethodDecl *CurMethod = SemaRef.getCurMethodDecl())
5912 Results.setPreferredSelector(CurMethod->getSelector());
5914 VisitedSelectorSet Selectors;
5916 AddObjCMethods(CDecl, false, MK_Any, SelIdents,
5917 SemaRef.CurContext, Selectors, AtArgumentExpression,
5920 // We're messaging "id" as a type; provide all class/factory methods.
5922 // If we have an external source, load the entire class method
5923 // pool from the AST file.
5924 if (SemaRef.getExternalSource()) {
5925 for (uint32_t I = 0,
5926 N = SemaRef.getExternalSource()->GetNumExternalSelectors();
5928 Selector Sel = SemaRef.getExternalSource()->GetExternalSelector(I);
5929 if (Sel.isNull() || SemaRef.MethodPool.count(Sel))
5932 SemaRef.ReadMethodPool(Sel);
5936 for (Sema::GlobalMethodPool::iterator M = SemaRef.MethodPool.begin(),
5937 MEnd = SemaRef.MethodPool.end();
5939 for (ObjCMethodList *MethList = &M->second.second;
5940 MethList && MethList->getMethod();
5941 MethList = MethList->getNext()) {
5942 if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents))
5945 Result R(MethList->getMethod(),
5946 Results.getBasePriority(MethList->getMethod()), nullptr);
5947 R.StartParameter = SelIdents.size();
5948 R.AllParametersAreInformative = false;
5949 Results.MaybeAddResult(R, SemaRef.CurContext);
5954 Results.ExitScope();
5957 void Sema::CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
5958 ArrayRef<IdentifierInfo *> SelIdents,
5959 bool AtArgumentExpression,
5962 QualType T = this->GetTypeFromParser(Receiver);
5964 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5965 CodeCompleter->getCodeCompletionTUInfo(),
5966 CodeCompletionContext(CodeCompletionContext::CCC_ObjCClassMessage,
5969 AddClassMessageCompletions(*this, S, Receiver, SelIdents,
5970 AtArgumentExpression, IsSuper, Results);
5972 // If we're actually at the argument expression (rather than prior to the
5973 // selector), we're actually performing code completion for an expression.
5974 // Determine whether we have a single, best method. If so, we can
5975 // code-complete the expression using the corresponding parameter type as
5976 // our preferred type, improving completion results.
5977 if (AtArgumentExpression) {
5978 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results,
5980 if (PreferredType.isNull())
5981 CodeCompleteOrdinaryName(S, PCC_Expression);
5983 CodeCompleteExpression(S, PreferredType);
5987 HandleCodeCompleteResults(this, CodeCompleter,
5988 Results.getCompletionContext(),
5989 Results.data(), Results.size());
5992 void Sema::CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
5993 ArrayRef<IdentifierInfo *> SelIdents,
5994 bool AtArgumentExpression,
5995 ObjCInterfaceDecl *Super) {
5996 typedef CodeCompletionResult Result;
5998 Expr *RecExpr = static_cast<Expr *>(Receiver);
6000 // If necessary, apply function/array conversion to the receiver.
6001 // C99 6.7.5.3p[7,8].
6003 ExprResult Conv = DefaultFunctionArrayLvalueConversion(RecExpr);
6004 if (Conv.isInvalid()) // conversion failed. bail.
6006 RecExpr = Conv.get();
6008 QualType ReceiverType = RecExpr? RecExpr->getType()
6009 : Super? Context.getObjCObjectPointerType(
6010 Context.getObjCInterfaceType(Super))
6011 : Context.getObjCIdType();
6013 // If we're messaging an expression with type "id" or "Class", check
6014 // whether we know something special about the receiver that allows
6015 // us to assume a more-specific receiver type.
6016 if (ReceiverType->isObjCIdType() || ReceiverType->isObjCClassType()) {
6017 if (ObjCInterfaceDecl *IFace = GetAssumedMessageSendExprType(RecExpr)) {
6018 if (ReceiverType->isObjCClassType())
6019 return CodeCompleteObjCClassMessage(S,
6020 ParsedType::make(Context.getObjCInterfaceType(IFace)),
6022 AtArgumentExpression, Super);
6024 ReceiverType = Context.getObjCObjectPointerType(
6025 Context.getObjCInterfaceType(IFace));
6027 } else if (RecExpr && getLangOpts().CPlusPlus) {
6028 ExprResult Conv = PerformContextuallyConvertToObjCPointer(RecExpr);
6029 if (Conv.isUsable()) {
6030 RecExpr = Conv.get();
6031 ReceiverType = RecExpr->getType();
6035 // Build the set of methods we can see.
6036 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6037 CodeCompleter->getCodeCompletionTUInfo(),
6038 CodeCompletionContext(CodeCompletionContext::CCC_ObjCInstanceMessage,
6039 ReceiverType, SelIdents));
6041 Results.EnterNewScope();
6043 // If this is a send-to-super, try to add the special "super" send
6046 if (ObjCMethodDecl *SuperMethod
6047 = AddSuperSendCompletion(*this, false, SelIdents, Results))
6048 Results.Ignore(SuperMethod);
6051 // If we're inside an Objective-C method definition, prefer its selector to
6053 if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
6054 Results.setPreferredSelector(CurMethod->getSelector());
6056 // Keep track of the selectors we've already added.
6057 VisitedSelectorSet Selectors;
6059 // Handle messages to Class. This really isn't a message to an instance
6060 // method, so we treat it the same way we would treat a message send to a
6062 if (ReceiverType->isObjCClassType() ||
6063 ReceiverType->isObjCQualifiedClassType()) {
6064 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
6065 if (ObjCInterfaceDecl *ClassDecl = CurMethod->getClassInterface())
6066 AddObjCMethods(ClassDecl, false, MK_Any, SelIdents,
6067 CurContext, Selectors, AtArgumentExpression, Results);
6070 // Handle messages to a qualified ID ("id<foo>").
6071 else if (const ObjCObjectPointerType *QualID
6072 = ReceiverType->getAsObjCQualifiedIdType()) {
6073 // Search protocols for instance methods.
6074 for (auto *I : QualID->quals())
6075 AddObjCMethods(I, true, MK_Any, SelIdents, CurContext,
6076 Selectors, AtArgumentExpression, Results);
6078 // Handle messages to a pointer to interface type.
6079 else if (const ObjCObjectPointerType *IFacePtr
6080 = ReceiverType->getAsObjCInterfacePointerType()) {
6081 // Search the class, its superclasses, etc., for instance methods.
6082 AddObjCMethods(IFacePtr->getInterfaceDecl(), true, MK_Any, SelIdents,
6083 CurContext, Selectors, AtArgumentExpression,
6086 // Search protocols for instance methods.
6087 for (auto *I : IFacePtr->quals())
6088 AddObjCMethods(I, true, MK_Any, SelIdents, CurContext,
6089 Selectors, AtArgumentExpression, Results);
6091 // Handle messages to "id".
6092 else if (ReceiverType->isObjCIdType()) {
6093 // We're messaging "id", so provide all instance methods we know
6094 // about as code-completion results.
6096 // If we have an external source, load the entire class method
6097 // pool from the AST file.
6098 if (ExternalSource) {
6099 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
6101 Selector Sel = ExternalSource->GetExternalSelector(I);
6102 if (Sel.isNull() || MethodPool.count(Sel))
6105 ReadMethodPool(Sel);
6109 for (GlobalMethodPool::iterator M = MethodPool.begin(),
6110 MEnd = MethodPool.end();
6112 for (ObjCMethodList *MethList = &M->second.first;
6113 MethList && MethList->getMethod();
6114 MethList = MethList->getNext()) {
6115 if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents))
6118 if (!Selectors.insert(MethList->getMethod()->getSelector()).second)
6121 Result R(MethList->getMethod(),
6122 Results.getBasePriority(MethList->getMethod()), nullptr);
6123 R.StartParameter = SelIdents.size();
6124 R.AllParametersAreInformative = false;
6125 Results.MaybeAddResult(R, CurContext);
6129 Results.ExitScope();
6132 // If we're actually at the argument expression (rather than prior to the
6133 // selector), we're actually performing code completion for an expression.
6134 // Determine whether we have a single, best method. If so, we can
6135 // code-complete the expression using the corresponding parameter type as
6136 // our preferred type, improving completion results.
6137 if (AtArgumentExpression) {
6138 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results,
6140 if (PreferredType.isNull())
6141 CodeCompleteOrdinaryName(S, PCC_Expression);
6143 CodeCompleteExpression(S, PreferredType);
6147 HandleCodeCompleteResults(this, CodeCompleter,
6148 Results.getCompletionContext(),
6149 Results.data(),Results.size());
6152 void Sema::CodeCompleteObjCForCollection(Scope *S,
6153 DeclGroupPtrTy IterationVar) {
6154 CodeCompleteExpressionData Data;
6155 Data.ObjCCollection = true;
6157 if (IterationVar.getAsOpaquePtr()) {
6158 DeclGroupRef DG = IterationVar.get();
6159 for (DeclGroupRef::iterator I = DG.begin(), End = DG.end(); I != End; ++I) {
6161 Data.IgnoreDecls.push_back(*I);
6165 CodeCompleteExpression(S, Data);
6168 void Sema::CodeCompleteObjCSelector(Scope *S,
6169 ArrayRef<IdentifierInfo *> SelIdents) {
6170 // If we have an external source, load the entire class method
6171 // pool from the AST file.
6172 if (ExternalSource) {
6173 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
6175 Selector Sel = ExternalSource->GetExternalSelector(I);
6176 if (Sel.isNull() || MethodPool.count(Sel))
6179 ReadMethodPool(Sel);
6183 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6184 CodeCompleter->getCodeCompletionTUInfo(),
6185 CodeCompletionContext::CCC_SelectorName);
6186 Results.EnterNewScope();
6187 for (GlobalMethodPool::iterator M = MethodPool.begin(),
6188 MEnd = MethodPool.end();
6191 Selector Sel = M->first;
6192 if (!isAcceptableObjCSelector(Sel, MK_Any, SelIdents))
6195 CodeCompletionBuilder Builder(Results.getAllocator(),
6196 Results.getCodeCompletionTUInfo());
6197 if (Sel.isUnarySelector()) {
6198 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
6199 Sel.getNameForSlot(0)));
6200 Results.AddResult(Builder.TakeString());
6204 std::string Accumulator;
6205 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I) {
6206 if (I == SelIdents.size()) {
6207 if (!Accumulator.empty()) {
6208 Builder.AddInformativeChunk(Builder.getAllocator().CopyString(
6210 Accumulator.clear();
6214 Accumulator += Sel.getNameForSlot(I);
6217 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString( Accumulator));
6218 Results.AddResult(Builder.TakeString());
6220 Results.ExitScope();
6222 HandleCodeCompleteResults(this, CodeCompleter,
6223 CodeCompletionContext::CCC_SelectorName,
6224 Results.data(), Results.size());
6227 /// \brief Add all of the protocol declarations that we find in the given
6228 /// (translation unit) context.
6229 static void AddProtocolResults(DeclContext *Ctx, DeclContext *CurContext,
6230 bool OnlyForwardDeclarations,
6231 ResultBuilder &Results) {
6232 typedef CodeCompletionResult Result;
6234 for (const auto *D : Ctx->decls()) {
6235 // Record any protocols we find.
6236 if (const auto *Proto = dyn_cast<ObjCProtocolDecl>(D))
6237 if (!OnlyForwardDeclarations || !Proto->hasDefinition())
6238 Results.AddResult(Result(Proto, Results.getBasePriority(Proto),nullptr),
6239 CurContext, nullptr, false);
6243 void Sema::CodeCompleteObjCProtocolReferences(
6244 ArrayRef<IdentifierLocPair> Protocols) {
6245 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6246 CodeCompleter->getCodeCompletionTUInfo(),
6247 CodeCompletionContext::CCC_ObjCProtocolName);
6249 if (CodeCompleter->includeGlobals()) {
6250 Results.EnterNewScope();
6252 // Tell the result set to ignore all of the protocols we have
6254 // FIXME: This doesn't work when caching code-completion results.
6255 for (const IdentifierLocPair &Pair : Protocols)
6256 if (ObjCProtocolDecl *Protocol = LookupProtocol(Pair.first,
6258 Results.Ignore(Protocol);
6260 // Add all protocols.
6261 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, false,
6264 Results.ExitScope();
6267 HandleCodeCompleteResults(this, CodeCompleter,
6268 CodeCompletionContext::CCC_ObjCProtocolName,
6269 Results.data(),Results.size());
6272 void Sema::CodeCompleteObjCProtocolDecl(Scope *) {
6273 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6274 CodeCompleter->getCodeCompletionTUInfo(),
6275 CodeCompletionContext::CCC_ObjCProtocolName);
6277 if (CodeCompleter->includeGlobals()) {
6278 Results.EnterNewScope();
6280 // Add all protocols.
6281 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, true,
6284 Results.ExitScope();
6287 HandleCodeCompleteResults(this, CodeCompleter,
6288 CodeCompletionContext::CCC_ObjCProtocolName,
6289 Results.data(),Results.size());
6292 /// \brief Add all of the Objective-C interface declarations that we find in
6293 /// the given (translation unit) context.
6294 static void AddInterfaceResults(DeclContext *Ctx, DeclContext *CurContext,
6295 bool OnlyForwardDeclarations,
6296 bool OnlyUnimplemented,
6297 ResultBuilder &Results) {
6298 typedef CodeCompletionResult Result;
6300 for (const auto *D : Ctx->decls()) {
6301 // Record any interfaces we find.
6302 if (const auto *Class = dyn_cast<ObjCInterfaceDecl>(D))
6303 if ((!OnlyForwardDeclarations || !Class->hasDefinition()) &&
6304 (!OnlyUnimplemented || !Class->getImplementation()))
6305 Results.AddResult(Result(Class, Results.getBasePriority(Class),nullptr),
6306 CurContext, nullptr, false);
6310 void Sema::CodeCompleteObjCInterfaceDecl(Scope *S) {
6311 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6312 CodeCompleter->getCodeCompletionTUInfo(),
6313 CodeCompletionContext::CCC_Other);
6314 Results.EnterNewScope();
6316 if (CodeCompleter->includeGlobals()) {
6318 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
6322 Results.ExitScope();
6324 HandleCodeCompleteResults(this, CodeCompleter,
6325 CodeCompletionContext::CCC_ObjCInterfaceName,
6326 Results.data(),Results.size());
6329 void Sema::CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName,
6330 SourceLocation ClassNameLoc) {
6331 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6332 CodeCompleter->getCodeCompletionTUInfo(),
6333 CodeCompletionContext::CCC_ObjCInterfaceName);
6334 Results.EnterNewScope();
6336 // Make sure that we ignore the class we're currently defining.
6338 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
6339 if (CurClass && isa<ObjCInterfaceDecl>(CurClass))
6340 Results.Ignore(CurClass);
6342 if (CodeCompleter->includeGlobals()) {
6344 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
6348 Results.ExitScope();
6350 HandleCodeCompleteResults(this, CodeCompleter,
6351 CodeCompletionContext::CCC_ObjCInterfaceName,
6352 Results.data(),Results.size());
6355 void Sema::CodeCompleteObjCImplementationDecl(Scope *S) {
6356 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6357 CodeCompleter->getCodeCompletionTUInfo(),
6358 CodeCompletionContext::CCC_Other);
6359 Results.EnterNewScope();
6361 if (CodeCompleter->includeGlobals()) {
6362 // Add all unimplemented classes.
6363 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
6367 Results.ExitScope();
6369 HandleCodeCompleteResults(this, CodeCompleter,
6370 CodeCompletionContext::CCC_ObjCInterfaceName,
6371 Results.data(),Results.size());
6374 void Sema::CodeCompleteObjCInterfaceCategory(Scope *S,
6375 IdentifierInfo *ClassName,
6376 SourceLocation ClassNameLoc) {
6377 typedef CodeCompletionResult Result;
6379 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6380 CodeCompleter->getCodeCompletionTUInfo(),
6381 CodeCompletionContext::CCC_ObjCCategoryName);
6383 // Ignore any categories we find that have already been implemented by this
6385 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
6387 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
6388 if (ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass)){
6389 for (const auto *Cat : Class->visible_categories())
6390 CategoryNames.insert(Cat->getIdentifier());
6393 // Add all of the categories we know about.
6394 Results.EnterNewScope();
6395 TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
6396 for (const auto *D : TU->decls())
6397 if (const auto *Category = dyn_cast<ObjCCategoryDecl>(D))
6398 if (CategoryNames.insert(Category->getIdentifier()).second)
6399 Results.AddResult(Result(Category, Results.getBasePriority(Category),
6401 CurContext, nullptr, false);
6402 Results.ExitScope();
6404 HandleCodeCompleteResults(this, CodeCompleter,
6405 CodeCompletionContext::CCC_ObjCCategoryName,
6406 Results.data(),Results.size());
6409 void Sema::CodeCompleteObjCImplementationCategory(Scope *S,
6410 IdentifierInfo *ClassName,
6411 SourceLocation ClassNameLoc) {
6412 typedef CodeCompletionResult Result;
6414 // Find the corresponding interface. If we couldn't find the interface, the
6415 // program itself is ill-formed. However, we'll try to be helpful still by
6416 // providing the list of all of the categories we know about.
6418 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
6419 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass);
6421 return CodeCompleteObjCInterfaceCategory(S, ClassName, ClassNameLoc);
6423 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6424 CodeCompleter->getCodeCompletionTUInfo(),
6425 CodeCompletionContext::CCC_ObjCCategoryName);
6427 // Add all of the categories that have have corresponding interface
6428 // declarations in this class and any of its superclasses, except for
6429 // already-implemented categories in the class itself.
6430 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
6431 Results.EnterNewScope();
6432 bool IgnoreImplemented = true;
6434 for (const auto *Cat : Class->visible_categories()) {
6435 if ((!IgnoreImplemented || !Cat->getImplementation()) &&
6436 CategoryNames.insert(Cat->getIdentifier()).second)
6437 Results.AddResult(Result(Cat, Results.getBasePriority(Cat), nullptr),
6438 CurContext, nullptr, false);
6441 Class = Class->getSuperClass();
6442 IgnoreImplemented = false;
6444 Results.ExitScope();
6446 HandleCodeCompleteResults(this, CodeCompleter,
6447 CodeCompletionContext::CCC_ObjCCategoryName,
6448 Results.data(),Results.size());
6451 void Sema::CodeCompleteObjCPropertyDefinition(Scope *S) {
6452 CodeCompletionContext CCContext(CodeCompletionContext::CCC_Other);
6453 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6454 CodeCompleter->getCodeCompletionTUInfo(),
6457 // Figure out where this @synthesize lives.
6458 ObjCContainerDecl *Container
6459 = dyn_cast_or_null<ObjCContainerDecl>(CurContext);
6461 (!isa<ObjCImplementationDecl>(Container) &&
6462 !isa<ObjCCategoryImplDecl>(Container)))
6465 // Ignore any properties that have already been implemented.
6466 Container = getContainerDef(Container);
6467 for (const auto *D : Container->decls())
6468 if (const auto *PropertyImpl = dyn_cast<ObjCPropertyImplDecl>(D))
6469 Results.Ignore(PropertyImpl->getPropertyDecl());
6471 // Add any properties that we find.
6472 AddedPropertiesSet AddedProperties;
6473 Results.EnterNewScope();
6474 if (ObjCImplementationDecl *ClassImpl
6475 = dyn_cast<ObjCImplementationDecl>(Container))
6476 AddObjCProperties(CCContext, ClassImpl->getClassInterface(), false,
6477 /*AllowNullaryMethods=*/false, CurContext,
6478 AddedProperties, Results);
6480 AddObjCProperties(CCContext,
6481 cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl(),
6482 false, /*AllowNullaryMethods=*/false, CurContext,
6483 AddedProperties, Results);
6484 Results.ExitScope();
6486 HandleCodeCompleteResults(this, CodeCompleter,
6487 CodeCompletionContext::CCC_Other,
6488 Results.data(),Results.size());
6491 void Sema::CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
6492 IdentifierInfo *PropertyName) {
6493 typedef CodeCompletionResult Result;
6494 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6495 CodeCompleter->getCodeCompletionTUInfo(),
6496 CodeCompletionContext::CCC_Other);
6498 // Figure out where this @synthesize lives.
6499 ObjCContainerDecl *Container
6500 = dyn_cast_or_null<ObjCContainerDecl>(CurContext);
6502 (!isa<ObjCImplementationDecl>(Container) &&
6503 !isa<ObjCCategoryImplDecl>(Container)))
6506 // Figure out which interface we're looking into.
6507 ObjCInterfaceDecl *Class = nullptr;
6508 if (ObjCImplementationDecl *ClassImpl
6509 = dyn_cast<ObjCImplementationDecl>(Container))
6510 Class = ClassImpl->getClassInterface();
6512 Class = cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl()
6513 ->getClassInterface();
6515 // Determine the type of the property we're synthesizing.
6516 QualType PropertyType = Context.getObjCIdType();
6518 if (ObjCPropertyDecl *Property = Class->FindPropertyDeclaration(
6519 PropertyName, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
6521 = Property->getType().getNonReferenceType().getUnqualifiedType();
6523 // Give preference to ivars
6524 Results.setPreferredType(PropertyType);
6528 // Add all of the instance variables in this class and its superclasses.
6529 Results.EnterNewScope();
6530 bool SawSimilarlyNamedIvar = false;
6531 std::string NameWithPrefix;
6532 NameWithPrefix += '_';
6533 NameWithPrefix += PropertyName->getName();
6534 std::string NameWithSuffix = PropertyName->getName().str();
6535 NameWithSuffix += '_';
6536 for(; Class; Class = Class->getSuperClass()) {
6537 for (ObjCIvarDecl *Ivar = Class->all_declared_ivar_begin(); Ivar;
6538 Ivar = Ivar->getNextIvar()) {
6539 Results.AddResult(Result(Ivar, Results.getBasePriority(Ivar), nullptr),
6540 CurContext, nullptr, false);
6542 // Determine whether we've seen an ivar with a name similar to the
6544 if ((PropertyName == Ivar->getIdentifier() ||
6545 NameWithPrefix == Ivar->getName() ||
6546 NameWithSuffix == Ivar->getName())) {
6547 SawSimilarlyNamedIvar = true;
6549 // Reduce the priority of this result by one, to give it a slight
6550 // advantage over other results whose names don't match so closely.
6551 if (Results.size() &&
6552 Results.data()[Results.size() - 1].Kind
6553 == CodeCompletionResult::RK_Declaration &&
6554 Results.data()[Results.size() - 1].Declaration == Ivar)
6555 Results.data()[Results.size() - 1].Priority--;
6560 if (!SawSimilarlyNamedIvar) {
6561 // Create ivar result _propName, that the user can use to synthesize
6562 // an ivar of the appropriate type.
6563 unsigned Priority = CCP_MemberDeclaration + 1;
6564 typedef CodeCompletionResult Result;
6565 CodeCompletionAllocator &Allocator = Results.getAllocator();
6566 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo(),
6567 Priority,CXAvailability_Available);
6569 PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
6570 Builder.AddResultTypeChunk(GetCompletionTypeString(PropertyType, Context,
6571 Policy, Allocator));
6572 Builder.AddTypedTextChunk(Allocator.CopyString(NameWithPrefix));
6573 Results.AddResult(Result(Builder.TakeString(), Priority,
6574 CXCursor_ObjCIvarDecl));
6577 Results.ExitScope();
6579 HandleCodeCompleteResults(this, CodeCompleter,
6580 CodeCompletionContext::CCC_Other,
6581 Results.data(),Results.size());
6584 // Mapping from selectors to the methods that implement that selector, along
6585 // with the "in original class" flag.
6586 typedef llvm::DenseMap<
6587 Selector, llvm::PointerIntPair<ObjCMethodDecl *, 1, bool> > KnownMethodsMap;
6589 /// \brief Find all of the methods that reside in the given container
6590 /// (and its superclasses, protocols, etc.) that meet the given
6591 /// criteria. Insert those methods into the map of known methods,
6592 /// indexed by selector so they can be easily found.
6593 static void FindImplementableMethods(ASTContext &Context,
6594 ObjCContainerDecl *Container,
6595 bool WantInstanceMethods,
6596 QualType ReturnType,
6597 KnownMethodsMap &KnownMethods,
6598 bool InOriginalClass = true) {
6599 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)) {
6600 // Make sure we have a definition; that's what we'll walk.
6601 if (!IFace->hasDefinition())
6604 IFace = IFace->getDefinition();
6607 const ObjCList<ObjCProtocolDecl> &Protocols
6608 = IFace->getReferencedProtocols();
6609 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
6610 E = Protocols.end();
6612 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
6613 KnownMethods, InOriginalClass);
6615 // Add methods from any class extensions and categories.
6616 for (auto *Cat : IFace->visible_categories()) {
6617 FindImplementableMethods(Context, Cat, WantInstanceMethods, ReturnType,
6618 KnownMethods, false);
6621 // Visit the superclass.
6622 if (IFace->getSuperClass())
6623 FindImplementableMethods(Context, IFace->getSuperClass(),
6624 WantInstanceMethods, ReturnType,
6625 KnownMethods, false);
6628 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
6629 // Recurse into protocols.
6630 const ObjCList<ObjCProtocolDecl> &Protocols
6631 = Category->getReferencedProtocols();
6632 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
6633 E = Protocols.end();
6635 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
6636 KnownMethods, InOriginalClass);
6638 // If this category is the original class, jump to the interface.
6639 if (InOriginalClass && Category->getClassInterface())
6640 FindImplementableMethods(Context, Category->getClassInterface(),
6641 WantInstanceMethods, ReturnType, KnownMethods,
6645 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
6646 // Make sure we have a definition; that's what we'll walk.
6647 if (!Protocol->hasDefinition())
6649 Protocol = Protocol->getDefinition();
6650 Container = Protocol;
6652 // Recurse into protocols.
6653 const ObjCList<ObjCProtocolDecl> &Protocols
6654 = Protocol->getReferencedProtocols();
6655 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
6656 E = Protocols.end();
6658 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
6659 KnownMethods, false);
6662 // Add methods in this container. This operation occurs last because
6663 // we want the methods from this container to override any methods
6664 // we've previously seen with the same selector.
6665 for (auto *M : Container->methods()) {
6666 if (M->isInstanceMethod() == WantInstanceMethods) {
6667 if (!ReturnType.isNull() &&
6668 !Context.hasSameUnqualifiedType(ReturnType, M->getReturnType()))
6671 KnownMethods[M->getSelector()] =
6672 KnownMethodsMap::mapped_type(M, InOriginalClass);
6677 /// \brief Add the parenthesized return or parameter type chunk to a code
6678 /// completion string.
6679 static void AddObjCPassingTypeChunk(QualType Type,
6680 unsigned ObjCDeclQuals,
6681 ASTContext &Context,
6682 const PrintingPolicy &Policy,
6683 CodeCompletionBuilder &Builder) {
6684 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6685 std::string Quals = formatObjCParamQualifiers(ObjCDeclQuals, Type);
6687 Builder.AddTextChunk(Builder.getAllocator().CopyString(Quals));
6688 Builder.AddTextChunk(GetCompletionTypeString(Type, Context, Policy,
6689 Builder.getAllocator()));
6690 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6693 /// \brief Determine whether the given class is or inherits from a class by
6695 static bool InheritsFromClassNamed(ObjCInterfaceDecl *Class,
6700 if (Class->getIdentifier() && Class->getIdentifier()->getName() == Name)
6703 return InheritsFromClassNamed(Class->getSuperClass(), Name);
6706 /// \brief Add code completions for Objective-C Key-Value Coding (KVC) and
6707 /// Key-Value Observing (KVO).
6708 static void AddObjCKeyValueCompletions(ObjCPropertyDecl *Property,
6709 bool IsInstanceMethod,
6710 QualType ReturnType,
6711 ASTContext &Context,
6712 VisitedSelectorSet &KnownSelectors,
6713 ResultBuilder &Results) {
6714 IdentifierInfo *PropName = Property->getIdentifier();
6715 if (!PropName || PropName->getLength() == 0)
6718 PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema());
6720 // Builder that will create each code completion.
6721 typedef CodeCompletionResult Result;
6722 CodeCompletionAllocator &Allocator = Results.getAllocator();
6723 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
6725 // The selector table.
6726 SelectorTable &Selectors = Context.Selectors;
6728 // The property name, copied into the code completion allocation region
6731 CodeCompletionAllocator &Allocator;
6733 const char *CopiedKey;
6735 KeyHolder(CodeCompletionAllocator &Allocator, StringRef Key)
6736 : Allocator(Allocator), Key(Key), CopiedKey(nullptr) {}
6738 operator const char *() {
6742 return CopiedKey = Allocator.CopyString(Key);
6744 } Key(Allocator, PropName->getName());
6746 // The uppercased name of the property name.
6747 std::string UpperKey = PropName->getName();
6748 if (!UpperKey.empty())
6749 UpperKey[0] = toUppercase(UpperKey[0]);
6751 bool ReturnTypeMatchesProperty = ReturnType.isNull() ||
6752 Context.hasSameUnqualifiedType(ReturnType.getNonReferenceType(),
6753 Property->getType());
6754 bool ReturnTypeMatchesVoid
6755 = ReturnType.isNull() || ReturnType->isVoidType();
6757 // Add the normal accessor -(type)key.
6758 if (IsInstanceMethod &&
6759 KnownSelectors.insert(Selectors.getNullarySelector(PropName)).second &&
6760 ReturnTypeMatchesProperty && !Property->getGetterMethodDecl()) {
6761 if (ReturnType.isNull())
6762 AddObjCPassingTypeChunk(Property->getType(), /*Quals=*/0,
6763 Context, Policy, Builder);
6765 Builder.AddTypedTextChunk(Key);
6766 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6767 CXCursor_ObjCInstanceMethodDecl));
6770 // If we have an integral or boolean property (or the user has provided
6771 // an integral or boolean return type), add the accessor -(type)isKey.
6772 if (IsInstanceMethod &&
6773 ((!ReturnType.isNull() &&
6774 (ReturnType->isIntegerType() || ReturnType->isBooleanType())) ||
6775 (ReturnType.isNull() &&
6776 (Property->getType()->isIntegerType() ||
6777 Property->getType()->isBooleanType())))) {
6778 std::string SelectorName = (Twine("is") + UpperKey).str();
6779 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6780 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
6782 if (ReturnType.isNull()) {
6783 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6784 Builder.AddTextChunk("BOOL");
6785 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6788 Builder.AddTypedTextChunk(
6789 Allocator.CopyString(SelectorId->getName()));
6790 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6791 CXCursor_ObjCInstanceMethodDecl));
6795 // Add the normal mutator.
6796 if (IsInstanceMethod && ReturnTypeMatchesVoid &&
6797 !Property->getSetterMethodDecl()) {
6798 std::string SelectorName = (Twine("set") + UpperKey).str();
6799 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6800 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
6801 if (ReturnType.isNull()) {
6802 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6803 Builder.AddTextChunk("void");
6804 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6807 Builder.AddTypedTextChunk(
6808 Allocator.CopyString(SelectorId->getName()));
6809 Builder.AddTypedTextChunk(":");
6810 AddObjCPassingTypeChunk(Property->getType(), /*Quals=*/0,
6811 Context, Policy, Builder);
6812 Builder.AddTextChunk(Key);
6813 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6814 CXCursor_ObjCInstanceMethodDecl));
6818 // Indexed and unordered accessors
6819 unsigned IndexedGetterPriority = CCP_CodePattern;
6820 unsigned IndexedSetterPriority = CCP_CodePattern;
6821 unsigned UnorderedGetterPriority = CCP_CodePattern;
6822 unsigned UnorderedSetterPriority = CCP_CodePattern;
6823 if (const ObjCObjectPointerType *ObjCPointer
6824 = Property->getType()->getAs<ObjCObjectPointerType>()) {
6825 if (ObjCInterfaceDecl *IFace = ObjCPointer->getInterfaceDecl()) {
6826 // If this interface type is not provably derived from a known
6827 // collection, penalize the corresponding completions.
6828 if (!InheritsFromClassNamed(IFace, "NSMutableArray")) {
6829 IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
6830 if (!InheritsFromClassNamed(IFace, "NSArray"))
6831 IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
6834 if (!InheritsFromClassNamed(IFace, "NSMutableSet")) {
6835 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
6836 if (!InheritsFromClassNamed(IFace, "NSSet"))
6837 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
6841 IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
6842 IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
6843 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
6844 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
6847 // Add -(NSUInteger)countOf<key>
6848 if (IsInstanceMethod &&
6849 (ReturnType.isNull() || ReturnType->isIntegerType())) {
6850 std::string SelectorName = (Twine("countOf") + UpperKey).str();
6851 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6852 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
6854 if (ReturnType.isNull()) {
6855 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6856 Builder.AddTextChunk("NSUInteger");
6857 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6860 Builder.AddTypedTextChunk(
6861 Allocator.CopyString(SelectorId->getName()));
6862 Results.AddResult(Result(Builder.TakeString(),
6863 std::min(IndexedGetterPriority,
6864 UnorderedGetterPriority),
6865 CXCursor_ObjCInstanceMethodDecl));
6870 // Add -(id)objectInKeyAtIndex:(NSUInteger)index
6871 if (IsInstanceMethod &&
6872 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
6873 std::string SelectorName
6874 = (Twine("objectIn") + UpperKey + "AtIndex").str();
6875 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6876 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
6877 if (ReturnType.isNull()) {
6878 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6879 Builder.AddTextChunk("id");
6880 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6883 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6884 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6885 Builder.AddTextChunk("NSUInteger");
6886 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6887 Builder.AddTextChunk("index");
6888 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
6889 CXCursor_ObjCInstanceMethodDecl));
6893 // Add -(NSArray *)keyAtIndexes:(NSIndexSet *)indexes
6894 if (IsInstanceMethod &&
6895 (ReturnType.isNull() ||
6896 (ReturnType->isObjCObjectPointerType() &&
6897 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6898 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6899 ->getName() == "NSArray"))) {
6900 std::string SelectorName
6901 = (Twine(Property->getName()) + "AtIndexes").str();
6902 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6903 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
6904 if (ReturnType.isNull()) {
6905 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6906 Builder.AddTextChunk("NSArray *");
6907 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6910 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6911 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6912 Builder.AddTextChunk("NSIndexSet *");
6913 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6914 Builder.AddTextChunk("indexes");
6915 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
6916 CXCursor_ObjCInstanceMethodDecl));
6920 // Add -(void)getKey:(type **)buffer range:(NSRange)inRange
6921 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
6922 std::string SelectorName = (Twine("get") + UpperKey).str();
6923 IdentifierInfo *SelectorIds[2] = {
6924 &Context.Idents.get(SelectorName),
6925 &Context.Idents.get("range")
6928 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
6929 if (ReturnType.isNull()) {
6930 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6931 Builder.AddTextChunk("void");
6932 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6935 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6936 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6937 Builder.AddPlaceholderChunk("object-type");
6938 Builder.AddTextChunk(" **");
6939 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6940 Builder.AddTextChunk("buffer");
6941 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6942 Builder.AddTypedTextChunk("range:");
6943 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6944 Builder.AddTextChunk("NSRange");
6945 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6946 Builder.AddTextChunk("inRange");
6947 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
6948 CXCursor_ObjCInstanceMethodDecl));
6952 // Mutable indexed accessors
6954 // - (void)insertObject:(type *)object inKeyAtIndex:(NSUInteger)index
6955 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
6956 std::string SelectorName = (Twine("in") + UpperKey + "AtIndex").str();
6957 IdentifierInfo *SelectorIds[2] = {
6958 &Context.Idents.get("insertObject"),
6959 &Context.Idents.get(SelectorName)
6962 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
6963 if (ReturnType.isNull()) {
6964 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6965 Builder.AddTextChunk("void");
6966 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6969 Builder.AddTypedTextChunk("insertObject:");
6970 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6971 Builder.AddPlaceholderChunk("object-type");
6972 Builder.AddTextChunk(" *");
6973 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6974 Builder.AddTextChunk("object");
6975 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6976 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6977 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6978 Builder.AddPlaceholderChunk("NSUInteger");
6979 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6980 Builder.AddTextChunk("index");
6981 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6982 CXCursor_ObjCInstanceMethodDecl));
6986 // - (void)insertKey:(NSArray *)array atIndexes:(NSIndexSet *)indexes
6987 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
6988 std::string SelectorName = (Twine("insert") + UpperKey).str();
6989 IdentifierInfo *SelectorIds[2] = {
6990 &Context.Idents.get(SelectorName),
6991 &Context.Idents.get("atIndexes")
6994 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
6995 if (ReturnType.isNull()) {
6996 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6997 Builder.AddTextChunk("void");
6998 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7001 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
7002 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7003 Builder.AddTextChunk("NSArray *");
7004 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7005 Builder.AddTextChunk("array");
7006 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7007 Builder.AddTypedTextChunk("atIndexes:");
7008 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7009 Builder.AddPlaceholderChunk("NSIndexSet *");
7010 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7011 Builder.AddTextChunk("indexes");
7012 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
7013 CXCursor_ObjCInstanceMethodDecl));
7017 // -(void)removeObjectFromKeyAtIndex:(NSUInteger)index
7018 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
7019 std::string SelectorName
7020 = (Twine("removeObjectFrom") + UpperKey + "AtIndex").str();
7021 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
7022 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
7023 if (ReturnType.isNull()) {
7024 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7025 Builder.AddTextChunk("void");
7026 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7029 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
7030 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7031 Builder.AddTextChunk("NSUInteger");
7032 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7033 Builder.AddTextChunk("index");
7034 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
7035 CXCursor_ObjCInstanceMethodDecl));
7039 // -(void)removeKeyAtIndexes:(NSIndexSet *)indexes
7040 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
7041 std::string SelectorName
7042 = (Twine("remove") + UpperKey + "AtIndexes").str();
7043 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
7044 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
7045 if (ReturnType.isNull()) {
7046 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7047 Builder.AddTextChunk("void");
7048 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7051 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
7052 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7053 Builder.AddTextChunk("NSIndexSet *");
7054 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7055 Builder.AddTextChunk("indexes");
7056 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
7057 CXCursor_ObjCInstanceMethodDecl));
7061 // - (void)replaceObjectInKeyAtIndex:(NSUInteger)index withObject:(id)object
7062 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
7063 std::string SelectorName
7064 = (Twine("replaceObjectIn") + UpperKey + "AtIndex").str();
7065 IdentifierInfo *SelectorIds[2] = {
7066 &Context.Idents.get(SelectorName),
7067 &Context.Idents.get("withObject")
7070 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
7071 if (ReturnType.isNull()) {
7072 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7073 Builder.AddTextChunk("void");
7074 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7077 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
7078 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7079 Builder.AddPlaceholderChunk("NSUInteger");
7080 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7081 Builder.AddTextChunk("index");
7082 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7083 Builder.AddTypedTextChunk("withObject:");
7084 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7085 Builder.AddTextChunk("id");
7086 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7087 Builder.AddTextChunk("object");
7088 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
7089 CXCursor_ObjCInstanceMethodDecl));
7093 // - (void)replaceKeyAtIndexes:(NSIndexSet *)indexes withKey:(NSArray *)array
7094 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
7095 std::string SelectorName1
7096 = (Twine("replace") + UpperKey + "AtIndexes").str();
7097 std::string SelectorName2 = (Twine("with") + UpperKey).str();
7098 IdentifierInfo *SelectorIds[2] = {
7099 &Context.Idents.get(SelectorName1),
7100 &Context.Idents.get(SelectorName2)
7103 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
7104 if (ReturnType.isNull()) {
7105 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7106 Builder.AddTextChunk("void");
7107 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7110 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName1 + ":"));
7111 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7112 Builder.AddPlaceholderChunk("NSIndexSet *");
7113 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7114 Builder.AddTextChunk("indexes");
7115 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7116 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName2 + ":"));
7117 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7118 Builder.AddTextChunk("NSArray *");
7119 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7120 Builder.AddTextChunk("array");
7121 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
7122 CXCursor_ObjCInstanceMethodDecl));
7126 // Unordered getters
7127 // - (NSEnumerator *)enumeratorOfKey
7128 if (IsInstanceMethod &&
7129 (ReturnType.isNull() ||
7130 (ReturnType->isObjCObjectPointerType() &&
7131 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
7132 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
7133 ->getName() == "NSEnumerator"))) {
7134 std::string SelectorName = (Twine("enumeratorOf") + UpperKey).str();
7135 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
7136 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
7138 if (ReturnType.isNull()) {
7139 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7140 Builder.AddTextChunk("NSEnumerator *");
7141 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7144 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
7145 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
7146 CXCursor_ObjCInstanceMethodDecl));
7150 // - (type *)memberOfKey:(type *)object
7151 if (IsInstanceMethod &&
7152 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
7153 std::string SelectorName = (Twine("memberOf") + UpperKey).str();
7154 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
7155 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
7156 if (ReturnType.isNull()) {
7157 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7158 Builder.AddPlaceholderChunk("object-type");
7159 Builder.AddTextChunk(" *");
7160 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7163 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
7164 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7165 if (ReturnType.isNull()) {
7166 Builder.AddPlaceholderChunk("object-type");
7167 Builder.AddTextChunk(" *");
7169 Builder.AddTextChunk(GetCompletionTypeString(ReturnType, Context,
7171 Builder.getAllocator()));
7173 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7174 Builder.AddTextChunk("object");
7175 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
7176 CXCursor_ObjCInstanceMethodDecl));
7180 // Mutable unordered accessors
7181 // - (void)addKeyObject:(type *)object
7182 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
7183 std::string SelectorName
7184 = (Twine("add") + UpperKey + Twine("Object")).str();
7185 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
7186 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
7187 if (ReturnType.isNull()) {
7188 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7189 Builder.AddTextChunk("void");
7190 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7193 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
7194 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7195 Builder.AddPlaceholderChunk("object-type");
7196 Builder.AddTextChunk(" *");
7197 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7198 Builder.AddTextChunk("object");
7199 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
7200 CXCursor_ObjCInstanceMethodDecl));
7204 // - (void)addKey:(NSSet *)objects
7205 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
7206 std::string SelectorName = (Twine("add") + UpperKey).str();
7207 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
7208 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
7209 if (ReturnType.isNull()) {
7210 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7211 Builder.AddTextChunk("void");
7212 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7215 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
7216 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7217 Builder.AddTextChunk("NSSet *");
7218 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7219 Builder.AddTextChunk("objects");
7220 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
7221 CXCursor_ObjCInstanceMethodDecl));
7225 // - (void)removeKeyObject:(type *)object
7226 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
7227 std::string SelectorName
7228 = (Twine("remove") + UpperKey + Twine("Object")).str();
7229 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
7230 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
7231 if (ReturnType.isNull()) {
7232 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7233 Builder.AddTextChunk("void");
7234 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7237 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
7238 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7239 Builder.AddPlaceholderChunk("object-type");
7240 Builder.AddTextChunk(" *");
7241 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7242 Builder.AddTextChunk("object");
7243 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
7244 CXCursor_ObjCInstanceMethodDecl));
7248 // - (void)removeKey:(NSSet *)objects
7249 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
7250 std::string SelectorName = (Twine("remove") + UpperKey).str();
7251 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
7252 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
7253 if (ReturnType.isNull()) {
7254 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7255 Builder.AddTextChunk("void");
7256 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7259 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
7260 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7261 Builder.AddTextChunk("NSSet *");
7262 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7263 Builder.AddTextChunk("objects");
7264 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
7265 CXCursor_ObjCInstanceMethodDecl));
7269 // - (void)intersectKey:(NSSet *)objects
7270 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
7271 std::string SelectorName = (Twine("intersect") + UpperKey).str();
7272 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
7273 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
7274 if (ReturnType.isNull()) {
7275 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7276 Builder.AddTextChunk("void");
7277 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7280 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
7281 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7282 Builder.AddTextChunk("NSSet *");
7283 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7284 Builder.AddTextChunk("objects");
7285 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
7286 CXCursor_ObjCInstanceMethodDecl));
7290 // Key-Value Observing
7291 // + (NSSet *)keyPathsForValuesAffectingKey
7292 if (!IsInstanceMethod &&
7293 (ReturnType.isNull() ||
7294 (ReturnType->isObjCObjectPointerType() &&
7295 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
7296 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
7297 ->getName() == "NSSet"))) {
7298 std::string SelectorName
7299 = (Twine("keyPathsForValuesAffecting") + UpperKey).str();
7300 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
7301 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
7303 if (ReturnType.isNull()) {
7304 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7305 Builder.AddTextChunk("NSSet<NSString *> *");
7306 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7309 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
7310 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
7311 CXCursor_ObjCClassMethodDecl));
7315 // + (BOOL)automaticallyNotifiesObserversForKey
7316 if (!IsInstanceMethod &&
7317 (ReturnType.isNull() ||
7318 ReturnType->isIntegerType() ||
7319 ReturnType->isBooleanType())) {
7320 std::string SelectorName
7321 = (Twine("automaticallyNotifiesObserversOf") + UpperKey).str();
7322 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
7323 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
7325 if (ReturnType.isNull()) {
7326 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7327 Builder.AddTextChunk("BOOL");
7328 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7331 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
7332 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
7333 CXCursor_ObjCClassMethodDecl));
7338 void Sema::CodeCompleteObjCMethodDecl(Scope *S,
7339 bool IsInstanceMethod,
7340 ParsedType ReturnTy) {
7341 // Determine the return type of the method we're declaring, if
7343 QualType ReturnType = GetTypeFromParser(ReturnTy);
7344 Decl *IDecl = nullptr;
7345 if (CurContext->isObjCContainer()) {
7346 ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext);
7347 IDecl = cast<Decl>(OCD);
7349 // Determine where we should start searching for methods.
7350 ObjCContainerDecl *SearchDecl = nullptr;
7351 bool IsInImplementation = false;
7352 if (Decl *D = IDecl) {
7353 if (ObjCImplementationDecl *Impl = dyn_cast<ObjCImplementationDecl>(D)) {
7354 SearchDecl = Impl->getClassInterface();
7355 IsInImplementation = true;
7356 } else if (ObjCCategoryImplDecl *CatImpl
7357 = dyn_cast<ObjCCategoryImplDecl>(D)) {
7358 SearchDecl = CatImpl->getCategoryDecl();
7359 IsInImplementation = true;
7361 SearchDecl = dyn_cast<ObjCContainerDecl>(D);
7364 if (!SearchDecl && S) {
7365 if (DeclContext *DC = S->getEntity())
7366 SearchDecl = dyn_cast<ObjCContainerDecl>(DC);
7370 HandleCodeCompleteResults(this, CodeCompleter,
7371 CodeCompletionContext::CCC_Other,
7376 // Find all of the methods that we could declare/implement here.
7377 KnownMethodsMap KnownMethods;
7378 FindImplementableMethods(Context, SearchDecl, IsInstanceMethod,
7379 ReturnType, KnownMethods);
7381 // Add declarations or definitions for each of the known methods.
7382 typedef CodeCompletionResult Result;
7383 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
7384 CodeCompleter->getCodeCompletionTUInfo(),
7385 CodeCompletionContext::CCC_Other);
7386 Results.EnterNewScope();
7387 PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
7388 for (KnownMethodsMap::iterator M = KnownMethods.begin(),
7389 MEnd = KnownMethods.end();
7391 ObjCMethodDecl *Method = M->second.getPointer();
7392 CodeCompletionBuilder Builder(Results.getAllocator(),
7393 Results.getCodeCompletionTUInfo());
7395 // If the result type was not already provided, add it to the
7396 // pattern as (type).
7397 if (ReturnType.isNull()) {
7398 QualType ResTy = Method->getSendResultType().stripObjCKindOfType(Context);
7399 AttributedType::stripOuterNullability(ResTy);
7400 AddObjCPassingTypeChunk(ResTy,
7401 Method->getObjCDeclQualifier(), Context, Policy,
7405 Selector Sel = Method->getSelector();
7407 // Add the first part of the selector to the pattern.
7408 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
7409 Sel.getNameForSlot(0)));
7411 // Add parameters to the pattern.
7413 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
7414 PEnd = Method->param_end();
7415 P != PEnd; (void)++P, ++I) {
7416 // Add the part of the selector name.
7418 Builder.AddTypedTextChunk(":");
7419 else if (I < Sel.getNumArgs()) {
7420 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7421 Builder.AddTypedTextChunk(
7422 Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":"));
7426 // Add the parameter type.
7428 if ((*P)->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
7429 ParamType = (*P)->getType();
7431 ParamType = (*P)->getOriginalType();
7432 ParamType = ParamType.substObjCTypeArgs(Context, {},
7433 ObjCSubstitutionContext::Parameter);
7434 AttributedType::stripOuterNullability(ParamType);
7435 AddObjCPassingTypeChunk(ParamType,
7436 (*P)->getObjCDeclQualifier(),
7440 if (IdentifierInfo *Id = (*P)->getIdentifier())
7441 Builder.AddTextChunk(Builder.getAllocator().CopyString( Id->getName()));
7444 if (Method->isVariadic()) {
7445 if (Method->param_size() > 0)
7446 Builder.AddChunk(CodeCompletionString::CK_Comma);
7447 Builder.AddTextChunk("...");
7450 if (IsInImplementation && Results.includeCodePatterns()) {
7451 // We will be defining the method here, so add a compound statement.
7452 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7453 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
7454 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
7455 if (!Method->getReturnType()->isVoidType()) {
7456 // If the result type is not void, add a return clause.
7457 Builder.AddTextChunk("return");
7458 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7459 Builder.AddPlaceholderChunk("expression");
7460 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
7462 Builder.AddPlaceholderChunk("statements");
7464 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
7465 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
7468 unsigned Priority = CCP_CodePattern;
7469 if (!M->second.getInt())
7470 Priority += CCD_InBaseClass;
7472 Results.AddResult(Result(Builder.TakeString(), Method, Priority));
7475 // Add Key-Value-Coding and Key-Value-Observing accessor methods for all of
7476 // the properties in this class and its categories.
7477 if (Context.getLangOpts().ObjC2) {
7478 SmallVector<ObjCContainerDecl *, 4> Containers;
7479 Containers.push_back(SearchDecl);
7481 VisitedSelectorSet KnownSelectors;
7482 for (KnownMethodsMap::iterator M = KnownMethods.begin(),
7483 MEnd = KnownMethods.end();
7485 KnownSelectors.insert(M->first);
7488 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(SearchDecl);
7490 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(SearchDecl))
7491 IFace = Category->getClassInterface();
7494 for (auto *Cat : IFace->visible_categories())
7495 Containers.push_back(Cat);
7497 for (unsigned I = 0, N = Containers.size(); I != N; ++I)
7498 for (auto *P : Containers[I]->instance_properties())
7499 AddObjCKeyValueCompletions(P, IsInstanceMethod, ReturnType, Context,
7500 KnownSelectors, Results);
7503 Results.ExitScope();
7505 HandleCodeCompleteResults(this, CodeCompleter,
7506 CodeCompletionContext::CCC_Other,
7507 Results.data(),Results.size());
7510 void Sema::CodeCompleteObjCMethodDeclSelector(Scope *S,
7511 bool IsInstanceMethod,
7512 bool AtParameterName,
7513 ParsedType ReturnTy,
7514 ArrayRef<IdentifierInfo *> SelIdents) {
7515 // If we have an external source, load the entire class method
7516 // pool from the AST file.
7517 if (ExternalSource) {
7518 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
7520 Selector Sel = ExternalSource->GetExternalSelector(I);
7521 if (Sel.isNull() || MethodPool.count(Sel))
7524 ReadMethodPool(Sel);
7528 // Build the set of methods we can see.
7529 typedef CodeCompletionResult Result;
7530 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
7531 CodeCompleter->getCodeCompletionTUInfo(),
7532 CodeCompletionContext::CCC_Other);
7535 Results.setPreferredType(GetTypeFromParser(ReturnTy).getNonReferenceType());
7537 Results.EnterNewScope();
7538 for (GlobalMethodPool::iterator M = MethodPool.begin(),
7539 MEnd = MethodPool.end();
7541 for (ObjCMethodList *MethList = IsInstanceMethod ? &M->second.first :
7543 MethList && MethList->getMethod();
7544 MethList = MethList->getNext()) {
7545 if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents))
7548 if (AtParameterName) {
7549 // Suggest parameter names we've seen before.
7550 unsigned NumSelIdents = SelIdents.size();
7552 NumSelIdents <= MethList->getMethod()->param_size()) {
7553 ParmVarDecl *Param =
7554 MethList->getMethod()->parameters()[NumSelIdents - 1];
7555 if (Param->getIdentifier()) {
7556 CodeCompletionBuilder Builder(Results.getAllocator(),
7557 Results.getCodeCompletionTUInfo());
7558 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
7559 Param->getIdentifier()->getName()));
7560 Results.AddResult(Builder.TakeString());
7567 Result R(MethList->getMethod(),
7568 Results.getBasePriority(MethList->getMethod()), nullptr);
7569 R.StartParameter = SelIdents.size();
7570 R.AllParametersAreInformative = false;
7571 R.DeclaringEntity = true;
7572 Results.MaybeAddResult(R, CurContext);
7576 Results.ExitScope();
7578 if (!AtParameterName && !SelIdents.empty() &&
7579 SelIdents.front()->getName().startswith("init")) {
7580 for (const auto &M : PP.macros()) {
7581 if (M.first->getName() != "NS_DESIGNATED_INITIALIZER")
7583 Results.EnterNewScope();
7584 CodeCompletionBuilder Builder(Results.getAllocator(),
7585 Results.getCodeCompletionTUInfo());
7586 Builder.AddTypedTextChunk(
7587 Builder.getAllocator().CopyString(M.first->getName()));
7588 Results.AddResult(CodeCompletionResult(Builder.TakeString(), CCP_Macro,
7589 CXCursor_MacroDefinition));
7590 Results.ExitScope();
7594 HandleCodeCompleteResults(this, CodeCompleter,
7595 CodeCompletionContext::CCC_Other,
7596 Results.data(),Results.size());
7599 void Sema::CodeCompletePreprocessorDirective(bool InConditional) {
7600 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
7601 CodeCompleter->getCodeCompletionTUInfo(),
7602 CodeCompletionContext::CCC_PreprocessorDirective);
7603 Results.EnterNewScope();
7606 CodeCompletionBuilder Builder(Results.getAllocator(),
7607 Results.getCodeCompletionTUInfo());
7608 Builder.AddTypedTextChunk("if");
7609 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7610 Builder.AddPlaceholderChunk("condition");
7611 Results.AddResult(Builder.TakeString());
7614 Builder.AddTypedTextChunk("ifdef");
7615 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7616 Builder.AddPlaceholderChunk("macro");
7617 Results.AddResult(Builder.TakeString());
7620 Builder.AddTypedTextChunk("ifndef");
7621 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7622 Builder.AddPlaceholderChunk("macro");
7623 Results.AddResult(Builder.TakeString());
7625 if (InConditional) {
7626 // #elif <condition>
7627 Builder.AddTypedTextChunk("elif");
7628 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7629 Builder.AddPlaceholderChunk("condition");
7630 Results.AddResult(Builder.TakeString());
7633 Builder.AddTypedTextChunk("else");
7634 Results.AddResult(Builder.TakeString());
7637 Builder.AddTypedTextChunk("endif");
7638 Results.AddResult(Builder.TakeString());
7641 // #include "header"
7642 Builder.AddTypedTextChunk("include");
7643 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7644 Builder.AddTextChunk("\"");
7645 Builder.AddPlaceholderChunk("header");
7646 Builder.AddTextChunk("\"");
7647 Results.AddResult(Builder.TakeString());
7649 // #include <header>
7650 Builder.AddTypedTextChunk("include");
7651 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7652 Builder.AddTextChunk("<");
7653 Builder.AddPlaceholderChunk("header");
7654 Builder.AddTextChunk(">");
7655 Results.AddResult(Builder.TakeString());
7658 Builder.AddTypedTextChunk("define");
7659 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7660 Builder.AddPlaceholderChunk("macro");
7661 Results.AddResult(Builder.TakeString());
7663 // #define <macro>(<args>)
7664 Builder.AddTypedTextChunk("define");
7665 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7666 Builder.AddPlaceholderChunk("macro");
7667 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7668 Builder.AddPlaceholderChunk("args");
7669 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7670 Results.AddResult(Builder.TakeString());
7673 Builder.AddTypedTextChunk("undef");
7674 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7675 Builder.AddPlaceholderChunk("macro");
7676 Results.AddResult(Builder.TakeString());
7679 Builder.AddTypedTextChunk("line");
7680 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7681 Builder.AddPlaceholderChunk("number");
7682 Results.AddResult(Builder.TakeString());
7684 // #line <number> "filename"
7685 Builder.AddTypedTextChunk("line");
7686 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7687 Builder.AddPlaceholderChunk("number");
7688 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7689 Builder.AddTextChunk("\"");
7690 Builder.AddPlaceholderChunk("filename");
7691 Builder.AddTextChunk("\"");
7692 Results.AddResult(Builder.TakeString());
7695 Builder.AddTypedTextChunk("error");
7696 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7697 Builder.AddPlaceholderChunk("message");
7698 Results.AddResult(Builder.TakeString());
7700 // #pragma <arguments>
7701 Builder.AddTypedTextChunk("pragma");
7702 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7703 Builder.AddPlaceholderChunk("arguments");
7704 Results.AddResult(Builder.TakeString());
7706 if (getLangOpts().ObjC1) {
7708 Builder.AddTypedTextChunk("import");
7709 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7710 Builder.AddTextChunk("\"");
7711 Builder.AddPlaceholderChunk("header");
7712 Builder.AddTextChunk("\"");
7713 Results.AddResult(Builder.TakeString());
7716 Builder.AddTypedTextChunk("import");
7717 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7718 Builder.AddTextChunk("<");
7719 Builder.AddPlaceholderChunk("header");
7720 Builder.AddTextChunk(">");
7721 Results.AddResult(Builder.TakeString());
7724 // #include_next "header"
7725 Builder.AddTypedTextChunk("include_next");
7726 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7727 Builder.AddTextChunk("\"");
7728 Builder.AddPlaceholderChunk("header");
7729 Builder.AddTextChunk("\"");
7730 Results.AddResult(Builder.TakeString());
7732 // #include_next <header>
7733 Builder.AddTypedTextChunk("include_next");
7734 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7735 Builder.AddTextChunk("<");
7736 Builder.AddPlaceholderChunk("header");
7737 Builder.AddTextChunk(">");
7738 Results.AddResult(Builder.TakeString());
7740 // #warning <message>
7741 Builder.AddTypedTextChunk("warning");
7742 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7743 Builder.AddPlaceholderChunk("message");
7744 Results.AddResult(Builder.TakeString());
7746 // Note: #ident and #sccs are such crazy anachronisms that we don't provide
7747 // completions for them. And __include_macros is a Clang-internal extension
7748 // that we don't want to encourage anyone to use.
7750 // FIXME: we don't support #assert or #unassert, so don't suggest them.
7751 Results.ExitScope();
7753 HandleCodeCompleteResults(this, CodeCompleter,
7754 CodeCompletionContext::CCC_PreprocessorDirective,
7755 Results.data(), Results.size());
7758 void Sema::CodeCompleteInPreprocessorConditionalExclusion(Scope *S) {
7759 CodeCompleteOrdinaryName(S,
7760 S->getFnParent()? Sema::PCC_RecoveryInFunction
7761 : Sema::PCC_Namespace);
7764 void Sema::CodeCompletePreprocessorMacroName(bool IsDefinition) {
7765 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
7766 CodeCompleter->getCodeCompletionTUInfo(),
7767 IsDefinition? CodeCompletionContext::CCC_MacroName
7768 : CodeCompletionContext::CCC_MacroNameUse);
7769 if (!IsDefinition && (!CodeCompleter || CodeCompleter->includeMacros())) {
7770 // Add just the names of macros, not their arguments.
7771 CodeCompletionBuilder Builder(Results.getAllocator(),
7772 Results.getCodeCompletionTUInfo());
7773 Results.EnterNewScope();
7774 for (Preprocessor::macro_iterator M = PP.macro_begin(),
7775 MEnd = PP.macro_end();
7777 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
7778 M->first->getName()));
7779 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
7781 CXCursor_MacroDefinition));
7783 Results.ExitScope();
7784 } else if (IsDefinition) {
7785 // FIXME: Can we detect when the user just wrote an include guard above?
7788 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
7789 Results.data(), Results.size());
7792 void Sema::CodeCompletePreprocessorExpression() {
7793 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
7794 CodeCompleter->getCodeCompletionTUInfo(),
7795 CodeCompletionContext::CCC_PreprocessorExpression);
7797 if (!CodeCompleter || CodeCompleter->includeMacros())
7798 AddMacroResults(PP, Results, true);
7800 // defined (<macro>)
7801 Results.EnterNewScope();
7802 CodeCompletionBuilder Builder(Results.getAllocator(),
7803 Results.getCodeCompletionTUInfo());
7804 Builder.AddTypedTextChunk("defined");
7805 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7806 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7807 Builder.AddPlaceholderChunk("macro");
7808 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7809 Results.AddResult(Builder.TakeString());
7810 Results.ExitScope();
7812 HandleCodeCompleteResults(this, CodeCompleter,
7813 CodeCompletionContext::CCC_PreprocessorExpression,
7814 Results.data(), Results.size());
7817 void Sema::CodeCompletePreprocessorMacroArgument(Scope *S,
7818 IdentifierInfo *Macro,
7819 MacroInfo *MacroInfo,
7820 unsigned Argument) {
7821 // FIXME: In the future, we could provide "overload" results, much like we
7822 // do for function calls.
7824 // Now just ignore this. There will be another code-completion callback
7825 // for the expanded tokens.
7828 void Sema::CodeCompleteNaturalLanguage() {
7829 HandleCodeCompleteResults(this, CodeCompleter,
7830 CodeCompletionContext::CCC_NaturalLanguage,
7834 void Sema::CodeCompleteAvailabilityPlatformName() {
7835 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
7836 CodeCompleter->getCodeCompletionTUInfo(),
7837 CodeCompletionContext::CCC_Other);
7838 Results.EnterNewScope();
7839 static const char *Platforms[] = {"macOS", "iOS", "watchOS", "tvOS"};
7840 for (const char *Platform : llvm::makeArrayRef(Platforms)) {
7841 Results.AddResult(CodeCompletionResult(Platform));
7842 Results.AddResult(CodeCompletionResult(Results.getAllocator().CopyString(
7843 Twine(Platform) + "ApplicationExtension")));
7845 Results.ExitScope();
7846 HandleCodeCompleteResults(this, CodeCompleter,
7847 CodeCompletionContext::CCC_Other, Results.data(),
7851 void Sema::GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
7852 CodeCompletionTUInfo &CCTUInfo,
7853 SmallVectorImpl<CodeCompletionResult> &Results) {
7854 ResultBuilder Builder(*this, Allocator, CCTUInfo,
7855 CodeCompletionContext::CCC_Recovery);
7856 if (!CodeCompleter || CodeCompleter->includeGlobals()) {
7857 CodeCompletionDeclConsumer Consumer(Builder,
7858 Context.getTranslationUnitDecl());
7859 LookupVisibleDecls(Context.getTranslationUnitDecl(), LookupAnyName,
7863 if (!CodeCompleter || CodeCompleter->includeMacros())
7864 AddMacroResults(PP, Builder, true);
7867 Results.insert(Results.end(),
7868 Builder.data(), Builder.data() + Builder.size());