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/AST/DeclCXX.h"
14 #include "clang/AST/DeclObjC.h"
15 #include "clang/AST/ExprCXX.h"
16 #include "clang/AST/ExprObjC.h"
17 #include "clang/AST/QualTypeNames.h"
18 #include "clang/Basic/CharInfo.h"
19 #include "clang/Lex/HeaderSearch.h"
20 #include "clang/Lex/MacroInfo.h"
21 #include "clang/Lex/Preprocessor.h"
22 #include "clang/Sema/CodeCompleteConsumer.h"
23 #include "clang/Sema/Lookup.h"
24 #include "clang/Sema/Overload.h"
25 #include "clang/Sema/Scope.h"
26 #include "clang/Sema/ScopeInfo.h"
27 #include "clang/Sema/SemaInternal.h"
28 #include "llvm/ADT/DenseSet.h"
29 #include "llvm/ADT/SmallBitVector.h"
30 #include "llvm/ADT/SmallPtrSet.h"
31 #include "llvm/ADT/SmallString.h"
32 #include "llvm/ADT/StringExtras.h"
33 #include "llvm/ADT/StringSwitch.h"
34 #include "llvm/ADT/Twine.h"
39 using namespace clang;
43 /// \brief A container of code-completion results.
46 /// \brief The type of a name-lookup filter, which can be provided to the
47 /// name-lookup routines to specify which declarations should be included in
48 /// the result set (when it returns true) and which declarations should be
49 /// filtered out (returns false).
50 typedef bool (ResultBuilder::*LookupFilter)(const NamedDecl *) const;
52 typedef CodeCompletionResult Result;
55 /// \brief The actual results we have found.
56 std::vector<Result> Results;
58 /// \brief A record of all of the declarations we have found and placed
59 /// into the result set, used to ensure that no declaration ever gets into
60 /// the result set twice.
61 llvm::SmallPtrSet<const Decl*, 16> AllDeclsFound;
63 typedef std::pair<const NamedDecl *, unsigned> DeclIndexPair;
65 /// \brief An entry in the shadow map, which is optimized to store
66 /// a single (declaration, index) mapping (the common case) but
67 /// can also store a list of (declaration, index) mappings.
68 class ShadowMapEntry {
69 typedef SmallVector<DeclIndexPair, 4> DeclIndexPairVector;
71 /// \brief Contains either the solitary NamedDecl * or a vector
72 /// of (declaration, index) pairs.
73 llvm::PointerUnion<const NamedDecl *, DeclIndexPairVector*> DeclOrVector;
75 /// \brief When the entry contains a single declaration, this is
76 /// the index associated with that entry.
77 unsigned SingleDeclIndex;
80 ShadowMapEntry() : DeclOrVector(), SingleDeclIndex(0) { }
82 void Add(const NamedDecl *ND, unsigned Index) {
83 if (DeclOrVector.isNull()) {
84 // 0 - > 1 elements: just set the single element information.
86 SingleDeclIndex = Index;
90 if (const NamedDecl *PrevND =
91 DeclOrVector.dyn_cast<const NamedDecl *>()) {
92 // 1 -> 2 elements: create the vector of results and push in the
93 // existing declaration.
94 DeclIndexPairVector *Vec = new DeclIndexPairVector;
95 Vec->push_back(DeclIndexPair(PrevND, SingleDeclIndex));
99 // Add the new element to the end of the vector.
100 DeclOrVector.get<DeclIndexPairVector*>()->push_back(
101 DeclIndexPair(ND, Index));
105 if (DeclIndexPairVector *Vec
106 = DeclOrVector.dyn_cast<DeclIndexPairVector *>()) {
108 DeclOrVector = ((NamedDecl *)nullptr);
114 iterator begin() const;
115 iterator end() const;
118 /// \brief A mapping from declaration names to the declarations that have
119 /// this name within a particular scope and their index within the list of
121 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
123 /// \brief The semantic analysis object for which results are being
127 /// \brief The allocator used to allocate new code-completion strings.
128 CodeCompletionAllocator &Allocator;
130 CodeCompletionTUInfo &CCTUInfo;
132 /// \brief If non-NULL, a filter function used to remove any code-completion
133 /// results that are not desirable.
136 /// \brief Whether we should allow declarations as
137 /// nested-name-specifiers that would otherwise be filtered out.
138 bool AllowNestedNameSpecifiers;
140 /// \brief If set, the type that we would prefer our resulting value
141 /// declarations to have.
143 /// Closely matching the preferred type gives a boost to a result's
145 CanQualType PreferredType;
147 /// \brief A list of shadow maps, which is used to model name hiding at
148 /// different levels of, e.g., the inheritance hierarchy.
149 std::list<ShadowMap> ShadowMaps;
151 /// \brief If we're potentially referring to a C++ member function, the set
152 /// of qualifiers applied to the object type.
153 Qualifiers ObjectTypeQualifiers;
155 /// \brief Whether the \p ObjectTypeQualifiers field is active.
156 bool HasObjectTypeQualifiers;
158 /// \brief The selector that we prefer.
159 Selector PreferredSelector;
161 /// \brief The completion context in which we are gathering results.
162 CodeCompletionContext CompletionContext;
164 /// \brief If we are in an instance method definition, the \@implementation
166 ObjCImplementationDecl *ObjCImplementation;
168 void AdjustResultPriorityForDecl(Result &R);
170 void MaybeAddConstructorResults(Result R);
173 explicit ResultBuilder(Sema &SemaRef, CodeCompletionAllocator &Allocator,
174 CodeCompletionTUInfo &CCTUInfo,
175 const CodeCompletionContext &CompletionContext,
176 LookupFilter Filter = nullptr)
177 : SemaRef(SemaRef), Allocator(Allocator), CCTUInfo(CCTUInfo),
179 AllowNestedNameSpecifiers(false), HasObjectTypeQualifiers(false),
180 CompletionContext(CompletionContext),
181 ObjCImplementation(nullptr)
183 // If this is an Objective-C instance method definition, dig out the
184 // corresponding implementation.
185 switch (CompletionContext.getKind()) {
186 case CodeCompletionContext::CCC_Expression:
187 case CodeCompletionContext::CCC_ObjCMessageReceiver:
188 case CodeCompletionContext::CCC_ParenthesizedExpression:
189 case CodeCompletionContext::CCC_Statement:
190 case CodeCompletionContext::CCC_Recovery:
191 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl())
192 if (Method->isInstanceMethod())
193 if (ObjCInterfaceDecl *Interface = Method->getClassInterface())
194 ObjCImplementation = Interface->getImplementation();
202 /// \brief Determine the priority for a reference to the given declaration.
203 unsigned getBasePriority(const NamedDecl *D);
205 /// \brief Whether we should include code patterns in the completion
207 bool includeCodePatterns() const {
208 return SemaRef.CodeCompleter &&
209 SemaRef.CodeCompleter->includeCodePatterns();
212 /// \brief Set the filter used for code-completion results.
213 void setFilter(LookupFilter Filter) {
214 this->Filter = Filter;
217 Result *data() { return Results.empty()? nullptr : &Results.front(); }
218 unsigned size() const { return Results.size(); }
219 bool empty() const { return Results.empty(); }
221 /// \brief Specify the preferred type.
222 void setPreferredType(QualType T) {
223 PreferredType = SemaRef.Context.getCanonicalType(T);
226 /// \brief Set the cv-qualifiers on the object type, for us in filtering
227 /// calls to member functions.
229 /// When there are qualifiers in this set, they will be used to filter
230 /// out member functions that aren't available (because there will be a
231 /// cv-qualifier mismatch) or prefer functions with an exact qualifier
233 void setObjectTypeQualifiers(Qualifiers Quals) {
234 ObjectTypeQualifiers = Quals;
235 HasObjectTypeQualifiers = true;
238 /// \brief Set the preferred selector.
240 /// When an Objective-C method declaration result is added, and that
241 /// method's selector matches this preferred selector, we give that method
242 /// a slight priority boost.
243 void setPreferredSelector(Selector Sel) {
244 PreferredSelector = Sel;
247 /// \brief Retrieve the code-completion context for which results are
249 const CodeCompletionContext &getCompletionContext() const {
250 return CompletionContext;
253 /// \brief Specify whether nested-name-specifiers are allowed.
254 void allowNestedNameSpecifiers(bool Allow = true) {
255 AllowNestedNameSpecifiers = Allow;
258 /// \brief Return the semantic analysis object for which we are collecting
259 /// code completion results.
260 Sema &getSema() const { return SemaRef; }
262 /// \brief Retrieve the allocator used to allocate code completion strings.
263 CodeCompletionAllocator &getAllocator() const { return Allocator; }
265 CodeCompletionTUInfo &getCodeCompletionTUInfo() const { return CCTUInfo; }
267 /// \brief Determine whether the given declaration is at all interesting
268 /// as a code-completion result.
270 /// \param ND the declaration that we are inspecting.
272 /// \param AsNestedNameSpecifier will be set true if this declaration is
273 /// only interesting when it is a nested-name-specifier.
274 bool isInterestingDecl(const NamedDecl *ND,
275 bool &AsNestedNameSpecifier) const;
277 /// \brief Check whether the result is hidden by the Hiding declaration.
279 /// \returns true if the result is hidden and cannot be found, false if
280 /// the hidden result could still be found. When false, \p R may be
281 /// modified to describe how the result can be found (e.g., via extra
283 bool CheckHiddenResult(Result &R, DeclContext *CurContext,
284 const NamedDecl *Hiding);
286 /// \brief Add a new result to this result set (if it isn't already in one
287 /// of the shadow maps), or replace an existing result (for, e.g., a
290 /// \param R the result to add (if it is unique).
292 /// \param CurContext the context in which this result will be named.
293 void MaybeAddResult(Result R, DeclContext *CurContext = nullptr);
295 /// \brief Add a new result to this result set, where we already know
296 /// the hiding declaration (if any).
298 /// \param R the result to add (if it is unique).
300 /// \param CurContext the context in which this result will be named.
302 /// \param Hiding the declaration that hides the result.
304 /// \param InBaseClass whether the result was found in a base
305 /// class of the searched context.
306 void AddResult(Result R, DeclContext *CurContext, NamedDecl *Hiding,
309 /// \brief Add a new non-declaration result to this result set.
310 void AddResult(Result R);
312 /// \brief Enter into a new scope.
313 void EnterNewScope();
315 /// \brief Exit from the current scope.
318 /// \brief Ignore this declaration, if it is seen again.
319 void Ignore(const Decl *D) { AllDeclsFound.insert(D->getCanonicalDecl()); }
321 /// \name Name lookup predicates
323 /// These predicates can be passed to the name lookup functions to filter the
324 /// results of name lookup. All of the predicates have the same type, so that
327 bool IsOrdinaryName(const NamedDecl *ND) const;
328 bool IsOrdinaryNonTypeName(const NamedDecl *ND) const;
329 bool IsIntegralConstantValue(const NamedDecl *ND) const;
330 bool IsOrdinaryNonValueName(const NamedDecl *ND) const;
331 bool IsNestedNameSpecifier(const NamedDecl *ND) const;
332 bool IsEnum(const NamedDecl *ND) const;
333 bool IsClassOrStruct(const NamedDecl *ND) const;
334 bool IsUnion(const NamedDecl *ND) const;
335 bool IsNamespace(const NamedDecl *ND) const;
336 bool IsNamespaceOrAlias(const NamedDecl *ND) const;
337 bool IsType(const NamedDecl *ND) const;
338 bool IsMember(const NamedDecl *ND) const;
339 bool IsObjCIvar(const NamedDecl *ND) const;
340 bool IsObjCMessageReceiver(const NamedDecl *ND) const;
341 bool IsObjCMessageReceiverOrLambdaCapture(const NamedDecl *ND) const;
342 bool IsObjCCollection(const NamedDecl *ND) const;
343 bool IsImpossibleToSatisfy(const NamedDecl *ND) const;
348 class ResultBuilder::ShadowMapEntry::iterator {
349 llvm::PointerUnion<const NamedDecl *, const DeclIndexPair *> DeclOrIterator;
350 unsigned SingleDeclIndex;
353 typedef DeclIndexPair value_type;
354 typedef value_type reference;
355 typedef std::ptrdiff_t difference_type;
356 typedef std::input_iterator_tag iterator_category;
362 pointer(const DeclIndexPair &Value) : Value(Value) { }
364 const DeclIndexPair *operator->() const {
369 iterator() : DeclOrIterator((NamedDecl *)nullptr), SingleDeclIndex(0) {}
371 iterator(const NamedDecl *SingleDecl, unsigned Index)
372 : DeclOrIterator(SingleDecl), SingleDeclIndex(Index) { }
374 iterator(const DeclIndexPair *Iterator)
375 : DeclOrIterator(Iterator), SingleDeclIndex(0) { }
377 iterator &operator++() {
378 if (DeclOrIterator.is<const NamedDecl *>()) {
379 DeclOrIterator = (NamedDecl *)nullptr;
384 const DeclIndexPair *I = DeclOrIterator.get<const DeclIndexPair*>();
390 /*iterator operator++(int) {
396 reference operator*() const {
397 if (const NamedDecl *ND = DeclOrIterator.dyn_cast<const NamedDecl *>())
398 return reference(ND, SingleDeclIndex);
400 return *DeclOrIterator.get<const DeclIndexPair*>();
403 pointer operator->() const {
404 return pointer(**this);
407 friend bool operator==(const iterator &X, const iterator &Y) {
408 return X.DeclOrIterator.getOpaqueValue()
409 == Y.DeclOrIterator.getOpaqueValue() &&
410 X.SingleDeclIndex == Y.SingleDeclIndex;
413 friend bool operator!=(const iterator &X, const iterator &Y) {
418 ResultBuilder::ShadowMapEntry::iterator
419 ResultBuilder::ShadowMapEntry::begin() const {
420 if (DeclOrVector.isNull())
423 if (const NamedDecl *ND = DeclOrVector.dyn_cast<const NamedDecl *>())
424 return iterator(ND, SingleDeclIndex);
426 return iterator(DeclOrVector.get<DeclIndexPairVector *>()->begin());
429 ResultBuilder::ShadowMapEntry::iterator
430 ResultBuilder::ShadowMapEntry::end() const {
431 if (DeclOrVector.is<const NamedDecl *>() || DeclOrVector.isNull())
434 return iterator(DeclOrVector.get<DeclIndexPairVector *>()->end());
437 /// \brief Compute the qualification required to get from the current context
438 /// (\p CurContext) to the target context (\p TargetContext).
440 /// \param Context the AST context in which the qualification will be used.
442 /// \param CurContext the context where an entity is being named, which is
443 /// typically based on the current scope.
445 /// \param TargetContext the context in which the named entity actually
448 /// \returns a nested name specifier that refers into the target context, or
449 /// NULL if no qualification is needed.
450 static NestedNameSpecifier *
451 getRequiredQualification(ASTContext &Context,
452 const DeclContext *CurContext,
453 const DeclContext *TargetContext) {
454 SmallVector<const DeclContext *, 4> TargetParents;
456 for (const DeclContext *CommonAncestor = TargetContext;
457 CommonAncestor && !CommonAncestor->Encloses(CurContext);
458 CommonAncestor = CommonAncestor->getLookupParent()) {
459 if (CommonAncestor->isTransparentContext() ||
460 CommonAncestor->isFunctionOrMethod())
463 TargetParents.push_back(CommonAncestor);
466 NestedNameSpecifier *Result = nullptr;
467 while (!TargetParents.empty()) {
468 const DeclContext *Parent = TargetParents.pop_back_val();
470 if (const NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Parent)) {
471 if (!Namespace->getIdentifier())
474 Result = NestedNameSpecifier::Create(Context, Result, Namespace);
476 else if (const TagDecl *TD = dyn_cast<TagDecl>(Parent))
477 Result = NestedNameSpecifier::Create(Context, Result,
479 Context.getTypeDeclType(TD).getTypePtr());
484 /// Determine whether \p Id is a name reserved for the implementation (C99
485 /// 7.1.3, C++ [lib.global.names]).
486 static bool isReservedName(const IdentifierInfo *Id,
487 bool doubleUnderscoreOnly = false) {
488 if (Id->getLength() < 2)
490 const char *Name = Id->getNameStart();
491 return Name[0] == '_' &&
492 (Name[1] == '_' || (Name[1] >= 'A' && Name[1] <= 'Z' &&
493 !doubleUnderscoreOnly));
496 // Some declarations have reserved names that we don't want to ever show.
497 // Filter out names reserved for the implementation if they come from a
499 static bool shouldIgnoreDueToReservedName(const NamedDecl *ND, Sema &SemaRef) {
500 const IdentifierInfo *Id = ND->getIdentifier();
504 // Ignore reserved names for compiler provided decls.
505 if (isReservedName(Id) && ND->getLocation().isInvalid())
508 // For system headers ignore only double-underscore names.
509 // This allows for system headers providing private symbols with a single
511 if (isReservedName(Id, /*doubleUnderscoreOnly=*/true) &&
512 SemaRef.SourceMgr.isInSystemHeader(
513 SemaRef.SourceMgr.getSpellingLoc(ND->getLocation())))
519 bool ResultBuilder::isInterestingDecl(const NamedDecl *ND,
520 bool &AsNestedNameSpecifier) const {
521 AsNestedNameSpecifier = false;
524 ND = ND->getUnderlyingDecl();
526 // Skip unnamed entities.
527 if (!ND->getDeclName())
530 // Friend declarations and declarations introduced due to friends are never
532 if (ND->getFriendObjectKind() == Decl::FOK_Undeclared)
535 // Class template (partial) specializations are never added as results.
536 if (isa<ClassTemplateSpecializationDecl>(ND) ||
537 isa<ClassTemplatePartialSpecializationDecl>(ND))
540 // Using declarations themselves are never added as results.
541 if (isa<UsingDecl>(ND))
544 if (shouldIgnoreDueToReservedName(ND, SemaRef))
547 if (Filter == &ResultBuilder::IsNestedNameSpecifier ||
548 (isa<NamespaceDecl>(ND) &&
549 Filter != &ResultBuilder::IsNamespace &&
550 Filter != &ResultBuilder::IsNamespaceOrAlias &&
552 AsNestedNameSpecifier = true;
554 // Filter out any unwanted results.
555 if (Filter && !(this->*Filter)(Named)) {
556 // Check whether it is interesting as a nested-name-specifier.
557 if (AllowNestedNameSpecifiers && SemaRef.getLangOpts().CPlusPlus &&
558 IsNestedNameSpecifier(ND) &&
559 (Filter != &ResultBuilder::IsMember ||
560 (isa<CXXRecordDecl>(ND) &&
561 cast<CXXRecordDecl>(ND)->isInjectedClassName()))) {
562 AsNestedNameSpecifier = true;
568 // ... then it must be interesting!
572 bool ResultBuilder::CheckHiddenResult(Result &R, DeclContext *CurContext,
573 const NamedDecl *Hiding) {
574 // In C, there is no way to refer to a hidden name.
575 // FIXME: This isn't true; we can find a tag name hidden by an ordinary
576 // name if we introduce the tag type.
577 if (!SemaRef.getLangOpts().CPlusPlus)
580 const DeclContext *HiddenCtx =
581 R.Declaration->getDeclContext()->getRedeclContext();
583 // There is no way to qualify a name declared in a function or method.
584 if (HiddenCtx->isFunctionOrMethod())
587 if (HiddenCtx == Hiding->getDeclContext()->getRedeclContext())
590 // We can refer to the result with the appropriate qualification. Do it.
592 R.QualifierIsInformative = false;
595 R.Qualifier = getRequiredQualification(SemaRef.Context,
597 R.Declaration->getDeclContext());
601 /// \brief A simplified classification of types used to determine whether two
602 /// types are "similar enough" when adjusting priorities.
603 SimplifiedTypeClass clang::getSimplifiedTypeClass(CanQualType T) {
604 switch (T->getTypeClass()) {
606 switch (cast<BuiltinType>(T)->getKind()) {
607 case BuiltinType::Void:
610 case BuiltinType::NullPtr:
613 case BuiltinType::Overload:
614 case BuiltinType::Dependent:
617 case BuiltinType::ObjCId:
618 case BuiltinType::ObjCClass:
619 case BuiltinType::ObjCSel:
620 return STC_ObjectiveC;
623 return STC_Arithmetic;
627 return STC_Arithmetic;
632 case Type::BlockPointer:
635 case Type::LValueReference:
636 case Type::RValueReference:
637 return getSimplifiedTypeClass(T->getAs<ReferenceType>()->getPointeeType());
639 case Type::ConstantArray:
640 case Type::IncompleteArray:
641 case Type::VariableArray:
642 case Type::DependentSizedArray:
645 case Type::DependentSizedExtVector:
647 case Type::ExtVector:
648 return STC_Arithmetic;
650 case Type::FunctionProto:
651 case Type::FunctionNoProto:
658 return STC_Arithmetic;
660 case Type::ObjCObject:
661 case Type::ObjCInterface:
662 case Type::ObjCObjectPointer:
663 return STC_ObjectiveC;
670 /// \brief Get the type that a given expression will have if this declaration
671 /// is used as an expression in its "typical" code-completion form.
672 QualType clang::getDeclUsageType(ASTContext &C, const NamedDecl *ND) {
673 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
675 if (const TypeDecl *Type = dyn_cast<TypeDecl>(ND))
676 return C.getTypeDeclType(Type);
677 if (const ObjCInterfaceDecl *Iface = dyn_cast<ObjCInterfaceDecl>(ND))
678 return C.getObjCInterfaceType(Iface);
681 if (const FunctionDecl *Function = ND->getAsFunction())
682 T = Function->getCallResultType();
683 else if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND))
684 T = Method->getSendResultType();
685 else if (const EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND))
686 T = C.getTypeDeclType(cast<EnumDecl>(Enumerator->getDeclContext()));
687 else if (const ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND))
688 T = Property->getType();
689 else if (const ValueDecl *Value = dyn_cast<ValueDecl>(ND))
690 T = Value->getType();
694 // Dig through references, function pointers, and block pointers to
695 // get down to the likely type of an expression when the entity is
698 if (const ReferenceType *Ref = T->getAs<ReferenceType>()) {
699 T = Ref->getPointeeType();
703 if (const PointerType *Pointer = T->getAs<PointerType>()) {
704 if (Pointer->getPointeeType()->isFunctionType()) {
705 T = Pointer->getPointeeType();
712 if (const BlockPointerType *Block = T->getAs<BlockPointerType>()) {
713 T = Block->getPointeeType();
717 if (const FunctionType *Function = T->getAs<FunctionType>()) {
718 T = Function->getReturnType();
728 unsigned ResultBuilder::getBasePriority(const NamedDecl *ND) {
732 // Context-based decisions.
733 const DeclContext *LexicalDC = ND->getLexicalDeclContext();
734 if (LexicalDC->isFunctionOrMethod()) {
735 // _cmd is relatively rare
736 if (const ImplicitParamDecl *ImplicitParam =
737 dyn_cast<ImplicitParamDecl>(ND))
738 if (ImplicitParam->getIdentifier() &&
739 ImplicitParam->getIdentifier()->isStr("_cmd"))
742 return CCP_LocalDeclaration;
745 const DeclContext *DC = ND->getDeclContext()->getRedeclContext();
746 if (DC->isRecord() || isa<ObjCContainerDecl>(DC)) {
747 // Explicit destructor calls are very rare.
748 if (isa<CXXDestructorDecl>(ND))
750 // Explicit operator and conversion function calls are also very rare.
751 auto DeclNameKind = ND->getDeclName().getNameKind();
752 if (DeclNameKind == DeclarationName::CXXOperatorName ||
753 DeclNameKind == DeclarationName::CXXLiteralOperatorName ||
754 DeclNameKind == DeclarationName::CXXConversionFunctionName)
756 return CCP_MemberDeclaration;
759 // Content-based decisions.
760 if (isa<EnumConstantDecl>(ND))
763 // Use CCP_Type for type declarations unless we're in a statement, Objective-C
764 // message receiver, or parenthesized expression context. There, it's as
765 // likely that the user will want to write a type as other declarations.
766 if ((isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) &&
767 !(CompletionContext.getKind() == CodeCompletionContext::CCC_Statement ||
768 CompletionContext.getKind()
769 == CodeCompletionContext::CCC_ObjCMessageReceiver ||
770 CompletionContext.getKind()
771 == CodeCompletionContext::CCC_ParenthesizedExpression))
774 return CCP_Declaration;
777 void ResultBuilder::AdjustResultPriorityForDecl(Result &R) {
778 // If this is an Objective-C method declaration whose selector matches our
779 // preferred selector, give it a priority boost.
780 if (!PreferredSelector.isNull())
781 if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(R.Declaration))
782 if (PreferredSelector == Method->getSelector())
783 R.Priority += CCD_SelectorMatch;
785 // If we have a preferred type, adjust the priority for results with exactly-
786 // matching or nearly-matching types.
787 if (!PreferredType.isNull()) {
788 QualType T = getDeclUsageType(SemaRef.Context, R.Declaration);
790 CanQualType TC = SemaRef.Context.getCanonicalType(T);
791 // Check for exactly-matching types (modulo qualifiers).
792 if (SemaRef.Context.hasSameUnqualifiedType(PreferredType, TC))
793 R.Priority /= CCF_ExactTypeMatch;
794 // Check for nearly-matching types, based on classification of each.
795 else if ((getSimplifiedTypeClass(PreferredType)
796 == getSimplifiedTypeClass(TC)) &&
797 !(PreferredType->isEnumeralType() && TC->isEnumeralType()))
798 R.Priority /= CCF_SimilarTypeMatch;
803 void ResultBuilder::MaybeAddConstructorResults(Result R) {
804 if (!SemaRef.getLangOpts().CPlusPlus || !R.Declaration ||
805 !CompletionContext.wantConstructorResults())
808 ASTContext &Context = SemaRef.Context;
809 const NamedDecl *D = R.Declaration;
810 const CXXRecordDecl *Record = nullptr;
811 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D))
812 Record = ClassTemplate->getTemplatedDecl();
813 else if ((Record = dyn_cast<CXXRecordDecl>(D))) {
814 // Skip specializations and partial specializations.
815 if (isa<ClassTemplateSpecializationDecl>(Record))
818 // There are no constructors here.
822 Record = Record->getDefinition();
827 QualType RecordTy = Context.getTypeDeclType(Record);
828 DeclarationName ConstructorName
829 = Context.DeclarationNames.getCXXConstructorName(
830 Context.getCanonicalType(RecordTy));
831 DeclContext::lookup_result Ctors = Record->lookup(ConstructorName);
832 for (DeclContext::lookup_iterator I = Ctors.begin(),
836 R.CursorKind = getCursorKindForDecl(R.Declaration);
837 Results.push_back(R);
841 void ResultBuilder::MaybeAddResult(Result R, DeclContext *CurContext) {
842 assert(!ShadowMaps.empty() && "Must enter into a results scope");
844 if (R.Kind != Result::RK_Declaration) {
845 // For non-declaration results, just add the result.
846 Results.push_back(R);
850 // Look through using declarations.
851 if (const UsingShadowDecl *Using =
852 dyn_cast<UsingShadowDecl>(R.Declaration)) {
853 MaybeAddResult(Result(Using->getTargetDecl(),
854 getBasePriority(Using->getTargetDecl()),
860 const Decl *CanonDecl = R.Declaration->getCanonicalDecl();
861 unsigned IDNS = CanonDecl->getIdentifierNamespace();
863 bool AsNestedNameSpecifier = false;
864 if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
867 // C++ constructors are never found by name lookup.
868 if (isa<CXXConstructorDecl>(R.Declaration))
871 ShadowMap &SMap = ShadowMaps.back();
872 ShadowMapEntry::iterator I, IEnd;
873 ShadowMap::iterator NamePos = SMap.find(R.Declaration->getDeclName());
874 if (NamePos != SMap.end()) {
875 I = NamePos->second.begin();
876 IEnd = NamePos->second.end();
879 for (; I != IEnd; ++I) {
880 const NamedDecl *ND = I->first;
881 unsigned Index = I->second;
882 if (ND->getCanonicalDecl() == CanonDecl) {
883 // This is a redeclaration. Always pick the newer declaration.
884 Results[Index].Declaration = R.Declaration;
891 // This is a new declaration in this scope. However, check whether this
892 // declaration name is hidden by a similarly-named declaration in an outer
894 std::list<ShadowMap>::iterator SM, SMEnd = ShadowMaps.end();
896 for (SM = ShadowMaps.begin(); SM != SMEnd; ++SM) {
897 ShadowMapEntry::iterator I, IEnd;
898 ShadowMap::iterator NamePos = SM->find(R.Declaration->getDeclName());
899 if (NamePos != SM->end()) {
900 I = NamePos->second.begin();
901 IEnd = NamePos->second.end();
903 for (; I != IEnd; ++I) {
904 // A tag declaration does not hide a non-tag declaration.
905 if (I->first->hasTagIdentifierNamespace() &&
906 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
907 Decl::IDNS_LocalExtern | Decl::IDNS_ObjCProtocol)))
910 // Protocols are in distinct namespaces from everything else.
911 if (((I->first->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
912 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
913 I->first->getIdentifierNamespace() != IDNS)
916 // The newly-added result is hidden by an entry in the shadow map.
917 if (CheckHiddenResult(R, CurContext, I->first))
924 // Make sure that any given declaration only shows up in the result set once.
925 if (!AllDeclsFound.insert(CanonDecl).second)
928 // If the filter is for nested-name-specifiers, then this result starts a
929 // nested-name-specifier.
930 if (AsNestedNameSpecifier) {
931 R.StartsNestedNameSpecifier = true;
932 R.Priority = CCP_NestedNameSpecifier;
934 AdjustResultPriorityForDecl(R);
936 // If this result is supposed to have an informative qualifier, add one.
937 if (R.QualifierIsInformative && !R.Qualifier &&
938 !R.StartsNestedNameSpecifier) {
939 const DeclContext *Ctx = R.Declaration->getDeclContext();
940 if (const NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
941 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, nullptr,
943 else if (const TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
944 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, nullptr,
945 false, SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
947 R.QualifierIsInformative = false;
950 // Insert this result into the set of results and into the current shadow
952 SMap[R.Declaration->getDeclName()].Add(R.Declaration, Results.size());
953 Results.push_back(R);
955 if (!AsNestedNameSpecifier)
956 MaybeAddConstructorResults(R);
959 void ResultBuilder::AddResult(Result R, DeclContext *CurContext,
960 NamedDecl *Hiding, bool InBaseClass = false) {
961 if (R.Kind != Result::RK_Declaration) {
962 // For non-declaration results, just add the result.
963 Results.push_back(R);
967 // Look through using declarations.
968 if (const UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
969 AddResult(Result(Using->getTargetDecl(),
970 getBasePriority(Using->getTargetDecl()),
976 bool AsNestedNameSpecifier = false;
977 if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
980 // C++ constructors are never found by name lookup.
981 if (isa<CXXConstructorDecl>(R.Declaration))
984 if (Hiding && CheckHiddenResult(R, CurContext, Hiding))
987 // Make sure that any given declaration only shows up in the result set once.
988 if (!AllDeclsFound.insert(R.Declaration->getCanonicalDecl()).second)
991 // If the filter is for nested-name-specifiers, then this result starts a
992 // nested-name-specifier.
993 if (AsNestedNameSpecifier) {
994 R.StartsNestedNameSpecifier = true;
995 R.Priority = CCP_NestedNameSpecifier;
997 else if (Filter == &ResultBuilder::IsMember && !R.Qualifier && InBaseClass &&
998 isa<CXXRecordDecl>(R.Declaration->getDeclContext()
999 ->getRedeclContext()))
1000 R.QualifierIsInformative = true;
1002 // If this result is supposed to have an informative qualifier, add one.
1003 if (R.QualifierIsInformative && !R.Qualifier &&
1004 !R.StartsNestedNameSpecifier) {
1005 const DeclContext *Ctx = R.Declaration->getDeclContext();
1006 if (const NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
1007 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, nullptr,
1009 else if (const TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
1010 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, nullptr, false,
1011 SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
1013 R.QualifierIsInformative = false;
1016 // Adjust the priority if this result comes from a base class.
1018 R.Priority += CCD_InBaseClass;
1020 AdjustResultPriorityForDecl(R);
1022 if (HasObjectTypeQualifiers)
1023 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(R.Declaration))
1024 if (Method->isInstance()) {
1025 Qualifiers MethodQuals
1026 = Qualifiers::fromCVRMask(Method->getTypeQualifiers());
1027 if (ObjectTypeQualifiers == MethodQuals)
1028 R.Priority += CCD_ObjectQualifierMatch;
1029 else if (ObjectTypeQualifiers - MethodQuals) {
1030 // The method cannot be invoked, because doing so would drop
1036 // Insert this result into the set of results.
1037 Results.push_back(R);
1039 if (!AsNestedNameSpecifier)
1040 MaybeAddConstructorResults(R);
1043 void ResultBuilder::AddResult(Result R) {
1044 assert(R.Kind != Result::RK_Declaration &&
1045 "Declaration results need more context");
1046 Results.push_back(R);
1049 /// \brief Enter into a new scope.
1050 void ResultBuilder::EnterNewScope() { ShadowMaps.emplace_back(); }
1052 /// \brief Exit from the current scope.
1053 void ResultBuilder::ExitScope() {
1054 for (ShadowMap::iterator E = ShadowMaps.back().begin(),
1055 EEnd = ShadowMaps.back().end();
1058 E->second.Destroy();
1060 ShadowMaps.pop_back();
1063 /// \brief Determines whether this given declaration will be found by
1064 /// ordinary name lookup.
1065 bool ResultBuilder::IsOrdinaryName(const NamedDecl *ND) const {
1066 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
1068 // If name lookup finds a local extern declaration, then we are in a
1069 // context where it behaves like an ordinary name.
1070 unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_LocalExtern;
1071 if (SemaRef.getLangOpts().CPlusPlus)
1072 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
1073 else if (SemaRef.getLangOpts().ObjC1) {
1074 if (isa<ObjCIvarDecl>(ND))
1078 return ND->getIdentifierNamespace() & IDNS;
1081 /// \brief Determines whether this given declaration will be found by
1082 /// ordinary name lookup but is not a type name.
1083 bool ResultBuilder::IsOrdinaryNonTypeName(const NamedDecl *ND) const {
1084 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
1085 if (isa<TypeDecl>(ND))
1087 // Objective-C interfaces names are not filtered by this method because they
1088 // can be used in a class property expression. We can still filter out
1089 // @class declarations though.
1090 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND)) {
1091 if (!ID->getDefinition())
1095 unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_LocalExtern;
1096 if (SemaRef.getLangOpts().CPlusPlus)
1097 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
1098 else if (SemaRef.getLangOpts().ObjC1) {
1099 if (isa<ObjCIvarDecl>(ND))
1103 return ND->getIdentifierNamespace() & IDNS;
1106 bool ResultBuilder::IsIntegralConstantValue(const NamedDecl *ND) const {
1107 if (!IsOrdinaryNonTypeName(ND))
1110 if (const ValueDecl *VD = dyn_cast<ValueDecl>(ND->getUnderlyingDecl()))
1111 if (VD->getType()->isIntegralOrEnumerationType())
1117 /// \brief Determines whether this given declaration will be found by
1118 /// ordinary name lookup.
1119 bool ResultBuilder::IsOrdinaryNonValueName(const NamedDecl *ND) const {
1120 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
1122 unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_LocalExtern;
1123 if (SemaRef.getLangOpts().CPlusPlus)
1124 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace;
1126 return (ND->getIdentifierNamespace() & IDNS) &&
1127 !isa<ValueDecl>(ND) && !isa<FunctionTemplateDecl>(ND) &&
1128 !isa<ObjCPropertyDecl>(ND);
1131 /// \brief Determines whether the given declaration is suitable as the
1132 /// start of a C++ nested-name-specifier, e.g., a class or namespace.
1133 bool ResultBuilder::IsNestedNameSpecifier(const NamedDecl *ND) const {
1134 // Allow us to find class templates, too.
1135 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
1136 ND = ClassTemplate->getTemplatedDecl();
1138 return SemaRef.isAcceptableNestedNameSpecifier(ND);
1141 /// \brief Determines whether the given declaration is an enumeration.
1142 bool ResultBuilder::IsEnum(const NamedDecl *ND) const {
1143 return isa<EnumDecl>(ND);
1146 /// \brief Determines whether the given declaration is a class or struct.
1147 bool ResultBuilder::IsClassOrStruct(const NamedDecl *ND) const {
1148 // Allow us to find class templates, too.
1149 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
1150 ND = ClassTemplate->getTemplatedDecl();
1152 // For purposes of this check, interfaces match too.
1153 if (const RecordDecl *RD = dyn_cast<RecordDecl>(ND))
1154 return RD->getTagKind() == TTK_Class ||
1155 RD->getTagKind() == TTK_Struct ||
1156 RD->getTagKind() == TTK_Interface;
1161 /// \brief Determines whether the given declaration is a union.
1162 bool ResultBuilder::IsUnion(const NamedDecl *ND) const {
1163 // Allow us to find class templates, too.
1164 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
1165 ND = ClassTemplate->getTemplatedDecl();
1167 if (const RecordDecl *RD = dyn_cast<RecordDecl>(ND))
1168 return RD->getTagKind() == TTK_Union;
1173 /// \brief Determines whether the given declaration is a namespace.
1174 bool ResultBuilder::IsNamespace(const NamedDecl *ND) const {
1175 return isa<NamespaceDecl>(ND);
1178 /// \brief Determines whether the given declaration is a namespace or
1179 /// namespace alias.
1180 bool ResultBuilder::IsNamespaceOrAlias(const NamedDecl *ND) const {
1181 return isa<NamespaceDecl>(ND->getUnderlyingDecl());
1184 /// \brief Determines whether the given declaration is a type.
1185 bool ResultBuilder::IsType(const NamedDecl *ND) const {
1186 ND = ND->getUnderlyingDecl();
1187 return isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
1190 /// \brief Determines which members of a class should be visible via
1191 /// "." or "->". Only value declarations, nested name specifiers, and
1192 /// using declarations thereof should show up.
1193 bool ResultBuilder::IsMember(const NamedDecl *ND) const {
1194 ND = ND->getUnderlyingDecl();
1195 return isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND) ||
1196 isa<ObjCPropertyDecl>(ND);
1199 static bool isObjCReceiverType(ASTContext &C, QualType T) {
1200 T = C.getCanonicalType(T);
1201 switch (T->getTypeClass()) {
1202 case Type::ObjCObject:
1203 case Type::ObjCInterface:
1204 case Type::ObjCObjectPointer:
1208 switch (cast<BuiltinType>(T)->getKind()) {
1209 case BuiltinType::ObjCId:
1210 case BuiltinType::ObjCClass:
1211 case BuiltinType::ObjCSel:
1223 if (!C.getLangOpts().CPlusPlus)
1226 // FIXME: We could perform more analysis here to determine whether a
1227 // particular class type has any conversions to Objective-C types. For now,
1228 // just accept all class types.
1229 return T->isDependentType() || T->isRecordType();
1232 bool ResultBuilder::IsObjCMessageReceiver(const NamedDecl *ND) const {
1233 QualType T = getDeclUsageType(SemaRef.Context, ND);
1237 T = SemaRef.Context.getBaseElementType(T);
1238 return isObjCReceiverType(SemaRef.Context, T);
1241 bool ResultBuilder::IsObjCMessageReceiverOrLambdaCapture(const NamedDecl *ND) const {
1242 if (IsObjCMessageReceiver(ND))
1245 const VarDecl *Var = dyn_cast<VarDecl>(ND);
1249 return Var->hasLocalStorage() && !Var->hasAttr<BlocksAttr>();
1252 bool ResultBuilder::IsObjCCollection(const NamedDecl *ND) const {
1253 if ((SemaRef.getLangOpts().CPlusPlus && !IsOrdinaryName(ND)) ||
1254 (!SemaRef.getLangOpts().CPlusPlus && !IsOrdinaryNonTypeName(ND)))
1257 QualType T = getDeclUsageType(SemaRef.Context, ND);
1261 T = SemaRef.Context.getBaseElementType(T);
1262 return T->isObjCObjectType() || T->isObjCObjectPointerType() ||
1263 T->isObjCIdType() ||
1264 (SemaRef.getLangOpts().CPlusPlus && T->isRecordType());
1267 bool ResultBuilder::IsImpossibleToSatisfy(const NamedDecl *ND) const {
1271 /// \brief Determines whether the given declaration is an Objective-C
1272 /// instance variable.
1273 bool ResultBuilder::IsObjCIvar(const NamedDecl *ND) const {
1274 return isa<ObjCIvarDecl>(ND);
1278 /// \brief Visible declaration consumer that adds a code-completion result
1279 /// for each visible declaration.
1280 class CodeCompletionDeclConsumer : public VisibleDeclConsumer {
1281 ResultBuilder &Results;
1282 DeclContext *CurContext;
1285 CodeCompletionDeclConsumer(ResultBuilder &Results, DeclContext *CurContext)
1286 : Results(Results), CurContext(CurContext) { }
1288 void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
1289 bool InBaseClass) override {
1290 bool Accessible = true;
1292 Accessible = Results.getSema().IsSimplyAccessible(ND, Ctx);
1294 ResultBuilder::Result Result(ND, Results.getBasePriority(ND), nullptr,
1296 Results.AddResult(Result, CurContext, Hiding, InBaseClass);
1301 /// \brief Add type specifiers for the current language as keyword results.
1302 static void AddTypeSpecifierResults(const LangOptions &LangOpts,
1303 ResultBuilder &Results) {
1304 typedef CodeCompletionResult Result;
1305 Results.AddResult(Result("short", CCP_Type));
1306 Results.AddResult(Result("long", CCP_Type));
1307 Results.AddResult(Result("signed", CCP_Type));
1308 Results.AddResult(Result("unsigned", CCP_Type));
1309 Results.AddResult(Result("void", CCP_Type));
1310 Results.AddResult(Result("char", CCP_Type));
1311 Results.AddResult(Result("int", CCP_Type));
1312 Results.AddResult(Result("float", CCP_Type));
1313 Results.AddResult(Result("double", CCP_Type));
1314 Results.AddResult(Result("enum", CCP_Type));
1315 Results.AddResult(Result("struct", CCP_Type));
1316 Results.AddResult(Result("union", CCP_Type));
1317 Results.AddResult(Result("const", CCP_Type));
1318 Results.AddResult(Result("volatile", CCP_Type));
1322 Results.AddResult(Result("_Complex", CCP_Type));
1323 Results.AddResult(Result("_Imaginary", CCP_Type));
1324 Results.AddResult(Result("_Bool", CCP_Type));
1325 Results.AddResult(Result("restrict", CCP_Type));
1328 CodeCompletionBuilder Builder(Results.getAllocator(),
1329 Results.getCodeCompletionTUInfo());
1330 if (LangOpts.CPlusPlus) {
1332 Results.AddResult(Result("bool", CCP_Type +
1333 (LangOpts.ObjC1? CCD_bool_in_ObjC : 0)));
1334 Results.AddResult(Result("class", CCP_Type));
1335 Results.AddResult(Result("wchar_t", CCP_Type));
1337 // typename qualified-id
1338 Builder.AddTypedTextChunk("typename");
1339 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1340 Builder.AddPlaceholderChunk("qualifier");
1341 Builder.AddTextChunk("::");
1342 Builder.AddPlaceholderChunk("name");
1343 Results.AddResult(Result(Builder.TakeString()));
1345 if (LangOpts.CPlusPlus11) {
1346 Results.AddResult(Result("auto", CCP_Type));
1347 Results.AddResult(Result("char16_t", CCP_Type));
1348 Results.AddResult(Result("char32_t", CCP_Type));
1350 Builder.AddTypedTextChunk("decltype");
1351 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1352 Builder.AddPlaceholderChunk("expression");
1353 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1354 Results.AddResult(Result(Builder.TakeString()));
1357 Results.AddResult(Result("__auto_type", CCP_Type));
1360 if (LangOpts.GNUMode) {
1361 // FIXME: Enable when we actually support decimal floating point.
1362 // Results.AddResult(Result("_Decimal32"));
1363 // Results.AddResult(Result("_Decimal64"));
1364 // Results.AddResult(Result("_Decimal128"));
1366 Builder.AddTypedTextChunk("typeof");
1367 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1368 Builder.AddPlaceholderChunk("expression");
1369 Results.AddResult(Result(Builder.TakeString()));
1371 Builder.AddTypedTextChunk("typeof");
1372 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1373 Builder.AddPlaceholderChunk("type");
1374 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1375 Results.AddResult(Result(Builder.TakeString()));
1379 Results.AddResult(Result("_Nonnull", CCP_Type));
1380 Results.AddResult(Result("_Null_unspecified", CCP_Type));
1381 Results.AddResult(Result("_Nullable", CCP_Type));
1384 static void AddStorageSpecifiers(Sema::ParserCompletionContext CCC,
1385 const LangOptions &LangOpts,
1386 ResultBuilder &Results) {
1387 typedef CodeCompletionResult Result;
1388 // Note: we don't suggest either "auto" or "register", because both
1389 // are pointless as storage specifiers. Elsewhere, we suggest "auto"
1390 // in C++0x as a type specifier.
1391 Results.AddResult(Result("extern"));
1392 Results.AddResult(Result("static"));
1394 if (LangOpts.CPlusPlus11) {
1395 CodeCompletionAllocator &Allocator = Results.getAllocator();
1396 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
1399 Builder.AddTypedTextChunk("alignas");
1400 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1401 Builder.AddPlaceholderChunk("expression");
1402 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1403 Results.AddResult(Result(Builder.TakeString()));
1405 Results.AddResult(Result("constexpr"));
1406 Results.AddResult(Result("thread_local"));
1410 static void AddFunctionSpecifiers(Sema::ParserCompletionContext CCC,
1411 const LangOptions &LangOpts,
1412 ResultBuilder &Results) {
1413 typedef CodeCompletionResult Result;
1415 case Sema::PCC_Class:
1416 case Sema::PCC_MemberTemplate:
1417 if (LangOpts.CPlusPlus) {
1418 Results.AddResult(Result("explicit"));
1419 Results.AddResult(Result("friend"));
1420 Results.AddResult(Result("mutable"));
1421 Results.AddResult(Result("virtual"));
1425 case Sema::PCC_ObjCInterface:
1426 case Sema::PCC_ObjCImplementation:
1427 case Sema::PCC_Namespace:
1428 case Sema::PCC_Template:
1429 if (LangOpts.CPlusPlus || LangOpts.C99)
1430 Results.AddResult(Result("inline"));
1433 case Sema::PCC_ObjCInstanceVariableList:
1434 case Sema::PCC_Expression:
1435 case Sema::PCC_Statement:
1436 case Sema::PCC_ForInit:
1437 case Sema::PCC_Condition:
1438 case Sema::PCC_RecoveryInFunction:
1439 case Sema::PCC_Type:
1440 case Sema::PCC_ParenthesizedExpression:
1441 case Sema::PCC_LocalDeclarationSpecifiers:
1446 static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt);
1447 static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt);
1448 static void AddObjCVisibilityResults(const LangOptions &LangOpts,
1449 ResultBuilder &Results,
1451 static void AddObjCImplementationResults(const LangOptions &LangOpts,
1452 ResultBuilder &Results,
1454 static void AddObjCInterfaceResults(const LangOptions &LangOpts,
1455 ResultBuilder &Results,
1457 static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt);
1459 static void AddTypedefResult(ResultBuilder &Results) {
1460 CodeCompletionBuilder Builder(Results.getAllocator(),
1461 Results.getCodeCompletionTUInfo());
1462 Builder.AddTypedTextChunk("typedef");
1463 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1464 Builder.AddPlaceholderChunk("type");
1465 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1466 Builder.AddPlaceholderChunk("name");
1467 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
1470 static bool WantTypesInContext(Sema::ParserCompletionContext CCC,
1471 const LangOptions &LangOpts) {
1473 case Sema::PCC_Namespace:
1474 case Sema::PCC_Class:
1475 case Sema::PCC_ObjCInstanceVariableList:
1476 case Sema::PCC_Template:
1477 case Sema::PCC_MemberTemplate:
1478 case Sema::PCC_Statement:
1479 case Sema::PCC_RecoveryInFunction:
1480 case Sema::PCC_Type:
1481 case Sema::PCC_ParenthesizedExpression:
1482 case Sema::PCC_LocalDeclarationSpecifiers:
1485 case Sema::PCC_Expression:
1486 case Sema::PCC_Condition:
1487 return LangOpts.CPlusPlus;
1489 case Sema::PCC_ObjCInterface:
1490 case Sema::PCC_ObjCImplementation:
1493 case Sema::PCC_ForInit:
1494 return LangOpts.CPlusPlus || LangOpts.ObjC1 || LangOpts.C99;
1497 llvm_unreachable("Invalid ParserCompletionContext!");
1500 static PrintingPolicy getCompletionPrintingPolicy(const ASTContext &Context,
1501 const Preprocessor &PP) {
1502 PrintingPolicy Policy = Sema::getPrintingPolicy(Context, PP);
1503 Policy.AnonymousTagLocations = false;
1504 Policy.SuppressStrongLifetime = true;
1505 Policy.SuppressUnwrittenScope = true;
1506 Policy.SuppressScope = true;
1510 /// \brief Retrieve a printing policy suitable for code completion.
1511 static PrintingPolicy getCompletionPrintingPolicy(Sema &S) {
1512 return getCompletionPrintingPolicy(S.Context, S.PP);
1515 /// \brief Retrieve the string representation of the given type as a string
1516 /// that has the appropriate lifetime for code completion.
1518 /// This routine provides a fast path where we provide constant strings for
1519 /// common type names.
1520 static const char *GetCompletionTypeString(QualType T,
1521 ASTContext &Context,
1522 const PrintingPolicy &Policy,
1523 CodeCompletionAllocator &Allocator) {
1524 if (!T.getLocalQualifiers()) {
1525 // Built-in type names are constant strings.
1526 if (const BuiltinType *BT = dyn_cast<BuiltinType>(T))
1527 return BT->getNameAsCString(Policy);
1529 // Anonymous tag types are constant strings.
1530 if (const TagType *TagT = dyn_cast<TagType>(T))
1531 if (TagDecl *Tag = TagT->getDecl())
1532 if (!Tag->hasNameForLinkage()) {
1533 switch (Tag->getTagKind()) {
1534 case TTK_Struct: return "struct <anonymous>";
1535 case TTK_Interface: return "__interface <anonymous>";
1536 case TTK_Class: return "class <anonymous>";
1537 case TTK_Union: return "union <anonymous>";
1538 case TTK_Enum: return "enum <anonymous>";
1543 // Slow path: format the type as a string.
1545 T.getAsStringInternal(Result, Policy);
1546 return Allocator.CopyString(Result);
1549 /// \brief Add a completion for "this", if we're in a member function.
1550 static void addThisCompletion(Sema &S, ResultBuilder &Results) {
1551 QualType ThisTy = S.getCurrentThisType();
1552 if (ThisTy.isNull())
1555 CodeCompletionAllocator &Allocator = Results.getAllocator();
1556 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
1557 PrintingPolicy Policy = getCompletionPrintingPolicy(S);
1558 Builder.AddResultTypeChunk(GetCompletionTypeString(ThisTy,
1562 Builder.AddTypedTextChunk("this");
1563 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
1566 static void AddStaticAssertResult(CodeCompletionBuilder &Builder,
1567 ResultBuilder &Results,
1568 const LangOptions &LangOpts) {
1569 if (!LangOpts.CPlusPlus11)
1572 Builder.AddTypedTextChunk("static_assert");
1573 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1574 Builder.AddPlaceholderChunk("expression");
1575 Builder.AddChunk(CodeCompletionString::CK_Comma);
1576 Builder.AddPlaceholderChunk("message");
1577 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1578 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
1581 /// \brief Add language constructs that show up for "ordinary" names.
1582 static void AddOrdinaryNameResults(Sema::ParserCompletionContext CCC,
1585 ResultBuilder &Results) {
1586 CodeCompletionAllocator &Allocator = Results.getAllocator();
1587 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
1589 typedef CodeCompletionResult Result;
1591 case Sema::PCC_Namespace:
1592 if (SemaRef.getLangOpts().CPlusPlus) {
1593 if (Results.includeCodePatterns()) {
1594 // namespace <identifier> { declarations }
1595 Builder.AddTypedTextChunk("namespace");
1596 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1597 Builder.AddPlaceholderChunk("identifier");
1598 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1599 Builder.AddPlaceholderChunk("declarations");
1600 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1601 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1602 Results.AddResult(Result(Builder.TakeString()));
1605 // namespace identifier = identifier ;
1606 Builder.AddTypedTextChunk("namespace");
1607 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1608 Builder.AddPlaceholderChunk("name");
1609 Builder.AddChunk(CodeCompletionString::CK_Equal);
1610 Builder.AddPlaceholderChunk("namespace");
1611 Results.AddResult(Result(Builder.TakeString()));
1614 Builder.AddTypedTextChunk("using");
1615 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1616 Builder.AddTextChunk("namespace");
1617 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1618 Builder.AddPlaceholderChunk("identifier");
1619 Results.AddResult(Result(Builder.TakeString()));
1621 // asm(string-literal)
1622 Builder.AddTypedTextChunk("asm");
1623 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1624 Builder.AddPlaceholderChunk("string-literal");
1625 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1626 Results.AddResult(Result(Builder.TakeString()));
1628 if (Results.includeCodePatterns()) {
1629 // Explicit template instantiation
1630 Builder.AddTypedTextChunk("template");
1631 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1632 Builder.AddPlaceholderChunk("declaration");
1633 Results.AddResult(Result(Builder.TakeString()));
1637 if (SemaRef.getLangOpts().ObjC1)
1638 AddObjCTopLevelResults(Results, true);
1640 AddTypedefResult(Results);
1643 case Sema::PCC_Class:
1644 if (SemaRef.getLangOpts().CPlusPlus) {
1645 // Using declaration
1646 Builder.AddTypedTextChunk("using");
1647 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1648 Builder.AddPlaceholderChunk("qualifier");
1649 Builder.AddTextChunk("::");
1650 Builder.AddPlaceholderChunk("name");
1651 Results.AddResult(Result(Builder.TakeString()));
1653 // using typename qualifier::name (only in a dependent context)
1654 if (SemaRef.CurContext->isDependentContext()) {
1655 Builder.AddTypedTextChunk("using");
1656 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1657 Builder.AddTextChunk("typename");
1658 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1659 Builder.AddPlaceholderChunk("qualifier");
1660 Builder.AddTextChunk("::");
1661 Builder.AddPlaceholderChunk("name");
1662 Results.AddResult(Result(Builder.TakeString()));
1665 AddStaticAssertResult(Builder, Results, SemaRef.getLangOpts());
1667 if (CCC == Sema::PCC_Class) {
1668 AddTypedefResult(Results);
1670 bool IsNotInheritanceScope =
1671 !(S->getFlags() & Scope::ClassInheritanceScope);
1673 Builder.AddTypedTextChunk("public");
1674 if (IsNotInheritanceScope && Results.includeCodePatterns())
1675 Builder.AddChunk(CodeCompletionString::CK_Colon);
1676 Results.AddResult(Result(Builder.TakeString()));
1679 Builder.AddTypedTextChunk("protected");
1680 if (IsNotInheritanceScope && Results.includeCodePatterns())
1681 Builder.AddChunk(CodeCompletionString::CK_Colon);
1682 Results.AddResult(Result(Builder.TakeString()));
1685 Builder.AddTypedTextChunk("private");
1686 if (IsNotInheritanceScope && Results.includeCodePatterns())
1687 Builder.AddChunk(CodeCompletionString::CK_Colon);
1688 Results.AddResult(Result(Builder.TakeString()));
1693 case Sema::PCC_Template:
1694 case Sema::PCC_MemberTemplate:
1695 if (SemaRef.getLangOpts().CPlusPlus && Results.includeCodePatterns()) {
1696 // template < parameters >
1697 Builder.AddTypedTextChunk("template");
1698 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1699 Builder.AddPlaceholderChunk("parameters");
1700 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1701 Results.AddResult(Result(Builder.TakeString()));
1704 AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
1705 AddFunctionSpecifiers(CCC, SemaRef.getLangOpts(), Results);
1708 case Sema::PCC_ObjCInterface:
1709 AddObjCInterfaceResults(SemaRef.getLangOpts(), Results, true);
1710 AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
1711 AddFunctionSpecifiers(CCC, SemaRef.getLangOpts(), Results);
1714 case Sema::PCC_ObjCImplementation:
1715 AddObjCImplementationResults(SemaRef.getLangOpts(), Results, true);
1716 AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
1717 AddFunctionSpecifiers(CCC, SemaRef.getLangOpts(), Results);
1720 case Sema::PCC_ObjCInstanceVariableList:
1721 AddObjCVisibilityResults(SemaRef.getLangOpts(), Results, true);
1724 case Sema::PCC_RecoveryInFunction:
1725 case Sema::PCC_Statement: {
1726 AddTypedefResult(Results);
1728 if (SemaRef.getLangOpts().CPlusPlus && Results.includeCodePatterns() &&
1729 SemaRef.getLangOpts().CXXExceptions) {
1730 Builder.AddTypedTextChunk("try");
1731 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1732 Builder.AddPlaceholderChunk("statements");
1733 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1734 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1735 Builder.AddTextChunk("catch");
1736 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1737 Builder.AddPlaceholderChunk("declaration");
1738 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1739 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1740 Builder.AddPlaceholderChunk("statements");
1741 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1742 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1743 Results.AddResult(Result(Builder.TakeString()));
1745 if (SemaRef.getLangOpts().ObjC1)
1746 AddObjCStatementResults(Results, true);
1748 if (Results.includeCodePatterns()) {
1749 // if (condition) { statements }
1750 Builder.AddTypedTextChunk("if");
1751 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1752 if (SemaRef.getLangOpts().CPlusPlus)
1753 Builder.AddPlaceholderChunk("condition");
1755 Builder.AddPlaceholderChunk("expression");
1756 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1757 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1758 Builder.AddPlaceholderChunk("statements");
1759 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1760 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1761 Results.AddResult(Result(Builder.TakeString()));
1763 // switch (condition) { }
1764 Builder.AddTypedTextChunk("switch");
1765 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1766 if (SemaRef.getLangOpts().CPlusPlus)
1767 Builder.AddPlaceholderChunk("condition");
1769 Builder.AddPlaceholderChunk("expression");
1770 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1771 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1772 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1773 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1774 Results.AddResult(Result(Builder.TakeString()));
1777 // Switch-specific statements.
1778 if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
1780 Builder.AddTypedTextChunk("case");
1781 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1782 Builder.AddPlaceholderChunk("expression");
1783 Builder.AddChunk(CodeCompletionString::CK_Colon);
1784 Results.AddResult(Result(Builder.TakeString()));
1787 Builder.AddTypedTextChunk("default");
1788 Builder.AddChunk(CodeCompletionString::CK_Colon);
1789 Results.AddResult(Result(Builder.TakeString()));
1792 if (Results.includeCodePatterns()) {
1793 /// while (condition) { statements }
1794 Builder.AddTypedTextChunk("while");
1795 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1796 if (SemaRef.getLangOpts().CPlusPlus)
1797 Builder.AddPlaceholderChunk("condition");
1799 Builder.AddPlaceholderChunk("expression");
1800 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1801 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1802 Builder.AddPlaceholderChunk("statements");
1803 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1804 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1805 Results.AddResult(Result(Builder.TakeString()));
1807 // do { statements } while ( expression );
1808 Builder.AddTypedTextChunk("do");
1809 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1810 Builder.AddPlaceholderChunk("statements");
1811 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1812 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1813 Builder.AddTextChunk("while");
1814 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1815 Builder.AddPlaceholderChunk("expression");
1816 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1817 Results.AddResult(Result(Builder.TakeString()));
1819 // for ( for-init-statement ; condition ; expression ) { statements }
1820 Builder.AddTypedTextChunk("for");
1821 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1822 if (SemaRef.getLangOpts().CPlusPlus || SemaRef.getLangOpts().C99)
1823 Builder.AddPlaceholderChunk("init-statement");
1825 Builder.AddPlaceholderChunk("init-expression");
1826 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
1827 Builder.AddPlaceholderChunk("condition");
1828 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
1829 Builder.AddPlaceholderChunk("inc-expression");
1830 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1831 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1832 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1833 Builder.AddPlaceholderChunk("statements");
1834 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1835 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1836 Results.AddResult(Result(Builder.TakeString()));
1839 if (S->getContinueParent()) {
1841 Builder.AddTypedTextChunk("continue");
1842 Results.AddResult(Result(Builder.TakeString()));
1845 if (S->getBreakParent()) {
1847 Builder.AddTypedTextChunk("break");
1848 Results.AddResult(Result(Builder.TakeString()));
1851 // "return expression ;" or "return ;", depending on whether we
1852 // know the function is void or not.
1853 bool isVoid = false;
1854 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(SemaRef.CurContext))
1855 isVoid = Function->getReturnType()->isVoidType();
1856 else if (ObjCMethodDecl *Method
1857 = dyn_cast<ObjCMethodDecl>(SemaRef.CurContext))
1858 isVoid = Method->getReturnType()->isVoidType();
1859 else if (SemaRef.getCurBlock() &&
1860 !SemaRef.getCurBlock()->ReturnType.isNull())
1861 isVoid = SemaRef.getCurBlock()->ReturnType->isVoidType();
1862 Builder.AddTypedTextChunk("return");
1864 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1865 Builder.AddPlaceholderChunk("expression");
1867 Results.AddResult(Result(Builder.TakeString()));
1869 // goto identifier ;
1870 Builder.AddTypedTextChunk("goto");
1871 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1872 Builder.AddPlaceholderChunk("label");
1873 Results.AddResult(Result(Builder.TakeString()));
1876 Builder.AddTypedTextChunk("using");
1877 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1878 Builder.AddTextChunk("namespace");
1879 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1880 Builder.AddPlaceholderChunk("identifier");
1881 Results.AddResult(Result(Builder.TakeString()));
1883 AddStaticAssertResult(Builder, Results, SemaRef.getLangOpts());
1887 // Fall through (for statement expressions).
1888 case Sema::PCC_ForInit:
1889 case Sema::PCC_Condition:
1890 AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
1891 // Fall through: conditions and statements can have expressions.
1894 case Sema::PCC_ParenthesizedExpression:
1895 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
1896 CCC == Sema::PCC_ParenthesizedExpression) {
1897 // (__bridge <type>)<expression>
1898 Builder.AddTypedTextChunk("__bridge");
1899 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1900 Builder.AddPlaceholderChunk("type");
1901 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1902 Builder.AddPlaceholderChunk("expression");
1903 Results.AddResult(Result(Builder.TakeString()));
1905 // (__bridge_transfer <Objective-C type>)<expression>
1906 Builder.AddTypedTextChunk("__bridge_transfer");
1907 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1908 Builder.AddPlaceholderChunk("Objective-C type");
1909 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1910 Builder.AddPlaceholderChunk("expression");
1911 Results.AddResult(Result(Builder.TakeString()));
1913 // (__bridge_retained <CF type>)<expression>
1914 Builder.AddTypedTextChunk("__bridge_retained");
1915 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1916 Builder.AddPlaceholderChunk("CF type");
1917 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1918 Builder.AddPlaceholderChunk("expression");
1919 Results.AddResult(Result(Builder.TakeString()));
1924 case Sema::PCC_Expression: {
1925 if (SemaRef.getLangOpts().CPlusPlus) {
1926 // 'this', if we're in a non-static member function.
1927 addThisCompletion(SemaRef, Results);
1930 Builder.AddResultTypeChunk("bool");
1931 Builder.AddTypedTextChunk("true");
1932 Results.AddResult(Result(Builder.TakeString()));
1935 Builder.AddResultTypeChunk("bool");
1936 Builder.AddTypedTextChunk("false");
1937 Results.AddResult(Result(Builder.TakeString()));
1939 if (SemaRef.getLangOpts().RTTI) {
1940 // dynamic_cast < type-id > ( expression )
1941 Builder.AddTypedTextChunk("dynamic_cast");
1942 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1943 Builder.AddPlaceholderChunk("type");
1944 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1945 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1946 Builder.AddPlaceholderChunk("expression");
1947 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1948 Results.AddResult(Result(Builder.TakeString()));
1951 // static_cast < type-id > ( expression )
1952 Builder.AddTypedTextChunk("static_cast");
1953 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1954 Builder.AddPlaceholderChunk("type");
1955 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1956 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1957 Builder.AddPlaceholderChunk("expression");
1958 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1959 Results.AddResult(Result(Builder.TakeString()));
1961 // reinterpret_cast < type-id > ( expression )
1962 Builder.AddTypedTextChunk("reinterpret_cast");
1963 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1964 Builder.AddPlaceholderChunk("type");
1965 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1966 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1967 Builder.AddPlaceholderChunk("expression");
1968 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1969 Results.AddResult(Result(Builder.TakeString()));
1971 // const_cast < type-id > ( expression )
1972 Builder.AddTypedTextChunk("const_cast");
1973 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1974 Builder.AddPlaceholderChunk("type");
1975 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1976 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1977 Builder.AddPlaceholderChunk("expression");
1978 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1979 Results.AddResult(Result(Builder.TakeString()));
1981 if (SemaRef.getLangOpts().RTTI) {
1982 // typeid ( expression-or-type )
1983 Builder.AddResultTypeChunk("std::type_info");
1984 Builder.AddTypedTextChunk("typeid");
1985 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1986 Builder.AddPlaceholderChunk("expression-or-type");
1987 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1988 Results.AddResult(Result(Builder.TakeString()));
1992 Builder.AddTypedTextChunk("new");
1993 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1994 Builder.AddPlaceholderChunk("type");
1995 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1996 Builder.AddPlaceholderChunk("expressions");
1997 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1998 Results.AddResult(Result(Builder.TakeString()));
2000 // new T [ ] ( ... )
2001 Builder.AddTypedTextChunk("new");
2002 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2003 Builder.AddPlaceholderChunk("type");
2004 Builder.AddChunk(CodeCompletionString::CK_LeftBracket);
2005 Builder.AddPlaceholderChunk("size");
2006 Builder.AddChunk(CodeCompletionString::CK_RightBracket);
2007 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2008 Builder.AddPlaceholderChunk("expressions");
2009 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2010 Results.AddResult(Result(Builder.TakeString()));
2012 // delete expression
2013 Builder.AddResultTypeChunk("void");
2014 Builder.AddTypedTextChunk("delete");
2015 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2016 Builder.AddPlaceholderChunk("expression");
2017 Results.AddResult(Result(Builder.TakeString()));
2019 // delete [] expression
2020 Builder.AddResultTypeChunk("void");
2021 Builder.AddTypedTextChunk("delete");
2022 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2023 Builder.AddChunk(CodeCompletionString::CK_LeftBracket);
2024 Builder.AddChunk(CodeCompletionString::CK_RightBracket);
2025 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2026 Builder.AddPlaceholderChunk("expression");
2027 Results.AddResult(Result(Builder.TakeString()));
2029 if (SemaRef.getLangOpts().CXXExceptions) {
2031 Builder.AddResultTypeChunk("void");
2032 Builder.AddTypedTextChunk("throw");
2033 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2034 Builder.AddPlaceholderChunk("expression");
2035 Results.AddResult(Result(Builder.TakeString()));
2040 if (SemaRef.getLangOpts().CPlusPlus11) {
2042 Builder.AddResultTypeChunk("std::nullptr_t");
2043 Builder.AddTypedTextChunk("nullptr");
2044 Results.AddResult(Result(Builder.TakeString()));
2047 Builder.AddResultTypeChunk("size_t");
2048 Builder.AddTypedTextChunk("alignof");
2049 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2050 Builder.AddPlaceholderChunk("type");
2051 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2052 Results.AddResult(Result(Builder.TakeString()));
2055 Builder.AddResultTypeChunk("bool");
2056 Builder.AddTypedTextChunk("noexcept");
2057 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2058 Builder.AddPlaceholderChunk("expression");
2059 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2060 Results.AddResult(Result(Builder.TakeString()));
2062 // sizeof... expression
2063 Builder.AddResultTypeChunk("size_t");
2064 Builder.AddTypedTextChunk("sizeof...");
2065 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2066 Builder.AddPlaceholderChunk("parameter-pack");
2067 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2068 Results.AddResult(Result(Builder.TakeString()));
2072 if (SemaRef.getLangOpts().ObjC1) {
2073 // Add "super", if we're in an Objective-C class with a superclass.
2074 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
2075 // The interface can be NULL.
2076 if (ObjCInterfaceDecl *ID = Method->getClassInterface())
2077 if (ID->getSuperClass()) {
2078 std::string SuperType;
2079 SuperType = ID->getSuperClass()->getNameAsString();
2080 if (Method->isInstanceMethod())
2083 Builder.AddResultTypeChunk(Allocator.CopyString(SuperType));
2084 Builder.AddTypedTextChunk("super");
2085 Results.AddResult(Result(Builder.TakeString()));
2089 AddObjCExpressionResults(Results, true);
2092 if (SemaRef.getLangOpts().C11) {
2094 Builder.AddResultTypeChunk("size_t");
2095 if (SemaRef.PP.isMacroDefined("alignof"))
2096 Builder.AddTypedTextChunk("alignof");
2098 Builder.AddTypedTextChunk("_Alignof");
2099 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2100 Builder.AddPlaceholderChunk("type");
2101 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2102 Results.AddResult(Result(Builder.TakeString()));
2105 // sizeof expression
2106 Builder.AddResultTypeChunk("size_t");
2107 Builder.AddTypedTextChunk("sizeof");
2108 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2109 Builder.AddPlaceholderChunk("expression-or-type");
2110 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2111 Results.AddResult(Result(Builder.TakeString()));
2115 case Sema::PCC_Type:
2116 case Sema::PCC_LocalDeclarationSpecifiers:
2120 if (WantTypesInContext(CCC, SemaRef.getLangOpts()))
2121 AddTypeSpecifierResults(SemaRef.getLangOpts(), Results);
2123 if (SemaRef.getLangOpts().CPlusPlus && CCC != Sema::PCC_Type)
2124 Results.AddResult(Result("operator"));
2127 /// \brief If the given declaration has an associated type, add it as a result
2129 static void AddResultTypeChunk(ASTContext &Context,
2130 const PrintingPolicy &Policy,
2131 const NamedDecl *ND,
2133 CodeCompletionBuilder &Result) {
2137 // Skip constructors and conversion functions, which have their return types
2138 // built into their names.
2139 if (isa<CXXConstructorDecl>(ND) || isa<CXXConversionDecl>(ND))
2142 // Determine the type of the declaration (if it has a type).
2144 if (const FunctionDecl *Function = ND->getAsFunction())
2145 T = Function->getReturnType();
2146 else if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND)) {
2147 if (!BaseType.isNull())
2148 T = Method->getSendResultType(BaseType);
2150 T = Method->getReturnType();
2151 } else if (const EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND)) {
2152 T = Context.getTypeDeclType(cast<TypeDecl>(Enumerator->getDeclContext()));
2153 T = clang::TypeName::getFullyQualifiedType(T, Context);
2154 } else if (isa<UnresolvedUsingValueDecl>(ND)) {
2155 /* Do nothing: ignore unresolved using declarations*/
2156 } else if (const ObjCIvarDecl *Ivar = dyn_cast<ObjCIvarDecl>(ND)) {
2157 if (!BaseType.isNull())
2158 T = Ivar->getUsageType(BaseType);
2160 T = Ivar->getType();
2161 } else if (const ValueDecl *Value = dyn_cast<ValueDecl>(ND)) {
2162 T = Value->getType();
2163 } else if (const ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND)) {
2164 if (!BaseType.isNull())
2165 T = Property->getUsageType(BaseType);
2167 T = Property->getType();
2170 if (T.isNull() || Context.hasSameType(T, Context.DependentTy))
2173 Result.AddResultTypeChunk(GetCompletionTypeString(T, Context, Policy,
2174 Result.getAllocator()));
2177 static void MaybeAddSentinel(Preprocessor &PP,
2178 const NamedDecl *FunctionOrMethod,
2179 CodeCompletionBuilder &Result) {
2180 if (SentinelAttr *Sentinel = FunctionOrMethod->getAttr<SentinelAttr>())
2181 if (Sentinel->getSentinel() == 0) {
2182 if (PP.getLangOpts().ObjC1 && PP.isMacroDefined("nil"))
2183 Result.AddTextChunk(", nil");
2184 else if (PP.isMacroDefined("NULL"))
2185 Result.AddTextChunk(", NULL");
2187 Result.AddTextChunk(", (void*)0");
2191 static std::string formatObjCParamQualifiers(unsigned ObjCQuals,
2194 if (ObjCQuals & Decl::OBJC_TQ_In)
2196 else if (ObjCQuals & Decl::OBJC_TQ_Inout)
2198 else if (ObjCQuals & Decl::OBJC_TQ_Out)
2200 if (ObjCQuals & Decl::OBJC_TQ_Bycopy)
2201 Result += "bycopy ";
2202 else if (ObjCQuals & Decl::OBJC_TQ_Byref)
2204 if (ObjCQuals & Decl::OBJC_TQ_Oneway)
2205 Result += "oneway ";
2206 if (ObjCQuals & Decl::OBJC_TQ_CSNullability) {
2207 if (auto nullability = AttributedType::stripOuterNullability(Type)) {
2208 switch (*nullability) {
2209 case NullabilityKind::NonNull:
2210 Result += "nonnull ";
2213 case NullabilityKind::Nullable:
2214 Result += "nullable ";
2217 case NullabilityKind::Unspecified:
2218 Result += "null_unspecified ";
2226 /// \brief Tries to find the most appropriate type location for an Objective-C
2227 /// block placeholder.
2229 /// This function ignores things like typedefs and qualifiers in order to
2230 /// present the most relevant and accurate block placeholders in code completion
2232 static void findTypeLocationForBlockDecl(const TypeSourceInfo *TSInfo,
2233 FunctionTypeLoc &Block,
2234 FunctionProtoTypeLoc &BlockProto,
2235 bool SuppressBlock = false) {
2238 TypeLoc TL = TSInfo->getTypeLoc().getUnqualifiedLoc();
2240 // Look through typedefs.
2241 if (!SuppressBlock) {
2242 if (TypedefTypeLoc TypedefTL = TL.getAs<TypedefTypeLoc>()) {
2243 if (TypeSourceInfo *InnerTSInfo =
2244 TypedefTL.getTypedefNameDecl()->getTypeSourceInfo()) {
2245 TL = InnerTSInfo->getTypeLoc().getUnqualifiedLoc();
2250 // Look through qualified types
2251 if (QualifiedTypeLoc QualifiedTL = TL.getAs<QualifiedTypeLoc>()) {
2252 TL = QualifiedTL.getUnqualifiedLoc();
2256 if (AttributedTypeLoc AttrTL = TL.getAs<AttributedTypeLoc>()) {
2257 TL = AttrTL.getModifiedLoc();
2262 // Try to get the function prototype behind the block pointer type,
2264 if (BlockPointerTypeLoc BlockPtr = TL.getAs<BlockPointerTypeLoc>()) {
2265 TL = BlockPtr.getPointeeLoc().IgnoreParens();
2266 Block = TL.getAs<FunctionTypeLoc>();
2267 BlockProto = TL.getAs<FunctionProtoTypeLoc>();
2274 formatBlockPlaceholder(const PrintingPolicy &Policy, const NamedDecl *BlockDecl,
2275 FunctionTypeLoc &Block, FunctionProtoTypeLoc &BlockProto,
2276 bool SuppressBlockName = false,
2277 bool SuppressBlock = false,
2278 Optional<ArrayRef<QualType>> ObjCSubsts = None);
2280 static std::string FormatFunctionParameter(const PrintingPolicy &Policy,
2281 const ParmVarDecl *Param,
2282 bool SuppressName = false,
2283 bool SuppressBlock = false,
2284 Optional<ArrayRef<QualType>> ObjCSubsts = None) {
2285 bool ObjCMethodParam = isa<ObjCMethodDecl>(Param->getDeclContext());
2286 if (Param->getType()->isDependentType() ||
2287 !Param->getType()->isBlockPointerType()) {
2288 // The argument for a dependent or non-block parameter is a placeholder
2289 // containing that parameter's type.
2292 if (Param->getIdentifier() && !ObjCMethodParam && !SuppressName)
2293 Result = Param->getIdentifier()->getName();
2295 QualType Type = Param->getType();
2297 Type = Type.substObjCTypeArgs(Param->getASTContext(), *ObjCSubsts,
2298 ObjCSubstitutionContext::Parameter);
2299 if (ObjCMethodParam) {
2300 Result = "(" + formatObjCParamQualifiers(Param->getObjCDeclQualifier(),
2302 Result += Type.getAsString(Policy) + ")";
2303 if (Param->getIdentifier() && !SuppressName)
2304 Result += Param->getIdentifier()->getName();
2306 Type.getAsStringInternal(Result, Policy);
2311 // The argument for a block pointer parameter is a block literal with
2312 // the appropriate type.
2313 FunctionTypeLoc Block;
2314 FunctionProtoTypeLoc BlockProto;
2315 findTypeLocationForBlockDecl(Param->getTypeSourceInfo(), Block, BlockProto,
2317 // Try to retrieve the block type information from the property if this is a
2318 // parameter in a setter.
2319 if (!Block && ObjCMethodParam &&
2320 cast<ObjCMethodDecl>(Param->getDeclContext())->isPropertyAccessor()) {
2321 if (const auto *PD = cast<ObjCMethodDecl>(Param->getDeclContext())
2322 ->findPropertyDecl(/*CheckOverrides=*/false))
2323 findTypeLocationForBlockDecl(PD->getTypeSourceInfo(), Block, BlockProto,
2328 // We were unable to find a FunctionProtoTypeLoc with parameter names
2329 // for the block; just use the parameter type as a placeholder.
2331 if (!ObjCMethodParam && Param->getIdentifier())
2332 Result = Param->getIdentifier()->getName();
2334 QualType Type = Param->getType().getUnqualifiedType();
2336 if (ObjCMethodParam) {
2337 Result = Type.getAsString(Policy);
2339 formatObjCParamQualifiers(Param->getObjCDeclQualifier(), Type);
2341 Result = "(" + Quals + " " + Result + ")";
2342 if (Result.back() != ')')
2344 if (Param->getIdentifier())
2345 Result += Param->getIdentifier()->getName();
2347 Type.getAsStringInternal(Result, Policy);
2353 // We have the function prototype behind the block pointer type, as it was
2354 // written in the source.
2355 return formatBlockPlaceholder(Policy, Param, Block, BlockProto,
2356 /*SuppressBlockName=*/false, SuppressBlock,
2360 /// \brief Returns a placeholder string that corresponds to an Objective-C block
2363 /// \param BlockDecl A declaration with an Objective-C block type.
2365 /// \param Block The most relevant type location for that block type.
2367 /// \param SuppressBlockName Determines wether or not the name of the block
2368 /// declaration is included in the resulting string.
2370 formatBlockPlaceholder(const PrintingPolicy &Policy, const NamedDecl *BlockDecl,
2371 FunctionTypeLoc &Block, FunctionProtoTypeLoc &BlockProto,
2372 bool SuppressBlockName, bool SuppressBlock,
2373 Optional<ArrayRef<QualType>> ObjCSubsts) {
2375 QualType ResultType = Block.getTypePtr()->getReturnType();
2378 ResultType.substObjCTypeArgs(BlockDecl->getASTContext(), *ObjCSubsts,
2379 ObjCSubstitutionContext::Result);
2380 if (!ResultType->isVoidType() || SuppressBlock)
2381 ResultType.getAsStringInternal(Result, Policy);
2383 // Format the parameter list.
2385 if (!BlockProto || Block.getNumParams() == 0) {
2386 if (BlockProto && BlockProto.getTypePtr()->isVariadic())
2392 for (unsigned I = 0, N = Block.getNumParams(); I != N; ++I) {
2395 Params += FormatFunctionParameter(Policy, Block.getParam(I),
2396 /*SuppressName=*/false,
2397 /*SuppressBlock=*/true, ObjCSubsts);
2399 if (I == N - 1 && BlockProto.getTypePtr()->isVariadic())
2405 if (SuppressBlock) {
2406 // Format as a parameter.
2407 Result = Result + " (^";
2408 if (!SuppressBlockName && BlockDecl->getIdentifier())
2409 Result += BlockDecl->getIdentifier()->getName();
2413 // Format as a block literal argument.
2414 Result = '^' + Result;
2417 if (!SuppressBlockName && BlockDecl->getIdentifier())
2418 Result += BlockDecl->getIdentifier()->getName();
2424 static std::string GetDefaultValueString(const ParmVarDecl *Param,
2425 const SourceManager &SM,
2426 const LangOptions &LangOpts) {
2427 const SourceRange SrcRange = Param->getDefaultArgRange();
2428 CharSourceRange CharSrcRange = CharSourceRange::getTokenRange(SrcRange);
2429 bool Invalid = CharSrcRange.isInvalid();
2432 StringRef srcText = Lexer::getSourceText(CharSrcRange, SM, LangOpts, &Invalid);
2436 if (srcText.empty() || srcText == "=") {
2437 // Lexer can't determine the value.
2438 // This happens if the code is incorrect (for example class is forward declared).
2441 std::string DefValue(srcText.str());
2442 // FIXME: remove this check if the Lexer::getSourceText value is fixed and
2443 // this value always has (or always does not have) '=' in front of it
2444 if (DefValue.at(0) != '=') {
2445 // If we don't have '=' in front of value.
2446 // Lexer returns built-in types values without '=' and user-defined types values with it.
2447 return " = " + DefValue;
2449 return " " + DefValue;
2452 /// \brief Add function parameter chunks to the given code completion string.
2453 static void AddFunctionParameterChunks(Preprocessor &PP,
2454 const PrintingPolicy &Policy,
2455 const FunctionDecl *Function,
2456 CodeCompletionBuilder &Result,
2458 bool InOptional = false) {
2459 bool FirstParameter = true;
2461 for (unsigned P = Start, N = Function->getNumParams(); P != N; ++P) {
2462 const ParmVarDecl *Param = Function->getParamDecl(P);
2464 if (Param->hasDefaultArg() && !InOptional) {
2465 // When we see an optional default argument, put that argument and
2466 // the remaining default arguments into a new, optional string.
2467 CodeCompletionBuilder Opt(Result.getAllocator(),
2468 Result.getCodeCompletionTUInfo());
2469 if (!FirstParameter)
2470 Opt.AddChunk(CodeCompletionString::CK_Comma);
2471 AddFunctionParameterChunks(PP, Policy, Function, Opt, P, true);
2472 Result.AddOptionalChunk(Opt.TakeString());
2477 FirstParameter = false;
2479 Result.AddChunk(CodeCompletionString::CK_Comma);
2483 // Format the placeholder string.
2484 std::string PlaceholderStr = FormatFunctionParameter(Policy, Param);
2485 if (Param->hasDefaultArg())
2486 PlaceholderStr += GetDefaultValueString(Param, PP.getSourceManager(), PP.getLangOpts());
2488 if (Function->isVariadic() && P == N - 1)
2489 PlaceholderStr += ", ...";
2491 // Add the placeholder string.
2492 Result.AddPlaceholderChunk(
2493 Result.getAllocator().CopyString(PlaceholderStr));
2496 if (const FunctionProtoType *Proto
2497 = Function->getType()->getAs<FunctionProtoType>())
2498 if (Proto->isVariadic()) {
2499 if (Proto->getNumParams() == 0)
2500 Result.AddPlaceholderChunk("...");
2502 MaybeAddSentinel(PP, Function, Result);
2506 /// \brief Add template parameter chunks to the given code completion string.
2507 static void AddTemplateParameterChunks(ASTContext &Context,
2508 const PrintingPolicy &Policy,
2509 const TemplateDecl *Template,
2510 CodeCompletionBuilder &Result,
2511 unsigned MaxParameters = 0,
2513 bool InDefaultArg = false) {
2514 bool FirstParameter = true;
2516 // Prefer to take the template parameter names from the first declaration of
2518 Template = cast<TemplateDecl>(Template->getCanonicalDecl());
2520 TemplateParameterList *Params = Template->getTemplateParameters();
2521 TemplateParameterList::iterator PEnd = Params->end();
2523 PEnd = Params->begin() + MaxParameters;
2524 for (TemplateParameterList::iterator P = Params->begin() + Start;
2526 bool HasDefaultArg = false;
2527 std::string PlaceholderStr;
2528 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
2529 if (TTP->wasDeclaredWithTypename())
2530 PlaceholderStr = "typename";
2532 PlaceholderStr = "class";
2534 if (TTP->getIdentifier()) {
2535 PlaceholderStr += ' ';
2536 PlaceholderStr += TTP->getIdentifier()->getName();
2539 HasDefaultArg = TTP->hasDefaultArgument();
2540 } else if (NonTypeTemplateParmDecl *NTTP
2541 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
2542 if (NTTP->getIdentifier())
2543 PlaceholderStr = NTTP->getIdentifier()->getName();
2544 NTTP->getType().getAsStringInternal(PlaceholderStr, Policy);
2545 HasDefaultArg = NTTP->hasDefaultArgument();
2547 assert(isa<TemplateTemplateParmDecl>(*P));
2548 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
2550 // Since putting the template argument list into the placeholder would
2551 // be very, very long, we just use an abbreviation.
2552 PlaceholderStr = "template<...> class";
2553 if (TTP->getIdentifier()) {
2554 PlaceholderStr += ' ';
2555 PlaceholderStr += TTP->getIdentifier()->getName();
2558 HasDefaultArg = TTP->hasDefaultArgument();
2561 if (HasDefaultArg && !InDefaultArg) {
2562 // When we see an optional default argument, put that argument and
2563 // the remaining default arguments into a new, optional string.
2564 CodeCompletionBuilder Opt(Result.getAllocator(),
2565 Result.getCodeCompletionTUInfo());
2566 if (!FirstParameter)
2567 Opt.AddChunk(CodeCompletionString::CK_Comma);
2568 AddTemplateParameterChunks(Context, Policy, Template, Opt, MaxParameters,
2569 P - Params->begin(), true);
2570 Result.AddOptionalChunk(Opt.TakeString());
2574 InDefaultArg = false;
2577 FirstParameter = false;
2579 Result.AddChunk(CodeCompletionString::CK_Comma);
2581 // Add the placeholder string.
2582 Result.AddPlaceholderChunk(
2583 Result.getAllocator().CopyString(PlaceholderStr));
2587 /// \brief Add a qualifier to the given code-completion string, if the
2588 /// provided nested-name-specifier is non-NULL.
2590 AddQualifierToCompletionString(CodeCompletionBuilder &Result,
2591 NestedNameSpecifier *Qualifier,
2592 bool QualifierIsInformative,
2593 ASTContext &Context,
2594 const PrintingPolicy &Policy) {
2598 std::string PrintedNNS;
2600 llvm::raw_string_ostream OS(PrintedNNS);
2601 Qualifier->print(OS, Policy);
2603 if (QualifierIsInformative)
2604 Result.AddInformativeChunk(Result.getAllocator().CopyString(PrintedNNS));
2606 Result.AddTextChunk(Result.getAllocator().CopyString(PrintedNNS));
2610 AddFunctionTypeQualsToCompletionString(CodeCompletionBuilder &Result,
2611 const FunctionDecl *Function) {
2612 const FunctionProtoType *Proto
2613 = Function->getType()->getAs<FunctionProtoType>();
2614 if (!Proto || !Proto->getTypeQuals())
2617 // FIXME: Add ref-qualifier!
2619 // Handle single qualifiers without copying
2620 if (Proto->getTypeQuals() == Qualifiers::Const) {
2621 Result.AddInformativeChunk(" const");
2625 if (Proto->getTypeQuals() == Qualifiers::Volatile) {
2626 Result.AddInformativeChunk(" volatile");
2630 if (Proto->getTypeQuals() == Qualifiers::Restrict) {
2631 Result.AddInformativeChunk(" restrict");
2635 // Handle multiple qualifiers.
2636 std::string QualsStr;
2637 if (Proto->isConst())
2638 QualsStr += " const";
2639 if (Proto->isVolatile())
2640 QualsStr += " volatile";
2641 if (Proto->isRestrict())
2642 QualsStr += " restrict";
2643 Result.AddInformativeChunk(Result.getAllocator().CopyString(QualsStr));
2646 /// \brief Add the name of the given declaration
2647 static void AddTypedNameChunk(ASTContext &Context, const PrintingPolicy &Policy,
2648 const NamedDecl *ND,
2649 CodeCompletionBuilder &Result) {
2650 DeclarationName Name = ND->getDeclName();
2654 switch (Name.getNameKind()) {
2655 case DeclarationName::CXXOperatorName: {
2656 const char *OperatorName = nullptr;
2657 switch (Name.getCXXOverloadedOperator()) {
2659 case OO_Conditional:
2660 case NUM_OVERLOADED_OPERATORS:
2661 OperatorName = "operator";
2664 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2665 case OO_##Name: OperatorName = "operator" Spelling; break;
2666 #define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
2667 #include "clang/Basic/OperatorKinds.def"
2669 case OO_New: OperatorName = "operator new"; break;
2670 case OO_Delete: OperatorName = "operator delete"; break;
2671 case OO_Array_New: OperatorName = "operator new[]"; break;
2672 case OO_Array_Delete: OperatorName = "operator delete[]"; break;
2673 case OO_Call: OperatorName = "operator()"; break;
2674 case OO_Subscript: OperatorName = "operator[]"; break;
2676 Result.AddTypedTextChunk(OperatorName);
2680 case DeclarationName::Identifier:
2681 case DeclarationName::CXXConversionFunctionName:
2682 case DeclarationName::CXXDestructorName:
2683 case DeclarationName::CXXLiteralOperatorName:
2684 Result.AddTypedTextChunk(
2685 Result.getAllocator().CopyString(ND->getNameAsString()));
2688 case DeclarationName::CXXDeductionGuideName:
2689 case DeclarationName::CXXUsingDirective:
2690 case DeclarationName::ObjCZeroArgSelector:
2691 case DeclarationName::ObjCOneArgSelector:
2692 case DeclarationName::ObjCMultiArgSelector:
2695 case DeclarationName::CXXConstructorName: {
2696 CXXRecordDecl *Record = nullptr;
2697 QualType Ty = Name.getCXXNameType();
2698 if (const RecordType *RecordTy = Ty->getAs<RecordType>())
2699 Record = cast<CXXRecordDecl>(RecordTy->getDecl());
2700 else if (const InjectedClassNameType *InjectedTy
2701 = Ty->getAs<InjectedClassNameType>())
2702 Record = InjectedTy->getDecl();
2704 Result.AddTypedTextChunk(
2705 Result.getAllocator().CopyString(ND->getNameAsString()));
2709 Result.AddTypedTextChunk(
2710 Result.getAllocator().CopyString(Record->getNameAsString()));
2711 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) {
2712 Result.AddChunk(CodeCompletionString::CK_LeftAngle);
2713 AddTemplateParameterChunks(Context, Policy, Template, Result);
2714 Result.AddChunk(CodeCompletionString::CK_RightAngle);
2721 CodeCompletionString *CodeCompletionResult::CreateCodeCompletionString(Sema &S,
2722 const CodeCompletionContext &CCContext,
2723 CodeCompletionAllocator &Allocator,
2724 CodeCompletionTUInfo &CCTUInfo,
2725 bool IncludeBriefComments) {
2726 return CreateCodeCompletionString(S.Context, S.PP, CCContext, Allocator,
2727 CCTUInfo, IncludeBriefComments);
2730 /// \brief If possible, create a new code completion string for the given
2733 /// \returns Either a new, heap-allocated code completion string describing
2734 /// how to use this result, or NULL to indicate that the string or name of the
2735 /// result is all that is needed.
2736 CodeCompletionString *
2737 CodeCompletionResult::CreateCodeCompletionString(ASTContext &Ctx,
2739 const CodeCompletionContext &CCContext,
2740 CodeCompletionAllocator &Allocator,
2741 CodeCompletionTUInfo &CCTUInfo,
2742 bool IncludeBriefComments) {
2743 CodeCompletionBuilder Result(Allocator, CCTUInfo, Priority, Availability);
2745 PrintingPolicy Policy = getCompletionPrintingPolicy(Ctx, PP);
2746 if (Kind == RK_Pattern) {
2747 Pattern->Priority = Priority;
2748 Pattern->Availability = Availability;
2751 Result.addParentContext(Declaration->getDeclContext());
2752 Pattern->ParentName = Result.getParentName();
2753 // Provide code completion comment for self.GetterName where
2754 // GetterName is the getter method for a property with name
2755 // different from the property name (declared via a property
2756 // getter attribute.
2757 const NamedDecl *ND = Declaration;
2758 if (const ObjCMethodDecl *M = dyn_cast<ObjCMethodDecl>(ND))
2759 if (M->isPropertyAccessor())
2760 if (const ObjCPropertyDecl *PDecl = M->findPropertyDecl())
2761 if (PDecl->getGetterName() == M->getSelector() &&
2762 PDecl->getIdentifier() != M->getIdentifier()) {
2763 if (const RawComment *RC =
2764 Ctx.getRawCommentForAnyRedecl(M)) {
2765 Result.addBriefComment(RC->getBriefText(Ctx));
2766 Pattern->BriefComment = Result.getBriefComment();
2768 else if (const RawComment *RC =
2769 Ctx.getRawCommentForAnyRedecl(PDecl)) {
2770 Result.addBriefComment(RC->getBriefText(Ctx));
2771 Pattern->BriefComment = Result.getBriefComment();
2779 if (Kind == RK_Keyword) {
2780 Result.AddTypedTextChunk(Keyword);
2781 return Result.TakeString();
2784 if (Kind == RK_Macro) {
2785 const MacroInfo *MI = PP.getMacroInfo(Macro);
2786 Result.AddTypedTextChunk(
2787 Result.getAllocator().CopyString(Macro->getName()));
2789 if (!MI || !MI->isFunctionLike())
2790 return Result.TakeString();
2792 // Format a function-like macro with placeholders for the arguments.
2793 Result.AddChunk(CodeCompletionString::CK_LeftParen);
2794 MacroInfo::param_iterator A = MI->param_begin(), AEnd = MI->param_end();
2796 // C99 variadic macros add __VA_ARGS__ at the end. Skip it.
2797 if (MI->isC99Varargs()) {
2801 Result.AddPlaceholderChunk("...");
2805 for (MacroInfo::param_iterator A = MI->param_begin(); A != AEnd; ++A) {
2806 if (A != MI->param_begin())
2807 Result.AddChunk(CodeCompletionString::CK_Comma);
2809 if (MI->isVariadic() && (A+1) == AEnd) {
2810 SmallString<32> Arg = (*A)->getName();
2811 if (MI->isC99Varargs())
2815 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
2819 // Non-variadic macros are simple.
2820 Result.AddPlaceholderChunk(
2821 Result.getAllocator().CopyString((*A)->getName()));
2823 Result.AddChunk(CodeCompletionString::CK_RightParen);
2824 return Result.TakeString();
2827 assert(Kind == RK_Declaration && "Missed a result kind?");
2828 const NamedDecl *ND = Declaration;
2829 Result.addParentContext(ND->getDeclContext());
2831 if (IncludeBriefComments) {
2832 // Add documentation comment, if it exists.
2833 if (const RawComment *RC = Ctx.getRawCommentForAnyRedecl(ND)) {
2834 Result.addBriefComment(RC->getBriefText(Ctx));
2836 else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
2837 if (OMD->isPropertyAccessor())
2838 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
2839 if (const RawComment *RC = Ctx.getRawCommentForAnyRedecl(PDecl))
2840 Result.addBriefComment(RC->getBriefText(Ctx));
2843 if (StartsNestedNameSpecifier) {
2844 Result.AddTypedTextChunk(
2845 Result.getAllocator().CopyString(ND->getNameAsString()));
2846 Result.AddTextChunk("::");
2847 return Result.TakeString();
2850 for (const auto *I : ND->specific_attrs<AnnotateAttr>())
2851 Result.AddAnnotation(Result.getAllocator().CopyString(I->getAnnotation()));
2853 AddResultTypeChunk(Ctx, Policy, ND, CCContext.getBaseType(), Result);
2855 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(ND)) {
2856 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2858 AddTypedNameChunk(Ctx, Policy, ND, Result);
2859 Result.AddChunk(CodeCompletionString::CK_LeftParen);
2860 AddFunctionParameterChunks(PP, Policy, Function, Result);
2861 Result.AddChunk(CodeCompletionString::CK_RightParen);
2862 AddFunctionTypeQualsToCompletionString(Result, Function);
2863 return Result.TakeString();
2866 if (const FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND)) {
2867 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2869 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
2870 AddTypedNameChunk(Ctx, Policy, Function, Result);
2872 // Figure out which template parameters are deduced (or have default
2874 llvm::SmallBitVector Deduced;
2875 Sema::MarkDeducedTemplateParameters(Ctx, FunTmpl, Deduced);
2876 unsigned LastDeducibleArgument;
2877 for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0;
2878 --LastDeducibleArgument) {
2879 if (!Deduced[LastDeducibleArgument - 1]) {
2880 // C++0x: Figure out if the template argument has a default. If so,
2881 // the user doesn't need to type this argument.
2882 // FIXME: We need to abstract template parameters better!
2883 bool HasDefaultArg = false;
2884 NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam(
2885 LastDeducibleArgument - 1);
2886 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2887 HasDefaultArg = TTP->hasDefaultArgument();
2888 else if (NonTypeTemplateParmDecl *NTTP
2889 = dyn_cast<NonTypeTemplateParmDecl>(Param))
2890 HasDefaultArg = NTTP->hasDefaultArgument();
2892 assert(isa<TemplateTemplateParmDecl>(Param));
2894 = cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument();
2902 if (LastDeducibleArgument) {
2903 // Some of the function template arguments cannot be deduced from a
2904 // function call, so we introduce an explicit template argument list
2905 // containing all of the arguments up to the first deducible argument.
2906 Result.AddChunk(CodeCompletionString::CK_LeftAngle);
2907 AddTemplateParameterChunks(Ctx, Policy, FunTmpl, Result,
2908 LastDeducibleArgument);
2909 Result.AddChunk(CodeCompletionString::CK_RightAngle);
2912 // Add the function parameters
2913 Result.AddChunk(CodeCompletionString::CK_LeftParen);
2914 AddFunctionParameterChunks(PP, Policy, Function, Result);
2915 Result.AddChunk(CodeCompletionString::CK_RightParen);
2916 AddFunctionTypeQualsToCompletionString(Result, Function);
2917 return Result.TakeString();
2920 if (const TemplateDecl *Template = dyn_cast<TemplateDecl>(ND)) {
2921 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2923 Result.AddTypedTextChunk(
2924 Result.getAllocator().CopyString(Template->getNameAsString()));
2925 Result.AddChunk(CodeCompletionString::CK_LeftAngle);
2926 AddTemplateParameterChunks(Ctx, Policy, Template, Result);
2927 Result.AddChunk(CodeCompletionString::CK_RightAngle);
2928 return Result.TakeString();
2931 if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND)) {
2932 Selector Sel = Method->getSelector();
2933 if (Sel.isUnarySelector()) {
2934 Result.AddTypedTextChunk(Result.getAllocator().CopyString(
2935 Sel.getNameForSlot(0)));
2936 return Result.TakeString();
2939 std::string SelName = Sel.getNameForSlot(0).str();
2941 if (StartParameter == 0)
2942 Result.AddTypedTextChunk(Result.getAllocator().CopyString(SelName));
2944 Result.AddInformativeChunk(Result.getAllocator().CopyString(SelName));
2946 // If there is only one parameter, and we're past it, add an empty
2947 // typed-text chunk since there is nothing to type.
2948 if (Method->param_size() == 1)
2949 Result.AddTypedTextChunk("");
2952 for (ObjCMethodDecl::param_const_iterator P = Method->param_begin(),
2953 PEnd = Method->param_end();
2954 P != PEnd; (void)++P, ++Idx) {
2956 std::string Keyword;
2957 if (Idx > StartParameter)
2958 Result.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2959 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(Idx))
2960 Keyword += II->getName();
2962 if (Idx < StartParameter || AllParametersAreInformative)
2963 Result.AddInformativeChunk(Result.getAllocator().CopyString(Keyword));
2965 Result.AddTypedTextChunk(Result.getAllocator().CopyString(Keyword));
2968 // If we're before the starting parameter, skip the placeholder.
2969 if (Idx < StartParameter)
2973 QualType ParamType = (*P)->getType();
2974 Optional<ArrayRef<QualType>> ObjCSubsts;
2975 if (!CCContext.getBaseType().isNull())
2976 ObjCSubsts = CCContext.getBaseType()->getObjCSubstitutions(Method);
2978 if (ParamType->isBlockPointerType() && !DeclaringEntity)
2979 Arg = FormatFunctionParameter(Policy, *P, true,
2980 /*SuppressBlock=*/false,
2984 ParamType = ParamType.substObjCTypeArgs(Ctx, *ObjCSubsts,
2985 ObjCSubstitutionContext::Parameter);
2986 Arg = "(" + formatObjCParamQualifiers((*P)->getObjCDeclQualifier(),
2988 Arg += ParamType.getAsString(Policy) + ")";
2989 if (IdentifierInfo *II = (*P)->getIdentifier())
2990 if (DeclaringEntity || AllParametersAreInformative)
2991 Arg += II->getName();
2994 if (Method->isVariadic() && (P + 1) == PEnd)
2997 if (DeclaringEntity)
2998 Result.AddTextChunk(Result.getAllocator().CopyString(Arg));
2999 else if (AllParametersAreInformative)
3000 Result.AddInformativeChunk(Result.getAllocator().CopyString(Arg));
3002 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
3005 if (Method->isVariadic()) {
3006 if (Method->param_size() == 0) {
3007 if (DeclaringEntity)
3008 Result.AddTextChunk(", ...");
3009 else if (AllParametersAreInformative)
3010 Result.AddInformativeChunk(", ...");
3012 Result.AddPlaceholderChunk(", ...");
3015 MaybeAddSentinel(PP, Method, Result);
3018 return Result.TakeString();
3022 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
3025 Result.AddTypedTextChunk(
3026 Result.getAllocator().CopyString(ND->getNameAsString()));
3027 return Result.TakeString();
3030 /// \brief Add function overload parameter chunks to the given code completion
3032 static void AddOverloadParameterChunks(ASTContext &Context,
3033 const PrintingPolicy &Policy,
3034 const FunctionDecl *Function,
3035 const FunctionProtoType *Prototype,
3036 CodeCompletionBuilder &Result,
3037 unsigned CurrentArg,
3039 bool InOptional = false) {
3040 bool FirstParameter = true;
3041 unsigned NumParams = Function ? Function->getNumParams()
3042 : Prototype->getNumParams();
3044 for (unsigned P = Start; P != NumParams; ++P) {
3045 if (Function && Function->getParamDecl(P)->hasDefaultArg() && !InOptional) {
3046 // When we see an optional default argument, put that argument and
3047 // the remaining default arguments into a new, optional string.
3048 CodeCompletionBuilder Opt(Result.getAllocator(),
3049 Result.getCodeCompletionTUInfo());
3050 if (!FirstParameter)
3051 Opt.AddChunk(CodeCompletionString::CK_Comma);
3052 // Optional sections are nested.
3053 AddOverloadParameterChunks(Context, Policy, Function, Prototype, Opt,
3054 CurrentArg, P, /*InOptional=*/true);
3055 Result.AddOptionalChunk(Opt.TakeString());
3060 FirstParameter = false;
3062 Result.AddChunk(CodeCompletionString::CK_Comma);
3066 // Format the placeholder string.
3067 std::string Placeholder;
3069 const ParmVarDecl *Param = Function->getParamDecl(P);
3070 Placeholder = FormatFunctionParameter(Policy, Param);
3071 if (Param->hasDefaultArg())
3072 Placeholder += GetDefaultValueString(Param, Context.getSourceManager(), Context.getLangOpts());
3074 Placeholder = Prototype->getParamType(P).getAsString(Policy);
3077 if (P == CurrentArg)
3078 Result.AddCurrentParameterChunk(
3079 Result.getAllocator().CopyString(Placeholder));
3081 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Placeholder));
3084 if (Prototype && Prototype->isVariadic()) {
3085 CodeCompletionBuilder Opt(Result.getAllocator(),
3086 Result.getCodeCompletionTUInfo());
3087 if (!FirstParameter)
3088 Opt.AddChunk(CodeCompletionString::CK_Comma);
3090 if (CurrentArg < NumParams)
3091 Opt.AddPlaceholderChunk("...");
3093 Opt.AddCurrentParameterChunk("...");
3095 Result.AddOptionalChunk(Opt.TakeString());
3099 CodeCompletionString *
3100 CodeCompleteConsumer::OverloadCandidate::CreateSignatureString(
3101 unsigned CurrentArg, Sema &S,
3102 CodeCompletionAllocator &Allocator,
3103 CodeCompletionTUInfo &CCTUInfo,
3104 bool IncludeBriefComments) const {
3105 PrintingPolicy Policy = getCompletionPrintingPolicy(S);
3107 // FIXME: Set priority, availability appropriately.
3108 CodeCompletionBuilder Result(Allocator,CCTUInfo, 1, CXAvailability_Available);
3109 FunctionDecl *FDecl = getFunction();
3110 const FunctionProtoType *Proto
3111 = dyn_cast<FunctionProtoType>(getFunctionType());
3112 if (!FDecl && !Proto) {
3113 // Function without a prototype. Just give the return type and a
3114 // highlighted ellipsis.
3115 const FunctionType *FT = getFunctionType();
3116 Result.AddResultTypeChunk(Result.getAllocator().CopyString(
3117 FT->getReturnType().getAsString(Policy)));
3118 Result.AddChunk(CodeCompletionString::CK_LeftParen);
3119 Result.AddChunk(CodeCompletionString::CK_CurrentParameter, "...");
3120 Result.AddChunk(CodeCompletionString::CK_RightParen);
3121 return Result.TakeString();
3125 if (IncludeBriefComments && CurrentArg < FDecl->getNumParams())
3126 if (auto RC = S.getASTContext().getRawCommentForAnyRedecl(
3127 FDecl->getParamDecl(CurrentArg)))
3128 Result.addBriefComment(RC->getBriefText(S.getASTContext()));
3129 AddResultTypeChunk(S.Context, Policy, FDecl, QualType(), Result);
3130 Result.AddTextChunk(
3131 Result.getAllocator().CopyString(FDecl->getNameAsString()));
3133 Result.AddResultTypeChunk(
3134 Result.getAllocator().CopyString(
3135 Proto->getReturnType().getAsString(Policy)));
3138 Result.AddChunk(CodeCompletionString::CK_LeftParen);
3139 AddOverloadParameterChunks(S.getASTContext(), Policy, FDecl, Proto, Result,
3141 Result.AddChunk(CodeCompletionString::CK_RightParen);
3143 return Result.TakeString();
3146 unsigned clang::getMacroUsagePriority(StringRef MacroName,
3147 const LangOptions &LangOpts,
3148 bool PreferredTypeIsPointer) {
3149 unsigned Priority = CCP_Macro;
3151 // Treat the "nil", "Nil" and "NULL" macros as null pointer constants.
3152 if (MacroName.equals("nil") || MacroName.equals("NULL") ||
3153 MacroName.equals("Nil")) {
3154 Priority = CCP_Constant;
3155 if (PreferredTypeIsPointer)
3156 Priority = Priority / CCF_SimilarTypeMatch;
3158 // Treat "YES", "NO", "true", and "false" as constants.
3159 else if (MacroName.equals("YES") || MacroName.equals("NO") ||
3160 MacroName.equals("true") || MacroName.equals("false"))
3161 Priority = CCP_Constant;
3162 // Treat "bool" as a type.
3163 else if (MacroName.equals("bool"))
3164 Priority = CCP_Type + (LangOpts.ObjC1? CCD_bool_in_ObjC : 0);
3170 CXCursorKind clang::getCursorKindForDecl(const Decl *D) {
3172 return CXCursor_UnexposedDecl;
3174 switch (D->getKind()) {
3175 case Decl::Enum: return CXCursor_EnumDecl;
3176 case Decl::EnumConstant: return CXCursor_EnumConstantDecl;
3177 case Decl::Field: return CXCursor_FieldDecl;
3178 case Decl::Function:
3179 return CXCursor_FunctionDecl;
3180 case Decl::ObjCCategory: return CXCursor_ObjCCategoryDecl;
3181 case Decl::ObjCCategoryImpl: return CXCursor_ObjCCategoryImplDecl;
3182 case Decl::ObjCImplementation: return CXCursor_ObjCImplementationDecl;
3184 case Decl::ObjCInterface: return CXCursor_ObjCInterfaceDecl;
3185 case Decl::ObjCIvar: return CXCursor_ObjCIvarDecl;
3186 case Decl::ObjCMethod:
3187 return cast<ObjCMethodDecl>(D)->isInstanceMethod()
3188 ? CXCursor_ObjCInstanceMethodDecl : CXCursor_ObjCClassMethodDecl;
3189 case Decl::CXXMethod: return CXCursor_CXXMethod;
3190 case Decl::CXXConstructor: return CXCursor_Constructor;
3191 case Decl::CXXDestructor: return CXCursor_Destructor;
3192 case Decl::CXXConversion: return CXCursor_ConversionFunction;
3193 case Decl::ObjCProperty: return CXCursor_ObjCPropertyDecl;
3194 case Decl::ObjCProtocol: return CXCursor_ObjCProtocolDecl;
3195 case Decl::ParmVar: return CXCursor_ParmDecl;
3196 case Decl::Typedef: return CXCursor_TypedefDecl;
3197 case Decl::TypeAlias: return CXCursor_TypeAliasDecl;
3198 case Decl::TypeAliasTemplate: return CXCursor_TypeAliasTemplateDecl;
3199 case Decl::Var: return CXCursor_VarDecl;
3200 case Decl::Namespace: return CXCursor_Namespace;
3201 case Decl::NamespaceAlias: return CXCursor_NamespaceAlias;
3202 case Decl::TemplateTypeParm: return CXCursor_TemplateTypeParameter;
3203 case Decl::NonTypeTemplateParm:return CXCursor_NonTypeTemplateParameter;
3204 case Decl::TemplateTemplateParm:return CXCursor_TemplateTemplateParameter;
3205 case Decl::FunctionTemplate: return CXCursor_FunctionTemplate;
3206 case Decl::ClassTemplate: return CXCursor_ClassTemplate;
3207 case Decl::AccessSpec: return CXCursor_CXXAccessSpecifier;
3208 case Decl::ClassTemplatePartialSpecialization:
3209 return CXCursor_ClassTemplatePartialSpecialization;
3210 case Decl::UsingDirective: return CXCursor_UsingDirective;
3211 case Decl::StaticAssert: return CXCursor_StaticAssert;
3212 case Decl::Friend: return CXCursor_FriendDecl;
3213 case Decl::TranslationUnit: return CXCursor_TranslationUnit;
3216 case Decl::UnresolvedUsingValue:
3217 case Decl::UnresolvedUsingTypename:
3218 return CXCursor_UsingDeclaration;
3220 case Decl::ObjCPropertyImpl:
3221 switch (cast<ObjCPropertyImplDecl>(D)->getPropertyImplementation()) {
3222 case ObjCPropertyImplDecl::Dynamic:
3223 return CXCursor_ObjCDynamicDecl;
3225 case ObjCPropertyImplDecl::Synthesize:
3226 return CXCursor_ObjCSynthesizeDecl;
3230 return CXCursor_ModuleImportDecl;
3232 case Decl::ObjCTypeParam: return CXCursor_TemplateTypeParameter;
3235 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
3236 switch (TD->getTagKind()) {
3237 case TTK_Interface: // fall through
3238 case TTK_Struct: return CXCursor_StructDecl;
3239 case TTK_Class: return CXCursor_ClassDecl;
3240 case TTK_Union: return CXCursor_UnionDecl;
3241 case TTK_Enum: return CXCursor_EnumDecl;
3246 return CXCursor_UnexposedDecl;
3249 static void AddMacroResults(Preprocessor &PP, ResultBuilder &Results,
3250 bool IncludeUndefined,
3251 bool TargetTypeIsPointer = false) {
3252 typedef CodeCompletionResult Result;
3254 Results.EnterNewScope();
3256 for (Preprocessor::macro_iterator M = PP.macro_begin(),
3257 MEnd = PP.macro_end();
3259 auto MD = PP.getMacroDefinition(M->first);
3260 if (IncludeUndefined || MD) {
3261 if (MacroInfo *MI = MD.getMacroInfo())
3262 if (MI->isUsedForHeaderGuard())
3265 Results.AddResult(Result(M->first,
3266 getMacroUsagePriority(M->first->getName(),
3268 TargetTypeIsPointer)));
3272 Results.ExitScope();
3276 static void AddPrettyFunctionResults(const LangOptions &LangOpts,
3277 ResultBuilder &Results) {
3278 typedef CodeCompletionResult Result;
3280 Results.EnterNewScope();
3282 Results.AddResult(Result("__PRETTY_FUNCTION__", CCP_Constant));
3283 Results.AddResult(Result("__FUNCTION__", CCP_Constant));
3284 if (LangOpts.C99 || LangOpts.CPlusPlus11)
3285 Results.AddResult(Result("__func__", CCP_Constant));
3286 Results.ExitScope();
3289 static void HandleCodeCompleteResults(Sema *S,
3290 CodeCompleteConsumer *CodeCompleter,
3291 CodeCompletionContext Context,
3292 CodeCompletionResult *Results,
3293 unsigned NumResults) {
3295 CodeCompleter->ProcessCodeCompleteResults(*S, Context, Results, NumResults);
3298 static enum CodeCompletionContext::Kind mapCodeCompletionContext(Sema &S,
3299 Sema::ParserCompletionContext PCC) {
3301 case Sema::PCC_Namespace:
3302 return CodeCompletionContext::CCC_TopLevel;
3304 case Sema::PCC_Class:
3305 return CodeCompletionContext::CCC_ClassStructUnion;
3307 case Sema::PCC_ObjCInterface:
3308 return CodeCompletionContext::CCC_ObjCInterface;
3310 case Sema::PCC_ObjCImplementation:
3311 return CodeCompletionContext::CCC_ObjCImplementation;
3313 case Sema::PCC_ObjCInstanceVariableList:
3314 return CodeCompletionContext::CCC_ObjCIvarList;
3316 case Sema::PCC_Template:
3317 case Sema::PCC_MemberTemplate:
3318 if (S.CurContext->isFileContext())
3319 return CodeCompletionContext::CCC_TopLevel;
3320 if (S.CurContext->isRecord())
3321 return CodeCompletionContext::CCC_ClassStructUnion;
3322 return CodeCompletionContext::CCC_Other;
3324 case Sema::PCC_RecoveryInFunction:
3325 return CodeCompletionContext::CCC_Recovery;
3327 case Sema::PCC_ForInit:
3328 if (S.getLangOpts().CPlusPlus || S.getLangOpts().C99 ||
3329 S.getLangOpts().ObjC1)
3330 return CodeCompletionContext::CCC_ParenthesizedExpression;
3332 return CodeCompletionContext::CCC_Expression;
3334 case Sema::PCC_Expression:
3335 case Sema::PCC_Condition:
3336 return CodeCompletionContext::CCC_Expression;
3338 case Sema::PCC_Statement:
3339 return CodeCompletionContext::CCC_Statement;
3341 case Sema::PCC_Type:
3342 return CodeCompletionContext::CCC_Type;
3344 case Sema::PCC_ParenthesizedExpression:
3345 return CodeCompletionContext::CCC_ParenthesizedExpression;
3347 case Sema::PCC_LocalDeclarationSpecifiers:
3348 return CodeCompletionContext::CCC_Type;
3351 llvm_unreachable("Invalid ParserCompletionContext!");
3354 /// \brief If we're in a C++ virtual member function, add completion results
3355 /// that invoke the functions we override, since it's common to invoke the
3356 /// overridden function as well as adding new functionality.
3358 /// \param S The semantic analysis object for which we are generating results.
3360 /// \param InContext This context in which the nested-name-specifier preceding
3361 /// the code-completion point
3362 static void MaybeAddOverrideCalls(Sema &S, DeclContext *InContext,
3363 ResultBuilder &Results) {
3364 // Look through blocks.
3365 DeclContext *CurContext = S.CurContext;
3366 while (isa<BlockDecl>(CurContext))
3367 CurContext = CurContext->getParent();
3370 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(CurContext);
3371 if (!Method || !Method->isVirtual())
3374 // We need to have names for all of the parameters, if we're going to
3375 // generate a forwarding call.
3376 for (auto P : Method->parameters())
3377 if (!P->getDeclName())
3380 PrintingPolicy Policy = getCompletionPrintingPolicy(S);
3381 for (const CXXMethodDecl *Overridden : Method->overridden_methods()) {
3382 CodeCompletionBuilder Builder(Results.getAllocator(),
3383 Results.getCodeCompletionTUInfo());
3384 if (Overridden->getCanonicalDecl() == Method->getCanonicalDecl())
3387 // If we need a nested-name-specifier, add one now.
3389 NestedNameSpecifier *NNS
3390 = getRequiredQualification(S.Context, CurContext,
3391 Overridden->getDeclContext());
3394 llvm::raw_string_ostream OS(Str);
3395 NNS->print(OS, Policy);
3396 Builder.AddTextChunk(Results.getAllocator().CopyString(OS.str()));
3398 } else if (!InContext->Equals(Overridden->getDeclContext()))
3401 Builder.AddTypedTextChunk(Results.getAllocator().CopyString(
3402 Overridden->getNameAsString()));
3403 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
3404 bool FirstParam = true;
3405 for (auto P : Method->parameters()) {
3409 Builder.AddChunk(CodeCompletionString::CK_Comma);
3411 Builder.AddPlaceholderChunk(
3412 Results.getAllocator().CopyString(P->getIdentifier()->getName()));
3414 Builder.AddChunk(CodeCompletionString::CK_RightParen);
3415 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
3416 CCP_SuperCompletion,
3418 CXAvailability_Available,
3420 Results.Ignore(Overridden);
3424 void Sema::CodeCompleteModuleImport(SourceLocation ImportLoc,
3425 ModuleIdPath Path) {
3426 typedef CodeCompletionResult Result;
3427 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3428 CodeCompleter->getCodeCompletionTUInfo(),
3429 CodeCompletionContext::CCC_Other);
3430 Results.EnterNewScope();
3432 CodeCompletionAllocator &Allocator = Results.getAllocator();
3433 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
3434 typedef CodeCompletionResult Result;
3436 // Enumerate all top-level modules.
3437 SmallVector<Module *, 8> Modules;
3438 PP.getHeaderSearchInfo().collectAllModules(Modules);
3439 for (unsigned I = 0, N = Modules.size(); I != N; ++I) {
3440 Builder.AddTypedTextChunk(
3441 Builder.getAllocator().CopyString(Modules[I]->Name));
3442 Results.AddResult(Result(Builder.TakeString(),
3444 CXCursor_ModuleImportDecl,
3445 Modules[I]->isAvailable()
3446 ? CXAvailability_Available
3447 : CXAvailability_NotAvailable));
3449 } else if (getLangOpts().Modules) {
3450 // Load the named module.
3451 Module *Mod = PP.getModuleLoader().loadModule(ImportLoc, Path,
3453 /*IsInclusionDirective=*/false);
3454 // Enumerate submodules.
3456 for (Module::submodule_iterator Sub = Mod->submodule_begin(),
3457 SubEnd = Mod->submodule_end();
3458 Sub != SubEnd; ++Sub) {
3460 Builder.AddTypedTextChunk(
3461 Builder.getAllocator().CopyString((*Sub)->Name));
3462 Results.AddResult(Result(Builder.TakeString(),
3464 CXCursor_ModuleImportDecl,
3465 (*Sub)->isAvailable()
3466 ? CXAvailability_Available
3467 : CXAvailability_NotAvailable));
3471 Results.ExitScope();
3472 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
3473 Results.data(),Results.size());
3476 void Sema::CodeCompleteOrdinaryName(Scope *S,
3477 ParserCompletionContext CompletionContext) {
3478 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3479 CodeCompleter->getCodeCompletionTUInfo(),
3480 mapCodeCompletionContext(*this, CompletionContext));
3481 Results.EnterNewScope();
3483 // Determine how to filter results, e.g., so that the names of
3484 // values (functions, enumerators, function templates, etc.) are
3485 // only allowed where we can have an expression.
3486 switch (CompletionContext) {
3489 case PCC_ObjCInterface:
3490 case PCC_ObjCImplementation:
3491 case PCC_ObjCInstanceVariableList:
3493 case PCC_MemberTemplate:
3495 case PCC_LocalDeclarationSpecifiers:
3496 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
3500 case PCC_ParenthesizedExpression:
3501 case PCC_Expression:
3504 if (WantTypesInContext(CompletionContext, getLangOpts()))
3505 Results.setFilter(&ResultBuilder::IsOrdinaryName);
3507 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
3509 if (getLangOpts().CPlusPlus)
3510 MaybeAddOverrideCalls(*this, /*InContext=*/nullptr, Results);
3513 case PCC_RecoveryInFunction:
3518 // If we are in a C++ non-static member function, check the qualifiers on
3519 // the member function to filter/prioritize the results list.
3520 if (CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext))
3521 if (CurMethod->isInstance())
3522 Results.setObjectTypeQualifiers(
3523 Qualifiers::fromCVRMask(CurMethod->getTypeQualifiers()));
3525 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3526 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3527 CodeCompleter->includeGlobals());
3529 AddOrdinaryNameResults(CompletionContext, S, *this, Results);
3530 Results.ExitScope();
3532 switch (CompletionContext) {
3533 case PCC_ParenthesizedExpression:
3534 case PCC_Expression:
3536 case PCC_RecoveryInFunction:
3537 if (S->getFnParent())
3538 AddPrettyFunctionResults(getLangOpts(), Results);
3543 case PCC_ObjCInterface:
3544 case PCC_ObjCImplementation:
3545 case PCC_ObjCInstanceVariableList:
3547 case PCC_MemberTemplate:
3551 case PCC_LocalDeclarationSpecifiers:
3555 if (CodeCompleter->includeMacros())
3556 AddMacroResults(PP, Results, false);
3558 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
3559 Results.data(),Results.size());
3562 static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
3563 ParsedType Receiver,
3564 ArrayRef<IdentifierInfo *> SelIdents,
3565 bool AtArgumentExpression,
3567 ResultBuilder &Results);
3569 void Sema::CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
3570 bool AllowNonIdentifiers,
3571 bool AllowNestedNameSpecifiers) {
3572 typedef CodeCompletionResult Result;
3573 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3574 CodeCompleter->getCodeCompletionTUInfo(),
3575 AllowNestedNameSpecifiers
3576 ? CodeCompletionContext::CCC_PotentiallyQualifiedName
3577 : CodeCompletionContext::CCC_Name);
3578 Results.EnterNewScope();
3580 // Type qualifiers can come after names.
3581 Results.AddResult(Result("const"));
3582 Results.AddResult(Result("volatile"));
3583 if (getLangOpts().C99)
3584 Results.AddResult(Result("restrict"));
3586 if (getLangOpts().CPlusPlus) {
3587 if (getLangOpts().CPlusPlus11 &&
3588 (DS.getTypeSpecType() == DeclSpec::TST_class ||
3589 DS.getTypeSpecType() == DeclSpec::TST_struct))
3590 Results.AddResult("final");
3592 if (AllowNonIdentifiers) {
3593 Results.AddResult(Result("operator"));
3596 // Add nested-name-specifiers.
3597 if (AllowNestedNameSpecifiers) {
3598 Results.allowNestedNameSpecifiers();
3599 Results.setFilter(&ResultBuilder::IsImpossibleToSatisfy);
3600 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3601 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer,
3602 CodeCompleter->includeGlobals());
3603 Results.setFilter(nullptr);
3606 Results.ExitScope();
3608 // If we're in a context where we might have an expression (rather than a
3609 // declaration), and what we've seen so far is an Objective-C type that could
3610 // be a receiver of a class message, this may be a class message send with
3611 // the initial opening bracket '[' missing. Add appropriate completions.
3612 if (AllowNonIdentifiers && !AllowNestedNameSpecifiers &&
3613 DS.getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier &&
3614 DS.getTypeSpecType() == DeclSpec::TST_typename &&
3615 DS.getTypeSpecComplex() == DeclSpec::TSC_unspecified &&
3616 DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
3617 !DS.isTypeAltiVecVector() &&
3619 (S->getFlags() & Scope::DeclScope) != 0 &&
3620 (S->getFlags() & (Scope::ClassScope | Scope::TemplateParamScope |
3621 Scope::FunctionPrototypeScope |
3622 Scope::AtCatchScope)) == 0) {
3623 ParsedType T = DS.getRepAsType();
3624 if (!T.get().isNull() && T.get()->isObjCObjectOrInterfaceType())
3625 AddClassMessageCompletions(*this, S, T, None, false, false, Results);
3628 // Note that we intentionally suppress macro results here, since we do not
3629 // encourage using macros to produce the names of entities.
3631 HandleCodeCompleteResults(this, CodeCompleter,
3632 Results.getCompletionContext(),
3633 Results.data(), Results.size());
3636 struct Sema::CodeCompleteExpressionData {
3637 CodeCompleteExpressionData(QualType PreferredType = QualType())
3638 : PreferredType(PreferredType), IntegralConstantExpression(false),
3639 ObjCCollection(false) { }
3641 QualType PreferredType;
3642 bool IntegralConstantExpression;
3643 bool ObjCCollection;
3644 SmallVector<Decl *, 4> IgnoreDecls;
3647 /// \brief Perform code-completion in an expression context when we know what
3648 /// type we're looking for.
3649 void Sema::CodeCompleteExpression(Scope *S,
3650 const CodeCompleteExpressionData &Data) {
3651 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3652 CodeCompleter->getCodeCompletionTUInfo(),
3653 CodeCompletionContext::CCC_Expression);
3654 if (Data.ObjCCollection)
3655 Results.setFilter(&ResultBuilder::IsObjCCollection);
3656 else if (Data.IntegralConstantExpression)
3657 Results.setFilter(&ResultBuilder::IsIntegralConstantValue);
3658 else if (WantTypesInContext(PCC_Expression, getLangOpts()))
3659 Results.setFilter(&ResultBuilder::IsOrdinaryName);
3661 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
3663 if (!Data.PreferredType.isNull())
3664 Results.setPreferredType(Data.PreferredType.getNonReferenceType());
3666 // Ignore any declarations that we were told that we don't care about.
3667 for (unsigned I = 0, N = Data.IgnoreDecls.size(); I != N; ++I)
3668 Results.Ignore(Data.IgnoreDecls[I]);
3670 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3671 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3672 CodeCompleter->includeGlobals());
3674 Results.EnterNewScope();
3675 AddOrdinaryNameResults(PCC_Expression, S, *this, Results);
3676 Results.ExitScope();
3678 bool PreferredTypeIsPointer = false;
3679 if (!Data.PreferredType.isNull())
3680 PreferredTypeIsPointer = Data.PreferredType->isAnyPointerType()
3681 || Data.PreferredType->isMemberPointerType()
3682 || Data.PreferredType->isBlockPointerType();
3684 if (S->getFnParent() &&
3685 !Data.ObjCCollection &&
3686 !Data.IntegralConstantExpression)
3687 AddPrettyFunctionResults(getLangOpts(), Results);
3689 if (CodeCompleter->includeMacros())
3690 AddMacroResults(PP, Results, false, PreferredTypeIsPointer);
3691 HandleCodeCompleteResults(this, CodeCompleter,
3692 CodeCompletionContext(CodeCompletionContext::CCC_Expression,
3693 Data.PreferredType),
3694 Results.data(),Results.size());
3697 void Sema::CodeCompletePostfixExpression(Scope *S, ExprResult E) {
3699 CodeCompleteOrdinaryName(S, PCC_RecoveryInFunction);
3700 else if (getLangOpts().ObjC1)
3701 CodeCompleteObjCInstanceMessage(S, E.get(), None, false);
3704 /// \brief The set of properties that have already been added, referenced by
3706 typedef llvm::SmallPtrSet<IdentifierInfo*, 16> AddedPropertiesSet;
3708 /// \brief Retrieve the container definition, if any?
3709 static ObjCContainerDecl *getContainerDef(ObjCContainerDecl *Container) {
3710 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
3711 if (Interface->hasDefinition())
3712 return Interface->getDefinition();
3717 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
3718 if (Protocol->hasDefinition())
3719 return Protocol->getDefinition();
3726 /// \brief Adds a block invocation code completion result for the given block
3727 /// declaration \p BD.
3728 static void AddObjCBlockCall(ASTContext &Context, const PrintingPolicy &Policy,
3729 CodeCompletionBuilder &Builder,
3730 const NamedDecl *BD,
3731 const FunctionTypeLoc &BlockLoc,
3732 const FunctionProtoTypeLoc &BlockProtoLoc) {
3733 Builder.AddResultTypeChunk(
3734 GetCompletionTypeString(BlockLoc.getReturnLoc().getType(), Context,
3735 Policy, Builder.getAllocator()));
3737 AddTypedNameChunk(Context, Policy, BD, Builder);
3738 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
3740 if (BlockProtoLoc && BlockProtoLoc.getTypePtr()->isVariadic()) {
3741 Builder.AddPlaceholderChunk("...");
3743 for (unsigned I = 0, N = BlockLoc.getNumParams(); I != N; ++I) {
3745 Builder.AddChunk(CodeCompletionString::CK_Comma);
3747 // Format the placeholder string.
3748 std::string PlaceholderStr =
3749 FormatFunctionParameter(Policy, BlockLoc.getParam(I));
3751 if (I == N - 1 && BlockProtoLoc &&
3752 BlockProtoLoc.getTypePtr()->isVariadic())
3753 PlaceholderStr += ", ...";
3755 // Add the placeholder string.
3756 Builder.AddPlaceholderChunk(
3757 Builder.getAllocator().CopyString(PlaceholderStr));
3761 Builder.AddChunk(CodeCompletionString::CK_RightParen);
3764 static void AddObjCProperties(
3765 const CodeCompletionContext &CCContext, ObjCContainerDecl *Container,
3766 bool AllowCategories, bool AllowNullaryMethods, DeclContext *CurContext,
3767 AddedPropertiesSet &AddedProperties, ResultBuilder &Results,
3768 bool IsBaseExprStatement = false, bool IsClassProperty = false) {
3769 typedef CodeCompletionResult Result;
3771 // Retrieve the definition.
3772 Container = getContainerDef(Container);
3774 // Add properties in this container.
3775 const auto AddProperty = [&](const ObjCPropertyDecl *P) {
3776 if (!AddedProperties.insert(P->getIdentifier()).second)
3779 // FIXME: Provide block invocation completion for non-statement
3781 if (!P->getType().getTypePtr()->isBlockPointerType() ||
3782 !IsBaseExprStatement) {
3783 Results.MaybeAddResult(Result(P, Results.getBasePriority(P), nullptr),
3788 // Block setter and invocation completion is provided only when we are able
3789 // to find the FunctionProtoTypeLoc with parameter names for the block.
3790 FunctionTypeLoc BlockLoc;
3791 FunctionProtoTypeLoc BlockProtoLoc;
3792 findTypeLocationForBlockDecl(P->getTypeSourceInfo(), BlockLoc,
3795 Results.MaybeAddResult(Result(P, Results.getBasePriority(P), nullptr),
3800 // The default completion result for block properties should be the block
3801 // invocation completion when the base expression is a statement.
3802 CodeCompletionBuilder Builder(Results.getAllocator(),
3803 Results.getCodeCompletionTUInfo());
3804 AddObjCBlockCall(Container->getASTContext(),
3805 getCompletionPrintingPolicy(Results.getSema()), Builder, P,
3806 BlockLoc, BlockProtoLoc);
3807 Results.MaybeAddResult(
3808 Result(Builder.TakeString(), P, Results.getBasePriority(P)),
3811 // Provide additional block setter completion iff the base expression is a
3812 // statement and the block property is mutable.
3813 if (!P->isReadOnly()) {
3814 CodeCompletionBuilder Builder(Results.getAllocator(),
3815 Results.getCodeCompletionTUInfo());
3816 AddResultTypeChunk(Container->getASTContext(),
3817 getCompletionPrintingPolicy(Results.getSema()), P,
3818 CCContext.getBaseType(), Builder);
3819 Builder.AddTypedTextChunk(
3820 Results.getAllocator().CopyString(P->getName()));
3821 Builder.AddChunk(CodeCompletionString::CK_Equal);
3823 std::string PlaceholderStr = formatBlockPlaceholder(
3824 getCompletionPrintingPolicy(Results.getSema()), P, BlockLoc,
3825 BlockProtoLoc, /*SuppressBlockName=*/true);
3826 // Add the placeholder string.
3827 Builder.AddPlaceholderChunk(
3828 Builder.getAllocator().CopyString(PlaceholderStr));
3830 // When completing blocks properties that return void the default
3831 // property completion result should show up before the setter,
3832 // otherwise the setter completion should show up before the default
3833 // property completion, as we normally want to use the result of the
3835 Results.MaybeAddResult(
3836 Result(Builder.TakeString(), P,
3837 Results.getBasePriority(P) +
3838 (BlockLoc.getTypePtr()->getReturnType()->isVoidType()
3839 ? CCD_BlockPropertySetter
3840 : -CCD_BlockPropertySetter)),
3845 if (IsClassProperty) {
3846 for (const auto *P : Container->class_properties())
3849 for (const auto *P : Container->instance_properties())
3853 // Add nullary methods or implicit class properties
3854 if (AllowNullaryMethods) {
3855 ASTContext &Context = Container->getASTContext();
3856 PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema());
3857 // Adds a method result
3858 const auto AddMethod = [&](const ObjCMethodDecl *M) {
3859 IdentifierInfo *Name = M->getSelector().getIdentifierInfoForSlot(0);
3862 if (!AddedProperties.insert(Name).second)
3864 CodeCompletionBuilder Builder(Results.getAllocator(),
3865 Results.getCodeCompletionTUInfo());
3866 AddResultTypeChunk(Context, Policy, M, CCContext.getBaseType(), Builder);
3867 Builder.AddTypedTextChunk(
3868 Results.getAllocator().CopyString(Name->getName()));
3869 Results.MaybeAddResult(
3870 Result(Builder.TakeString(), M,
3871 CCP_MemberDeclaration + CCD_MethodAsProperty),
3875 if (IsClassProperty) {
3876 for (const auto *M : Container->methods()) {
3877 // Gather the class method that can be used as implicit property
3878 // getters. Methods with arguments or methods that return void aren't
3879 // added to the results as they can't be used as a getter.
3880 if (!M->getSelector().isUnarySelector() ||
3881 M->getReturnType()->isVoidType() || M->isInstanceMethod())
3886 for (auto *M : Container->methods()) {
3887 if (M->getSelector().isUnarySelector())
3893 // Add properties in referenced protocols.
3894 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
3895 for (auto *P : Protocol->protocols())
3896 AddObjCProperties(CCContext, P, AllowCategories, AllowNullaryMethods,
3897 CurContext, AddedProperties, Results,
3898 IsBaseExprStatement, IsClassProperty);
3899 } else if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)){
3900 if (AllowCategories) {
3901 // Look through categories.
3902 for (auto *Cat : IFace->known_categories())
3903 AddObjCProperties(CCContext, Cat, AllowCategories, AllowNullaryMethods,
3904 CurContext, AddedProperties, Results,
3905 IsBaseExprStatement, IsClassProperty);
3908 // Look through protocols.
3909 for (auto *I : IFace->all_referenced_protocols())
3910 AddObjCProperties(CCContext, I, AllowCategories, AllowNullaryMethods,
3911 CurContext, AddedProperties, Results,
3912 IsBaseExprStatement, IsClassProperty);
3914 // Look in the superclass.
3915 if (IFace->getSuperClass())
3916 AddObjCProperties(CCContext, IFace->getSuperClass(), AllowCategories,
3917 AllowNullaryMethods, CurContext, AddedProperties,
3918 Results, IsBaseExprStatement, IsClassProperty);
3919 } else if (const ObjCCategoryDecl *Category
3920 = dyn_cast<ObjCCategoryDecl>(Container)) {
3921 // Look through protocols.
3922 for (auto *P : Category->protocols())
3923 AddObjCProperties(CCContext, P, AllowCategories, AllowNullaryMethods,
3924 CurContext, AddedProperties, Results,
3925 IsBaseExprStatement, IsClassProperty);
3929 static void AddRecordMembersCompletionResults(Sema &SemaRef,
3930 ResultBuilder &Results, Scope *S,
3933 // Indicate that we are performing a member access, and the cv-qualifiers
3934 // for the base object type.
3935 Results.setObjectTypeQualifiers(BaseType.getQualifiers());
3937 // Access to a C/C++ class, struct, or union.
3938 Results.allowNestedNameSpecifiers();
3939 CodeCompletionDeclConsumer Consumer(Results, SemaRef.CurContext);
3940 SemaRef.LookupVisibleDecls(RD, Sema::LookupMemberName, Consumer,
3941 SemaRef.CodeCompleter->includeGlobals(),
3942 /*IncludeDependentBases=*/true);
3944 if (SemaRef.getLangOpts().CPlusPlus) {
3945 if (!Results.empty()) {
3946 // The "template" keyword can follow "->" or "." in the grammar.
3947 // However, we only want to suggest the template keyword if something
3949 bool IsDependent = BaseType->isDependentType();
3951 for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent())
3952 if (DeclContext *Ctx = DepScope->getEntity()) {
3953 IsDependent = Ctx->isDependentContext();
3959 Results.AddResult(CodeCompletionResult("template"));
3964 void Sema::CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base,
3965 SourceLocation OpLoc, bool IsArrow,
3966 bool IsBaseExprStatement) {
3967 if (!Base || !CodeCompleter)
3970 ExprResult ConvertedBase = PerformMemberExprBaseConversion(Base, IsArrow);
3971 if (ConvertedBase.isInvalid())
3973 Base = ConvertedBase.get();
3975 QualType BaseType = Base->getType();
3978 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
3979 BaseType = Ptr->getPointeeType();
3980 else if (BaseType->isObjCObjectPointerType())
3986 enum CodeCompletionContext::Kind contextKind;
3989 contextKind = CodeCompletionContext::CCC_ArrowMemberAccess;
3992 if (BaseType->isObjCObjectPointerType() ||
3993 BaseType->isObjCObjectOrInterfaceType()) {
3994 contextKind = CodeCompletionContext::CCC_ObjCPropertyAccess;
3997 contextKind = CodeCompletionContext::CCC_DotMemberAccess;
4001 CodeCompletionContext CCContext(contextKind, BaseType);
4002 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4003 CodeCompleter->getCodeCompletionTUInfo(),
4005 &ResultBuilder::IsMember);
4006 Results.EnterNewScope();
4007 if (const RecordType *Record = BaseType->getAs<RecordType>()) {
4008 AddRecordMembersCompletionResults(*this, Results, S, BaseType,
4010 } else if (const auto *TST = BaseType->getAs<TemplateSpecializationType>()) {
4011 TemplateName TN = TST->getTemplateName();
4012 if (const auto *TD =
4013 dyn_cast_or_null<ClassTemplateDecl>(TN.getAsTemplateDecl())) {
4014 CXXRecordDecl *RD = TD->getTemplatedDecl();
4015 AddRecordMembersCompletionResults(*this, Results, S, BaseType, RD);
4017 } else if (const auto *ICNT = BaseType->getAs<InjectedClassNameType>()) {
4018 if (auto *RD = ICNT->getDecl())
4019 AddRecordMembersCompletionResults(*this, Results, S, BaseType, RD);
4020 } else if (!IsArrow && BaseType->isObjCObjectPointerType()) {
4021 // Objective-C property reference.
4022 AddedPropertiesSet AddedProperties;
4024 if (const ObjCObjectPointerType *ObjCPtr =
4025 BaseType->getAsObjCInterfacePointerType()) {
4026 // Add property results based on our interface.
4027 assert(ObjCPtr && "Non-NULL pointer guaranteed above!");
4028 AddObjCProperties(CCContext, ObjCPtr->getInterfaceDecl(), true,
4029 /*AllowNullaryMethods=*/true, CurContext,
4030 AddedProperties, Results, IsBaseExprStatement);
4033 // Add properties from the protocols in a qualified interface.
4034 for (auto *I : BaseType->getAs<ObjCObjectPointerType>()->quals())
4035 AddObjCProperties(CCContext, I, true, /*AllowNullaryMethods=*/true,
4036 CurContext, AddedProperties, Results,
4037 IsBaseExprStatement);
4038 } else if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
4039 (!IsArrow && BaseType->isObjCObjectType())) {
4040 // Objective-C instance variable access.
4041 ObjCInterfaceDecl *Class = nullptr;
4042 if (const ObjCObjectPointerType *ObjCPtr
4043 = BaseType->getAs<ObjCObjectPointerType>())
4044 Class = ObjCPtr->getInterfaceDecl();
4046 Class = BaseType->getAs<ObjCObjectType>()->getInterface();
4048 // Add all ivars from this class and its superclasses.
4050 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4051 Results.setFilter(&ResultBuilder::IsObjCIvar);
4052 LookupVisibleDecls(Class, LookupMemberName, Consumer,
4053 CodeCompleter->includeGlobals());
4057 // FIXME: How do we cope with isa?
4059 Results.ExitScope();
4061 // Hand off the results found for code completion.
4062 HandleCodeCompleteResults(this, CodeCompleter,
4063 Results.getCompletionContext(),
4064 Results.data(),Results.size());
4067 void Sema::CodeCompleteObjCClassPropertyRefExpr(Scope *S,
4068 IdentifierInfo &ClassName,
4069 SourceLocation ClassNameLoc,
4070 bool IsBaseExprStatement) {
4071 IdentifierInfo *ClassNamePtr = &ClassName;
4072 ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(ClassNamePtr, ClassNameLoc);
4075 CodeCompletionContext CCContext(
4076 CodeCompletionContext::CCC_ObjCPropertyAccess);
4077 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4078 CodeCompleter->getCodeCompletionTUInfo(), CCContext,
4079 &ResultBuilder::IsMember);
4080 Results.EnterNewScope();
4081 AddedPropertiesSet AddedProperties;
4082 AddObjCProperties(CCContext, IFace, true,
4083 /*AllowNullaryMethods=*/true, CurContext, AddedProperties,
4084 Results, IsBaseExprStatement,
4085 /*IsClassProperty=*/true);
4086 Results.ExitScope();
4087 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4088 Results.data(), Results.size());
4091 void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) {
4095 ResultBuilder::LookupFilter Filter = nullptr;
4096 enum CodeCompletionContext::Kind ContextKind
4097 = CodeCompletionContext::CCC_Other;
4098 switch ((DeclSpec::TST)TagSpec) {
4099 case DeclSpec::TST_enum:
4100 Filter = &ResultBuilder::IsEnum;
4101 ContextKind = CodeCompletionContext::CCC_EnumTag;
4104 case DeclSpec::TST_union:
4105 Filter = &ResultBuilder::IsUnion;
4106 ContextKind = CodeCompletionContext::CCC_UnionTag;
4109 case DeclSpec::TST_struct:
4110 case DeclSpec::TST_class:
4111 case DeclSpec::TST_interface:
4112 Filter = &ResultBuilder::IsClassOrStruct;
4113 ContextKind = CodeCompletionContext::CCC_ClassOrStructTag;
4117 llvm_unreachable("Unknown type specifier kind in CodeCompleteTag");
4120 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4121 CodeCompleter->getCodeCompletionTUInfo(), ContextKind);
4122 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4124 // First pass: look for tags.
4125 Results.setFilter(Filter);
4126 LookupVisibleDecls(S, LookupTagName, Consumer,
4127 CodeCompleter->includeGlobals());
4129 if (CodeCompleter->includeGlobals()) {
4130 // Second pass: look for nested name specifiers.
4131 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
4132 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer);
4135 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4136 Results.data(),Results.size());
4139 static void AddTypeQualifierResults(DeclSpec &DS, ResultBuilder &Results,
4140 const LangOptions &LangOpts) {
4141 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_const))
4142 Results.AddResult("const");
4143 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_volatile))
4144 Results.AddResult("volatile");
4145 if (LangOpts.C99 && !(DS.getTypeQualifiers() & DeclSpec::TQ_restrict))
4146 Results.AddResult("restrict");
4147 if (LangOpts.C11 && !(DS.getTypeQualifiers() & DeclSpec::TQ_atomic))
4148 Results.AddResult("_Atomic");
4149 if (LangOpts.MSVCCompat && !(DS.getTypeQualifiers() & DeclSpec::TQ_unaligned))
4150 Results.AddResult("__unaligned");
4153 void Sema::CodeCompleteTypeQualifiers(DeclSpec &DS) {
4154 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4155 CodeCompleter->getCodeCompletionTUInfo(),
4156 CodeCompletionContext::CCC_TypeQualifiers);
4157 Results.EnterNewScope();
4158 AddTypeQualifierResults(DS, Results, LangOpts);
4159 Results.ExitScope();
4160 HandleCodeCompleteResults(this, CodeCompleter,
4161 Results.getCompletionContext(),
4162 Results.data(), Results.size());
4165 void Sema::CodeCompleteFunctionQualifiers(DeclSpec &DS, Declarator &D,
4166 const VirtSpecifiers *VS) {
4167 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4168 CodeCompleter->getCodeCompletionTUInfo(),
4169 CodeCompletionContext::CCC_TypeQualifiers);
4170 Results.EnterNewScope();
4171 AddTypeQualifierResults(DS, Results, LangOpts);
4172 if (LangOpts.CPlusPlus11) {
4173 Results.AddResult("noexcept");
4174 if (D.getContext() == DeclaratorContext::MemberContext &&
4175 !D.isCtorOrDtor() && !D.isStaticMember()) {
4176 if (!VS || !VS->isFinalSpecified())
4177 Results.AddResult("final");
4178 if (!VS || !VS->isOverrideSpecified())
4179 Results.AddResult("override");
4182 Results.ExitScope();
4183 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4184 Results.data(), Results.size());
4187 void Sema::CodeCompleteBracketDeclarator(Scope *S) {
4188 CodeCompleteExpression(S, QualType(getASTContext().getSizeType()));
4191 void Sema::CodeCompleteCase(Scope *S) {
4192 if (getCurFunction()->SwitchStack.empty() || !CodeCompleter)
4195 SwitchStmt *Switch = getCurFunction()->SwitchStack.back();
4196 QualType type = Switch->getCond()->IgnoreImplicit()->getType();
4197 if (!type->isEnumeralType()) {
4198 CodeCompleteExpressionData Data(type);
4199 Data.IntegralConstantExpression = true;
4200 CodeCompleteExpression(S, Data);
4204 // Code-complete the cases of a switch statement over an enumeration type
4205 // by providing the list of
4206 EnumDecl *Enum = type->castAs<EnumType>()->getDecl();
4207 if (EnumDecl *Def = Enum->getDefinition())
4210 // Determine which enumerators we have already seen in the switch statement.
4211 // FIXME: Ideally, we would also be able to look *past* the code-completion
4212 // token, in case we are code-completing in the middle of the switch and not
4213 // at the end. However, we aren't able to do so at the moment.
4214 llvm::SmallPtrSet<EnumConstantDecl *, 8> EnumeratorsSeen;
4215 NestedNameSpecifier *Qualifier = nullptr;
4216 for (SwitchCase *SC = Switch->getSwitchCaseList(); SC;
4217 SC = SC->getNextSwitchCase()) {
4218 CaseStmt *Case = dyn_cast<CaseStmt>(SC);
4222 Expr *CaseVal = Case->getLHS()->IgnoreParenCasts();
4223 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseVal))
4224 if (EnumConstantDecl *Enumerator
4225 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
4226 // We look into the AST of the case statement to determine which
4227 // enumerator was named. Alternatively, we could compute the value of
4228 // the integral constant expression, then compare it against the
4229 // values of each enumerator. However, value-based approach would not
4230 // work as well with C++ templates where enumerators declared within a
4231 // template are type- and value-dependent.
4232 EnumeratorsSeen.insert(Enumerator);
4234 // If this is a qualified-id, keep track of the nested-name-specifier
4235 // so that we can reproduce it as part of code completion, e.g.,
4237 // switch (TagD.getKind()) {
4238 // case TagDecl::TK_enum:
4242 // At the XXX, our completions are TagDecl::TK_union,
4243 // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
4244 // TK_struct, and TK_class.
4245 Qualifier = DRE->getQualifier();
4249 if (getLangOpts().CPlusPlus && !Qualifier && EnumeratorsSeen.empty()) {
4250 // If there are no prior enumerators in C++, check whether we have to
4251 // qualify the names of the enumerators that we suggest, because they
4252 // may not be visible in this scope.
4253 Qualifier = getRequiredQualification(Context, CurContext, Enum);
4256 // Add any enumerators that have not yet been mentioned.
4257 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4258 CodeCompleter->getCodeCompletionTUInfo(),
4259 CodeCompletionContext::CCC_Expression);
4260 Results.EnterNewScope();
4261 for (auto *E : Enum->enumerators()) {
4262 if (EnumeratorsSeen.count(E))
4265 CodeCompletionResult R(E, CCP_EnumInCase, Qualifier);
4266 Results.AddResult(R, CurContext, nullptr, false);
4268 Results.ExitScope();
4270 //We need to make sure we're setting the right context,
4271 //so only say we include macros if the code completer says we do
4272 enum CodeCompletionContext::Kind kind = CodeCompletionContext::CCC_Other;
4273 if (CodeCompleter->includeMacros()) {
4274 AddMacroResults(PP, Results, false);
4275 kind = CodeCompletionContext::CCC_OtherWithMacros;
4278 HandleCodeCompleteResults(this, CodeCompleter,
4280 Results.data(),Results.size());
4283 static bool anyNullArguments(ArrayRef<Expr *> Args) {
4284 if (Args.size() && !Args.data())
4287 for (unsigned I = 0; I != Args.size(); ++I)
4294 typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate;
4296 static void mergeCandidatesWithResults(Sema &SemaRef,
4297 SmallVectorImpl<ResultCandidate> &Results,
4298 OverloadCandidateSet &CandidateSet,
4299 SourceLocation Loc) {
4300 if (!CandidateSet.empty()) {
4301 // Sort the overload candidate set by placing the best overloads first.
4303 CandidateSet.begin(), CandidateSet.end(),
4304 [&](const OverloadCandidate &X, const OverloadCandidate &Y) {
4305 return isBetterOverloadCandidate(SemaRef, X, Y, Loc,
4306 CandidateSet.getKind());
4309 // Add the remaining viable overload candidates as code-completion results.
4310 for (auto &Candidate : CandidateSet) {
4311 if (Candidate.Function && Candidate.Function->isDeleted())
4313 if (Candidate.Viable)
4314 Results.push_back(ResultCandidate(Candidate.Function));
4319 /// \brief Get the type of the Nth parameter from a given set of overload
4321 static QualType getParamType(Sema &SemaRef,
4322 ArrayRef<ResultCandidate> Candidates,
4325 // Given the overloads 'Candidates' for a function call matching all arguments
4326 // up to N, return the type of the Nth parameter if it is the same for all
4327 // overload candidates.
4329 for (auto &Candidate : Candidates) {
4330 if (auto FType = Candidate.getFunctionType())
4331 if (auto Proto = dyn_cast<FunctionProtoType>(FType))
4332 if (N < Proto->getNumParams()) {
4333 if (ParamType.isNull())
4334 ParamType = Proto->getParamType(N);
4335 else if (!SemaRef.Context.hasSameUnqualifiedType(
4336 ParamType.getNonReferenceType(),
4337 Proto->getParamType(N).getNonReferenceType()))
4338 // Otherwise return a default-constructed QualType.
4346 static void CodeCompleteOverloadResults(Sema &SemaRef, Scope *S,
4347 MutableArrayRef<ResultCandidate> Candidates,
4348 unsigned CurrentArg,
4349 bool CompleteExpressionWithCurrentArg = true) {
4351 if (CompleteExpressionWithCurrentArg)
4352 ParamType = getParamType(SemaRef, Candidates, CurrentArg);
4354 if (ParamType.isNull())
4355 SemaRef.CodeCompleteOrdinaryName(S, Sema::PCC_Expression);
4357 SemaRef.CodeCompleteExpression(S, ParamType);
4359 if (!Candidates.empty())
4360 SemaRef.CodeCompleter->ProcessOverloadCandidates(SemaRef, CurrentArg,
4365 void Sema::CodeCompleteCall(Scope *S, Expr *Fn, ArrayRef<Expr *> Args) {
4369 // When we're code-completing for a call, we fall back to ordinary
4370 // name code-completion whenever we can't produce specific
4371 // results. We may want to revisit this strategy in the future,
4372 // e.g., by merging the two kinds of results.
4374 // FIXME: Provide support for variadic template functions.
4376 // Ignore type-dependent call expressions entirely.
4377 if (!Fn || Fn->isTypeDependent() || anyNullArguments(Args) ||
4378 Expr::hasAnyTypeDependentArguments(Args)) {
4379 CodeCompleteOrdinaryName(S, PCC_Expression);
4383 // Build an overload candidate set based on the functions we find.
4384 SourceLocation Loc = Fn->getExprLoc();
4385 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
4387 SmallVector<ResultCandidate, 8> Results;
4389 Expr *NakedFn = Fn->IgnoreParenCasts();
4390 if (auto ULE = dyn_cast<UnresolvedLookupExpr>(NakedFn))
4391 AddOverloadedCallCandidates(ULE, Args, CandidateSet,
4392 /*PartialOverloading=*/true);
4393 else if (auto UME = dyn_cast<UnresolvedMemberExpr>(NakedFn)) {
4394 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
4395 if (UME->hasExplicitTemplateArgs()) {
4396 UME->copyTemplateArgumentsInto(TemplateArgsBuffer);
4397 TemplateArgs = &TemplateArgsBuffer;
4400 // Add the base as first argument (use a nullptr if the base is implicit).
4401 SmallVector<Expr *, 12> ArgExprs(
4402 1, UME->isImplicitAccess() ? nullptr : UME->getBase());
4403 ArgExprs.append(Args.begin(), Args.end());
4404 UnresolvedSet<8> Decls;
4405 Decls.append(UME->decls_begin(), UME->decls_end());
4406 const bool FirstArgumentIsBase = !UME->isImplicitAccess() && UME->getBase();
4407 AddFunctionCandidates(Decls, ArgExprs, CandidateSet, TemplateArgs,
4408 /*SuppressUsedConversions=*/false,
4409 /*PartialOverloading=*/true,
4410 FirstArgumentIsBase);
4412 FunctionDecl *FD = nullptr;
4413 if (auto MCE = dyn_cast<MemberExpr>(NakedFn))
4414 FD = dyn_cast<FunctionDecl>(MCE->getMemberDecl());
4415 else if (auto DRE = dyn_cast<DeclRefExpr>(NakedFn))
4416 FD = dyn_cast<FunctionDecl>(DRE->getDecl());
4417 if (FD) { // We check whether it's a resolved function declaration.
4418 if (!getLangOpts().CPlusPlus ||
4419 !FD->getType()->getAs<FunctionProtoType>())
4420 Results.push_back(ResultCandidate(FD));
4422 AddOverloadCandidate(FD, DeclAccessPair::make(FD, FD->getAccess()),
4424 /*SuppressUsedConversions=*/false,
4425 /*PartialOverloading=*/true);
4427 } else if (auto DC = NakedFn->getType()->getAsCXXRecordDecl()) {
4428 // If expression's type is CXXRecordDecl, it may overload the function
4429 // call operator, so we check if it does and add them as candidates.
4430 // A complete type is needed to lookup for member function call operators.
4431 if (isCompleteType(Loc, NakedFn->getType())) {
4432 DeclarationName OpName = Context.DeclarationNames
4433 .getCXXOperatorName(OO_Call);
4434 LookupResult R(*this, OpName, Loc, LookupOrdinaryName);
4435 LookupQualifiedName(R, DC);
4436 R.suppressDiagnostics();
4437 SmallVector<Expr *, 12> ArgExprs(1, NakedFn);
4438 ArgExprs.append(Args.begin(), Args.end());
4439 AddFunctionCandidates(R.asUnresolvedSet(), ArgExprs, CandidateSet,
4440 /*ExplicitArgs=*/nullptr,
4441 /*SuppressUsedConversions=*/false,
4442 /*PartialOverloading=*/true);
4445 // Lastly we check whether expression's type is function pointer or
4447 QualType T = NakedFn->getType();
4448 if (!T->getPointeeType().isNull())
4449 T = T->getPointeeType();
4451 if (auto FP = T->getAs<FunctionProtoType>()) {
4452 if (!TooManyArguments(FP->getNumParams(), Args.size(),
4453 /*PartialOverloading=*/true) ||
4455 Results.push_back(ResultCandidate(FP));
4456 } else if (auto FT = T->getAs<FunctionType>())
4457 // No prototype and declaration, it may be a K & R style function.
4458 Results.push_back(ResultCandidate(FT));
4462 mergeCandidatesWithResults(*this, Results, CandidateSet, Loc);
4463 CodeCompleteOverloadResults(*this, S, Results, Args.size(),
4464 !CandidateSet.empty());
4467 void Sema::CodeCompleteConstructor(Scope *S, QualType Type, SourceLocation Loc,
4468 ArrayRef<Expr *> Args) {
4472 // A complete type is needed to lookup for constructors.
4473 if (!isCompleteType(Loc, Type))
4476 CXXRecordDecl *RD = Type->getAsCXXRecordDecl();
4478 CodeCompleteExpression(S, Type);
4482 // FIXME: Provide support for member initializers.
4483 // FIXME: Provide support for variadic template constructors.
4485 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
4487 for (auto C : LookupConstructors(RD)) {
4488 if (auto FD = dyn_cast<FunctionDecl>(C)) {
4489 AddOverloadCandidate(FD, DeclAccessPair::make(FD, C->getAccess()),
4491 /*SuppressUsedConversions=*/false,
4492 /*PartialOverloading=*/true);
4493 } else if (auto FTD = dyn_cast<FunctionTemplateDecl>(C)) {
4494 AddTemplateOverloadCandidate(FTD,
4495 DeclAccessPair::make(FTD, C->getAccess()),
4496 /*ExplicitTemplateArgs=*/nullptr,
4498 /*SuppressUsedConversions=*/false,
4499 /*PartialOverloading=*/true);
4503 SmallVector<ResultCandidate, 8> Results;
4504 mergeCandidatesWithResults(*this, Results, CandidateSet, Loc);
4505 CodeCompleteOverloadResults(*this, S, Results, Args.size());
4508 void Sema::CodeCompleteInitializer(Scope *S, Decl *D) {
4509 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
4511 CodeCompleteOrdinaryName(S, PCC_Expression);
4515 CodeCompleteExpression(S, VD->getType());
4518 void Sema::CodeCompleteReturn(Scope *S) {
4519 QualType ResultType;
4520 if (isa<BlockDecl>(CurContext)) {
4521 if (BlockScopeInfo *BSI = getCurBlock())
4522 ResultType = BSI->ReturnType;
4523 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(CurContext))
4524 ResultType = Function->getReturnType();
4525 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(CurContext))
4526 ResultType = Method->getReturnType();
4528 if (ResultType.isNull())
4529 CodeCompleteOrdinaryName(S, PCC_Expression);
4531 CodeCompleteExpression(S, ResultType);
4534 void Sema::CodeCompleteAfterIf(Scope *S) {
4535 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4536 CodeCompleter->getCodeCompletionTUInfo(),
4537 mapCodeCompletionContext(*this, PCC_Statement));
4538 Results.setFilter(&ResultBuilder::IsOrdinaryName);
4539 Results.EnterNewScope();
4541 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4542 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4543 CodeCompleter->includeGlobals());
4545 AddOrdinaryNameResults(PCC_Statement, S, *this, Results);
4548 CodeCompletionBuilder Builder(Results.getAllocator(),
4549 Results.getCodeCompletionTUInfo());
4550 Builder.AddTypedTextChunk("else");
4551 if (Results.includeCodePatterns()) {
4552 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4553 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4554 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
4555 Builder.AddPlaceholderChunk("statements");
4556 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
4557 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4559 Results.AddResult(Builder.TakeString());
4562 Builder.AddTypedTextChunk("else");
4563 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4564 Builder.AddTextChunk("if");
4565 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4566 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4567 if (getLangOpts().CPlusPlus)
4568 Builder.AddPlaceholderChunk("condition");
4570 Builder.AddPlaceholderChunk("expression");
4571 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4572 if (Results.includeCodePatterns()) {
4573 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4574 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4575 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
4576 Builder.AddPlaceholderChunk("statements");
4577 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
4578 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4580 Results.AddResult(Builder.TakeString());
4582 Results.ExitScope();
4584 if (S->getFnParent())
4585 AddPrettyFunctionResults(getLangOpts(), Results);
4587 if (CodeCompleter->includeMacros())
4588 AddMacroResults(PP, Results, false);
4590 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4591 Results.data(),Results.size());
4594 void Sema::CodeCompleteAssignmentRHS(Scope *S, Expr *LHS) {
4596 CodeCompleteExpression(S, static_cast<Expr *>(LHS)->getType());
4598 CodeCompleteOrdinaryName(S, PCC_Expression);
4601 void Sema::CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
4602 bool EnteringContext) {
4603 if (SS.isEmpty() || !CodeCompleter)
4606 // We want to keep the scope specifier even if it's invalid (e.g. the scope
4607 // "a::b::" is not corresponding to any context/namespace in the AST), since
4608 // it can be useful for global code completion which have information about
4609 // contexts/symbols that are not in the AST.
4610 if (SS.isInvalid()) {
4611 CodeCompletionContext CC(CodeCompletionContext::CCC_Name);
4612 CC.setCXXScopeSpecifier(SS);
4613 HandleCodeCompleteResults(this, CodeCompleter, CC, nullptr, 0);
4616 // Always pretend to enter a context to ensure that a dependent type
4617 // resolves to a dependent record.
4618 DeclContext *Ctx = computeDeclContext(SS, /*EnteringContext=*/true);
4622 // Try to instantiate any non-dependent declaration contexts before
4624 if (!isDependentScopeSpecifier(SS) && RequireCompleteDeclContext(SS, Ctx))
4627 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4628 CodeCompleter->getCodeCompletionTUInfo(),
4629 CodeCompletionContext::CCC_Name);
4630 Results.EnterNewScope();
4632 // The "template" keyword can follow "::" in the grammar, but only
4633 // put it into the grammar if the nested-name-specifier is dependent.
4634 NestedNameSpecifier *NNS = SS.getScopeRep();
4635 if (!Results.empty() && NNS->isDependent())
4636 Results.AddResult("template");
4638 // Add calls to overridden virtual functions, if there are any.
4640 // FIXME: This isn't wonderful, because we don't know whether we're actually
4641 // in a context that permits expressions. This is a general issue with
4642 // qualified-id completions.
4643 if (!EnteringContext)
4644 MaybeAddOverrideCalls(*this, Ctx, Results);
4645 Results.ExitScope();
4647 if (CodeCompleter->includeNamespaceLevelDecls() ||
4648 (!Ctx->isNamespace() && !Ctx->isTranslationUnit())) {
4649 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4650 LookupVisibleDecls(Ctx, LookupOrdinaryName, Consumer,
4651 /*IncludeGlobalScope=*/true,
4652 /*IncludeDependentBases=*/true);
4655 auto CC = Results.getCompletionContext();
4656 CC.setCXXScopeSpecifier(SS);
4658 HandleCodeCompleteResults(this, CodeCompleter, CC, Results.data(),
4662 void Sema::CodeCompleteUsing(Scope *S) {
4666 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4667 CodeCompleter->getCodeCompletionTUInfo(),
4668 CodeCompletionContext::CCC_PotentiallyQualifiedName,
4669 &ResultBuilder::IsNestedNameSpecifier);
4670 Results.EnterNewScope();
4672 // If we aren't in class scope, we could see the "namespace" keyword.
4673 if (!S->isClassScope())
4674 Results.AddResult(CodeCompletionResult("namespace"));
4676 // After "using", we can see anything that would start a
4677 // nested-name-specifier.
4678 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4679 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4680 CodeCompleter->includeGlobals());
4681 Results.ExitScope();
4683 HandleCodeCompleteResults(this, CodeCompleter,
4684 CodeCompletionContext::CCC_PotentiallyQualifiedName,
4685 Results.data(),Results.size());
4688 void Sema::CodeCompleteUsingDirective(Scope *S) {
4692 // After "using namespace", we expect to see a namespace name or namespace
4694 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4695 CodeCompleter->getCodeCompletionTUInfo(),
4696 CodeCompletionContext::CCC_Namespace,
4697 &ResultBuilder::IsNamespaceOrAlias);
4698 Results.EnterNewScope();
4699 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4700 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4701 CodeCompleter->includeGlobals());
4702 Results.ExitScope();
4703 HandleCodeCompleteResults(this, CodeCompleter,
4704 CodeCompletionContext::CCC_Namespace,
4705 Results.data(),Results.size());
4708 void Sema::CodeCompleteNamespaceDecl(Scope *S) {
4712 DeclContext *Ctx = S->getEntity();
4713 if (!S->getParent())
4714 Ctx = Context.getTranslationUnitDecl();
4716 bool SuppressedGlobalResults
4717 = Ctx && !CodeCompleter->includeGlobals() && isa<TranslationUnitDecl>(Ctx);
4719 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4720 CodeCompleter->getCodeCompletionTUInfo(),
4721 SuppressedGlobalResults
4722 ? CodeCompletionContext::CCC_Namespace
4723 : CodeCompletionContext::CCC_Other,
4724 &ResultBuilder::IsNamespace);
4726 if (Ctx && Ctx->isFileContext() && !SuppressedGlobalResults) {
4727 // We only want to see those namespaces that have already been defined
4728 // within this scope, because its likely that the user is creating an
4729 // extended namespace declaration. Keep track of the most recent
4730 // definition of each namespace.
4731 std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest;
4732 for (DeclContext::specific_decl_iterator<NamespaceDecl>
4733 NS(Ctx->decls_begin()), NSEnd(Ctx->decls_end());
4735 OrigToLatest[NS->getOriginalNamespace()] = *NS;
4737 // Add the most recent definition (or extended definition) of each
4738 // namespace to the list of results.
4739 Results.EnterNewScope();
4740 for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator
4741 NS = OrigToLatest.begin(),
4742 NSEnd = OrigToLatest.end();
4744 Results.AddResult(CodeCompletionResult(
4745 NS->second, Results.getBasePriority(NS->second),
4747 CurContext, nullptr, false);
4748 Results.ExitScope();
4751 HandleCodeCompleteResults(this, CodeCompleter,
4752 Results.getCompletionContext(),
4753 Results.data(),Results.size());
4756 void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) {
4760 // After "namespace", we expect to see a namespace or alias.
4761 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4762 CodeCompleter->getCodeCompletionTUInfo(),
4763 CodeCompletionContext::CCC_Namespace,
4764 &ResultBuilder::IsNamespaceOrAlias);
4765 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4766 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4767 CodeCompleter->includeGlobals());
4768 HandleCodeCompleteResults(this, CodeCompleter,
4769 Results.getCompletionContext(),
4770 Results.data(),Results.size());
4773 void Sema::CodeCompleteOperatorName(Scope *S) {
4777 typedef CodeCompletionResult Result;
4778 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4779 CodeCompleter->getCodeCompletionTUInfo(),
4780 CodeCompletionContext::CCC_Type,
4781 &ResultBuilder::IsType);
4782 Results.EnterNewScope();
4784 // Add the names of overloadable operators.
4785 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
4786 if (std::strcmp(Spelling, "?")) \
4787 Results.AddResult(Result(Spelling));
4788 #include "clang/Basic/OperatorKinds.def"
4790 // Add any type names visible from the current scope
4791 Results.allowNestedNameSpecifiers();
4792 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4793 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4794 CodeCompleter->includeGlobals());
4796 // Add any type specifiers
4797 AddTypeSpecifierResults(getLangOpts(), Results);
4798 Results.ExitScope();
4800 HandleCodeCompleteResults(this, CodeCompleter,
4801 CodeCompletionContext::CCC_Type,
4802 Results.data(),Results.size());
4805 void Sema::CodeCompleteConstructorInitializer(
4807 ArrayRef <CXXCtorInitializer *> Initializers) {
4811 AdjustDeclIfTemplate(ConstructorD);
4813 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ConstructorD);
4817 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4818 CodeCompleter->getCodeCompletionTUInfo(),
4819 CodeCompletionContext::CCC_PotentiallyQualifiedName);
4820 Results.EnterNewScope();
4822 // Fill in any already-initialized fields or base classes.
4823 llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields;
4824 llvm::SmallPtrSet<CanQualType, 4> InitializedBases;
4825 for (unsigned I = 0, E = Initializers.size(); I != E; ++I) {
4826 if (Initializers[I]->isBaseInitializer())
4827 InitializedBases.insert(
4828 Context.getCanonicalType(QualType(Initializers[I]->getBaseClass(), 0)));
4830 InitializedFields.insert(cast<FieldDecl>(
4831 Initializers[I]->getAnyMember()));
4834 // Add completions for base classes.
4835 CodeCompletionBuilder Builder(Results.getAllocator(),
4836 Results.getCodeCompletionTUInfo());
4837 PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
4838 bool SawLastInitializer = Initializers.empty();
4839 CXXRecordDecl *ClassDecl = Constructor->getParent();
4840 for (const auto &Base : ClassDecl->bases()) {
4841 if (!InitializedBases.insert(Context.getCanonicalType(Base.getType()))
4844 = !Initializers.empty() &&
4845 Initializers.back()->isBaseInitializer() &&
4846 Context.hasSameUnqualifiedType(Base.getType(),
4847 QualType(Initializers.back()->getBaseClass(), 0));
4851 Builder.AddTypedTextChunk(
4852 Results.getAllocator().CopyString(
4853 Base.getType().getAsString(Policy)));
4854 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4855 Builder.AddPlaceholderChunk("args");
4856 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4857 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
4858 SawLastInitializer? CCP_NextInitializer
4859 : CCP_MemberDeclaration));
4860 SawLastInitializer = false;
4863 // Add completions for virtual base classes.
4864 for (const auto &Base : ClassDecl->vbases()) {
4865 if (!InitializedBases.insert(Context.getCanonicalType(Base.getType()))
4868 = !Initializers.empty() &&
4869 Initializers.back()->isBaseInitializer() &&
4870 Context.hasSameUnqualifiedType(Base.getType(),
4871 QualType(Initializers.back()->getBaseClass(), 0));
4875 Builder.AddTypedTextChunk(
4876 Builder.getAllocator().CopyString(
4877 Base.getType().getAsString(Policy)));
4878 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4879 Builder.AddPlaceholderChunk("args");
4880 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4881 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
4882 SawLastInitializer? CCP_NextInitializer
4883 : CCP_MemberDeclaration));
4884 SawLastInitializer = false;
4887 // Add completions for members.
4888 for (auto *Field : ClassDecl->fields()) {
4889 if (!InitializedFields.insert(cast<FieldDecl>(Field->getCanonicalDecl()))
4892 = !Initializers.empty() &&
4893 Initializers.back()->isAnyMemberInitializer() &&
4894 Initializers.back()->getAnyMember() == Field;
4898 if (!Field->getDeclName())
4901 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
4902 Field->getIdentifier()->getName()));
4903 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4904 Builder.AddPlaceholderChunk("args");
4905 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4906 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
4907 SawLastInitializer? CCP_NextInitializer
4908 : CCP_MemberDeclaration,
4910 CXAvailability_Available,
4912 SawLastInitializer = false;
4914 Results.ExitScope();
4916 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4917 Results.data(), Results.size());
4920 /// \brief Determine whether this scope denotes a namespace.
4921 static bool isNamespaceScope(Scope *S) {
4922 DeclContext *DC = S->getEntity();
4926 return DC->isFileContext();
4929 void Sema::CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro,
4930 bool AfterAmpersand) {
4931 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4932 CodeCompleter->getCodeCompletionTUInfo(),
4933 CodeCompletionContext::CCC_Other);
4934 Results.EnterNewScope();
4936 // Note what has already been captured.
4937 llvm::SmallPtrSet<IdentifierInfo *, 4> Known;
4938 bool IncludedThis = false;
4939 for (const auto &C : Intro.Captures) {
4940 if (C.Kind == LCK_This) {
4941 IncludedThis = true;
4948 // Look for other capturable variables.
4949 for (; S && !isNamespaceScope(S); S = S->getParent()) {
4950 for (const auto *D : S->decls()) {
4951 const auto *Var = dyn_cast<VarDecl>(D);
4953 !Var->hasLocalStorage() ||
4954 Var->hasAttr<BlocksAttr>())
4957 if (Known.insert(Var->getIdentifier()).second)
4958 Results.AddResult(CodeCompletionResult(Var, CCP_LocalDeclaration),
4959 CurContext, nullptr, false);
4963 // Add 'this', if it would be valid.
4964 if (!IncludedThis && !AfterAmpersand && Intro.Default != LCD_ByCopy)
4965 addThisCompletion(*this, Results);
4967 Results.ExitScope();
4969 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4970 Results.data(), Results.size());
4973 /// Macro that optionally prepends an "@" to the string literal passed in via
4974 /// Keyword, depending on whether NeedAt is true or false.
4975 #define OBJC_AT_KEYWORD_NAME(NeedAt,Keyword) ((NeedAt)? "@" Keyword : Keyword)
4977 static void AddObjCImplementationResults(const LangOptions &LangOpts,
4978 ResultBuilder &Results,
4980 typedef CodeCompletionResult Result;
4981 // Since we have an implementation, we can end it.
4982 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"end")));
4984 CodeCompletionBuilder Builder(Results.getAllocator(),
4985 Results.getCodeCompletionTUInfo());
4986 if (LangOpts.ObjC2) {
4988 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"dynamic"));
4989 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4990 Builder.AddPlaceholderChunk("property");
4991 Results.AddResult(Result(Builder.TakeString()));
4994 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"synthesize"));
4995 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4996 Builder.AddPlaceholderChunk("property");
4997 Results.AddResult(Result(Builder.TakeString()));
5001 static void AddObjCInterfaceResults(const LangOptions &LangOpts,
5002 ResultBuilder &Results,
5004 typedef CodeCompletionResult Result;
5006 // Since we have an interface or protocol, we can end it.
5007 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"end")));
5009 if (LangOpts.ObjC2) {
5011 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"property")));
5014 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"required")));
5017 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"optional")));
5021 static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt) {
5022 typedef CodeCompletionResult Result;
5023 CodeCompletionBuilder Builder(Results.getAllocator(),
5024 Results.getCodeCompletionTUInfo());
5027 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"class"));
5028 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5029 Builder.AddPlaceholderChunk("name");
5030 Results.AddResult(Result(Builder.TakeString()));
5032 if (Results.includeCodePatterns()) {
5034 // FIXME: Could introduce the whole pattern, including superclasses and
5036 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"interface"));
5037 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5038 Builder.AddPlaceholderChunk("class");
5039 Results.AddResult(Result(Builder.TakeString()));
5042 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"protocol"));
5043 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5044 Builder.AddPlaceholderChunk("protocol");
5045 Results.AddResult(Result(Builder.TakeString()));
5047 // @implementation name
5048 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"implementation"));
5049 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5050 Builder.AddPlaceholderChunk("class");
5051 Results.AddResult(Result(Builder.TakeString()));
5054 // @compatibility_alias name
5055 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"compatibility_alias"));
5056 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5057 Builder.AddPlaceholderChunk("alias");
5058 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5059 Builder.AddPlaceholderChunk("class");
5060 Results.AddResult(Result(Builder.TakeString()));
5062 if (Results.getSema().getLangOpts().Modules) {
5064 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "import"));
5065 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5066 Builder.AddPlaceholderChunk("module");
5067 Results.AddResult(Result(Builder.TakeString()));
5071 void Sema::CodeCompleteObjCAtDirective(Scope *S) {
5072 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5073 CodeCompleter->getCodeCompletionTUInfo(),
5074 CodeCompletionContext::CCC_Other);
5075 Results.EnterNewScope();
5076 if (isa<ObjCImplDecl>(CurContext))
5077 AddObjCImplementationResults(getLangOpts(), Results, false);
5078 else if (CurContext->isObjCContainer())
5079 AddObjCInterfaceResults(getLangOpts(), Results, false);
5081 AddObjCTopLevelResults(Results, false);
5082 Results.ExitScope();
5083 HandleCodeCompleteResults(this, CodeCompleter,
5084 CodeCompletionContext::CCC_Other,
5085 Results.data(),Results.size());
5088 static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt) {
5089 typedef CodeCompletionResult Result;
5090 CodeCompletionBuilder Builder(Results.getAllocator(),
5091 Results.getCodeCompletionTUInfo());
5093 // @encode ( type-name )
5094 const char *EncodeType = "char[]";
5095 if (Results.getSema().getLangOpts().CPlusPlus ||
5096 Results.getSema().getLangOpts().ConstStrings)
5097 EncodeType = "const char[]";
5098 Builder.AddResultTypeChunk(EncodeType);
5099 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"encode"));
5100 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5101 Builder.AddPlaceholderChunk("type-name");
5102 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5103 Results.AddResult(Result(Builder.TakeString()));
5105 // @protocol ( protocol-name )
5106 Builder.AddResultTypeChunk("Protocol *");
5107 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"protocol"));
5108 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5109 Builder.AddPlaceholderChunk("protocol-name");
5110 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5111 Results.AddResult(Result(Builder.TakeString()));
5113 // @selector ( selector )
5114 Builder.AddResultTypeChunk("SEL");
5115 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"selector"));
5116 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5117 Builder.AddPlaceholderChunk("selector");
5118 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5119 Results.AddResult(Result(Builder.TakeString()));
5122 Builder.AddResultTypeChunk("NSString *");
5123 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"\""));
5124 Builder.AddPlaceholderChunk("string");
5125 Builder.AddTextChunk("\"");
5126 Results.AddResult(Result(Builder.TakeString()));
5129 Builder.AddResultTypeChunk("NSArray *");
5130 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"["));
5131 Builder.AddPlaceholderChunk("objects, ...");
5132 Builder.AddChunk(CodeCompletionString::CK_RightBracket);
5133 Results.AddResult(Result(Builder.TakeString()));
5135 // @{key : object, ...}
5136 Builder.AddResultTypeChunk("NSDictionary *");
5137 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"{"));
5138 Builder.AddPlaceholderChunk("key");
5139 Builder.AddChunk(CodeCompletionString::CK_Colon);
5140 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5141 Builder.AddPlaceholderChunk("object, ...");
5142 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
5143 Results.AddResult(Result(Builder.TakeString()));
5146 Builder.AddResultTypeChunk("id");
5147 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "("));
5148 Builder.AddPlaceholderChunk("expression");
5149 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5150 Results.AddResult(Result(Builder.TakeString()));
5153 static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt) {
5154 typedef CodeCompletionResult Result;
5155 CodeCompletionBuilder Builder(Results.getAllocator(),
5156 Results.getCodeCompletionTUInfo());
5158 if (Results.includeCodePatterns()) {
5159 // @try { statements } @catch ( declaration ) { statements } @finally
5161 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"try"));
5162 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
5163 Builder.AddPlaceholderChunk("statements");
5164 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
5165 Builder.AddTextChunk("@catch");
5166 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5167 Builder.AddPlaceholderChunk("parameter");
5168 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5169 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
5170 Builder.AddPlaceholderChunk("statements");
5171 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
5172 Builder.AddTextChunk("@finally");
5173 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
5174 Builder.AddPlaceholderChunk("statements");
5175 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
5176 Results.AddResult(Result(Builder.TakeString()));
5180 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"throw"));
5181 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5182 Builder.AddPlaceholderChunk("expression");
5183 Results.AddResult(Result(Builder.TakeString()));
5185 if (Results.includeCodePatterns()) {
5186 // @synchronized ( expression ) { statements }
5187 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"synchronized"));
5188 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5189 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5190 Builder.AddPlaceholderChunk("expression");
5191 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5192 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
5193 Builder.AddPlaceholderChunk("statements");
5194 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
5195 Results.AddResult(Result(Builder.TakeString()));
5199 static void AddObjCVisibilityResults(const LangOptions &LangOpts,
5200 ResultBuilder &Results,
5202 typedef CodeCompletionResult Result;
5203 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"private")));
5204 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"protected")));
5205 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"public")));
5207 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"package")));
5210 void Sema::CodeCompleteObjCAtVisibility(Scope *S) {
5211 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5212 CodeCompleter->getCodeCompletionTUInfo(),
5213 CodeCompletionContext::CCC_Other);
5214 Results.EnterNewScope();
5215 AddObjCVisibilityResults(getLangOpts(), Results, false);
5216 Results.ExitScope();
5217 HandleCodeCompleteResults(this, CodeCompleter,
5218 CodeCompletionContext::CCC_Other,
5219 Results.data(),Results.size());
5222 void Sema::CodeCompleteObjCAtStatement(Scope *S) {
5223 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5224 CodeCompleter->getCodeCompletionTUInfo(),
5225 CodeCompletionContext::CCC_Other);
5226 Results.EnterNewScope();
5227 AddObjCStatementResults(Results, false);
5228 AddObjCExpressionResults(Results, false);
5229 Results.ExitScope();
5230 HandleCodeCompleteResults(this, CodeCompleter,
5231 CodeCompletionContext::CCC_Other,
5232 Results.data(),Results.size());
5235 void Sema::CodeCompleteObjCAtExpression(Scope *S) {
5236 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5237 CodeCompleter->getCodeCompletionTUInfo(),
5238 CodeCompletionContext::CCC_Other);
5239 Results.EnterNewScope();
5240 AddObjCExpressionResults(Results, false);
5241 Results.ExitScope();
5242 HandleCodeCompleteResults(this, CodeCompleter,
5243 CodeCompletionContext::CCC_Other,
5244 Results.data(),Results.size());
5247 /// \brief Determine whether the addition of the given flag to an Objective-C
5248 /// property's attributes will cause a conflict.
5249 static bool ObjCPropertyFlagConflicts(unsigned Attributes, unsigned NewFlag) {
5250 // Check if we've already added this flag.
5251 if (Attributes & NewFlag)
5254 Attributes |= NewFlag;
5256 // Check for collisions with "readonly".
5257 if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
5258 (Attributes & ObjCDeclSpec::DQ_PR_readwrite))
5261 // Check for more than one of { assign, copy, retain, strong, weak }.
5262 unsigned AssignCopyRetMask = Attributes & (ObjCDeclSpec::DQ_PR_assign |
5263 ObjCDeclSpec::DQ_PR_unsafe_unretained |
5264 ObjCDeclSpec::DQ_PR_copy |
5265 ObjCDeclSpec::DQ_PR_retain |
5266 ObjCDeclSpec::DQ_PR_strong |
5267 ObjCDeclSpec::DQ_PR_weak);
5268 if (AssignCopyRetMask &&
5269 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_assign &&
5270 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_unsafe_unretained &&
5271 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_copy &&
5272 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_retain &&
5273 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_strong &&
5274 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_weak)
5280 void Sema::CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS) {
5284 unsigned Attributes = ODS.getPropertyAttributes();
5286 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5287 CodeCompleter->getCodeCompletionTUInfo(),
5288 CodeCompletionContext::CCC_Other);
5289 Results.EnterNewScope();
5290 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readonly))
5291 Results.AddResult(CodeCompletionResult("readonly"));
5292 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_assign))
5293 Results.AddResult(CodeCompletionResult("assign"));
5294 if (!ObjCPropertyFlagConflicts(Attributes,
5295 ObjCDeclSpec::DQ_PR_unsafe_unretained))
5296 Results.AddResult(CodeCompletionResult("unsafe_unretained"));
5297 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readwrite))
5298 Results.AddResult(CodeCompletionResult("readwrite"));
5299 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_retain))
5300 Results.AddResult(CodeCompletionResult("retain"));
5301 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_strong))
5302 Results.AddResult(CodeCompletionResult("strong"));
5303 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_copy))
5304 Results.AddResult(CodeCompletionResult("copy"));
5305 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nonatomic))
5306 Results.AddResult(CodeCompletionResult("nonatomic"));
5307 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_atomic))
5308 Results.AddResult(CodeCompletionResult("atomic"));
5310 // Only suggest "weak" if we're compiling for ARC-with-weak-references or GC.
5311 if (getLangOpts().ObjCWeak || getLangOpts().getGC() != LangOptions::NonGC)
5312 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_weak))
5313 Results.AddResult(CodeCompletionResult("weak"));
5315 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_setter)) {
5316 CodeCompletionBuilder Setter(Results.getAllocator(),
5317 Results.getCodeCompletionTUInfo());
5318 Setter.AddTypedTextChunk("setter");
5319 Setter.AddTextChunk("=");
5320 Setter.AddPlaceholderChunk("method");
5321 Results.AddResult(CodeCompletionResult(Setter.TakeString()));
5323 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_getter)) {
5324 CodeCompletionBuilder Getter(Results.getAllocator(),
5325 Results.getCodeCompletionTUInfo());
5326 Getter.AddTypedTextChunk("getter");
5327 Getter.AddTextChunk("=");
5328 Getter.AddPlaceholderChunk("method");
5329 Results.AddResult(CodeCompletionResult(Getter.TakeString()));
5331 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nullability)) {
5332 Results.AddResult(CodeCompletionResult("nonnull"));
5333 Results.AddResult(CodeCompletionResult("nullable"));
5334 Results.AddResult(CodeCompletionResult("null_unspecified"));
5335 Results.AddResult(CodeCompletionResult("null_resettable"));
5337 Results.ExitScope();
5338 HandleCodeCompleteResults(this, CodeCompleter,
5339 CodeCompletionContext::CCC_Other,
5340 Results.data(),Results.size());
5343 /// \brief Describes the kind of Objective-C method that we want to find
5344 /// via code completion.
5345 enum ObjCMethodKind {
5346 MK_Any, ///< Any kind of method, provided it means other specified criteria.
5347 MK_ZeroArgSelector, ///< Zero-argument (unary) selector.
5348 MK_OneArgSelector ///< One-argument selector.
5351 static bool isAcceptableObjCSelector(Selector Sel,
5352 ObjCMethodKind WantKind,
5353 ArrayRef<IdentifierInfo *> SelIdents,
5354 bool AllowSameLength = true) {
5355 unsigned NumSelIdents = SelIdents.size();
5356 if (NumSelIdents > Sel.getNumArgs())
5361 case MK_ZeroArgSelector: return Sel.isUnarySelector();
5362 case MK_OneArgSelector: return Sel.getNumArgs() == 1;
5365 if (!AllowSameLength && NumSelIdents && NumSelIdents == Sel.getNumArgs())
5368 for (unsigned I = 0; I != NumSelIdents; ++I)
5369 if (SelIdents[I] != Sel.getIdentifierInfoForSlot(I))
5375 static bool isAcceptableObjCMethod(ObjCMethodDecl *Method,
5376 ObjCMethodKind WantKind,
5377 ArrayRef<IdentifierInfo *> SelIdents,
5378 bool AllowSameLength = true) {
5379 return isAcceptableObjCSelector(Method->getSelector(), WantKind, SelIdents,
5384 /// \brief A set of selectors, which is used to avoid introducing multiple
5385 /// completions with the same selector into the result set.
5386 typedef llvm::SmallPtrSet<Selector, 16> VisitedSelectorSet;
5389 /// \brief Add all of the Objective-C methods in the given Objective-C
5390 /// container to the set of results.
5392 /// The container will be a class, protocol, category, or implementation of
5393 /// any of the above. This mether will recurse to include methods from
5394 /// the superclasses of classes along with their categories, protocols, and
5395 /// implementations.
5397 /// \param Container the container in which we'll look to find methods.
5399 /// \param WantInstanceMethods Whether to add instance methods (only); if
5400 /// false, this routine will add factory methods (only).
5402 /// \param CurContext the context in which we're performing the lookup that
5405 /// \param AllowSameLength Whether we allow a method to be added to the list
5406 /// when it has the same number of parameters as we have selector identifiers.
5408 /// \param Results the structure into which we'll add results.
5409 static void AddObjCMethods(ObjCContainerDecl *Container,
5410 bool WantInstanceMethods, ObjCMethodKind WantKind,
5411 ArrayRef<IdentifierInfo *> SelIdents,
5412 DeclContext *CurContext,
5413 VisitedSelectorSet &Selectors, bool AllowSameLength,
5414 ResultBuilder &Results, bool InOriginalClass = true,
5415 bool IsRootClass = false) {
5416 typedef CodeCompletionResult Result;
5417 Container = getContainerDef(Container);
5418 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container);
5419 IsRootClass = IsRootClass || (IFace && !IFace->getSuperClass());
5420 for (auto *M : Container->methods()) {
5421 // The instance methods on the root class can be messaged via the
5423 if (M->isInstanceMethod() == WantInstanceMethods ||
5424 (IsRootClass && !WantInstanceMethods)) {
5425 // Check whether the selector identifiers we've been given are a
5426 // subset of the identifiers for this particular method.
5427 if (!isAcceptableObjCMethod(M, WantKind, SelIdents, AllowSameLength))
5430 if (!Selectors.insert(M->getSelector()).second)
5433 Result R = Result(M, Results.getBasePriority(M), nullptr);
5434 R.StartParameter = SelIdents.size();
5435 R.AllParametersAreInformative = (WantKind != MK_Any);
5436 if (!InOriginalClass)
5437 R.Priority += CCD_InBaseClass;
5438 Results.MaybeAddResult(R, CurContext);
5442 // Visit the protocols of protocols.
5443 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
5444 if (Protocol->hasDefinition()) {
5445 const ObjCList<ObjCProtocolDecl> &Protocols
5446 = Protocol->getReferencedProtocols();
5447 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
5448 E = Protocols.end();
5450 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, CurContext,
5451 Selectors, AllowSameLength, Results, false, IsRootClass);
5455 if (!IFace || !IFace->hasDefinition())
5458 // Add methods in protocols.
5459 for (auto *I : IFace->protocols())
5460 AddObjCMethods(I, WantInstanceMethods, WantKind, SelIdents, CurContext,
5461 Selectors, AllowSameLength, Results, false, IsRootClass);
5463 // Add methods in categories.
5464 for (auto *CatDecl : IFace->known_categories()) {
5465 AddObjCMethods(CatDecl, WantInstanceMethods, WantKind, SelIdents,
5466 CurContext, Selectors, AllowSameLength, Results,
5467 InOriginalClass, IsRootClass);
5469 // Add a categories protocol methods.
5470 const ObjCList<ObjCProtocolDecl> &Protocols
5471 = CatDecl->getReferencedProtocols();
5472 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
5473 E = Protocols.end();
5475 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, CurContext,
5476 Selectors, AllowSameLength, Results, false, IsRootClass);
5478 // Add methods in category implementations.
5479 if (ObjCCategoryImplDecl *Impl = CatDecl->getImplementation())
5480 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents, CurContext,
5481 Selectors, AllowSameLength, Results, InOriginalClass,
5485 // Add methods in superclass.
5486 // Avoid passing in IsRootClass since root classes won't have super classes.
5487 if (IFace->getSuperClass())
5488 AddObjCMethods(IFace->getSuperClass(), WantInstanceMethods, WantKind,
5489 SelIdents, CurContext, Selectors, AllowSameLength, Results,
5490 /*IsRootClass=*/false);
5492 // Add methods in our implementation, if any.
5493 if (ObjCImplementationDecl *Impl = IFace->getImplementation())
5494 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents, CurContext,
5495 Selectors, AllowSameLength, Results, InOriginalClass,
5500 void Sema::CodeCompleteObjCPropertyGetter(Scope *S) {
5501 // Try to find the interface where getters might live.
5502 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext);
5504 if (ObjCCategoryDecl *Category
5505 = dyn_cast_or_null<ObjCCategoryDecl>(CurContext))
5506 Class = Category->getClassInterface();
5512 // Find all of the potential getters.
5513 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5514 CodeCompleter->getCodeCompletionTUInfo(),
5515 CodeCompletionContext::CCC_Other);
5516 Results.EnterNewScope();
5518 VisitedSelectorSet Selectors;
5519 AddObjCMethods(Class, true, MK_ZeroArgSelector, None, CurContext, Selectors,
5520 /*AllowSameLength=*/true, Results);
5521 Results.ExitScope();
5522 HandleCodeCompleteResults(this, CodeCompleter,
5523 CodeCompletionContext::CCC_Other,
5524 Results.data(),Results.size());
5527 void Sema::CodeCompleteObjCPropertySetter(Scope *S) {
5528 // Try to find the interface where setters might live.
5529 ObjCInterfaceDecl *Class
5530 = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext);
5532 if (ObjCCategoryDecl *Category
5533 = dyn_cast_or_null<ObjCCategoryDecl>(CurContext))
5534 Class = Category->getClassInterface();
5540 // Find all of the potential getters.
5541 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5542 CodeCompleter->getCodeCompletionTUInfo(),
5543 CodeCompletionContext::CCC_Other);
5544 Results.EnterNewScope();
5546 VisitedSelectorSet Selectors;
5547 AddObjCMethods(Class, true, MK_OneArgSelector, None, CurContext,
5548 Selectors, /*AllowSameLength=*/true, Results);
5550 Results.ExitScope();
5551 HandleCodeCompleteResults(this, CodeCompleter,
5552 CodeCompletionContext::CCC_Other,
5553 Results.data(),Results.size());
5556 void Sema::CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
5558 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5559 CodeCompleter->getCodeCompletionTUInfo(),
5560 CodeCompletionContext::CCC_Type);
5561 Results.EnterNewScope();
5563 // Add context-sensitive, Objective-C parameter-passing keywords.
5564 bool AddedInOut = false;
5565 if ((DS.getObjCDeclQualifier() &
5566 (ObjCDeclSpec::DQ_In | ObjCDeclSpec::DQ_Inout)) == 0) {
5567 Results.AddResult("in");
5568 Results.AddResult("inout");
5571 if ((DS.getObjCDeclQualifier() &
5572 (ObjCDeclSpec::DQ_Out | ObjCDeclSpec::DQ_Inout)) == 0) {
5573 Results.AddResult("out");
5575 Results.AddResult("inout");
5577 if ((DS.getObjCDeclQualifier() &
5578 (ObjCDeclSpec::DQ_Bycopy | ObjCDeclSpec::DQ_Byref |
5579 ObjCDeclSpec::DQ_Oneway)) == 0) {
5580 Results.AddResult("bycopy");
5581 Results.AddResult("byref");
5582 Results.AddResult("oneway");
5584 if ((DS.getObjCDeclQualifier() & ObjCDeclSpec::DQ_CSNullability) == 0) {
5585 Results.AddResult("nonnull");
5586 Results.AddResult("nullable");
5587 Results.AddResult("null_unspecified");
5590 // If we're completing the return type of an Objective-C method and the
5591 // identifier IBAction refers to a macro, provide a completion item for
5593 // IBAction)<#selector#>:(id)sender
5594 if (DS.getObjCDeclQualifier() == 0 && !IsParameter &&
5595 PP.isMacroDefined("IBAction")) {
5596 CodeCompletionBuilder Builder(Results.getAllocator(),
5597 Results.getCodeCompletionTUInfo(),
5598 CCP_CodePattern, CXAvailability_Available);
5599 Builder.AddTypedTextChunk("IBAction");
5600 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5601 Builder.AddPlaceholderChunk("selector");
5602 Builder.AddChunk(CodeCompletionString::CK_Colon);
5603 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5604 Builder.AddTextChunk("id");
5605 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5606 Builder.AddTextChunk("sender");
5607 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
5610 // If we're completing the return type, provide 'instancetype'.
5612 Results.AddResult(CodeCompletionResult("instancetype"));
5615 // Add various builtin type names and specifiers.
5616 AddOrdinaryNameResults(PCC_Type, S, *this, Results);
5617 Results.ExitScope();
5619 // Add the various type names
5620 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
5621 CodeCompletionDeclConsumer Consumer(Results, CurContext);
5622 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
5623 CodeCompleter->includeGlobals());
5625 if (CodeCompleter->includeMacros())
5626 AddMacroResults(PP, Results, false);
5628 HandleCodeCompleteResults(this, CodeCompleter,
5629 CodeCompletionContext::CCC_Type,
5630 Results.data(), Results.size());
5633 /// \brief When we have an expression with type "id", we may assume
5634 /// that it has some more-specific class type based on knowledge of
5635 /// common uses of Objective-C. This routine returns that class type,
5636 /// or NULL if no better result could be determined.
5637 static ObjCInterfaceDecl *GetAssumedMessageSendExprType(Expr *E) {
5638 ObjCMessageExpr *Msg = dyn_cast_or_null<ObjCMessageExpr>(E);
5642 Selector Sel = Msg->getSelector();
5646 IdentifierInfo *Id = Sel.getIdentifierInfoForSlot(0);
5650 ObjCMethodDecl *Method = Msg->getMethodDecl();
5654 // Determine the class that we're sending the message to.
5655 ObjCInterfaceDecl *IFace = nullptr;
5656 switch (Msg->getReceiverKind()) {
5657 case ObjCMessageExpr::Class:
5658 if (const ObjCObjectType *ObjType
5659 = Msg->getClassReceiver()->getAs<ObjCObjectType>())
5660 IFace = ObjType->getInterface();
5663 case ObjCMessageExpr::Instance: {
5664 QualType T = Msg->getInstanceReceiver()->getType();
5665 if (const ObjCObjectPointerType *Ptr = T->getAs<ObjCObjectPointerType>())
5666 IFace = Ptr->getInterfaceDecl();
5670 case ObjCMessageExpr::SuperInstance:
5671 case ObjCMessageExpr::SuperClass:
5678 ObjCInterfaceDecl *Super = IFace->getSuperClass();
5679 if (Method->isInstanceMethod())
5680 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
5681 .Case("retain", IFace)
5682 .Case("strong", IFace)
5683 .Case("autorelease", IFace)
5684 .Case("copy", IFace)
5685 .Case("copyWithZone", IFace)
5686 .Case("mutableCopy", IFace)
5687 .Case("mutableCopyWithZone", IFace)
5688 .Case("awakeFromCoder", IFace)
5689 .Case("replacementObjectFromCoder", IFace)
5690 .Case("class", IFace)
5691 .Case("classForCoder", IFace)
5692 .Case("superclass", Super)
5695 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
5697 .Case("alloc", IFace)
5698 .Case("allocWithZone", IFace)
5699 .Case("class", IFace)
5700 .Case("superclass", Super)
5704 // Add a special completion for a message send to "super", which fills in the
5705 // most likely case of forwarding all of our arguments to the superclass
5708 /// \param S The semantic analysis object.
5710 /// \param NeedSuperKeyword Whether we need to prefix this completion with
5711 /// the "super" keyword. Otherwise, we just need to provide the arguments.
5713 /// \param SelIdents The identifiers in the selector that have already been
5714 /// provided as arguments for a send to "super".
5716 /// \param Results The set of results to augment.
5718 /// \returns the Objective-C method declaration that would be invoked by
5719 /// this "super" completion. If NULL, no completion was added.
5720 static ObjCMethodDecl *AddSuperSendCompletion(
5721 Sema &S, bool NeedSuperKeyword,
5722 ArrayRef<IdentifierInfo *> SelIdents,
5723 ResultBuilder &Results) {
5724 ObjCMethodDecl *CurMethod = S.getCurMethodDecl();
5728 ObjCInterfaceDecl *Class = CurMethod->getClassInterface();
5732 // Try to find a superclass method with the same selector.
5733 ObjCMethodDecl *SuperMethod = nullptr;
5734 while ((Class = Class->getSuperClass()) && !SuperMethod) {
5735 // Check in the class
5736 SuperMethod = Class->getMethod(CurMethod->getSelector(),
5737 CurMethod->isInstanceMethod());
5739 // Check in categories or class extensions.
5741 for (const auto *Cat : Class->known_categories()) {
5742 if ((SuperMethod = Cat->getMethod(CurMethod->getSelector(),
5743 CurMethod->isInstanceMethod())))
5752 // Check whether the superclass method has the same signature.
5753 if (CurMethod->param_size() != SuperMethod->param_size() ||
5754 CurMethod->isVariadic() != SuperMethod->isVariadic())
5757 for (ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin(),
5758 CurPEnd = CurMethod->param_end(),
5759 SuperP = SuperMethod->param_begin();
5760 CurP != CurPEnd; ++CurP, ++SuperP) {
5761 // Make sure the parameter types are compatible.
5762 if (!S.Context.hasSameUnqualifiedType((*CurP)->getType(),
5763 (*SuperP)->getType()))
5766 // Make sure we have a parameter name to forward!
5767 if (!(*CurP)->getIdentifier())
5771 // We have a superclass method. Now, form the send-to-super completion.
5772 CodeCompletionBuilder Builder(Results.getAllocator(),
5773 Results.getCodeCompletionTUInfo());
5775 // Give this completion a return type.
5776 AddResultTypeChunk(S.Context, getCompletionPrintingPolicy(S), SuperMethod,
5777 Results.getCompletionContext().getBaseType(),
5780 // If we need the "super" keyword, add it (plus some spacing).
5781 if (NeedSuperKeyword) {
5782 Builder.AddTypedTextChunk("super");
5783 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5786 Selector Sel = CurMethod->getSelector();
5787 if (Sel.isUnarySelector()) {
5788 if (NeedSuperKeyword)
5789 Builder.AddTextChunk(Builder.getAllocator().CopyString(
5790 Sel.getNameForSlot(0)));
5792 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
5793 Sel.getNameForSlot(0)));
5795 ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin();
5796 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I, ++CurP) {
5797 if (I > SelIdents.size())
5798 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5800 if (I < SelIdents.size())
5801 Builder.AddInformativeChunk(
5802 Builder.getAllocator().CopyString(
5803 Sel.getNameForSlot(I) + ":"));
5804 else if (NeedSuperKeyword || I > SelIdents.size()) {
5805 Builder.AddTextChunk(
5806 Builder.getAllocator().CopyString(
5807 Sel.getNameForSlot(I) + ":"));
5808 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
5809 (*CurP)->getIdentifier()->getName()));
5811 Builder.AddTypedTextChunk(
5812 Builder.getAllocator().CopyString(
5813 Sel.getNameForSlot(I) + ":"));
5814 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
5815 (*CurP)->getIdentifier()->getName()));
5820 Results.AddResult(CodeCompletionResult(Builder.TakeString(), SuperMethod,
5821 CCP_SuperCompletion));
5825 void Sema::CodeCompleteObjCMessageReceiver(Scope *S) {
5826 typedef CodeCompletionResult Result;
5827 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5828 CodeCompleter->getCodeCompletionTUInfo(),
5829 CodeCompletionContext::CCC_ObjCMessageReceiver,
5830 getLangOpts().CPlusPlus11
5831 ? &ResultBuilder::IsObjCMessageReceiverOrLambdaCapture
5832 : &ResultBuilder::IsObjCMessageReceiver);
5834 CodeCompletionDeclConsumer Consumer(Results, CurContext);
5835 Results.EnterNewScope();
5836 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
5837 CodeCompleter->includeGlobals());
5839 // If we are in an Objective-C method inside a class that has a superclass,
5840 // add "super" as an option.
5841 if (ObjCMethodDecl *Method = getCurMethodDecl())
5842 if (ObjCInterfaceDecl *Iface = Method->getClassInterface())
5843 if (Iface->getSuperClass()) {
5844 Results.AddResult(Result("super"));
5846 AddSuperSendCompletion(*this, /*NeedSuperKeyword=*/true, None, Results);
5849 if (getLangOpts().CPlusPlus11)
5850 addThisCompletion(*this, Results);
5852 Results.ExitScope();
5854 if (CodeCompleter->includeMacros())
5855 AddMacroResults(PP, Results, false);
5856 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
5857 Results.data(), Results.size());
5861 void Sema::CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
5862 ArrayRef<IdentifierInfo *> SelIdents,
5863 bool AtArgumentExpression) {
5864 ObjCInterfaceDecl *CDecl = nullptr;
5865 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
5866 // Figure out which interface we're in.
5867 CDecl = CurMethod->getClassInterface();
5871 // Find the superclass of this class.
5872 CDecl = CDecl->getSuperClass();
5876 if (CurMethod->isInstanceMethod()) {
5877 // We are inside an instance method, which means that the message
5878 // send [super ...] is actually calling an instance method on the
5880 return CodeCompleteObjCInstanceMessage(S, nullptr, SelIdents,
5881 AtArgumentExpression,
5885 // Fall through to send to the superclass in CDecl.
5887 // "super" may be the name of a type or variable. Figure out which
5889 IdentifierInfo *Super = getSuperIdentifier();
5890 NamedDecl *ND = LookupSingleName(S, Super, SuperLoc,
5891 LookupOrdinaryName);
5892 if ((CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(ND))) {
5893 // "super" names an interface. Use it.
5894 } else if (TypeDecl *TD = dyn_cast_or_null<TypeDecl>(ND)) {
5895 if (const ObjCObjectType *Iface
5896 = Context.getTypeDeclType(TD)->getAs<ObjCObjectType>())
5897 CDecl = Iface->getInterface();
5898 } else if (ND && isa<UnresolvedUsingTypenameDecl>(ND)) {
5899 // "super" names an unresolved type; we can't be more specific.
5901 // Assume that "super" names some kind of value and parse that way.
5903 SourceLocation TemplateKWLoc;
5905 id.setIdentifier(Super, SuperLoc);
5906 ExprResult SuperExpr = ActOnIdExpression(S, SS, TemplateKWLoc, id,
5908 return CodeCompleteObjCInstanceMessage(S, (Expr *)SuperExpr.get(),
5910 AtArgumentExpression);
5916 ParsedType Receiver;
5918 Receiver = ParsedType::make(Context.getObjCInterfaceType(CDecl));
5919 return CodeCompleteObjCClassMessage(S, Receiver, SelIdents,
5920 AtArgumentExpression,
5924 /// \brief Given a set of code-completion results for the argument of a message
5925 /// send, determine the preferred type (if any) for that argument expression.
5926 static QualType getPreferredArgumentTypeForMessageSend(ResultBuilder &Results,
5927 unsigned NumSelIdents) {
5928 typedef CodeCompletionResult Result;
5929 ASTContext &Context = Results.getSema().Context;
5931 QualType PreferredType;
5932 unsigned BestPriority = CCP_Unlikely * 2;
5933 Result *ResultsData = Results.data();
5934 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
5935 Result &R = ResultsData[I];
5936 if (R.Kind == Result::RK_Declaration &&
5937 isa<ObjCMethodDecl>(R.Declaration)) {
5938 if (R.Priority <= BestPriority) {
5939 const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(R.Declaration);
5940 if (NumSelIdents <= Method->param_size()) {
5941 QualType MyPreferredType = Method->parameters()[NumSelIdents - 1]
5943 if (R.Priority < BestPriority || PreferredType.isNull()) {
5944 BestPriority = R.Priority;
5945 PreferredType = MyPreferredType;
5946 } else if (!Context.hasSameUnqualifiedType(PreferredType,
5948 PreferredType = QualType();
5955 return PreferredType;
5958 static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
5959 ParsedType Receiver,
5960 ArrayRef<IdentifierInfo *> SelIdents,
5961 bool AtArgumentExpression,
5963 ResultBuilder &Results) {
5964 typedef CodeCompletionResult Result;
5965 ObjCInterfaceDecl *CDecl = nullptr;
5967 // If the given name refers to an interface type, retrieve the
5968 // corresponding declaration.
5970 QualType T = SemaRef.GetTypeFromParser(Receiver, nullptr);
5972 if (const ObjCObjectType *Interface = T->getAs<ObjCObjectType>())
5973 CDecl = Interface->getInterface();
5976 // Add all of the factory methods in this Objective-C class, its protocols,
5977 // superclasses, categories, implementation, etc.
5978 Results.EnterNewScope();
5980 // If this is a send-to-super, try to add the special "super" send
5983 if (ObjCMethodDecl *SuperMethod
5984 = AddSuperSendCompletion(SemaRef, false, SelIdents, Results))
5985 Results.Ignore(SuperMethod);
5988 // If we're inside an Objective-C method definition, prefer its selector to
5990 if (ObjCMethodDecl *CurMethod = SemaRef.getCurMethodDecl())
5991 Results.setPreferredSelector(CurMethod->getSelector());
5993 VisitedSelectorSet Selectors;
5995 AddObjCMethods(CDecl, false, MK_Any, SelIdents,
5996 SemaRef.CurContext, Selectors, AtArgumentExpression,
5999 // We're messaging "id" as a type; provide all class/factory methods.
6001 // If we have an external source, load the entire class method
6002 // pool from the AST file.
6003 if (SemaRef.getExternalSource()) {
6004 for (uint32_t I = 0,
6005 N = SemaRef.getExternalSource()->GetNumExternalSelectors();
6007 Selector Sel = SemaRef.getExternalSource()->GetExternalSelector(I);
6008 if (Sel.isNull() || SemaRef.MethodPool.count(Sel))
6011 SemaRef.ReadMethodPool(Sel);
6015 for (Sema::GlobalMethodPool::iterator M = SemaRef.MethodPool.begin(),
6016 MEnd = SemaRef.MethodPool.end();
6018 for (ObjCMethodList *MethList = &M->second.second;
6019 MethList && MethList->getMethod();
6020 MethList = MethList->getNext()) {
6021 if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents))
6024 Result R(MethList->getMethod(),
6025 Results.getBasePriority(MethList->getMethod()), nullptr);
6026 R.StartParameter = SelIdents.size();
6027 R.AllParametersAreInformative = false;
6028 Results.MaybeAddResult(R, SemaRef.CurContext);
6033 Results.ExitScope();
6036 void Sema::CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
6037 ArrayRef<IdentifierInfo *> SelIdents,
6038 bool AtArgumentExpression,
6041 QualType T = this->GetTypeFromParser(Receiver);
6043 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6044 CodeCompleter->getCodeCompletionTUInfo(),
6045 CodeCompletionContext(CodeCompletionContext::CCC_ObjCClassMessage,
6048 AddClassMessageCompletions(*this, S, Receiver, SelIdents,
6049 AtArgumentExpression, IsSuper, Results);
6051 // If we're actually at the argument expression (rather than prior to the
6052 // selector), we're actually performing code completion for an expression.
6053 // Determine whether we have a single, best method. If so, we can
6054 // code-complete the expression using the corresponding parameter type as
6055 // our preferred type, improving completion results.
6056 if (AtArgumentExpression) {
6057 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results,
6059 if (PreferredType.isNull())
6060 CodeCompleteOrdinaryName(S, PCC_Expression);
6062 CodeCompleteExpression(S, PreferredType);
6066 HandleCodeCompleteResults(this, CodeCompleter,
6067 Results.getCompletionContext(),
6068 Results.data(), Results.size());
6071 void Sema::CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
6072 ArrayRef<IdentifierInfo *> SelIdents,
6073 bool AtArgumentExpression,
6074 ObjCInterfaceDecl *Super) {
6075 typedef CodeCompletionResult Result;
6077 Expr *RecExpr = static_cast<Expr *>(Receiver);
6079 // If necessary, apply function/array conversion to the receiver.
6080 // C99 6.7.5.3p[7,8].
6082 ExprResult Conv = DefaultFunctionArrayLvalueConversion(RecExpr);
6083 if (Conv.isInvalid()) // conversion failed. bail.
6085 RecExpr = Conv.get();
6087 QualType ReceiverType = RecExpr? RecExpr->getType()
6088 : Super? Context.getObjCObjectPointerType(
6089 Context.getObjCInterfaceType(Super))
6090 : Context.getObjCIdType();
6092 // If we're messaging an expression with type "id" or "Class", check
6093 // whether we know something special about the receiver that allows
6094 // us to assume a more-specific receiver type.
6095 if (ReceiverType->isObjCIdType() || ReceiverType->isObjCClassType()) {
6096 if (ObjCInterfaceDecl *IFace = GetAssumedMessageSendExprType(RecExpr)) {
6097 if (ReceiverType->isObjCClassType())
6098 return CodeCompleteObjCClassMessage(S,
6099 ParsedType::make(Context.getObjCInterfaceType(IFace)),
6101 AtArgumentExpression, Super);
6103 ReceiverType = Context.getObjCObjectPointerType(
6104 Context.getObjCInterfaceType(IFace));
6106 } else if (RecExpr && getLangOpts().CPlusPlus) {
6107 ExprResult Conv = PerformContextuallyConvertToObjCPointer(RecExpr);
6108 if (Conv.isUsable()) {
6109 RecExpr = Conv.get();
6110 ReceiverType = RecExpr->getType();
6114 // Build the set of methods we can see.
6115 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6116 CodeCompleter->getCodeCompletionTUInfo(),
6117 CodeCompletionContext(CodeCompletionContext::CCC_ObjCInstanceMessage,
6118 ReceiverType, SelIdents));
6120 Results.EnterNewScope();
6122 // If this is a send-to-super, try to add the special "super" send
6125 if (ObjCMethodDecl *SuperMethod
6126 = AddSuperSendCompletion(*this, false, SelIdents, Results))
6127 Results.Ignore(SuperMethod);
6130 // If we're inside an Objective-C method definition, prefer its selector to
6132 if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
6133 Results.setPreferredSelector(CurMethod->getSelector());
6135 // Keep track of the selectors we've already added.
6136 VisitedSelectorSet Selectors;
6138 // Handle messages to Class. This really isn't a message to an instance
6139 // method, so we treat it the same way we would treat a message send to a
6141 if (ReceiverType->isObjCClassType() ||
6142 ReceiverType->isObjCQualifiedClassType()) {
6143 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
6144 if (ObjCInterfaceDecl *ClassDecl = CurMethod->getClassInterface())
6145 AddObjCMethods(ClassDecl, false, MK_Any, SelIdents,
6146 CurContext, Selectors, AtArgumentExpression, Results);
6149 // Handle messages to a qualified ID ("id<foo>").
6150 else if (const ObjCObjectPointerType *QualID
6151 = ReceiverType->getAsObjCQualifiedIdType()) {
6152 // Search protocols for instance methods.
6153 for (auto *I : QualID->quals())
6154 AddObjCMethods(I, true, MK_Any, SelIdents, CurContext,
6155 Selectors, AtArgumentExpression, Results);
6157 // Handle messages to a pointer to interface type.
6158 else if (const ObjCObjectPointerType *IFacePtr
6159 = ReceiverType->getAsObjCInterfacePointerType()) {
6160 // Search the class, its superclasses, etc., for instance methods.
6161 AddObjCMethods(IFacePtr->getInterfaceDecl(), true, MK_Any, SelIdents,
6162 CurContext, Selectors, AtArgumentExpression,
6165 // Search protocols for instance methods.
6166 for (auto *I : IFacePtr->quals())
6167 AddObjCMethods(I, true, MK_Any, SelIdents, CurContext,
6168 Selectors, AtArgumentExpression, Results);
6170 // Handle messages to "id".
6171 else if (ReceiverType->isObjCIdType()) {
6172 // We're messaging "id", so provide all instance methods we know
6173 // about as code-completion results.
6175 // If we have an external source, load the entire class method
6176 // pool from the AST file.
6177 if (ExternalSource) {
6178 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
6180 Selector Sel = ExternalSource->GetExternalSelector(I);
6181 if (Sel.isNull() || MethodPool.count(Sel))
6184 ReadMethodPool(Sel);
6188 for (GlobalMethodPool::iterator M = MethodPool.begin(),
6189 MEnd = MethodPool.end();
6191 for (ObjCMethodList *MethList = &M->second.first;
6192 MethList && MethList->getMethod();
6193 MethList = MethList->getNext()) {
6194 if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents))
6197 if (!Selectors.insert(MethList->getMethod()->getSelector()).second)
6200 Result R(MethList->getMethod(),
6201 Results.getBasePriority(MethList->getMethod()), nullptr);
6202 R.StartParameter = SelIdents.size();
6203 R.AllParametersAreInformative = false;
6204 Results.MaybeAddResult(R, CurContext);
6208 Results.ExitScope();
6211 // If we're actually at the argument expression (rather than prior to the
6212 // selector), we're actually performing code completion for an expression.
6213 // Determine whether we have a single, best method. If so, we can
6214 // code-complete the expression using the corresponding parameter type as
6215 // our preferred type, improving completion results.
6216 if (AtArgumentExpression) {
6217 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results,
6219 if (PreferredType.isNull())
6220 CodeCompleteOrdinaryName(S, PCC_Expression);
6222 CodeCompleteExpression(S, PreferredType);
6226 HandleCodeCompleteResults(this, CodeCompleter,
6227 Results.getCompletionContext(),
6228 Results.data(),Results.size());
6231 void Sema::CodeCompleteObjCForCollection(Scope *S,
6232 DeclGroupPtrTy IterationVar) {
6233 CodeCompleteExpressionData Data;
6234 Data.ObjCCollection = true;
6236 if (IterationVar.getAsOpaquePtr()) {
6237 DeclGroupRef DG = IterationVar.get();
6238 for (DeclGroupRef::iterator I = DG.begin(), End = DG.end(); I != End; ++I) {
6240 Data.IgnoreDecls.push_back(*I);
6244 CodeCompleteExpression(S, Data);
6247 void Sema::CodeCompleteObjCSelector(Scope *S,
6248 ArrayRef<IdentifierInfo *> SelIdents) {
6249 // If we have an external source, load the entire class method
6250 // pool from the AST file.
6251 if (ExternalSource) {
6252 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
6254 Selector Sel = ExternalSource->GetExternalSelector(I);
6255 if (Sel.isNull() || MethodPool.count(Sel))
6258 ReadMethodPool(Sel);
6262 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6263 CodeCompleter->getCodeCompletionTUInfo(),
6264 CodeCompletionContext::CCC_SelectorName);
6265 Results.EnterNewScope();
6266 for (GlobalMethodPool::iterator M = MethodPool.begin(),
6267 MEnd = MethodPool.end();
6270 Selector Sel = M->first;
6271 if (!isAcceptableObjCSelector(Sel, MK_Any, SelIdents))
6274 CodeCompletionBuilder Builder(Results.getAllocator(),
6275 Results.getCodeCompletionTUInfo());
6276 if (Sel.isUnarySelector()) {
6277 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
6278 Sel.getNameForSlot(0)));
6279 Results.AddResult(Builder.TakeString());
6283 std::string Accumulator;
6284 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I) {
6285 if (I == SelIdents.size()) {
6286 if (!Accumulator.empty()) {
6287 Builder.AddInformativeChunk(Builder.getAllocator().CopyString(
6289 Accumulator.clear();
6293 Accumulator += Sel.getNameForSlot(I);
6296 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString( Accumulator));
6297 Results.AddResult(Builder.TakeString());
6299 Results.ExitScope();
6301 HandleCodeCompleteResults(this, CodeCompleter,
6302 CodeCompletionContext::CCC_SelectorName,
6303 Results.data(), Results.size());
6306 /// \brief Add all of the protocol declarations that we find in the given
6307 /// (translation unit) context.
6308 static void AddProtocolResults(DeclContext *Ctx, DeclContext *CurContext,
6309 bool OnlyForwardDeclarations,
6310 ResultBuilder &Results) {
6311 typedef CodeCompletionResult Result;
6313 for (const auto *D : Ctx->decls()) {
6314 // Record any protocols we find.
6315 if (const auto *Proto = dyn_cast<ObjCProtocolDecl>(D))
6316 if (!OnlyForwardDeclarations || !Proto->hasDefinition())
6317 Results.AddResult(Result(Proto, Results.getBasePriority(Proto),nullptr),
6318 CurContext, nullptr, false);
6322 void Sema::CodeCompleteObjCProtocolReferences(
6323 ArrayRef<IdentifierLocPair> Protocols) {
6324 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6325 CodeCompleter->getCodeCompletionTUInfo(),
6326 CodeCompletionContext::CCC_ObjCProtocolName);
6328 if (CodeCompleter->includeGlobals()) {
6329 Results.EnterNewScope();
6331 // Tell the result set to ignore all of the protocols we have
6333 // FIXME: This doesn't work when caching code-completion results.
6334 for (const IdentifierLocPair &Pair : Protocols)
6335 if (ObjCProtocolDecl *Protocol = LookupProtocol(Pair.first,
6337 Results.Ignore(Protocol);
6339 // Add all protocols.
6340 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, false,
6343 Results.ExitScope();
6346 HandleCodeCompleteResults(this, CodeCompleter,
6347 CodeCompletionContext::CCC_ObjCProtocolName,
6348 Results.data(),Results.size());
6351 void Sema::CodeCompleteObjCProtocolDecl(Scope *) {
6352 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6353 CodeCompleter->getCodeCompletionTUInfo(),
6354 CodeCompletionContext::CCC_ObjCProtocolName);
6356 if (CodeCompleter->includeGlobals()) {
6357 Results.EnterNewScope();
6359 // Add all protocols.
6360 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, true,
6363 Results.ExitScope();
6366 HandleCodeCompleteResults(this, CodeCompleter,
6367 CodeCompletionContext::CCC_ObjCProtocolName,
6368 Results.data(),Results.size());
6371 /// \brief Add all of the Objective-C interface declarations that we find in
6372 /// the given (translation unit) context.
6373 static void AddInterfaceResults(DeclContext *Ctx, DeclContext *CurContext,
6374 bool OnlyForwardDeclarations,
6375 bool OnlyUnimplemented,
6376 ResultBuilder &Results) {
6377 typedef CodeCompletionResult Result;
6379 for (const auto *D : Ctx->decls()) {
6380 // Record any interfaces we find.
6381 if (const auto *Class = dyn_cast<ObjCInterfaceDecl>(D))
6382 if ((!OnlyForwardDeclarations || !Class->hasDefinition()) &&
6383 (!OnlyUnimplemented || !Class->getImplementation()))
6384 Results.AddResult(Result(Class, Results.getBasePriority(Class),nullptr),
6385 CurContext, nullptr, false);
6389 void Sema::CodeCompleteObjCInterfaceDecl(Scope *S) {
6390 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6391 CodeCompleter->getCodeCompletionTUInfo(),
6392 CodeCompletionContext::CCC_Other);
6393 Results.EnterNewScope();
6395 if (CodeCompleter->includeGlobals()) {
6397 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
6401 Results.ExitScope();
6403 HandleCodeCompleteResults(this, CodeCompleter,
6404 CodeCompletionContext::CCC_ObjCInterfaceName,
6405 Results.data(),Results.size());
6408 void Sema::CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName,
6409 SourceLocation ClassNameLoc) {
6410 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6411 CodeCompleter->getCodeCompletionTUInfo(),
6412 CodeCompletionContext::CCC_ObjCInterfaceName);
6413 Results.EnterNewScope();
6415 // Make sure that we ignore the class we're currently defining.
6417 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
6418 if (CurClass && isa<ObjCInterfaceDecl>(CurClass))
6419 Results.Ignore(CurClass);
6421 if (CodeCompleter->includeGlobals()) {
6423 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
6427 Results.ExitScope();
6429 HandleCodeCompleteResults(this, CodeCompleter,
6430 CodeCompletionContext::CCC_ObjCInterfaceName,
6431 Results.data(),Results.size());
6434 void Sema::CodeCompleteObjCImplementationDecl(Scope *S) {
6435 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6436 CodeCompleter->getCodeCompletionTUInfo(),
6437 CodeCompletionContext::CCC_Other);
6438 Results.EnterNewScope();
6440 if (CodeCompleter->includeGlobals()) {
6441 // Add all unimplemented classes.
6442 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
6446 Results.ExitScope();
6448 HandleCodeCompleteResults(this, CodeCompleter,
6449 CodeCompletionContext::CCC_ObjCInterfaceName,
6450 Results.data(),Results.size());
6453 void Sema::CodeCompleteObjCInterfaceCategory(Scope *S,
6454 IdentifierInfo *ClassName,
6455 SourceLocation ClassNameLoc) {
6456 typedef CodeCompletionResult Result;
6458 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6459 CodeCompleter->getCodeCompletionTUInfo(),
6460 CodeCompletionContext::CCC_ObjCCategoryName);
6462 // Ignore any categories we find that have already been implemented by this
6464 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
6466 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
6467 if (ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass)){
6468 for (const auto *Cat : Class->visible_categories())
6469 CategoryNames.insert(Cat->getIdentifier());
6472 // Add all of the categories we know about.
6473 Results.EnterNewScope();
6474 TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
6475 for (const auto *D : TU->decls())
6476 if (const auto *Category = dyn_cast<ObjCCategoryDecl>(D))
6477 if (CategoryNames.insert(Category->getIdentifier()).second)
6478 Results.AddResult(Result(Category, Results.getBasePriority(Category),
6480 CurContext, nullptr, false);
6481 Results.ExitScope();
6483 HandleCodeCompleteResults(this, CodeCompleter,
6484 CodeCompletionContext::CCC_ObjCCategoryName,
6485 Results.data(),Results.size());
6488 void Sema::CodeCompleteObjCImplementationCategory(Scope *S,
6489 IdentifierInfo *ClassName,
6490 SourceLocation ClassNameLoc) {
6491 typedef CodeCompletionResult Result;
6493 // Find the corresponding interface. If we couldn't find the interface, the
6494 // program itself is ill-formed. However, we'll try to be helpful still by
6495 // providing the list of all of the categories we know about.
6497 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
6498 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass);
6500 return CodeCompleteObjCInterfaceCategory(S, ClassName, ClassNameLoc);
6502 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6503 CodeCompleter->getCodeCompletionTUInfo(),
6504 CodeCompletionContext::CCC_ObjCCategoryName);
6506 // Add all of the categories that have have corresponding interface
6507 // declarations in this class and any of its superclasses, except for
6508 // already-implemented categories in the class itself.
6509 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
6510 Results.EnterNewScope();
6511 bool IgnoreImplemented = true;
6513 for (const auto *Cat : Class->visible_categories()) {
6514 if ((!IgnoreImplemented || !Cat->getImplementation()) &&
6515 CategoryNames.insert(Cat->getIdentifier()).second)
6516 Results.AddResult(Result(Cat, Results.getBasePriority(Cat), nullptr),
6517 CurContext, nullptr, false);
6520 Class = Class->getSuperClass();
6521 IgnoreImplemented = false;
6523 Results.ExitScope();
6525 HandleCodeCompleteResults(this, CodeCompleter,
6526 CodeCompletionContext::CCC_ObjCCategoryName,
6527 Results.data(),Results.size());
6530 void Sema::CodeCompleteObjCPropertyDefinition(Scope *S) {
6531 CodeCompletionContext CCContext(CodeCompletionContext::CCC_Other);
6532 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6533 CodeCompleter->getCodeCompletionTUInfo(),
6536 // Figure out where this @synthesize lives.
6537 ObjCContainerDecl *Container
6538 = dyn_cast_or_null<ObjCContainerDecl>(CurContext);
6540 (!isa<ObjCImplementationDecl>(Container) &&
6541 !isa<ObjCCategoryImplDecl>(Container)))
6544 // Ignore any properties that have already been implemented.
6545 Container = getContainerDef(Container);
6546 for (const auto *D : Container->decls())
6547 if (const auto *PropertyImpl = dyn_cast<ObjCPropertyImplDecl>(D))
6548 Results.Ignore(PropertyImpl->getPropertyDecl());
6550 // Add any properties that we find.
6551 AddedPropertiesSet AddedProperties;
6552 Results.EnterNewScope();
6553 if (ObjCImplementationDecl *ClassImpl
6554 = dyn_cast<ObjCImplementationDecl>(Container))
6555 AddObjCProperties(CCContext, ClassImpl->getClassInterface(), false,
6556 /*AllowNullaryMethods=*/false, CurContext,
6557 AddedProperties, Results);
6559 AddObjCProperties(CCContext,
6560 cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl(),
6561 false, /*AllowNullaryMethods=*/false, CurContext,
6562 AddedProperties, Results);
6563 Results.ExitScope();
6565 HandleCodeCompleteResults(this, CodeCompleter,
6566 CodeCompletionContext::CCC_Other,
6567 Results.data(),Results.size());
6570 void Sema::CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
6571 IdentifierInfo *PropertyName) {
6572 typedef CodeCompletionResult Result;
6573 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6574 CodeCompleter->getCodeCompletionTUInfo(),
6575 CodeCompletionContext::CCC_Other);
6577 // Figure out where this @synthesize lives.
6578 ObjCContainerDecl *Container
6579 = dyn_cast_or_null<ObjCContainerDecl>(CurContext);
6581 (!isa<ObjCImplementationDecl>(Container) &&
6582 !isa<ObjCCategoryImplDecl>(Container)))
6585 // Figure out which interface we're looking into.
6586 ObjCInterfaceDecl *Class = nullptr;
6587 if (ObjCImplementationDecl *ClassImpl
6588 = dyn_cast<ObjCImplementationDecl>(Container))
6589 Class = ClassImpl->getClassInterface();
6591 Class = cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl()
6592 ->getClassInterface();
6594 // Determine the type of the property we're synthesizing.
6595 QualType PropertyType = Context.getObjCIdType();
6597 if (ObjCPropertyDecl *Property = Class->FindPropertyDeclaration(
6598 PropertyName, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
6600 = Property->getType().getNonReferenceType().getUnqualifiedType();
6602 // Give preference to ivars
6603 Results.setPreferredType(PropertyType);
6607 // Add all of the instance variables in this class and its superclasses.
6608 Results.EnterNewScope();
6609 bool SawSimilarlyNamedIvar = false;
6610 std::string NameWithPrefix;
6611 NameWithPrefix += '_';
6612 NameWithPrefix += PropertyName->getName();
6613 std::string NameWithSuffix = PropertyName->getName().str();
6614 NameWithSuffix += '_';
6615 for(; Class; Class = Class->getSuperClass()) {
6616 for (ObjCIvarDecl *Ivar = Class->all_declared_ivar_begin(); Ivar;
6617 Ivar = Ivar->getNextIvar()) {
6618 Results.AddResult(Result(Ivar, Results.getBasePriority(Ivar), nullptr),
6619 CurContext, nullptr, false);
6621 // Determine whether we've seen an ivar with a name similar to the
6623 if ((PropertyName == Ivar->getIdentifier() ||
6624 NameWithPrefix == Ivar->getName() ||
6625 NameWithSuffix == Ivar->getName())) {
6626 SawSimilarlyNamedIvar = true;
6628 // Reduce the priority of this result by one, to give it a slight
6629 // advantage over other results whose names don't match so closely.
6630 if (Results.size() &&
6631 Results.data()[Results.size() - 1].Kind
6632 == CodeCompletionResult::RK_Declaration &&
6633 Results.data()[Results.size() - 1].Declaration == Ivar)
6634 Results.data()[Results.size() - 1].Priority--;
6639 if (!SawSimilarlyNamedIvar) {
6640 // Create ivar result _propName, that the user can use to synthesize
6641 // an ivar of the appropriate type.
6642 unsigned Priority = CCP_MemberDeclaration + 1;
6643 typedef CodeCompletionResult Result;
6644 CodeCompletionAllocator &Allocator = Results.getAllocator();
6645 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo(),
6646 Priority,CXAvailability_Available);
6648 PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
6649 Builder.AddResultTypeChunk(GetCompletionTypeString(PropertyType, Context,
6650 Policy, Allocator));
6651 Builder.AddTypedTextChunk(Allocator.CopyString(NameWithPrefix));
6652 Results.AddResult(Result(Builder.TakeString(), Priority,
6653 CXCursor_ObjCIvarDecl));
6656 Results.ExitScope();
6658 HandleCodeCompleteResults(this, CodeCompleter,
6659 CodeCompletionContext::CCC_Other,
6660 Results.data(),Results.size());
6663 // Mapping from selectors to the methods that implement that selector, along
6664 // with the "in original class" flag.
6665 typedef llvm::DenseMap<
6666 Selector, llvm::PointerIntPair<ObjCMethodDecl *, 1, bool> > KnownMethodsMap;
6668 /// \brief Find all of the methods that reside in the given container
6669 /// (and its superclasses, protocols, etc.) that meet the given
6670 /// criteria. Insert those methods into the map of known methods,
6671 /// indexed by selector so they can be easily found.
6672 static void FindImplementableMethods(ASTContext &Context,
6673 ObjCContainerDecl *Container,
6674 Optional<bool> WantInstanceMethods,
6675 QualType ReturnType,
6676 KnownMethodsMap &KnownMethods,
6677 bool InOriginalClass = true) {
6678 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)) {
6679 // Make sure we have a definition; that's what we'll walk.
6680 if (!IFace->hasDefinition())
6683 IFace = IFace->getDefinition();
6686 const ObjCList<ObjCProtocolDecl> &Protocols
6687 = IFace->getReferencedProtocols();
6688 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
6689 E = Protocols.end();
6691 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
6692 KnownMethods, InOriginalClass);
6694 // Add methods from any class extensions and categories.
6695 for (auto *Cat : IFace->visible_categories()) {
6696 FindImplementableMethods(Context, Cat, WantInstanceMethods, ReturnType,
6697 KnownMethods, false);
6700 // Visit the superclass.
6701 if (IFace->getSuperClass())
6702 FindImplementableMethods(Context, IFace->getSuperClass(),
6703 WantInstanceMethods, ReturnType,
6704 KnownMethods, false);
6707 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
6708 // Recurse into protocols.
6709 const ObjCList<ObjCProtocolDecl> &Protocols
6710 = Category->getReferencedProtocols();
6711 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
6712 E = Protocols.end();
6714 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
6715 KnownMethods, InOriginalClass);
6717 // If this category is the original class, jump to the interface.
6718 if (InOriginalClass && Category->getClassInterface())
6719 FindImplementableMethods(Context, Category->getClassInterface(),
6720 WantInstanceMethods, ReturnType, KnownMethods,
6724 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
6725 // Make sure we have a definition; that's what we'll walk.
6726 if (!Protocol->hasDefinition())
6728 Protocol = Protocol->getDefinition();
6729 Container = Protocol;
6731 // Recurse into protocols.
6732 const ObjCList<ObjCProtocolDecl> &Protocols
6733 = Protocol->getReferencedProtocols();
6734 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
6735 E = Protocols.end();
6737 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
6738 KnownMethods, false);
6741 // Add methods in this container. This operation occurs last because
6742 // we want the methods from this container to override any methods
6743 // we've previously seen with the same selector.
6744 for (auto *M : Container->methods()) {
6745 if (!WantInstanceMethods || M->isInstanceMethod() == *WantInstanceMethods) {
6746 if (!ReturnType.isNull() &&
6747 !Context.hasSameUnqualifiedType(ReturnType, M->getReturnType()))
6750 KnownMethods[M->getSelector()] =
6751 KnownMethodsMap::mapped_type(M, InOriginalClass);
6756 /// \brief Add the parenthesized return or parameter type chunk to a code
6757 /// completion string.
6758 static void AddObjCPassingTypeChunk(QualType Type,
6759 unsigned ObjCDeclQuals,
6760 ASTContext &Context,
6761 const PrintingPolicy &Policy,
6762 CodeCompletionBuilder &Builder) {
6763 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6764 std::string Quals = formatObjCParamQualifiers(ObjCDeclQuals, Type);
6766 Builder.AddTextChunk(Builder.getAllocator().CopyString(Quals));
6767 Builder.AddTextChunk(GetCompletionTypeString(Type, Context, Policy,
6768 Builder.getAllocator()));
6769 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6772 /// \brief Determine whether the given class is or inherits from a class by
6774 static bool InheritsFromClassNamed(ObjCInterfaceDecl *Class,
6779 if (Class->getIdentifier() && Class->getIdentifier()->getName() == Name)
6782 return InheritsFromClassNamed(Class->getSuperClass(), Name);
6785 /// \brief Add code completions for Objective-C Key-Value Coding (KVC) and
6786 /// Key-Value Observing (KVO).
6787 static void AddObjCKeyValueCompletions(ObjCPropertyDecl *Property,
6788 bool IsInstanceMethod,
6789 QualType ReturnType,
6790 ASTContext &Context,
6791 VisitedSelectorSet &KnownSelectors,
6792 ResultBuilder &Results) {
6793 IdentifierInfo *PropName = Property->getIdentifier();
6794 if (!PropName || PropName->getLength() == 0)
6797 PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema());
6799 // Builder that will create each code completion.
6800 typedef CodeCompletionResult Result;
6801 CodeCompletionAllocator &Allocator = Results.getAllocator();
6802 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
6804 // The selector table.
6805 SelectorTable &Selectors = Context.Selectors;
6807 // The property name, copied into the code completion allocation region
6810 CodeCompletionAllocator &Allocator;
6812 const char *CopiedKey;
6814 KeyHolder(CodeCompletionAllocator &Allocator, StringRef Key)
6815 : Allocator(Allocator), Key(Key), CopiedKey(nullptr) {}
6817 operator const char *() {
6821 return CopiedKey = Allocator.CopyString(Key);
6823 } Key(Allocator, PropName->getName());
6825 // The uppercased name of the property name.
6826 std::string UpperKey = PropName->getName();
6827 if (!UpperKey.empty())
6828 UpperKey[0] = toUppercase(UpperKey[0]);
6830 bool ReturnTypeMatchesProperty = ReturnType.isNull() ||
6831 Context.hasSameUnqualifiedType(ReturnType.getNonReferenceType(),
6832 Property->getType());
6833 bool ReturnTypeMatchesVoid
6834 = ReturnType.isNull() || ReturnType->isVoidType();
6836 // Add the normal accessor -(type)key.
6837 if (IsInstanceMethod &&
6838 KnownSelectors.insert(Selectors.getNullarySelector(PropName)).second &&
6839 ReturnTypeMatchesProperty && !Property->getGetterMethodDecl()) {
6840 if (ReturnType.isNull())
6841 AddObjCPassingTypeChunk(Property->getType(), /*Quals=*/0,
6842 Context, Policy, Builder);
6844 Builder.AddTypedTextChunk(Key);
6845 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6846 CXCursor_ObjCInstanceMethodDecl));
6849 // If we have an integral or boolean property (or the user has provided
6850 // an integral or boolean return type), add the accessor -(type)isKey.
6851 if (IsInstanceMethod &&
6852 ((!ReturnType.isNull() &&
6853 (ReturnType->isIntegerType() || ReturnType->isBooleanType())) ||
6854 (ReturnType.isNull() &&
6855 (Property->getType()->isIntegerType() ||
6856 Property->getType()->isBooleanType())))) {
6857 std::string SelectorName = (Twine("is") + UpperKey).str();
6858 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6859 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
6861 if (ReturnType.isNull()) {
6862 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6863 Builder.AddTextChunk("BOOL");
6864 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6867 Builder.AddTypedTextChunk(
6868 Allocator.CopyString(SelectorId->getName()));
6869 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6870 CXCursor_ObjCInstanceMethodDecl));
6874 // Add the normal mutator.
6875 if (IsInstanceMethod && ReturnTypeMatchesVoid &&
6876 !Property->getSetterMethodDecl()) {
6877 std::string SelectorName = (Twine("set") + UpperKey).str();
6878 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6879 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
6880 if (ReturnType.isNull()) {
6881 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6882 Builder.AddTextChunk("void");
6883 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6886 Builder.AddTypedTextChunk(
6887 Allocator.CopyString(SelectorId->getName()));
6888 Builder.AddTypedTextChunk(":");
6889 AddObjCPassingTypeChunk(Property->getType(), /*Quals=*/0,
6890 Context, Policy, Builder);
6891 Builder.AddTextChunk(Key);
6892 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6893 CXCursor_ObjCInstanceMethodDecl));
6897 // Indexed and unordered accessors
6898 unsigned IndexedGetterPriority = CCP_CodePattern;
6899 unsigned IndexedSetterPriority = CCP_CodePattern;
6900 unsigned UnorderedGetterPriority = CCP_CodePattern;
6901 unsigned UnorderedSetterPriority = CCP_CodePattern;
6902 if (const ObjCObjectPointerType *ObjCPointer
6903 = Property->getType()->getAs<ObjCObjectPointerType>()) {
6904 if (ObjCInterfaceDecl *IFace = ObjCPointer->getInterfaceDecl()) {
6905 // If this interface type is not provably derived from a known
6906 // collection, penalize the corresponding completions.
6907 if (!InheritsFromClassNamed(IFace, "NSMutableArray")) {
6908 IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
6909 if (!InheritsFromClassNamed(IFace, "NSArray"))
6910 IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
6913 if (!InheritsFromClassNamed(IFace, "NSMutableSet")) {
6914 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
6915 if (!InheritsFromClassNamed(IFace, "NSSet"))
6916 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
6920 IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
6921 IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
6922 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
6923 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
6926 // Add -(NSUInteger)countOf<key>
6927 if (IsInstanceMethod &&
6928 (ReturnType.isNull() || ReturnType->isIntegerType())) {
6929 std::string SelectorName = (Twine("countOf") + UpperKey).str();
6930 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6931 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
6933 if (ReturnType.isNull()) {
6934 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6935 Builder.AddTextChunk("NSUInteger");
6936 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6939 Builder.AddTypedTextChunk(
6940 Allocator.CopyString(SelectorId->getName()));
6941 Results.AddResult(Result(Builder.TakeString(),
6942 std::min(IndexedGetterPriority,
6943 UnorderedGetterPriority),
6944 CXCursor_ObjCInstanceMethodDecl));
6949 // Add -(id)objectInKeyAtIndex:(NSUInteger)index
6950 if (IsInstanceMethod &&
6951 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
6952 std::string SelectorName
6953 = (Twine("objectIn") + UpperKey + "AtIndex").str();
6954 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6955 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
6956 if (ReturnType.isNull()) {
6957 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6958 Builder.AddTextChunk("id");
6959 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6962 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6963 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6964 Builder.AddTextChunk("NSUInteger");
6965 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6966 Builder.AddTextChunk("index");
6967 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
6968 CXCursor_ObjCInstanceMethodDecl));
6972 // Add -(NSArray *)keyAtIndexes:(NSIndexSet *)indexes
6973 if (IsInstanceMethod &&
6974 (ReturnType.isNull() ||
6975 (ReturnType->isObjCObjectPointerType() &&
6976 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6977 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6978 ->getName() == "NSArray"))) {
6979 std::string SelectorName
6980 = (Twine(Property->getName()) + "AtIndexes").str();
6981 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6982 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
6983 if (ReturnType.isNull()) {
6984 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6985 Builder.AddTextChunk("NSArray *");
6986 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6989 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6990 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6991 Builder.AddTextChunk("NSIndexSet *");
6992 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6993 Builder.AddTextChunk("indexes");
6994 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
6995 CXCursor_ObjCInstanceMethodDecl));
6999 // Add -(void)getKey:(type **)buffer range:(NSRange)inRange
7000 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
7001 std::string SelectorName = (Twine("get") + UpperKey).str();
7002 IdentifierInfo *SelectorIds[2] = {
7003 &Context.Idents.get(SelectorName),
7004 &Context.Idents.get("range")
7007 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
7008 if (ReturnType.isNull()) {
7009 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7010 Builder.AddTextChunk("void");
7011 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7014 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
7015 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7016 Builder.AddPlaceholderChunk("object-type");
7017 Builder.AddTextChunk(" **");
7018 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7019 Builder.AddTextChunk("buffer");
7020 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7021 Builder.AddTypedTextChunk("range:");
7022 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7023 Builder.AddTextChunk("NSRange");
7024 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7025 Builder.AddTextChunk("inRange");
7026 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
7027 CXCursor_ObjCInstanceMethodDecl));
7031 // Mutable indexed accessors
7033 // - (void)insertObject:(type *)object inKeyAtIndex:(NSUInteger)index
7034 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
7035 std::string SelectorName = (Twine("in") + UpperKey + "AtIndex").str();
7036 IdentifierInfo *SelectorIds[2] = {
7037 &Context.Idents.get("insertObject"),
7038 &Context.Idents.get(SelectorName)
7041 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
7042 if (ReturnType.isNull()) {
7043 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7044 Builder.AddTextChunk("void");
7045 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7048 Builder.AddTypedTextChunk("insertObject:");
7049 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7050 Builder.AddPlaceholderChunk("object-type");
7051 Builder.AddTextChunk(" *");
7052 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7053 Builder.AddTextChunk("object");
7054 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7055 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
7056 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7057 Builder.AddPlaceholderChunk("NSUInteger");
7058 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7059 Builder.AddTextChunk("index");
7060 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
7061 CXCursor_ObjCInstanceMethodDecl));
7065 // - (void)insertKey:(NSArray *)array atIndexes:(NSIndexSet *)indexes
7066 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
7067 std::string SelectorName = (Twine("insert") + UpperKey).str();
7068 IdentifierInfo *SelectorIds[2] = {
7069 &Context.Idents.get(SelectorName),
7070 &Context.Idents.get("atIndexes")
7073 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
7074 if (ReturnType.isNull()) {
7075 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7076 Builder.AddTextChunk("void");
7077 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7080 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
7081 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7082 Builder.AddTextChunk("NSArray *");
7083 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7084 Builder.AddTextChunk("array");
7085 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7086 Builder.AddTypedTextChunk("atIndexes:");
7087 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7088 Builder.AddPlaceholderChunk("NSIndexSet *");
7089 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7090 Builder.AddTextChunk("indexes");
7091 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
7092 CXCursor_ObjCInstanceMethodDecl));
7096 // -(void)removeObjectFromKeyAtIndex:(NSUInteger)index
7097 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
7098 std::string SelectorName
7099 = (Twine("removeObjectFrom") + UpperKey + "AtIndex").str();
7100 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
7101 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
7102 if (ReturnType.isNull()) {
7103 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7104 Builder.AddTextChunk("void");
7105 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7108 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
7109 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7110 Builder.AddTextChunk("NSUInteger");
7111 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7112 Builder.AddTextChunk("index");
7113 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
7114 CXCursor_ObjCInstanceMethodDecl));
7118 // -(void)removeKeyAtIndexes:(NSIndexSet *)indexes
7119 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
7120 std::string SelectorName
7121 = (Twine("remove") + UpperKey + "AtIndexes").str();
7122 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
7123 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
7124 if (ReturnType.isNull()) {
7125 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7126 Builder.AddTextChunk("void");
7127 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7130 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
7131 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7132 Builder.AddTextChunk("NSIndexSet *");
7133 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7134 Builder.AddTextChunk("indexes");
7135 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
7136 CXCursor_ObjCInstanceMethodDecl));
7140 // - (void)replaceObjectInKeyAtIndex:(NSUInteger)index withObject:(id)object
7141 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
7142 std::string SelectorName
7143 = (Twine("replaceObjectIn") + UpperKey + "AtIndex").str();
7144 IdentifierInfo *SelectorIds[2] = {
7145 &Context.Idents.get(SelectorName),
7146 &Context.Idents.get("withObject")
7149 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
7150 if (ReturnType.isNull()) {
7151 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7152 Builder.AddTextChunk("void");
7153 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7156 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
7157 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7158 Builder.AddPlaceholderChunk("NSUInteger");
7159 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7160 Builder.AddTextChunk("index");
7161 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7162 Builder.AddTypedTextChunk("withObject:");
7163 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7164 Builder.AddTextChunk("id");
7165 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7166 Builder.AddTextChunk("object");
7167 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
7168 CXCursor_ObjCInstanceMethodDecl));
7172 // - (void)replaceKeyAtIndexes:(NSIndexSet *)indexes withKey:(NSArray *)array
7173 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
7174 std::string SelectorName1
7175 = (Twine("replace") + UpperKey + "AtIndexes").str();
7176 std::string SelectorName2 = (Twine("with") + UpperKey).str();
7177 IdentifierInfo *SelectorIds[2] = {
7178 &Context.Idents.get(SelectorName1),
7179 &Context.Idents.get(SelectorName2)
7182 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
7183 if (ReturnType.isNull()) {
7184 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7185 Builder.AddTextChunk("void");
7186 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7189 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName1 + ":"));
7190 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7191 Builder.AddPlaceholderChunk("NSIndexSet *");
7192 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7193 Builder.AddTextChunk("indexes");
7194 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7195 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName2 + ":"));
7196 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7197 Builder.AddTextChunk("NSArray *");
7198 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7199 Builder.AddTextChunk("array");
7200 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
7201 CXCursor_ObjCInstanceMethodDecl));
7205 // Unordered getters
7206 // - (NSEnumerator *)enumeratorOfKey
7207 if (IsInstanceMethod &&
7208 (ReturnType.isNull() ||
7209 (ReturnType->isObjCObjectPointerType() &&
7210 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
7211 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
7212 ->getName() == "NSEnumerator"))) {
7213 std::string SelectorName = (Twine("enumeratorOf") + UpperKey).str();
7214 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
7215 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
7217 if (ReturnType.isNull()) {
7218 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7219 Builder.AddTextChunk("NSEnumerator *");
7220 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7223 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
7224 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
7225 CXCursor_ObjCInstanceMethodDecl));
7229 // - (type *)memberOfKey:(type *)object
7230 if (IsInstanceMethod &&
7231 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
7232 std::string SelectorName = (Twine("memberOf") + UpperKey).str();
7233 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
7234 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
7235 if (ReturnType.isNull()) {
7236 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7237 Builder.AddPlaceholderChunk("object-type");
7238 Builder.AddTextChunk(" *");
7239 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7242 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
7243 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7244 if (ReturnType.isNull()) {
7245 Builder.AddPlaceholderChunk("object-type");
7246 Builder.AddTextChunk(" *");
7248 Builder.AddTextChunk(GetCompletionTypeString(ReturnType, Context,
7250 Builder.getAllocator()));
7252 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7253 Builder.AddTextChunk("object");
7254 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
7255 CXCursor_ObjCInstanceMethodDecl));
7259 // Mutable unordered accessors
7260 // - (void)addKeyObject:(type *)object
7261 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
7262 std::string SelectorName
7263 = (Twine("add") + UpperKey + Twine("Object")).str();
7264 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
7265 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
7266 if (ReturnType.isNull()) {
7267 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7268 Builder.AddTextChunk("void");
7269 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7272 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
7273 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7274 Builder.AddPlaceholderChunk("object-type");
7275 Builder.AddTextChunk(" *");
7276 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7277 Builder.AddTextChunk("object");
7278 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
7279 CXCursor_ObjCInstanceMethodDecl));
7283 // - (void)addKey:(NSSet *)objects
7284 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
7285 std::string SelectorName = (Twine("add") + UpperKey).str();
7286 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
7287 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
7288 if (ReturnType.isNull()) {
7289 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7290 Builder.AddTextChunk("void");
7291 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7294 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
7295 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7296 Builder.AddTextChunk("NSSet *");
7297 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7298 Builder.AddTextChunk("objects");
7299 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
7300 CXCursor_ObjCInstanceMethodDecl));
7304 // - (void)removeKeyObject:(type *)object
7305 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
7306 std::string SelectorName
7307 = (Twine("remove") + UpperKey + Twine("Object")).str();
7308 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
7309 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
7310 if (ReturnType.isNull()) {
7311 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7312 Builder.AddTextChunk("void");
7313 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7316 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
7317 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7318 Builder.AddPlaceholderChunk("object-type");
7319 Builder.AddTextChunk(" *");
7320 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7321 Builder.AddTextChunk("object");
7322 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
7323 CXCursor_ObjCInstanceMethodDecl));
7327 // - (void)removeKey:(NSSet *)objects
7328 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
7329 std::string SelectorName = (Twine("remove") + UpperKey).str();
7330 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
7331 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
7332 if (ReturnType.isNull()) {
7333 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7334 Builder.AddTextChunk("void");
7335 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7338 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
7339 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7340 Builder.AddTextChunk("NSSet *");
7341 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7342 Builder.AddTextChunk("objects");
7343 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
7344 CXCursor_ObjCInstanceMethodDecl));
7348 // - (void)intersectKey:(NSSet *)objects
7349 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
7350 std::string SelectorName = (Twine("intersect") + UpperKey).str();
7351 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
7352 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
7353 if (ReturnType.isNull()) {
7354 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7355 Builder.AddTextChunk("void");
7356 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7359 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
7360 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7361 Builder.AddTextChunk("NSSet *");
7362 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7363 Builder.AddTextChunk("objects");
7364 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
7365 CXCursor_ObjCInstanceMethodDecl));
7369 // Key-Value Observing
7370 // + (NSSet *)keyPathsForValuesAffectingKey
7371 if (!IsInstanceMethod &&
7372 (ReturnType.isNull() ||
7373 (ReturnType->isObjCObjectPointerType() &&
7374 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
7375 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
7376 ->getName() == "NSSet"))) {
7377 std::string SelectorName
7378 = (Twine("keyPathsForValuesAffecting") + UpperKey).str();
7379 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
7380 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
7382 if (ReturnType.isNull()) {
7383 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7384 Builder.AddTextChunk("NSSet<NSString *> *");
7385 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7388 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
7389 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
7390 CXCursor_ObjCClassMethodDecl));
7394 // + (BOOL)automaticallyNotifiesObserversForKey
7395 if (!IsInstanceMethod &&
7396 (ReturnType.isNull() ||
7397 ReturnType->isIntegerType() ||
7398 ReturnType->isBooleanType())) {
7399 std::string SelectorName
7400 = (Twine("automaticallyNotifiesObserversOf") + UpperKey).str();
7401 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
7402 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
7404 if (ReturnType.isNull()) {
7405 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7406 Builder.AddTextChunk("BOOL");
7407 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7410 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
7411 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
7412 CXCursor_ObjCClassMethodDecl));
7417 void Sema::CodeCompleteObjCMethodDecl(Scope *S, Optional<bool> IsInstanceMethod,
7418 ParsedType ReturnTy) {
7419 // Determine the return type of the method we're declaring, if
7421 QualType ReturnType = GetTypeFromParser(ReturnTy);
7422 Decl *IDecl = nullptr;
7423 if (CurContext->isObjCContainer()) {
7424 ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext);
7425 IDecl = cast<Decl>(OCD);
7427 // Determine where we should start searching for methods.
7428 ObjCContainerDecl *SearchDecl = nullptr;
7429 bool IsInImplementation = false;
7430 if (Decl *D = IDecl) {
7431 if (ObjCImplementationDecl *Impl = dyn_cast<ObjCImplementationDecl>(D)) {
7432 SearchDecl = Impl->getClassInterface();
7433 IsInImplementation = true;
7434 } else if (ObjCCategoryImplDecl *CatImpl
7435 = dyn_cast<ObjCCategoryImplDecl>(D)) {
7436 SearchDecl = CatImpl->getCategoryDecl();
7437 IsInImplementation = true;
7439 SearchDecl = dyn_cast<ObjCContainerDecl>(D);
7442 if (!SearchDecl && S) {
7443 if (DeclContext *DC = S->getEntity())
7444 SearchDecl = dyn_cast<ObjCContainerDecl>(DC);
7448 HandleCodeCompleteResults(this, CodeCompleter,
7449 CodeCompletionContext::CCC_Other,
7454 // Find all of the methods that we could declare/implement here.
7455 KnownMethodsMap KnownMethods;
7456 FindImplementableMethods(Context, SearchDecl, IsInstanceMethod,
7457 ReturnType, KnownMethods);
7459 // Add declarations or definitions for each of the known methods.
7460 typedef CodeCompletionResult Result;
7461 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
7462 CodeCompleter->getCodeCompletionTUInfo(),
7463 CodeCompletionContext::CCC_Other);
7464 Results.EnterNewScope();
7465 PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
7466 for (KnownMethodsMap::iterator M = KnownMethods.begin(),
7467 MEnd = KnownMethods.end();
7469 ObjCMethodDecl *Method = M->second.getPointer();
7470 CodeCompletionBuilder Builder(Results.getAllocator(),
7471 Results.getCodeCompletionTUInfo());
7473 // Add the '-'/'+' prefix if it wasn't provided yet.
7474 if (!IsInstanceMethod) {
7475 Builder.AddTextChunk(Method->isInstanceMethod() ? "-" : "+");
7476 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7479 // If the result type was not already provided, add it to the
7480 // pattern as (type).
7481 if (ReturnType.isNull()) {
7482 QualType ResTy = Method->getSendResultType().stripObjCKindOfType(Context);
7483 AttributedType::stripOuterNullability(ResTy);
7484 AddObjCPassingTypeChunk(ResTy,
7485 Method->getObjCDeclQualifier(), Context, Policy,
7489 Selector Sel = Method->getSelector();
7491 // Add the first part of the selector to the pattern.
7492 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
7493 Sel.getNameForSlot(0)));
7495 // Add parameters to the pattern.
7497 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
7498 PEnd = Method->param_end();
7499 P != PEnd; (void)++P, ++I) {
7500 // Add the part of the selector name.
7502 Builder.AddTypedTextChunk(":");
7503 else if (I < Sel.getNumArgs()) {
7504 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7505 Builder.AddTypedTextChunk(
7506 Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":"));
7510 // Add the parameter type.
7512 if ((*P)->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
7513 ParamType = (*P)->getType();
7515 ParamType = (*P)->getOriginalType();
7516 ParamType = ParamType.substObjCTypeArgs(Context, {},
7517 ObjCSubstitutionContext::Parameter);
7518 AttributedType::stripOuterNullability(ParamType);
7519 AddObjCPassingTypeChunk(ParamType,
7520 (*P)->getObjCDeclQualifier(),
7524 if (IdentifierInfo *Id = (*P)->getIdentifier())
7525 Builder.AddTextChunk(Builder.getAllocator().CopyString( Id->getName()));
7528 if (Method->isVariadic()) {
7529 if (Method->param_size() > 0)
7530 Builder.AddChunk(CodeCompletionString::CK_Comma);
7531 Builder.AddTextChunk("...");
7534 if (IsInImplementation && Results.includeCodePatterns()) {
7535 // We will be defining the method here, so add a compound statement.
7536 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7537 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
7538 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
7539 if (!Method->getReturnType()->isVoidType()) {
7540 // If the result type is not void, add a return clause.
7541 Builder.AddTextChunk("return");
7542 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7543 Builder.AddPlaceholderChunk("expression");
7544 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
7546 Builder.AddPlaceholderChunk("statements");
7548 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
7549 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
7552 unsigned Priority = CCP_CodePattern;
7553 if (!M->second.getInt())
7554 Priority += CCD_InBaseClass;
7556 Results.AddResult(Result(Builder.TakeString(), Method, Priority));
7559 // Add Key-Value-Coding and Key-Value-Observing accessor methods for all of
7560 // the properties in this class and its categories.
7561 if (Context.getLangOpts().ObjC2) {
7562 SmallVector<ObjCContainerDecl *, 4> Containers;
7563 Containers.push_back(SearchDecl);
7565 VisitedSelectorSet KnownSelectors;
7566 for (KnownMethodsMap::iterator M = KnownMethods.begin(),
7567 MEnd = KnownMethods.end();
7569 KnownSelectors.insert(M->first);
7572 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(SearchDecl);
7574 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(SearchDecl))
7575 IFace = Category->getClassInterface();
7578 for (auto *Cat : IFace->visible_categories())
7579 Containers.push_back(Cat);
7581 if (IsInstanceMethod) {
7582 for (unsigned I = 0, N = Containers.size(); I != N; ++I)
7583 for (auto *P : Containers[I]->instance_properties())
7584 AddObjCKeyValueCompletions(P, *IsInstanceMethod, ReturnType, Context,
7585 KnownSelectors, Results);
7589 Results.ExitScope();
7591 HandleCodeCompleteResults(this, CodeCompleter,
7592 CodeCompletionContext::CCC_Other,
7593 Results.data(),Results.size());
7596 void Sema::CodeCompleteObjCMethodDeclSelector(Scope *S,
7597 bool IsInstanceMethod,
7598 bool AtParameterName,
7599 ParsedType ReturnTy,
7600 ArrayRef<IdentifierInfo *> SelIdents) {
7601 // If we have an external source, load the entire class method
7602 // pool from the AST file.
7603 if (ExternalSource) {
7604 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
7606 Selector Sel = ExternalSource->GetExternalSelector(I);
7607 if (Sel.isNull() || MethodPool.count(Sel))
7610 ReadMethodPool(Sel);
7614 // Build the set of methods we can see.
7615 typedef CodeCompletionResult Result;
7616 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
7617 CodeCompleter->getCodeCompletionTUInfo(),
7618 CodeCompletionContext::CCC_Other);
7621 Results.setPreferredType(GetTypeFromParser(ReturnTy).getNonReferenceType());
7623 Results.EnterNewScope();
7624 for (GlobalMethodPool::iterator M = MethodPool.begin(),
7625 MEnd = MethodPool.end();
7627 for (ObjCMethodList *MethList = IsInstanceMethod ? &M->second.first :
7629 MethList && MethList->getMethod();
7630 MethList = MethList->getNext()) {
7631 if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents))
7634 if (AtParameterName) {
7635 // Suggest parameter names we've seen before.
7636 unsigned NumSelIdents = SelIdents.size();
7638 NumSelIdents <= MethList->getMethod()->param_size()) {
7639 ParmVarDecl *Param =
7640 MethList->getMethod()->parameters()[NumSelIdents - 1];
7641 if (Param->getIdentifier()) {
7642 CodeCompletionBuilder Builder(Results.getAllocator(),
7643 Results.getCodeCompletionTUInfo());
7644 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
7645 Param->getIdentifier()->getName()));
7646 Results.AddResult(Builder.TakeString());
7653 Result R(MethList->getMethod(),
7654 Results.getBasePriority(MethList->getMethod()), nullptr);
7655 R.StartParameter = SelIdents.size();
7656 R.AllParametersAreInformative = false;
7657 R.DeclaringEntity = true;
7658 Results.MaybeAddResult(R, CurContext);
7662 Results.ExitScope();
7664 if (!AtParameterName && !SelIdents.empty() &&
7665 SelIdents.front()->getName().startswith("init")) {
7666 for (const auto &M : PP.macros()) {
7667 if (M.first->getName() != "NS_DESIGNATED_INITIALIZER")
7669 Results.EnterNewScope();
7670 CodeCompletionBuilder Builder(Results.getAllocator(),
7671 Results.getCodeCompletionTUInfo());
7672 Builder.AddTypedTextChunk(
7673 Builder.getAllocator().CopyString(M.first->getName()));
7674 Results.AddResult(CodeCompletionResult(Builder.TakeString(), CCP_Macro,
7675 CXCursor_MacroDefinition));
7676 Results.ExitScope();
7680 HandleCodeCompleteResults(this, CodeCompleter,
7681 CodeCompletionContext::CCC_Other,
7682 Results.data(),Results.size());
7685 void Sema::CodeCompletePreprocessorDirective(bool InConditional) {
7686 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
7687 CodeCompleter->getCodeCompletionTUInfo(),
7688 CodeCompletionContext::CCC_PreprocessorDirective);
7689 Results.EnterNewScope();
7692 CodeCompletionBuilder Builder(Results.getAllocator(),
7693 Results.getCodeCompletionTUInfo());
7694 Builder.AddTypedTextChunk("if");
7695 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7696 Builder.AddPlaceholderChunk("condition");
7697 Results.AddResult(Builder.TakeString());
7700 Builder.AddTypedTextChunk("ifdef");
7701 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7702 Builder.AddPlaceholderChunk("macro");
7703 Results.AddResult(Builder.TakeString());
7706 Builder.AddTypedTextChunk("ifndef");
7707 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7708 Builder.AddPlaceholderChunk("macro");
7709 Results.AddResult(Builder.TakeString());
7711 if (InConditional) {
7712 // #elif <condition>
7713 Builder.AddTypedTextChunk("elif");
7714 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7715 Builder.AddPlaceholderChunk("condition");
7716 Results.AddResult(Builder.TakeString());
7719 Builder.AddTypedTextChunk("else");
7720 Results.AddResult(Builder.TakeString());
7723 Builder.AddTypedTextChunk("endif");
7724 Results.AddResult(Builder.TakeString());
7727 // #include "header"
7728 Builder.AddTypedTextChunk("include");
7729 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7730 Builder.AddTextChunk("\"");
7731 Builder.AddPlaceholderChunk("header");
7732 Builder.AddTextChunk("\"");
7733 Results.AddResult(Builder.TakeString());
7735 // #include <header>
7736 Builder.AddTypedTextChunk("include");
7737 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7738 Builder.AddTextChunk("<");
7739 Builder.AddPlaceholderChunk("header");
7740 Builder.AddTextChunk(">");
7741 Results.AddResult(Builder.TakeString());
7744 Builder.AddTypedTextChunk("define");
7745 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7746 Builder.AddPlaceholderChunk("macro");
7747 Results.AddResult(Builder.TakeString());
7749 // #define <macro>(<args>)
7750 Builder.AddTypedTextChunk("define");
7751 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7752 Builder.AddPlaceholderChunk("macro");
7753 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7754 Builder.AddPlaceholderChunk("args");
7755 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7756 Results.AddResult(Builder.TakeString());
7759 Builder.AddTypedTextChunk("undef");
7760 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7761 Builder.AddPlaceholderChunk("macro");
7762 Results.AddResult(Builder.TakeString());
7765 Builder.AddTypedTextChunk("line");
7766 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7767 Builder.AddPlaceholderChunk("number");
7768 Results.AddResult(Builder.TakeString());
7770 // #line <number> "filename"
7771 Builder.AddTypedTextChunk("line");
7772 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7773 Builder.AddPlaceholderChunk("number");
7774 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7775 Builder.AddTextChunk("\"");
7776 Builder.AddPlaceholderChunk("filename");
7777 Builder.AddTextChunk("\"");
7778 Results.AddResult(Builder.TakeString());
7781 Builder.AddTypedTextChunk("error");
7782 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7783 Builder.AddPlaceholderChunk("message");
7784 Results.AddResult(Builder.TakeString());
7786 // #pragma <arguments>
7787 Builder.AddTypedTextChunk("pragma");
7788 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7789 Builder.AddPlaceholderChunk("arguments");
7790 Results.AddResult(Builder.TakeString());
7792 if (getLangOpts().ObjC1) {
7794 Builder.AddTypedTextChunk("import");
7795 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7796 Builder.AddTextChunk("\"");
7797 Builder.AddPlaceholderChunk("header");
7798 Builder.AddTextChunk("\"");
7799 Results.AddResult(Builder.TakeString());
7802 Builder.AddTypedTextChunk("import");
7803 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7804 Builder.AddTextChunk("<");
7805 Builder.AddPlaceholderChunk("header");
7806 Builder.AddTextChunk(">");
7807 Results.AddResult(Builder.TakeString());
7810 // #include_next "header"
7811 Builder.AddTypedTextChunk("include_next");
7812 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7813 Builder.AddTextChunk("\"");
7814 Builder.AddPlaceholderChunk("header");
7815 Builder.AddTextChunk("\"");
7816 Results.AddResult(Builder.TakeString());
7818 // #include_next <header>
7819 Builder.AddTypedTextChunk("include_next");
7820 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7821 Builder.AddTextChunk("<");
7822 Builder.AddPlaceholderChunk("header");
7823 Builder.AddTextChunk(">");
7824 Results.AddResult(Builder.TakeString());
7826 // #warning <message>
7827 Builder.AddTypedTextChunk("warning");
7828 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7829 Builder.AddPlaceholderChunk("message");
7830 Results.AddResult(Builder.TakeString());
7832 // Note: #ident and #sccs are such crazy anachronisms that we don't provide
7833 // completions for them. And __include_macros is a Clang-internal extension
7834 // that we don't want to encourage anyone to use.
7836 // FIXME: we don't support #assert or #unassert, so don't suggest them.
7837 Results.ExitScope();
7839 HandleCodeCompleteResults(this, CodeCompleter,
7840 CodeCompletionContext::CCC_PreprocessorDirective,
7841 Results.data(), Results.size());
7844 void Sema::CodeCompleteInPreprocessorConditionalExclusion(Scope *S) {
7845 CodeCompleteOrdinaryName(S,
7846 S->getFnParent()? Sema::PCC_RecoveryInFunction
7847 : Sema::PCC_Namespace);
7850 void Sema::CodeCompletePreprocessorMacroName(bool IsDefinition) {
7851 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
7852 CodeCompleter->getCodeCompletionTUInfo(),
7853 IsDefinition? CodeCompletionContext::CCC_MacroName
7854 : CodeCompletionContext::CCC_MacroNameUse);
7855 if (!IsDefinition && (!CodeCompleter || CodeCompleter->includeMacros())) {
7856 // Add just the names of macros, not their arguments.
7857 CodeCompletionBuilder Builder(Results.getAllocator(),
7858 Results.getCodeCompletionTUInfo());
7859 Results.EnterNewScope();
7860 for (Preprocessor::macro_iterator M = PP.macro_begin(),
7861 MEnd = PP.macro_end();
7863 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
7864 M->first->getName()));
7865 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
7867 CXCursor_MacroDefinition));
7869 Results.ExitScope();
7870 } else if (IsDefinition) {
7871 // FIXME: Can we detect when the user just wrote an include guard above?
7874 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
7875 Results.data(), Results.size());
7878 void Sema::CodeCompletePreprocessorExpression() {
7879 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
7880 CodeCompleter->getCodeCompletionTUInfo(),
7881 CodeCompletionContext::CCC_PreprocessorExpression);
7883 if (!CodeCompleter || CodeCompleter->includeMacros())
7884 AddMacroResults(PP, Results, true);
7886 // defined (<macro>)
7887 Results.EnterNewScope();
7888 CodeCompletionBuilder Builder(Results.getAllocator(),
7889 Results.getCodeCompletionTUInfo());
7890 Builder.AddTypedTextChunk("defined");
7891 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7892 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7893 Builder.AddPlaceholderChunk("macro");
7894 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7895 Results.AddResult(Builder.TakeString());
7896 Results.ExitScope();
7898 HandleCodeCompleteResults(this, CodeCompleter,
7899 CodeCompletionContext::CCC_PreprocessorExpression,
7900 Results.data(), Results.size());
7903 void Sema::CodeCompletePreprocessorMacroArgument(Scope *S,
7904 IdentifierInfo *Macro,
7905 MacroInfo *MacroInfo,
7906 unsigned Argument) {
7907 // FIXME: In the future, we could provide "overload" results, much like we
7908 // do for function calls.
7910 // Now just ignore this. There will be another code-completion callback
7911 // for the expanded tokens.
7914 void Sema::CodeCompleteNaturalLanguage() {
7915 HandleCodeCompleteResults(this, CodeCompleter,
7916 CodeCompletionContext::CCC_NaturalLanguage,
7920 void Sema::CodeCompleteAvailabilityPlatformName() {
7921 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
7922 CodeCompleter->getCodeCompletionTUInfo(),
7923 CodeCompletionContext::CCC_Other);
7924 Results.EnterNewScope();
7925 static const char *Platforms[] = {"macOS", "iOS", "watchOS", "tvOS"};
7926 for (const char *Platform : llvm::makeArrayRef(Platforms)) {
7927 Results.AddResult(CodeCompletionResult(Platform));
7928 Results.AddResult(CodeCompletionResult(Results.getAllocator().CopyString(
7929 Twine(Platform) + "ApplicationExtension")));
7931 Results.ExitScope();
7932 HandleCodeCompleteResults(this, CodeCompleter,
7933 CodeCompletionContext::CCC_Other, Results.data(),
7937 void Sema::GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
7938 CodeCompletionTUInfo &CCTUInfo,
7939 SmallVectorImpl<CodeCompletionResult> &Results) {
7940 ResultBuilder Builder(*this, Allocator, CCTUInfo,
7941 CodeCompletionContext::CCC_Recovery);
7942 if (!CodeCompleter || CodeCompleter->includeGlobals()) {
7943 CodeCompletionDeclConsumer Consumer(Builder,
7944 Context.getTranslationUnitDecl());
7945 LookupVisibleDecls(Context.getTranslationUnitDecl(), LookupAnyName,
7949 if (!CodeCompleter || CodeCompleter->includeMacros())
7950 AddMacroResults(PP, Builder, true);
7953 Results.insert(Results.end(),
7954 Builder.data(), Builder.data() + Builder.size());