1 //===---------------- SemaCodeComplete.cpp - Code Completion ----*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the code-completion semantic actions.
12 //===----------------------------------------------------------------------===//
13 #include "clang/Sema/SemaInternal.h"
14 #include "clang/AST/DeclObjC.h"
15 #include "clang/AST/ExprCXX.h"
16 #include "clang/AST/ExprObjC.h"
17 #include "clang/Basic/CharInfo.h"
18 #include "clang/Lex/HeaderSearch.h"
19 #include "clang/Lex/MacroInfo.h"
20 #include "clang/Lex/Preprocessor.h"
21 #include "clang/Sema/CodeCompleteConsumer.h"
22 #include "clang/Sema/ExternalSemaSource.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 "llvm/ADT/DenseSet.h"
28 #include "llvm/ADT/SmallBitVector.h"
29 #include "llvm/ADT/SmallPtrSet.h"
30 #include "llvm/ADT/SmallString.h"
31 #include "llvm/ADT/StringExtras.h"
32 #include "llvm/ADT/StringSwitch.h"
33 #include "llvm/ADT/Twine.h"
38 using namespace clang;
42 /// \brief A container of code-completion results.
45 /// \brief The type of a name-lookup filter, which can be provided to the
46 /// name-lookup routines to specify which declarations should be included in
47 /// the result set (when it returns true) and which declarations should be
48 /// filtered out (returns false).
49 typedef bool (ResultBuilder::*LookupFilter)(const NamedDecl *) const;
51 typedef CodeCompletionResult Result;
54 /// \brief The actual results we have found.
55 std::vector<Result> Results;
57 /// \brief A record of all of the declarations we have found and placed
58 /// into the result set, used to ensure that no declaration ever gets into
59 /// the result set twice.
60 llvm::SmallPtrSet<const Decl*, 16> AllDeclsFound;
62 typedef std::pair<const NamedDecl *, unsigned> DeclIndexPair;
64 /// \brief An entry in the shadow map, which is optimized to store
65 /// a single (declaration, index) mapping (the common case) but
66 /// can also store a list of (declaration, index) mappings.
67 class ShadowMapEntry {
68 typedef SmallVector<DeclIndexPair, 4> DeclIndexPairVector;
70 /// \brief Contains either the solitary NamedDecl * or a vector
71 /// of (declaration, index) pairs.
72 llvm::PointerUnion<const NamedDecl *, DeclIndexPairVector*> DeclOrVector;
74 /// \brief When the entry contains a single declaration, this is
75 /// the index associated with that entry.
76 unsigned SingleDeclIndex;
79 ShadowMapEntry() : DeclOrVector(), SingleDeclIndex(0) { }
81 void Add(const NamedDecl *ND, unsigned Index) {
82 if (DeclOrVector.isNull()) {
83 // 0 - > 1 elements: just set the single element information.
85 SingleDeclIndex = Index;
89 if (const NamedDecl *PrevND =
90 DeclOrVector.dyn_cast<const NamedDecl *>()) {
91 // 1 -> 2 elements: create the vector of results and push in the
92 // existing declaration.
93 DeclIndexPairVector *Vec = new DeclIndexPairVector;
94 Vec->push_back(DeclIndexPair(PrevND, SingleDeclIndex));
98 // Add the new element to the end of the vector.
99 DeclOrVector.get<DeclIndexPairVector*>()->push_back(
100 DeclIndexPair(ND, Index));
104 if (DeclIndexPairVector *Vec
105 = DeclOrVector.dyn_cast<DeclIndexPairVector *>()) {
107 DeclOrVector = ((NamedDecl *)nullptr);
113 iterator begin() const;
114 iterator end() const;
117 /// \brief A mapping from declaration names to the declarations that have
118 /// this name within a particular scope and their index within the list of
120 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
122 /// \brief The semantic analysis object for which results are being
126 /// \brief The allocator used to allocate new code-completion strings.
127 CodeCompletionAllocator &Allocator;
129 CodeCompletionTUInfo &CCTUInfo;
131 /// \brief If non-NULL, a filter function used to remove any code-completion
132 /// results that are not desirable.
135 /// \brief Whether we should allow declarations as
136 /// nested-name-specifiers that would otherwise be filtered out.
137 bool AllowNestedNameSpecifiers;
139 /// \brief If set, the type that we would prefer our resulting value
140 /// declarations to have.
142 /// Closely matching the preferred type gives a boost to a result's
144 CanQualType PreferredType;
146 /// \brief A list of shadow maps, which is used to model name hiding at
147 /// different levels of, e.g., the inheritance hierarchy.
148 std::list<ShadowMap> ShadowMaps;
150 /// \brief If we're potentially referring to a C++ member function, the set
151 /// of qualifiers applied to the object type.
152 Qualifiers ObjectTypeQualifiers;
154 /// \brief Whether the \p ObjectTypeQualifiers field is active.
155 bool HasObjectTypeQualifiers;
157 /// \brief The selector that we prefer.
158 Selector PreferredSelector;
160 /// \brief The completion context in which we are gathering results.
161 CodeCompletionContext CompletionContext;
163 /// \brief If we are in an instance method definition, the \@implementation
165 ObjCImplementationDecl *ObjCImplementation;
167 void AdjustResultPriorityForDecl(Result &R);
169 void MaybeAddConstructorResults(Result R);
172 explicit ResultBuilder(Sema &SemaRef, CodeCompletionAllocator &Allocator,
173 CodeCompletionTUInfo &CCTUInfo,
174 const CodeCompletionContext &CompletionContext,
175 LookupFilter Filter = nullptr)
176 : SemaRef(SemaRef), Allocator(Allocator), CCTUInfo(CCTUInfo),
178 AllowNestedNameSpecifiers(false), HasObjectTypeQualifiers(false),
179 CompletionContext(CompletionContext),
180 ObjCImplementation(nullptr)
182 // If this is an Objective-C instance method definition, dig out the
183 // corresponding implementation.
184 switch (CompletionContext.getKind()) {
185 case CodeCompletionContext::CCC_Expression:
186 case CodeCompletionContext::CCC_ObjCMessageReceiver:
187 case CodeCompletionContext::CCC_ParenthesizedExpression:
188 case CodeCompletionContext::CCC_Statement:
189 case CodeCompletionContext::CCC_Recovery:
190 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl())
191 if (Method->isInstanceMethod())
192 if (ObjCInterfaceDecl *Interface = Method->getClassInterface())
193 ObjCImplementation = Interface->getImplementation();
201 /// \brief Determine the priority for a reference to the given declaration.
202 unsigned getBasePriority(const NamedDecl *D);
204 /// \brief Whether we should include code patterns in the completion
206 bool includeCodePatterns() const {
207 return SemaRef.CodeCompleter &&
208 SemaRef.CodeCompleter->includeCodePatterns();
211 /// \brief Set the filter used for code-completion results.
212 void setFilter(LookupFilter Filter) {
213 this->Filter = Filter;
216 Result *data() { return Results.empty()? nullptr : &Results.front(); }
217 unsigned size() const { return Results.size(); }
218 bool empty() const { return Results.empty(); }
220 /// \brief Specify the preferred type.
221 void setPreferredType(QualType T) {
222 PreferredType = SemaRef.Context.getCanonicalType(T);
225 /// \brief Set the cv-qualifiers on the object type, for us in filtering
226 /// calls to member functions.
228 /// When there are qualifiers in this set, they will be used to filter
229 /// out member functions that aren't available (because there will be a
230 /// cv-qualifier mismatch) or prefer functions with an exact qualifier
232 void setObjectTypeQualifiers(Qualifiers Quals) {
233 ObjectTypeQualifiers = Quals;
234 HasObjectTypeQualifiers = true;
237 /// \brief Set the preferred selector.
239 /// When an Objective-C method declaration result is added, and that
240 /// method's selector matches this preferred selector, we give that method
241 /// a slight priority boost.
242 void setPreferredSelector(Selector Sel) {
243 PreferredSelector = Sel;
246 /// \brief Retrieve the code-completion context for which results are
248 const CodeCompletionContext &getCompletionContext() const {
249 return CompletionContext;
252 /// \brief Specify whether nested-name-specifiers are allowed.
253 void allowNestedNameSpecifiers(bool Allow = true) {
254 AllowNestedNameSpecifiers = Allow;
257 /// \brief Return the semantic analysis object for which we are collecting
258 /// code completion results.
259 Sema &getSema() const { return SemaRef; }
261 /// \brief Retrieve the allocator used to allocate code completion strings.
262 CodeCompletionAllocator &getAllocator() const { return Allocator; }
264 CodeCompletionTUInfo &getCodeCompletionTUInfo() const { return CCTUInfo; }
266 /// \brief Determine whether the given declaration is at all interesting
267 /// as a code-completion result.
269 /// \param ND the declaration that we are inspecting.
271 /// \param AsNestedNameSpecifier will be set true if this declaration is
272 /// only interesting when it is a nested-name-specifier.
273 bool isInterestingDecl(const NamedDecl *ND,
274 bool &AsNestedNameSpecifier) const;
276 /// \brief Check whether the result is hidden by the Hiding declaration.
278 /// \returns true if the result is hidden and cannot be found, false if
279 /// the hidden result could still be found. When false, \p R may be
280 /// modified to describe how the result can be found (e.g., via extra
282 bool CheckHiddenResult(Result &R, DeclContext *CurContext,
283 const NamedDecl *Hiding);
285 /// \brief Add a new result to this result set (if it isn't already in one
286 /// of the shadow maps), or replace an existing result (for, e.g., a
289 /// \param R the result to add (if it is unique).
291 /// \param CurContext the context in which this result will be named.
292 void MaybeAddResult(Result R, DeclContext *CurContext = nullptr);
294 /// \brief Add a new result to this result set, where we already know
295 /// the hiding declaration (if any).
297 /// \param R the result to add (if it is unique).
299 /// \param CurContext the context in which this result will be named.
301 /// \param Hiding the declaration that hides the result.
303 /// \param InBaseClass whether the result was found in a base
304 /// class of the searched context.
305 void AddResult(Result R, DeclContext *CurContext, NamedDecl *Hiding,
308 /// \brief Add a new non-declaration result to this result set.
309 void AddResult(Result R);
311 /// \brief Enter into a new scope.
312 void EnterNewScope();
314 /// \brief Exit from the current scope.
317 /// \brief Ignore this declaration, if it is seen again.
318 void Ignore(const Decl *D) { AllDeclsFound.insert(D->getCanonicalDecl()); }
320 /// \name Name lookup predicates
322 /// These predicates can be passed to the name lookup functions to filter the
323 /// results of name lookup. All of the predicates have the same type, so that
326 bool IsOrdinaryName(const NamedDecl *ND) const;
327 bool IsOrdinaryNonTypeName(const NamedDecl *ND) const;
328 bool IsIntegralConstantValue(const NamedDecl *ND) const;
329 bool IsOrdinaryNonValueName(const NamedDecl *ND) const;
330 bool IsNestedNameSpecifier(const NamedDecl *ND) const;
331 bool IsEnum(const NamedDecl *ND) const;
332 bool IsClassOrStruct(const NamedDecl *ND) const;
333 bool IsUnion(const NamedDecl *ND) const;
334 bool IsNamespace(const NamedDecl *ND) const;
335 bool IsNamespaceOrAlias(const NamedDecl *ND) const;
336 bool IsType(const NamedDecl *ND) const;
337 bool IsMember(const NamedDecl *ND) const;
338 bool IsObjCIvar(const NamedDecl *ND) const;
339 bool IsObjCMessageReceiver(const NamedDecl *ND) const;
340 bool IsObjCMessageReceiverOrLambdaCapture(const NamedDecl *ND) const;
341 bool IsObjCCollection(const NamedDecl *ND) const;
342 bool IsImpossibleToSatisfy(const NamedDecl *ND) const;
347 class ResultBuilder::ShadowMapEntry::iterator {
348 llvm::PointerUnion<const NamedDecl *, const DeclIndexPair *> DeclOrIterator;
349 unsigned SingleDeclIndex;
352 typedef DeclIndexPair value_type;
353 typedef value_type reference;
354 typedef std::ptrdiff_t difference_type;
355 typedef std::input_iterator_tag iterator_category;
361 pointer(const DeclIndexPair &Value) : Value(Value) { }
363 const DeclIndexPair *operator->() const {
368 iterator() : DeclOrIterator((NamedDecl *)nullptr), SingleDeclIndex(0) {}
370 iterator(const NamedDecl *SingleDecl, unsigned Index)
371 : DeclOrIterator(SingleDecl), SingleDeclIndex(Index) { }
373 iterator(const DeclIndexPair *Iterator)
374 : DeclOrIterator(Iterator), SingleDeclIndex(0) { }
376 iterator &operator++() {
377 if (DeclOrIterator.is<const NamedDecl *>()) {
378 DeclOrIterator = (NamedDecl *)nullptr;
383 const DeclIndexPair *I = DeclOrIterator.get<const DeclIndexPair*>();
389 /*iterator operator++(int) {
395 reference operator*() const {
396 if (const NamedDecl *ND = DeclOrIterator.dyn_cast<const NamedDecl *>())
397 return reference(ND, SingleDeclIndex);
399 return *DeclOrIterator.get<const DeclIndexPair*>();
402 pointer operator->() const {
403 return pointer(**this);
406 friend bool operator==(const iterator &X, const iterator &Y) {
407 return X.DeclOrIterator.getOpaqueValue()
408 == Y.DeclOrIterator.getOpaqueValue() &&
409 X.SingleDeclIndex == Y.SingleDeclIndex;
412 friend bool operator!=(const iterator &X, const iterator &Y) {
417 ResultBuilder::ShadowMapEntry::iterator
418 ResultBuilder::ShadowMapEntry::begin() const {
419 if (DeclOrVector.isNull())
422 if (const NamedDecl *ND = DeclOrVector.dyn_cast<const NamedDecl *>())
423 return iterator(ND, SingleDeclIndex);
425 return iterator(DeclOrVector.get<DeclIndexPairVector *>()->begin());
428 ResultBuilder::ShadowMapEntry::iterator
429 ResultBuilder::ShadowMapEntry::end() const {
430 if (DeclOrVector.is<const NamedDecl *>() || DeclOrVector.isNull())
433 return iterator(DeclOrVector.get<DeclIndexPairVector *>()->end());
436 /// \brief Compute the qualification required to get from the current context
437 /// (\p CurContext) to the target context (\p TargetContext).
439 /// \param Context the AST context in which the qualification will be used.
441 /// \param CurContext the context where an entity is being named, which is
442 /// typically based on the current scope.
444 /// \param TargetContext the context in which the named entity actually
447 /// \returns a nested name specifier that refers into the target context, or
448 /// NULL if no qualification is needed.
449 static NestedNameSpecifier *
450 getRequiredQualification(ASTContext &Context,
451 const DeclContext *CurContext,
452 const DeclContext *TargetContext) {
453 SmallVector<const DeclContext *, 4> TargetParents;
455 for (const DeclContext *CommonAncestor = TargetContext;
456 CommonAncestor && !CommonAncestor->Encloses(CurContext);
457 CommonAncestor = CommonAncestor->getLookupParent()) {
458 if (CommonAncestor->isTransparentContext() ||
459 CommonAncestor->isFunctionOrMethod())
462 TargetParents.push_back(CommonAncestor);
465 NestedNameSpecifier *Result = nullptr;
466 while (!TargetParents.empty()) {
467 const DeclContext *Parent = TargetParents.pop_back_val();
469 if (const NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Parent)) {
470 if (!Namespace->getIdentifier())
473 Result = NestedNameSpecifier::Create(Context, Result, Namespace);
475 else if (const TagDecl *TD = dyn_cast<TagDecl>(Parent))
476 Result = NestedNameSpecifier::Create(Context, Result,
478 Context.getTypeDeclType(TD).getTypePtr());
483 /// Determine whether \p Id is a name reserved for the implementation (C99
484 /// 7.1.3, C++ [lib.global.names]).
485 static bool isReservedName(const IdentifierInfo *Id) {
486 if (Id->getLength() < 2)
488 const char *Name = Id->getNameStart();
489 return Name[0] == '_' &&
490 (Name[1] == '_' || (Name[1] >= 'A' && Name[1] <= 'Z'));
493 bool ResultBuilder::isInterestingDecl(const NamedDecl *ND,
494 bool &AsNestedNameSpecifier) const {
495 AsNestedNameSpecifier = false;
497 ND = ND->getUnderlyingDecl();
499 // Skip unnamed entities.
500 if (!ND->getDeclName())
503 // Friend declarations and declarations introduced due to friends are never
505 if (ND->getFriendObjectKind() == Decl::FOK_Undeclared)
508 // Class template (partial) specializations are never added as results.
509 if (isa<ClassTemplateSpecializationDecl>(ND) ||
510 isa<ClassTemplatePartialSpecializationDecl>(ND))
513 // Using declarations themselves are never added as results.
514 if (isa<UsingDecl>(ND))
517 // Some declarations have reserved names that we don't want to ever show.
518 // Filter out names reserved for the implementation if they come from a
520 // TODO: Add a predicate for this.
521 if (const IdentifierInfo *Id = ND->getIdentifier())
522 if (isReservedName(Id) &&
523 (ND->getLocation().isInvalid() ||
524 SemaRef.SourceMgr.isInSystemHeader(
525 SemaRef.SourceMgr.getSpellingLoc(ND->getLocation()))))
528 if (Filter == &ResultBuilder::IsNestedNameSpecifier ||
529 ((isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) &&
530 Filter != &ResultBuilder::IsNamespace &&
531 Filter != &ResultBuilder::IsNamespaceOrAlias &&
533 AsNestedNameSpecifier = true;
535 // Filter out any unwanted results.
536 if (Filter && !(this->*Filter)(ND)) {
537 // Check whether it is interesting as a nested-name-specifier.
538 if (AllowNestedNameSpecifiers && SemaRef.getLangOpts().CPlusPlus &&
539 IsNestedNameSpecifier(ND) &&
540 (Filter != &ResultBuilder::IsMember ||
541 (isa<CXXRecordDecl>(ND) &&
542 cast<CXXRecordDecl>(ND)->isInjectedClassName()))) {
543 AsNestedNameSpecifier = true;
549 // ... then it must be interesting!
553 bool ResultBuilder::CheckHiddenResult(Result &R, DeclContext *CurContext,
554 const NamedDecl *Hiding) {
555 // In C, there is no way to refer to a hidden name.
556 // FIXME: This isn't true; we can find a tag name hidden by an ordinary
557 // name if we introduce the tag type.
558 if (!SemaRef.getLangOpts().CPlusPlus)
561 const DeclContext *HiddenCtx =
562 R.Declaration->getDeclContext()->getRedeclContext();
564 // There is no way to qualify a name declared in a function or method.
565 if (HiddenCtx->isFunctionOrMethod())
568 if (HiddenCtx == Hiding->getDeclContext()->getRedeclContext())
571 // We can refer to the result with the appropriate qualification. Do it.
573 R.QualifierIsInformative = false;
576 R.Qualifier = getRequiredQualification(SemaRef.Context,
578 R.Declaration->getDeclContext());
582 /// \brief A simplified classification of types used to determine whether two
583 /// types are "similar enough" when adjusting priorities.
584 SimplifiedTypeClass clang::getSimplifiedTypeClass(CanQualType T) {
585 switch (T->getTypeClass()) {
587 switch (cast<BuiltinType>(T)->getKind()) {
588 case BuiltinType::Void:
591 case BuiltinType::NullPtr:
594 case BuiltinType::Overload:
595 case BuiltinType::Dependent:
598 case BuiltinType::ObjCId:
599 case BuiltinType::ObjCClass:
600 case BuiltinType::ObjCSel:
601 return STC_ObjectiveC;
604 return STC_Arithmetic;
608 return STC_Arithmetic;
613 case Type::BlockPointer:
616 case Type::LValueReference:
617 case Type::RValueReference:
618 return getSimplifiedTypeClass(T->getAs<ReferenceType>()->getPointeeType());
620 case Type::ConstantArray:
621 case Type::IncompleteArray:
622 case Type::VariableArray:
623 case Type::DependentSizedArray:
626 case Type::DependentSizedExtVector:
628 case Type::ExtVector:
629 return STC_Arithmetic;
631 case Type::FunctionProto:
632 case Type::FunctionNoProto:
639 return STC_Arithmetic;
641 case Type::ObjCObject:
642 case Type::ObjCInterface:
643 case Type::ObjCObjectPointer:
644 return STC_ObjectiveC;
651 /// \brief Get the type that a given expression will have if this declaration
652 /// is used as an expression in its "typical" code-completion form.
653 QualType clang::getDeclUsageType(ASTContext &C, const NamedDecl *ND) {
654 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
656 if (const TypeDecl *Type = dyn_cast<TypeDecl>(ND))
657 return C.getTypeDeclType(Type);
658 if (const ObjCInterfaceDecl *Iface = dyn_cast<ObjCInterfaceDecl>(ND))
659 return C.getObjCInterfaceType(Iface);
662 if (const FunctionDecl *Function = ND->getAsFunction())
663 T = Function->getCallResultType();
664 else if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND))
665 T = Method->getSendResultType();
666 else if (const EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND))
667 T = C.getTypeDeclType(cast<EnumDecl>(Enumerator->getDeclContext()));
668 else if (const ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND))
669 T = Property->getType();
670 else if (const ValueDecl *Value = dyn_cast<ValueDecl>(ND))
671 T = Value->getType();
675 // Dig through references, function pointers, and block pointers to
676 // get down to the likely type of an expression when the entity is
679 if (const ReferenceType *Ref = T->getAs<ReferenceType>()) {
680 T = Ref->getPointeeType();
684 if (const PointerType *Pointer = T->getAs<PointerType>()) {
685 if (Pointer->getPointeeType()->isFunctionType()) {
686 T = Pointer->getPointeeType();
693 if (const BlockPointerType *Block = T->getAs<BlockPointerType>()) {
694 T = Block->getPointeeType();
698 if (const FunctionType *Function = T->getAs<FunctionType>()) {
699 T = Function->getReturnType();
709 unsigned ResultBuilder::getBasePriority(const NamedDecl *ND) {
713 // Context-based decisions.
714 const DeclContext *LexicalDC = ND->getLexicalDeclContext();
715 if (LexicalDC->isFunctionOrMethod()) {
716 // _cmd is relatively rare
717 if (const ImplicitParamDecl *ImplicitParam =
718 dyn_cast<ImplicitParamDecl>(ND))
719 if (ImplicitParam->getIdentifier() &&
720 ImplicitParam->getIdentifier()->isStr("_cmd"))
723 return CCP_LocalDeclaration;
726 const DeclContext *DC = ND->getDeclContext()->getRedeclContext();
727 if (DC->isRecord() || isa<ObjCContainerDecl>(DC))
728 return CCP_MemberDeclaration;
730 // Content-based decisions.
731 if (isa<EnumConstantDecl>(ND))
734 // Use CCP_Type for type declarations unless we're in a statement, Objective-C
735 // message receiver, or parenthesized expression context. There, it's as
736 // likely that the user will want to write a type as other declarations.
737 if ((isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) &&
738 !(CompletionContext.getKind() == CodeCompletionContext::CCC_Statement ||
739 CompletionContext.getKind()
740 == CodeCompletionContext::CCC_ObjCMessageReceiver ||
741 CompletionContext.getKind()
742 == CodeCompletionContext::CCC_ParenthesizedExpression))
745 return CCP_Declaration;
748 void ResultBuilder::AdjustResultPriorityForDecl(Result &R) {
749 // If this is an Objective-C method declaration whose selector matches our
750 // preferred selector, give it a priority boost.
751 if (!PreferredSelector.isNull())
752 if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(R.Declaration))
753 if (PreferredSelector == Method->getSelector())
754 R.Priority += CCD_SelectorMatch;
756 // If we have a preferred type, adjust the priority for results with exactly-
757 // matching or nearly-matching types.
758 if (!PreferredType.isNull()) {
759 QualType T = getDeclUsageType(SemaRef.Context, R.Declaration);
761 CanQualType TC = SemaRef.Context.getCanonicalType(T);
762 // Check for exactly-matching types (modulo qualifiers).
763 if (SemaRef.Context.hasSameUnqualifiedType(PreferredType, TC))
764 R.Priority /= CCF_ExactTypeMatch;
765 // Check for nearly-matching types, based on classification of each.
766 else if ((getSimplifiedTypeClass(PreferredType)
767 == getSimplifiedTypeClass(TC)) &&
768 !(PreferredType->isEnumeralType() && TC->isEnumeralType()))
769 R.Priority /= CCF_SimilarTypeMatch;
774 void ResultBuilder::MaybeAddConstructorResults(Result R) {
775 if (!SemaRef.getLangOpts().CPlusPlus || !R.Declaration ||
776 !CompletionContext.wantConstructorResults())
779 ASTContext &Context = SemaRef.Context;
780 const NamedDecl *D = R.Declaration;
781 const CXXRecordDecl *Record = nullptr;
782 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D))
783 Record = ClassTemplate->getTemplatedDecl();
784 else if ((Record = dyn_cast<CXXRecordDecl>(D))) {
785 // Skip specializations and partial specializations.
786 if (isa<ClassTemplateSpecializationDecl>(Record))
789 // There are no constructors here.
793 Record = Record->getDefinition();
798 QualType RecordTy = Context.getTypeDeclType(Record);
799 DeclarationName ConstructorName
800 = Context.DeclarationNames.getCXXConstructorName(
801 Context.getCanonicalType(RecordTy));
802 DeclContext::lookup_result Ctors = Record->lookup(ConstructorName);
803 for (DeclContext::lookup_iterator I = Ctors.begin(),
807 R.CursorKind = getCursorKindForDecl(R.Declaration);
808 Results.push_back(R);
812 void ResultBuilder::MaybeAddResult(Result R, DeclContext *CurContext) {
813 assert(!ShadowMaps.empty() && "Must enter into a results scope");
815 if (R.Kind != Result::RK_Declaration) {
816 // For non-declaration results, just add the result.
817 Results.push_back(R);
821 // Look through using declarations.
822 if (const UsingShadowDecl *Using =
823 dyn_cast<UsingShadowDecl>(R.Declaration)) {
824 MaybeAddResult(Result(Using->getTargetDecl(),
825 getBasePriority(Using->getTargetDecl()),
831 const Decl *CanonDecl = R.Declaration->getCanonicalDecl();
832 unsigned IDNS = CanonDecl->getIdentifierNamespace();
834 bool AsNestedNameSpecifier = false;
835 if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
838 // C++ constructors are never found by name lookup.
839 if (isa<CXXConstructorDecl>(R.Declaration))
842 ShadowMap &SMap = ShadowMaps.back();
843 ShadowMapEntry::iterator I, IEnd;
844 ShadowMap::iterator NamePos = SMap.find(R.Declaration->getDeclName());
845 if (NamePos != SMap.end()) {
846 I = NamePos->second.begin();
847 IEnd = NamePos->second.end();
850 for (; I != IEnd; ++I) {
851 const NamedDecl *ND = I->first;
852 unsigned Index = I->second;
853 if (ND->getCanonicalDecl() == CanonDecl) {
854 // This is a redeclaration. Always pick the newer declaration.
855 Results[Index].Declaration = R.Declaration;
862 // This is a new declaration in this scope. However, check whether this
863 // declaration name is hidden by a similarly-named declaration in an outer
865 std::list<ShadowMap>::iterator SM, SMEnd = ShadowMaps.end();
867 for (SM = ShadowMaps.begin(); SM != SMEnd; ++SM) {
868 ShadowMapEntry::iterator I, IEnd;
869 ShadowMap::iterator NamePos = SM->find(R.Declaration->getDeclName());
870 if (NamePos != SM->end()) {
871 I = NamePos->second.begin();
872 IEnd = NamePos->second.end();
874 for (; I != IEnd; ++I) {
875 // A tag declaration does not hide a non-tag declaration.
876 if (I->first->hasTagIdentifierNamespace() &&
877 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
878 Decl::IDNS_LocalExtern | Decl::IDNS_ObjCProtocol)))
881 // Protocols are in distinct namespaces from everything else.
882 if (((I->first->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
883 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
884 I->first->getIdentifierNamespace() != IDNS)
887 // The newly-added result is hidden by an entry in the shadow map.
888 if (CheckHiddenResult(R, CurContext, I->first))
895 // Make sure that any given declaration only shows up in the result set once.
896 if (!AllDeclsFound.insert(CanonDecl).second)
899 // If the filter is for nested-name-specifiers, then this result starts a
900 // nested-name-specifier.
901 if (AsNestedNameSpecifier) {
902 R.StartsNestedNameSpecifier = true;
903 R.Priority = CCP_NestedNameSpecifier;
905 AdjustResultPriorityForDecl(R);
907 // If this result is supposed to have an informative qualifier, add one.
908 if (R.QualifierIsInformative && !R.Qualifier &&
909 !R.StartsNestedNameSpecifier) {
910 const DeclContext *Ctx = R.Declaration->getDeclContext();
911 if (const NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
912 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, nullptr,
914 else if (const TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
915 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, nullptr,
916 false, SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
918 R.QualifierIsInformative = false;
921 // Insert this result into the set of results and into the current shadow
923 SMap[R.Declaration->getDeclName()].Add(R.Declaration, Results.size());
924 Results.push_back(R);
926 if (!AsNestedNameSpecifier)
927 MaybeAddConstructorResults(R);
930 void ResultBuilder::AddResult(Result R, DeclContext *CurContext,
931 NamedDecl *Hiding, bool InBaseClass = false) {
932 if (R.Kind != Result::RK_Declaration) {
933 // For non-declaration results, just add the result.
934 Results.push_back(R);
938 // Look through using declarations.
939 if (const UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
940 AddResult(Result(Using->getTargetDecl(),
941 getBasePriority(Using->getTargetDecl()),
947 bool AsNestedNameSpecifier = false;
948 if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
951 // C++ constructors are never found by name lookup.
952 if (isa<CXXConstructorDecl>(R.Declaration))
955 if (Hiding && CheckHiddenResult(R, CurContext, Hiding))
958 // Make sure that any given declaration only shows up in the result set once.
959 if (!AllDeclsFound.insert(R.Declaration->getCanonicalDecl()).second)
962 // If the filter is for nested-name-specifiers, then this result starts a
963 // nested-name-specifier.
964 if (AsNestedNameSpecifier) {
965 R.StartsNestedNameSpecifier = true;
966 R.Priority = CCP_NestedNameSpecifier;
968 else if (Filter == &ResultBuilder::IsMember && !R.Qualifier && InBaseClass &&
969 isa<CXXRecordDecl>(R.Declaration->getDeclContext()
970 ->getRedeclContext()))
971 R.QualifierIsInformative = true;
973 // If this result is supposed to have an informative qualifier, add one.
974 if (R.QualifierIsInformative && !R.Qualifier &&
975 !R.StartsNestedNameSpecifier) {
976 const DeclContext *Ctx = R.Declaration->getDeclContext();
977 if (const NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
978 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, nullptr,
980 else if (const TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
981 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, nullptr, false,
982 SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
984 R.QualifierIsInformative = false;
987 // Adjust the priority if this result comes from a base class.
989 R.Priority += CCD_InBaseClass;
991 AdjustResultPriorityForDecl(R);
993 if (HasObjectTypeQualifiers)
994 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(R.Declaration))
995 if (Method->isInstance()) {
996 Qualifiers MethodQuals
997 = Qualifiers::fromCVRMask(Method->getTypeQualifiers());
998 if (ObjectTypeQualifiers == MethodQuals)
999 R.Priority += CCD_ObjectQualifierMatch;
1000 else if (ObjectTypeQualifiers - MethodQuals) {
1001 // The method cannot be invoked, because doing so would drop
1007 // Insert this result into the set of results.
1008 Results.push_back(R);
1010 if (!AsNestedNameSpecifier)
1011 MaybeAddConstructorResults(R);
1014 void ResultBuilder::AddResult(Result R) {
1015 assert(R.Kind != Result::RK_Declaration &&
1016 "Declaration results need more context");
1017 Results.push_back(R);
1020 /// \brief Enter into a new scope.
1021 void ResultBuilder::EnterNewScope() { ShadowMaps.emplace_back(); }
1023 /// \brief Exit from the current scope.
1024 void ResultBuilder::ExitScope() {
1025 for (ShadowMap::iterator E = ShadowMaps.back().begin(),
1026 EEnd = ShadowMaps.back().end();
1029 E->second.Destroy();
1031 ShadowMaps.pop_back();
1034 /// \brief Determines whether this given declaration will be found by
1035 /// ordinary name lookup.
1036 bool ResultBuilder::IsOrdinaryName(const NamedDecl *ND) const {
1037 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
1039 // If name lookup finds a local extern declaration, then we are in a
1040 // context where it behaves like an ordinary name.
1041 unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_LocalExtern;
1042 if (SemaRef.getLangOpts().CPlusPlus)
1043 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
1044 else if (SemaRef.getLangOpts().ObjC1) {
1045 if (isa<ObjCIvarDecl>(ND))
1049 return ND->getIdentifierNamespace() & IDNS;
1052 /// \brief Determines whether this given declaration will be found by
1053 /// ordinary name lookup but is not a type name.
1054 bool ResultBuilder::IsOrdinaryNonTypeName(const NamedDecl *ND) const {
1055 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
1056 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND))
1059 unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_LocalExtern;
1060 if (SemaRef.getLangOpts().CPlusPlus)
1061 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
1062 else if (SemaRef.getLangOpts().ObjC1) {
1063 if (isa<ObjCIvarDecl>(ND))
1067 return ND->getIdentifierNamespace() & IDNS;
1070 bool ResultBuilder::IsIntegralConstantValue(const NamedDecl *ND) const {
1071 if (!IsOrdinaryNonTypeName(ND))
1074 if (const ValueDecl *VD = dyn_cast<ValueDecl>(ND->getUnderlyingDecl()))
1075 if (VD->getType()->isIntegralOrEnumerationType())
1081 /// \brief Determines whether this given declaration will be found by
1082 /// ordinary name lookup.
1083 bool ResultBuilder::IsOrdinaryNonValueName(const NamedDecl *ND) const {
1084 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
1086 unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_LocalExtern;
1087 if (SemaRef.getLangOpts().CPlusPlus)
1088 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace;
1090 return (ND->getIdentifierNamespace() & IDNS) &&
1091 !isa<ValueDecl>(ND) && !isa<FunctionTemplateDecl>(ND) &&
1092 !isa<ObjCPropertyDecl>(ND);
1095 /// \brief Determines whether the given declaration is suitable as the
1096 /// start of a C++ nested-name-specifier, e.g., a class or namespace.
1097 bool ResultBuilder::IsNestedNameSpecifier(const NamedDecl *ND) const {
1098 // Allow us to find class templates, too.
1099 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
1100 ND = ClassTemplate->getTemplatedDecl();
1102 return SemaRef.isAcceptableNestedNameSpecifier(ND);
1105 /// \brief Determines whether the given declaration is an enumeration.
1106 bool ResultBuilder::IsEnum(const NamedDecl *ND) const {
1107 return isa<EnumDecl>(ND);
1110 /// \brief Determines whether the given declaration is a class or struct.
1111 bool ResultBuilder::IsClassOrStruct(const NamedDecl *ND) const {
1112 // Allow us to find class templates, too.
1113 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
1114 ND = ClassTemplate->getTemplatedDecl();
1116 // For purposes of this check, interfaces match too.
1117 if (const RecordDecl *RD = dyn_cast<RecordDecl>(ND))
1118 return RD->getTagKind() == TTK_Class ||
1119 RD->getTagKind() == TTK_Struct ||
1120 RD->getTagKind() == TTK_Interface;
1125 /// \brief Determines whether the given declaration is a union.
1126 bool ResultBuilder::IsUnion(const NamedDecl *ND) const {
1127 // Allow us to find class templates, too.
1128 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
1129 ND = ClassTemplate->getTemplatedDecl();
1131 if (const RecordDecl *RD = dyn_cast<RecordDecl>(ND))
1132 return RD->getTagKind() == TTK_Union;
1137 /// \brief Determines whether the given declaration is a namespace.
1138 bool ResultBuilder::IsNamespace(const NamedDecl *ND) const {
1139 return isa<NamespaceDecl>(ND);
1142 /// \brief Determines whether the given declaration is a namespace or
1143 /// namespace alias.
1144 bool ResultBuilder::IsNamespaceOrAlias(const NamedDecl *ND) const {
1145 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
1148 /// \brief Determines whether the given declaration is a type.
1149 bool ResultBuilder::IsType(const NamedDecl *ND) const {
1150 if (const UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(ND))
1151 ND = Using->getTargetDecl();
1153 return isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
1156 /// \brief Determines which members of a class should be visible via
1157 /// "." or "->". Only value declarations, nested name specifiers, and
1158 /// using declarations thereof should show up.
1159 bool ResultBuilder::IsMember(const NamedDecl *ND) const {
1160 if (const UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(ND))
1161 ND = Using->getTargetDecl();
1163 return isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND) ||
1164 isa<ObjCPropertyDecl>(ND);
1167 static bool isObjCReceiverType(ASTContext &C, QualType T) {
1168 T = C.getCanonicalType(T);
1169 switch (T->getTypeClass()) {
1170 case Type::ObjCObject:
1171 case Type::ObjCInterface:
1172 case Type::ObjCObjectPointer:
1176 switch (cast<BuiltinType>(T)->getKind()) {
1177 case BuiltinType::ObjCId:
1178 case BuiltinType::ObjCClass:
1179 case BuiltinType::ObjCSel:
1191 if (!C.getLangOpts().CPlusPlus)
1194 // FIXME: We could perform more analysis here to determine whether a
1195 // particular class type has any conversions to Objective-C types. For now,
1196 // just accept all class types.
1197 return T->isDependentType() || T->isRecordType();
1200 bool ResultBuilder::IsObjCMessageReceiver(const NamedDecl *ND) const {
1201 QualType T = getDeclUsageType(SemaRef.Context, ND);
1205 T = SemaRef.Context.getBaseElementType(T);
1206 return isObjCReceiverType(SemaRef.Context, T);
1209 bool ResultBuilder::IsObjCMessageReceiverOrLambdaCapture(const NamedDecl *ND) const {
1210 if (IsObjCMessageReceiver(ND))
1213 const VarDecl *Var = dyn_cast<VarDecl>(ND);
1217 return Var->hasLocalStorage() && !Var->hasAttr<BlocksAttr>();
1220 bool ResultBuilder::IsObjCCollection(const NamedDecl *ND) const {
1221 if ((SemaRef.getLangOpts().CPlusPlus && !IsOrdinaryName(ND)) ||
1222 (!SemaRef.getLangOpts().CPlusPlus && !IsOrdinaryNonTypeName(ND)))
1225 QualType T = getDeclUsageType(SemaRef.Context, ND);
1229 T = SemaRef.Context.getBaseElementType(T);
1230 return T->isObjCObjectType() || T->isObjCObjectPointerType() ||
1231 T->isObjCIdType() ||
1232 (SemaRef.getLangOpts().CPlusPlus && T->isRecordType());
1235 bool ResultBuilder::IsImpossibleToSatisfy(const NamedDecl *ND) const {
1239 /// \brief Determines whether the given declaration is an Objective-C
1240 /// instance variable.
1241 bool ResultBuilder::IsObjCIvar(const NamedDecl *ND) const {
1242 return isa<ObjCIvarDecl>(ND);
1246 /// \brief Visible declaration consumer that adds a code-completion result
1247 /// for each visible declaration.
1248 class CodeCompletionDeclConsumer : public VisibleDeclConsumer {
1249 ResultBuilder &Results;
1250 DeclContext *CurContext;
1253 CodeCompletionDeclConsumer(ResultBuilder &Results, DeclContext *CurContext)
1254 : Results(Results), CurContext(CurContext) { }
1256 void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
1257 bool InBaseClass) override {
1258 bool Accessible = true;
1260 Accessible = Results.getSema().IsSimplyAccessible(ND, Ctx);
1262 ResultBuilder::Result Result(ND, Results.getBasePriority(ND), nullptr,
1264 Results.AddResult(Result, CurContext, Hiding, InBaseClass);
1269 /// \brief Add type specifiers for the current language as keyword results.
1270 static void AddTypeSpecifierResults(const LangOptions &LangOpts,
1271 ResultBuilder &Results) {
1272 typedef CodeCompletionResult Result;
1273 Results.AddResult(Result("short", CCP_Type));
1274 Results.AddResult(Result("long", CCP_Type));
1275 Results.AddResult(Result("signed", CCP_Type));
1276 Results.AddResult(Result("unsigned", CCP_Type));
1277 Results.AddResult(Result("void", CCP_Type));
1278 Results.AddResult(Result("char", CCP_Type));
1279 Results.AddResult(Result("int", CCP_Type));
1280 Results.AddResult(Result("float", CCP_Type));
1281 Results.AddResult(Result("double", CCP_Type));
1282 Results.AddResult(Result("enum", CCP_Type));
1283 Results.AddResult(Result("struct", CCP_Type));
1284 Results.AddResult(Result("union", CCP_Type));
1285 Results.AddResult(Result("const", CCP_Type));
1286 Results.AddResult(Result("volatile", CCP_Type));
1290 Results.AddResult(Result("_Complex", CCP_Type));
1291 Results.AddResult(Result("_Imaginary", CCP_Type));
1292 Results.AddResult(Result("_Bool", CCP_Type));
1293 Results.AddResult(Result("restrict", CCP_Type));
1296 CodeCompletionBuilder Builder(Results.getAllocator(),
1297 Results.getCodeCompletionTUInfo());
1298 if (LangOpts.CPlusPlus) {
1300 Results.AddResult(Result("bool", CCP_Type +
1301 (LangOpts.ObjC1? CCD_bool_in_ObjC : 0)));
1302 Results.AddResult(Result("class", CCP_Type));
1303 Results.AddResult(Result("wchar_t", CCP_Type));
1305 // typename qualified-id
1306 Builder.AddTypedTextChunk("typename");
1307 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1308 Builder.AddPlaceholderChunk("qualifier");
1309 Builder.AddTextChunk("::");
1310 Builder.AddPlaceholderChunk("name");
1311 Results.AddResult(Result(Builder.TakeString()));
1313 if (LangOpts.CPlusPlus11) {
1314 Results.AddResult(Result("auto", CCP_Type));
1315 Results.AddResult(Result("char16_t", CCP_Type));
1316 Results.AddResult(Result("char32_t", CCP_Type));
1318 Builder.AddTypedTextChunk("decltype");
1319 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1320 Builder.AddPlaceholderChunk("expression");
1321 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1322 Results.AddResult(Result(Builder.TakeString()));
1327 if (LangOpts.GNUMode) {
1328 // FIXME: Enable when we actually support decimal floating point.
1329 // Results.AddResult(Result("_Decimal32"));
1330 // Results.AddResult(Result("_Decimal64"));
1331 // Results.AddResult(Result("_Decimal128"));
1333 Builder.AddTypedTextChunk("typeof");
1334 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1335 Builder.AddPlaceholderChunk("expression");
1336 Results.AddResult(Result(Builder.TakeString()));
1338 Builder.AddTypedTextChunk("typeof");
1339 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1340 Builder.AddPlaceholderChunk("type");
1341 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1342 Results.AddResult(Result(Builder.TakeString()));
1346 Results.AddResult(Result("_Nonnull", CCP_Type));
1347 Results.AddResult(Result("_Null_unspecified", CCP_Type));
1348 Results.AddResult(Result("_Nullable", CCP_Type));
1351 static void AddStorageSpecifiers(Sema::ParserCompletionContext CCC,
1352 const LangOptions &LangOpts,
1353 ResultBuilder &Results) {
1354 typedef CodeCompletionResult Result;
1355 // Note: we don't suggest either "auto" or "register", because both
1356 // are pointless as storage specifiers. Elsewhere, we suggest "auto"
1357 // in C++0x as a type specifier.
1358 Results.AddResult(Result("extern"));
1359 Results.AddResult(Result("static"));
1362 static void AddFunctionSpecifiers(Sema::ParserCompletionContext CCC,
1363 const LangOptions &LangOpts,
1364 ResultBuilder &Results) {
1365 typedef CodeCompletionResult Result;
1367 case Sema::PCC_Class:
1368 case Sema::PCC_MemberTemplate:
1369 if (LangOpts.CPlusPlus) {
1370 Results.AddResult(Result("explicit"));
1371 Results.AddResult(Result("friend"));
1372 Results.AddResult(Result("mutable"));
1373 Results.AddResult(Result("virtual"));
1377 case Sema::PCC_ObjCInterface:
1378 case Sema::PCC_ObjCImplementation:
1379 case Sema::PCC_Namespace:
1380 case Sema::PCC_Template:
1381 if (LangOpts.CPlusPlus || LangOpts.C99)
1382 Results.AddResult(Result("inline"));
1385 case Sema::PCC_ObjCInstanceVariableList:
1386 case Sema::PCC_Expression:
1387 case Sema::PCC_Statement:
1388 case Sema::PCC_ForInit:
1389 case Sema::PCC_Condition:
1390 case Sema::PCC_RecoveryInFunction:
1391 case Sema::PCC_Type:
1392 case Sema::PCC_ParenthesizedExpression:
1393 case Sema::PCC_LocalDeclarationSpecifiers:
1398 static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt);
1399 static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt);
1400 static void AddObjCVisibilityResults(const LangOptions &LangOpts,
1401 ResultBuilder &Results,
1403 static void AddObjCImplementationResults(const LangOptions &LangOpts,
1404 ResultBuilder &Results,
1406 static void AddObjCInterfaceResults(const LangOptions &LangOpts,
1407 ResultBuilder &Results,
1409 static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt);
1411 static void AddTypedefResult(ResultBuilder &Results) {
1412 CodeCompletionBuilder Builder(Results.getAllocator(),
1413 Results.getCodeCompletionTUInfo());
1414 Builder.AddTypedTextChunk("typedef");
1415 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1416 Builder.AddPlaceholderChunk("type");
1417 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1418 Builder.AddPlaceholderChunk("name");
1419 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
1422 static bool WantTypesInContext(Sema::ParserCompletionContext CCC,
1423 const LangOptions &LangOpts) {
1425 case Sema::PCC_Namespace:
1426 case Sema::PCC_Class:
1427 case Sema::PCC_ObjCInstanceVariableList:
1428 case Sema::PCC_Template:
1429 case Sema::PCC_MemberTemplate:
1430 case Sema::PCC_Statement:
1431 case Sema::PCC_RecoveryInFunction:
1432 case Sema::PCC_Type:
1433 case Sema::PCC_ParenthesizedExpression:
1434 case Sema::PCC_LocalDeclarationSpecifiers:
1437 case Sema::PCC_Expression:
1438 case Sema::PCC_Condition:
1439 return LangOpts.CPlusPlus;
1441 case Sema::PCC_ObjCInterface:
1442 case Sema::PCC_ObjCImplementation:
1445 case Sema::PCC_ForInit:
1446 return LangOpts.CPlusPlus || LangOpts.ObjC1 || LangOpts.C99;
1449 llvm_unreachable("Invalid ParserCompletionContext!");
1452 static PrintingPolicy getCompletionPrintingPolicy(const ASTContext &Context,
1453 const Preprocessor &PP) {
1454 PrintingPolicy Policy = Sema::getPrintingPolicy(Context, PP);
1455 Policy.AnonymousTagLocations = false;
1456 Policy.SuppressStrongLifetime = true;
1457 Policy.SuppressUnwrittenScope = true;
1461 /// \brief Retrieve a printing policy suitable for code completion.
1462 static PrintingPolicy getCompletionPrintingPolicy(Sema &S) {
1463 return getCompletionPrintingPolicy(S.Context, S.PP);
1466 /// \brief Retrieve the string representation of the given type as a string
1467 /// that has the appropriate lifetime for code completion.
1469 /// This routine provides a fast path where we provide constant strings for
1470 /// common type names.
1471 static const char *GetCompletionTypeString(QualType T,
1472 ASTContext &Context,
1473 const PrintingPolicy &Policy,
1474 CodeCompletionAllocator &Allocator) {
1475 if (!T.getLocalQualifiers()) {
1476 // Built-in type names are constant strings.
1477 if (const BuiltinType *BT = dyn_cast<BuiltinType>(T))
1478 return BT->getNameAsCString(Policy);
1480 // Anonymous tag types are constant strings.
1481 if (const TagType *TagT = dyn_cast<TagType>(T))
1482 if (TagDecl *Tag = TagT->getDecl())
1483 if (!Tag->hasNameForLinkage()) {
1484 switch (Tag->getTagKind()) {
1485 case TTK_Struct: return "struct <anonymous>";
1486 case TTK_Interface: return "__interface <anonymous>";
1487 case TTK_Class: return "class <anonymous>";
1488 case TTK_Union: return "union <anonymous>";
1489 case TTK_Enum: return "enum <anonymous>";
1494 // Slow path: format the type as a string.
1496 T.getAsStringInternal(Result, Policy);
1497 return Allocator.CopyString(Result);
1500 /// \brief Add a completion for "this", if we're in a member function.
1501 static void addThisCompletion(Sema &S, ResultBuilder &Results) {
1502 QualType ThisTy = S.getCurrentThisType();
1503 if (ThisTy.isNull())
1506 CodeCompletionAllocator &Allocator = Results.getAllocator();
1507 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
1508 PrintingPolicy Policy = getCompletionPrintingPolicy(S);
1509 Builder.AddResultTypeChunk(GetCompletionTypeString(ThisTy,
1513 Builder.AddTypedTextChunk("this");
1514 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
1517 /// \brief Add language constructs that show up for "ordinary" names.
1518 static void AddOrdinaryNameResults(Sema::ParserCompletionContext CCC,
1521 ResultBuilder &Results) {
1522 CodeCompletionAllocator &Allocator = Results.getAllocator();
1523 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
1524 PrintingPolicy Policy = getCompletionPrintingPolicy(SemaRef);
1526 typedef CodeCompletionResult Result;
1528 case Sema::PCC_Namespace:
1529 if (SemaRef.getLangOpts().CPlusPlus) {
1530 if (Results.includeCodePatterns()) {
1531 // namespace <identifier> { declarations }
1532 Builder.AddTypedTextChunk("namespace");
1533 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1534 Builder.AddPlaceholderChunk("identifier");
1535 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1536 Builder.AddPlaceholderChunk("declarations");
1537 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1538 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1539 Results.AddResult(Result(Builder.TakeString()));
1542 // namespace identifier = identifier ;
1543 Builder.AddTypedTextChunk("namespace");
1544 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1545 Builder.AddPlaceholderChunk("name");
1546 Builder.AddChunk(CodeCompletionString::CK_Equal);
1547 Builder.AddPlaceholderChunk("namespace");
1548 Results.AddResult(Result(Builder.TakeString()));
1551 Builder.AddTypedTextChunk("using");
1552 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1553 Builder.AddTextChunk("namespace");
1554 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1555 Builder.AddPlaceholderChunk("identifier");
1556 Results.AddResult(Result(Builder.TakeString()));
1558 // asm(string-literal)
1559 Builder.AddTypedTextChunk("asm");
1560 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1561 Builder.AddPlaceholderChunk("string-literal");
1562 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1563 Results.AddResult(Result(Builder.TakeString()));
1565 if (Results.includeCodePatterns()) {
1566 // Explicit template instantiation
1567 Builder.AddTypedTextChunk("template");
1568 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1569 Builder.AddPlaceholderChunk("declaration");
1570 Results.AddResult(Result(Builder.TakeString()));
1574 if (SemaRef.getLangOpts().ObjC1)
1575 AddObjCTopLevelResults(Results, true);
1577 AddTypedefResult(Results);
1580 case Sema::PCC_Class:
1581 if (SemaRef.getLangOpts().CPlusPlus) {
1582 // Using declaration
1583 Builder.AddTypedTextChunk("using");
1584 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1585 Builder.AddPlaceholderChunk("qualifier");
1586 Builder.AddTextChunk("::");
1587 Builder.AddPlaceholderChunk("name");
1588 Results.AddResult(Result(Builder.TakeString()));
1590 // using typename qualifier::name (only in a dependent context)
1591 if (SemaRef.CurContext->isDependentContext()) {
1592 Builder.AddTypedTextChunk("using");
1593 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1594 Builder.AddTextChunk("typename");
1595 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1596 Builder.AddPlaceholderChunk("qualifier");
1597 Builder.AddTextChunk("::");
1598 Builder.AddPlaceholderChunk("name");
1599 Results.AddResult(Result(Builder.TakeString()));
1602 if (CCC == Sema::PCC_Class) {
1603 AddTypedefResult(Results);
1606 Builder.AddTypedTextChunk("public");
1607 if (Results.includeCodePatterns())
1608 Builder.AddChunk(CodeCompletionString::CK_Colon);
1609 Results.AddResult(Result(Builder.TakeString()));
1612 Builder.AddTypedTextChunk("protected");
1613 if (Results.includeCodePatterns())
1614 Builder.AddChunk(CodeCompletionString::CK_Colon);
1615 Results.AddResult(Result(Builder.TakeString()));
1618 Builder.AddTypedTextChunk("private");
1619 if (Results.includeCodePatterns())
1620 Builder.AddChunk(CodeCompletionString::CK_Colon);
1621 Results.AddResult(Result(Builder.TakeString()));
1626 case Sema::PCC_Template:
1627 case Sema::PCC_MemberTemplate:
1628 if (SemaRef.getLangOpts().CPlusPlus && Results.includeCodePatterns()) {
1629 // template < parameters >
1630 Builder.AddTypedTextChunk("template");
1631 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1632 Builder.AddPlaceholderChunk("parameters");
1633 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1634 Results.AddResult(Result(Builder.TakeString()));
1637 AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
1638 AddFunctionSpecifiers(CCC, SemaRef.getLangOpts(), Results);
1641 case Sema::PCC_ObjCInterface:
1642 AddObjCInterfaceResults(SemaRef.getLangOpts(), Results, true);
1643 AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
1644 AddFunctionSpecifiers(CCC, SemaRef.getLangOpts(), Results);
1647 case Sema::PCC_ObjCImplementation:
1648 AddObjCImplementationResults(SemaRef.getLangOpts(), Results, true);
1649 AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
1650 AddFunctionSpecifiers(CCC, SemaRef.getLangOpts(), Results);
1653 case Sema::PCC_ObjCInstanceVariableList:
1654 AddObjCVisibilityResults(SemaRef.getLangOpts(), Results, true);
1657 case Sema::PCC_RecoveryInFunction:
1658 case Sema::PCC_Statement: {
1659 AddTypedefResult(Results);
1661 if (SemaRef.getLangOpts().CPlusPlus && Results.includeCodePatterns() &&
1662 SemaRef.getLangOpts().CXXExceptions) {
1663 Builder.AddTypedTextChunk("try");
1664 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1665 Builder.AddPlaceholderChunk("statements");
1666 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1667 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1668 Builder.AddTextChunk("catch");
1669 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1670 Builder.AddPlaceholderChunk("declaration");
1671 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1672 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1673 Builder.AddPlaceholderChunk("statements");
1674 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1675 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1676 Results.AddResult(Result(Builder.TakeString()));
1678 if (SemaRef.getLangOpts().ObjC1)
1679 AddObjCStatementResults(Results, true);
1681 if (Results.includeCodePatterns()) {
1682 // if (condition) { statements }
1683 Builder.AddTypedTextChunk("if");
1684 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1685 if (SemaRef.getLangOpts().CPlusPlus)
1686 Builder.AddPlaceholderChunk("condition");
1688 Builder.AddPlaceholderChunk("expression");
1689 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1690 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1691 Builder.AddPlaceholderChunk("statements");
1692 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1693 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1694 Results.AddResult(Result(Builder.TakeString()));
1696 // switch (condition) { }
1697 Builder.AddTypedTextChunk("switch");
1698 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1699 if (SemaRef.getLangOpts().CPlusPlus)
1700 Builder.AddPlaceholderChunk("condition");
1702 Builder.AddPlaceholderChunk("expression");
1703 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1704 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1705 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1706 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1707 Results.AddResult(Result(Builder.TakeString()));
1710 // Switch-specific statements.
1711 if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
1713 Builder.AddTypedTextChunk("case");
1714 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1715 Builder.AddPlaceholderChunk("expression");
1716 Builder.AddChunk(CodeCompletionString::CK_Colon);
1717 Results.AddResult(Result(Builder.TakeString()));
1720 Builder.AddTypedTextChunk("default");
1721 Builder.AddChunk(CodeCompletionString::CK_Colon);
1722 Results.AddResult(Result(Builder.TakeString()));
1725 if (Results.includeCodePatterns()) {
1726 /// while (condition) { statements }
1727 Builder.AddTypedTextChunk("while");
1728 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1729 if (SemaRef.getLangOpts().CPlusPlus)
1730 Builder.AddPlaceholderChunk("condition");
1732 Builder.AddPlaceholderChunk("expression");
1733 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1734 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1735 Builder.AddPlaceholderChunk("statements");
1736 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1737 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1738 Results.AddResult(Result(Builder.TakeString()));
1740 // do { statements } while ( expression );
1741 Builder.AddTypedTextChunk("do");
1742 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1743 Builder.AddPlaceholderChunk("statements");
1744 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1745 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1746 Builder.AddTextChunk("while");
1747 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1748 Builder.AddPlaceholderChunk("expression");
1749 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1750 Results.AddResult(Result(Builder.TakeString()));
1752 // for ( for-init-statement ; condition ; expression ) { statements }
1753 Builder.AddTypedTextChunk("for");
1754 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1755 if (SemaRef.getLangOpts().CPlusPlus || SemaRef.getLangOpts().C99)
1756 Builder.AddPlaceholderChunk("init-statement");
1758 Builder.AddPlaceholderChunk("init-expression");
1759 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
1760 Builder.AddPlaceholderChunk("condition");
1761 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
1762 Builder.AddPlaceholderChunk("inc-expression");
1763 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1764 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1765 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1766 Builder.AddPlaceholderChunk("statements");
1767 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1768 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1769 Results.AddResult(Result(Builder.TakeString()));
1772 if (S->getContinueParent()) {
1774 Builder.AddTypedTextChunk("continue");
1775 Results.AddResult(Result(Builder.TakeString()));
1778 if (S->getBreakParent()) {
1780 Builder.AddTypedTextChunk("break");
1781 Results.AddResult(Result(Builder.TakeString()));
1784 // "return expression ;" or "return ;", depending on whether we
1785 // know the function is void or not.
1786 bool isVoid = false;
1787 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(SemaRef.CurContext))
1788 isVoid = Function->getReturnType()->isVoidType();
1789 else if (ObjCMethodDecl *Method
1790 = dyn_cast<ObjCMethodDecl>(SemaRef.CurContext))
1791 isVoid = Method->getReturnType()->isVoidType();
1792 else if (SemaRef.getCurBlock() &&
1793 !SemaRef.getCurBlock()->ReturnType.isNull())
1794 isVoid = SemaRef.getCurBlock()->ReturnType->isVoidType();
1795 Builder.AddTypedTextChunk("return");
1797 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1798 Builder.AddPlaceholderChunk("expression");
1800 Results.AddResult(Result(Builder.TakeString()));
1802 // goto identifier ;
1803 Builder.AddTypedTextChunk("goto");
1804 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1805 Builder.AddPlaceholderChunk("label");
1806 Results.AddResult(Result(Builder.TakeString()));
1809 Builder.AddTypedTextChunk("using");
1810 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1811 Builder.AddTextChunk("namespace");
1812 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1813 Builder.AddPlaceholderChunk("identifier");
1814 Results.AddResult(Result(Builder.TakeString()));
1817 // Fall through (for statement expressions).
1818 case Sema::PCC_ForInit:
1819 case Sema::PCC_Condition:
1820 AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
1821 // Fall through: conditions and statements can have expressions.
1823 case Sema::PCC_ParenthesizedExpression:
1824 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
1825 CCC == Sema::PCC_ParenthesizedExpression) {
1826 // (__bridge <type>)<expression>
1827 Builder.AddTypedTextChunk("__bridge");
1828 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1829 Builder.AddPlaceholderChunk("type");
1830 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1831 Builder.AddPlaceholderChunk("expression");
1832 Results.AddResult(Result(Builder.TakeString()));
1834 // (__bridge_transfer <Objective-C type>)<expression>
1835 Builder.AddTypedTextChunk("__bridge_transfer");
1836 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1837 Builder.AddPlaceholderChunk("Objective-C type");
1838 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1839 Builder.AddPlaceholderChunk("expression");
1840 Results.AddResult(Result(Builder.TakeString()));
1842 // (__bridge_retained <CF type>)<expression>
1843 Builder.AddTypedTextChunk("__bridge_retained");
1844 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1845 Builder.AddPlaceholderChunk("CF type");
1846 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1847 Builder.AddPlaceholderChunk("expression");
1848 Results.AddResult(Result(Builder.TakeString()));
1852 case Sema::PCC_Expression: {
1853 if (SemaRef.getLangOpts().CPlusPlus) {
1854 // 'this', if we're in a non-static member function.
1855 addThisCompletion(SemaRef, Results);
1858 Builder.AddResultTypeChunk("bool");
1859 Builder.AddTypedTextChunk("true");
1860 Results.AddResult(Result(Builder.TakeString()));
1863 Builder.AddResultTypeChunk("bool");
1864 Builder.AddTypedTextChunk("false");
1865 Results.AddResult(Result(Builder.TakeString()));
1867 if (SemaRef.getLangOpts().RTTI) {
1868 // dynamic_cast < type-id > ( expression )
1869 Builder.AddTypedTextChunk("dynamic_cast");
1870 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1871 Builder.AddPlaceholderChunk("type");
1872 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1873 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1874 Builder.AddPlaceholderChunk("expression");
1875 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1876 Results.AddResult(Result(Builder.TakeString()));
1879 // static_cast < type-id > ( expression )
1880 Builder.AddTypedTextChunk("static_cast");
1881 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1882 Builder.AddPlaceholderChunk("type");
1883 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1884 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1885 Builder.AddPlaceholderChunk("expression");
1886 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1887 Results.AddResult(Result(Builder.TakeString()));
1889 // reinterpret_cast < type-id > ( expression )
1890 Builder.AddTypedTextChunk("reinterpret_cast");
1891 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1892 Builder.AddPlaceholderChunk("type");
1893 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1894 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1895 Builder.AddPlaceholderChunk("expression");
1896 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1897 Results.AddResult(Result(Builder.TakeString()));
1899 // const_cast < type-id > ( expression )
1900 Builder.AddTypedTextChunk("const_cast");
1901 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1902 Builder.AddPlaceholderChunk("type");
1903 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1904 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1905 Builder.AddPlaceholderChunk("expression");
1906 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1907 Results.AddResult(Result(Builder.TakeString()));
1909 if (SemaRef.getLangOpts().RTTI) {
1910 // typeid ( expression-or-type )
1911 Builder.AddResultTypeChunk("std::type_info");
1912 Builder.AddTypedTextChunk("typeid");
1913 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1914 Builder.AddPlaceholderChunk("expression-or-type");
1915 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1916 Results.AddResult(Result(Builder.TakeString()));
1920 Builder.AddTypedTextChunk("new");
1921 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1922 Builder.AddPlaceholderChunk("type");
1923 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1924 Builder.AddPlaceholderChunk("expressions");
1925 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1926 Results.AddResult(Result(Builder.TakeString()));
1928 // new T [ ] ( ... )
1929 Builder.AddTypedTextChunk("new");
1930 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1931 Builder.AddPlaceholderChunk("type");
1932 Builder.AddChunk(CodeCompletionString::CK_LeftBracket);
1933 Builder.AddPlaceholderChunk("size");
1934 Builder.AddChunk(CodeCompletionString::CK_RightBracket);
1935 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1936 Builder.AddPlaceholderChunk("expressions");
1937 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1938 Results.AddResult(Result(Builder.TakeString()));
1940 // delete expression
1941 Builder.AddResultTypeChunk("void");
1942 Builder.AddTypedTextChunk("delete");
1943 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1944 Builder.AddPlaceholderChunk("expression");
1945 Results.AddResult(Result(Builder.TakeString()));
1947 // delete [] expression
1948 Builder.AddResultTypeChunk("void");
1949 Builder.AddTypedTextChunk("delete");
1950 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1951 Builder.AddChunk(CodeCompletionString::CK_LeftBracket);
1952 Builder.AddChunk(CodeCompletionString::CK_RightBracket);
1953 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1954 Builder.AddPlaceholderChunk("expression");
1955 Results.AddResult(Result(Builder.TakeString()));
1957 if (SemaRef.getLangOpts().CXXExceptions) {
1959 Builder.AddResultTypeChunk("void");
1960 Builder.AddTypedTextChunk("throw");
1961 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1962 Builder.AddPlaceholderChunk("expression");
1963 Results.AddResult(Result(Builder.TakeString()));
1968 if (SemaRef.getLangOpts().CPlusPlus11) {
1970 Builder.AddResultTypeChunk("std::nullptr_t");
1971 Builder.AddTypedTextChunk("nullptr");
1972 Results.AddResult(Result(Builder.TakeString()));
1975 Builder.AddResultTypeChunk("size_t");
1976 Builder.AddTypedTextChunk("alignof");
1977 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1978 Builder.AddPlaceholderChunk("type");
1979 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1980 Results.AddResult(Result(Builder.TakeString()));
1983 Builder.AddResultTypeChunk("bool");
1984 Builder.AddTypedTextChunk("noexcept");
1985 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1986 Builder.AddPlaceholderChunk("expression");
1987 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1988 Results.AddResult(Result(Builder.TakeString()));
1990 // sizeof... expression
1991 Builder.AddResultTypeChunk("size_t");
1992 Builder.AddTypedTextChunk("sizeof...");
1993 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1994 Builder.AddPlaceholderChunk("parameter-pack");
1995 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1996 Results.AddResult(Result(Builder.TakeString()));
2000 if (SemaRef.getLangOpts().ObjC1) {
2001 // Add "super", if we're in an Objective-C class with a superclass.
2002 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
2003 // The interface can be NULL.
2004 if (ObjCInterfaceDecl *ID = Method->getClassInterface())
2005 if (ID->getSuperClass()) {
2006 std::string SuperType;
2007 SuperType = ID->getSuperClass()->getNameAsString();
2008 if (Method->isInstanceMethod())
2011 Builder.AddResultTypeChunk(Allocator.CopyString(SuperType));
2012 Builder.AddTypedTextChunk("super");
2013 Results.AddResult(Result(Builder.TakeString()));
2017 AddObjCExpressionResults(Results, true);
2020 if (SemaRef.getLangOpts().C11) {
2022 Builder.AddResultTypeChunk("size_t");
2023 if (SemaRef.PP.isMacroDefined("alignof"))
2024 Builder.AddTypedTextChunk("alignof");
2026 Builder.AddTypedTextChunk("_Alignof");
2027 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2028 Builder.AddPlaceholderChunk("type");
2029 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2030 Results.AddResult(Result(Builder.TakeString()));
2033 // sizeof expression
2034 Builder.AddResultTypeChunk("size_t");
2035 Builder.AddTypedTextChunk("sizeof");
2036 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2037 Builder.AddPlaceholderChunk("expression-or-type");
2038 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2039 Results.AddResult(Result(Builder.TakeString()));
2043 case Sema::PCC_Type:
2044 case Sema::PCC_LocalDeclarationSpecifiers:
2048 if (WantTypesInContext(CCC, SemaRef.getLangOpts()))
2049 AddTypeSpecifierResults(SemaRef.getLangOpts(), Results);
2051 if (SemaRef.getLangOpts().CPlusPlus && CCC != Sema::PCC_Type)
2052 Results.AddResult(Result("operator"));
2055 /// \brief If the given declaration has an associated type, add it as a result
2057 static void AddResultTypeChunk(ASTContext &Context,
2058 const PrintingPolicy &Policy,
2059 const NamedDecl *ND,
2061 CodeCompletionBuilder &Result) {
2065 // Skip constructors and conversion functions, which have their return types
2066 // built into their names.
2067 if (isa<CXXConstructorDecl>(ND) || isa<CXXConversionDecl>(ND))
2070 // Determine the type of the declaration (if it has a type).
2072 if (const FunctionDecl *Function = ND->getAsFunction())
2073 T = Function->getReturnType();
2074 else if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND)) {
2075 if (!BaseType.isNull())
2076 T = Method->getSendResultType(BaseType);
2078 T = Method->getReturnType();
2079 } else if (const EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND))
2080 T = Context.getTypeDeclType(cast<TypeDecl>(Enumerator->getDeclContext()));
2081 else if (isa<UnresolvedUsingValueDecl>(ND)) {
2082 /* Do nothing: ignore unresolved using declarations*/
2083 } else if (const ObjCIvarDecl *Ivar = dyn_cast<ObjCIvarDecl>(ND)) {
2084 if (!BaseType.isNull())
2085 T = Ivar->getUsageType(BaseType);
2087 T = Ivar->getType();
2088 } else if (const ValueDecl *Value = dyn_cast<ValueDecl>(ND)) {
2089 T = Value->getType();
2090 } else if (const ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND)) {
2091 if (!BaseType.isNull())
2092 T = Property->getUsageType(BaseType);
2094 T = Property->getType();
2097 if (T.isNull() || Context.hasSameType(T, Context.DependentTy))
2100 Result.AddResultTypeChunk(GetCompletionTypeString(T, Context, Policy,
2101 Result.getAllocator()));
2104 static void MaybeAddSentinel(Preprocessor &PP,
2105 const NamedDecl *FunctionOrMethod,
2106 CodeCompletionBuilder &Result) {
2107 if (SentinelAttr *Sentinel = FunctionOrMethod->getAttr<SentinelAttr>())
2108 if (Sentinel->getSentinel() == 0) {
2109 if (PP.getLangOpts().ObjC1 && PP.isMacroDefined("nil"))
2110 Result.AddTextChunk(", nil");
2111 else if (PP.isMacroDefined("NULL"))
2112 Result.AddTextChunk(", NULL");
2114 Result.AddTextChunk(", (void*)0");
2118 static std::string formatObjCParamQualifiers(unsigned ObjCQuals,
2121 if (ObjCQuals & Decl::OBJC_TQ_In)
2123 else if (ObjCQuals & Decl::OBJC_TQ_Inout)
2125 else if (ObjCQuals & Decl::OBJC_TQ_Out)
2127 if (ObjCQuals & Decl::OBJC_TQ_Bycopy)
2128 Result += "bycopy ";
2129 else if (ObjCQuals & Decl::OBJC_TQ_Byref)
2131 if (ObjCQuals & Decl::OBJC_TQ_Oneway)
2132 Result += "oneway ";
2133 if (ObjCQuals & Decl::OBJC_TQ_CSNullability) {
2134 if (auto nullability = AttributedType::stripOuterNullability(Type)) {
2135 switch (*nullability) {
2136 case NullabilityKind::NonNull:
2137 Result += "nonnull ";
2140 case NullabilityKind::Nullable:
2141 Result += "nullable ";
2144 case NullabilityKind::Unspecified:
2145 Result += "null_unspecified ";
2153 static std::string FormatFunctionParameter(const PrintingPolicy &Policy,
2154 const ParmVarDecl *Param,
2155 bool SuppressName = false,
2156 bool SuppressBlock = false,
2157 Optional<ArrayRef<QualType>> ObjCSubsts = None) {
2158 bool ObjCMethodParam = isa<ObjCMethodDecl>(Param->getDeclContext());
2159 if (Param->getType()->isDependentType() ||
2160 !Param->getType()->isBlockPointerType()) {
2161 // The argument for a dependent or non-block parameter is a placeholder
2162 // containing that parameter's type.
2165 if (Param->getIdentifier() && !ObjCMethodParam && !SuppressName)
2166 Result = Param->getIdentifier()->getName();
2168 QualType Type = Param->getType();
2170 Type = Type.substObjCTypeArgs(Param->getASTContext(), *ObjCSubsts,
2171 ObjCSubstitutionContext::Parameter);
2172 if (ObjCMethodParam) {
2173 Result = "(" + formatObjCParamQualifiers(Param->getObjCDeclQualifier(),
2175 Result += Type.getAsString(Policy) + ")";
2176 if (Param->getIdentifier() && !SuppressName)
2177 Result += Param->getIdentifier()->getName();
2179 Type.getAsStringInternal(Result, Policy);
2184 // The argument for a block pointer parameter is a block literal with
2185 // the appropriate type.
2186 FunctionTypeLoc Block;
2187 FunctionProtoTypeLoc BlockProto;
2189 if (TypeSourceInfo *TSInfo = Param->getTypeSourceInfo()) {
2190 TL = TSInfo->getTypeLoc().getUnqualifiedLoc();
2192 // Look through typedefs.
2193 if (!SuppressBlock) {
2194 if (TypedefTypeLoc TypedefTL = TL.getAs<TypedefTypeLoc>()) {
2195 if (TypeSourceInfo *InnerTSInfo =
2196 TypedefTL.getTypedefNameDecl()->getTypeSourceInfo()) {
2197 TL = InnerTSInfo->getTypeLoc().getUnqualifiedLoc();
2202 // Look through qualified types
2203 if (QualifiedTypeLoc QualifiedTL = TL.getAs<QualifiedTypeLoc>()) {
2204 TL = QualifiedTL.getUnqualifiedLoc();
2208 if (AttributedTypeLoc AttrTL = TL.getAs<AttributedTypeLoc>()) {
2209 TL = AttrTL.getModifiedLoc();
2214 // Try to get the function prototype behind the block pointer type,
2216 if (BlockPointerTypeLoc BlockPtr = TL.getAs<BlockPointerTypeLoc>()) {
2217 TL = BlockPtr.getPointeeLoc().IgnoreParens();
2218 Block = TL.getAs<FunctionTypeLoc>();
2219 BlockProto = TL.getAs<FunctionProtoTypeLoc>();
2226 // We were unable to find a FunctionProtoTypeLoc with parameter names
2227 // for the block; just use the parameter type as a placeholder.
2229 if (!ObjCMethodParam && Param->getIdentifier())
2230 Result = Param->getIdentifier()->getName();
2232 QualType Type = Param->getType().getUnqualifiedType();
2234 if (ObjCMethodParam) {
2235 Result = "(" + formatObjCParamQualifiers(Param->getObjCDeclQualifier(),
2237 Result += Type.getAsString(Policy) + Result + ")";
2238 if (Param->getIdentifier())
2239 Result += Param->getIdentifier()->getName();
2241 Type.getAsStringInternal(Result, Policy);
2247 // We have the function prototype behind the block pointer type, as it was
2248 // written in the source.
2250 QualType ResultType = Block.getTypePtr()->getReturnType();
2252 ResultType = ResultType.substObjCTypeArgs(Param->getASTContext(),
2254 ObjCSubstitutionContext::Result);
2255 if (!ResultType->isVoidType() || SuppressBlock)
2256 ResultType.getAsStringInternal(Result, Policy);
2258 // Format the parameter list.
2260 if (!BlockProto || Block.getNumParams() == 0) {
2261 if (BlockProto && BlockProto.getTypePtr()->isVariadic())
2267 for (unsigned I = 0, N = Block.getNumParams(); I != N; ++I) {
2270 Params += FormatFunctionParameter(Policy, Block.getParam(I),
2271 /*SuppressName=*/false,
2272 /*SuppressBlock=*/true,
2275 if (I == N - 1 && BlockProto.getTypePtr()->isVariadic())
2281 if (SuppressBlock) {
2282 // Format as a parameter.
2283 Result = Result + " (^";
2284 if (Param->getIdentifier())
2285 Result += Param->getIdentifier()->getName();
2289 // Format as a block literal argument.
2290 Result = '^' + Result;
2293 if (Param->getIdentifier())
2294 Result += Param->getIdentifier()->getName();
2300 /// \brief Add function parameter chunks to the given code completion string.
2301 static void AddFunctionParameterChunks(Preprocessor &PP,
2302 const PrintingPolicy &Policy,
2303 const FunctionDecl *Function,
2304 CodeCompletionBuilder &Result,
2306 bool InOptional = false) {
2307 bool FirstParameter = true;
2309 for (unsigned P = Start, N = Function->getNumParams(); P != N; ++P) {
2310 const ParmVarDecl *Param = Function->getParamDecl(P);
2312 if (Param->hasDefaultArg() && !InOptional) {
2313 // When we see an optional default argument, put that argument and
2314 // the remaining default arguments into a new, optional string.
2315 CodeCompletionBuilder Opt(Result.getAllocator(),
2316 Result.getCodeCompletionTUInfo());
2317 if (!FirstParameter)
2318 Opt.AddChunk(CodeCompletionString::CK_Comma);
2319 AddFunctionParameterChunks(PP, Policy, Function, Opt, P, true);
2320 Result.AddOptionalChunk(Opt.TakeString());
2325 FirstParameter = false;
2327 Result.AddChunk(CodeCompletionString::CK_Comma);
2331 // Format the placeholder string.
2332 std::string PlaceholderStr = FormatFunctionParameter(Policy, Param);
2334 if (Function->isVariadic() && P == N - 1)
2335 PlaceholderStr += ", ...";
2337 // Add the placeholder string.
2338 Result.AddPlaceholderChunk(
2339 Result.getAllocator().CopyString(PlaceholderStr));
2342 if (const FunctionProtoType *Proto
2343 = Function->getType()->getAs<FunctionProtoType>())
2344 if (Proto->isVariadic()) {
2345 if (Proto->getNumParams() == 0)
2346 Result.AddPlaceholderChunk("...");
2348 MaybeAddSentinel(PP, Function, Result);
2352 /// \brief Add template parameter chunks to the given code completion string.
2353 static void AddTemplateParameterChunks(ASTContext &Context,
2354 const PrintingPolicy &Policy,
2355 const TemplateDecl *Template,
2356 CodeCompletionBuilder &Result,
2357 unsigned MaxParameters = 0,
2359 bool InDefaultArg = false) {
2360 bool FirstParameter = true;
2362 // Prefer to take the template parameter names from the first declaration of
2364 Template = cast<TemplateDecl>(Template->getCanonicalDecl());
2366 TemplateParameterList *Params = Template->getTemplateParameters();
2367 TemplateParameterList::iterator PEnd = Params->end();
2369 PEnd = Params->begin() + MaxParameters;
2370 for (TemplateParameterList::iterator P = Params->begin() + Start;
2372 bool HasDefaultArg = false;
2373 std::string PlaceholderStr;
2374 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
2375 if (TTP->wasDeclaredWithTypename())
2376 PlaceholderStr = "typename";
2378 PlaceholderStr = "class";
2380 if (TTP->getIdentifier()) {
2381 PlaceholderStr += ' ';
2382 PlaceholderStr += TTP->getIdentifier()->getName();
2385 HasDefaultArg = TTP->hasDefaultArgument();
2386 } else if (NonTypeTemplateParmDecl *NTTP
2387 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
2388 if (NTTP->getIdentifier())
2389 PlaceholderStr = NTTP->getIdentifier()->getName();
2390 NTTP->getType().getAsStringInternal(PlaceholderStr, Policy);
2391 HasDefaultArg = NTTP->hasDefaultArgument();
2393 assert(isa<TemplateTemplateParmDecl>(*P));
2394 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
2396 // Since putting the template argument list into the placeholder would
2397 // be very, very long, we just use an abbreviation.
2398 PlaceholderStr = "template<...> class";
2399 if (TTP->getIdentifier()) {
2400 PlaceholderStr += ' ';
2401 PlaceholderStr += TTP->getIdentifier()->getName();
2404 HasDefaultArg = TTP->hasDefaultArgument();
2407 if (HasDefaultArg && !InDefaultArg) {
2408 // When we see an optional default argument, put that argument and
2409 // the remaining default arguments into a new, optional string.
2410 CodeCompletionBuilder Opt(Result.getAllocator(),
2411 Result.getCodeCompletionTUInfo());
2412 if (!FirstParameter)
2413 Opt.AddChunk(CodeCompletionString::CK_Comma);
2414 AddTemplateParameterChunks(Context, Policy, Template, Opt, MaxParameters,
2415 P - Params->begin(), true);
2416 Result.AddOptionalChunk(Opt.TakeString());
2420 InDefaultArg = false;
2423 FirstParameter = false;
2425 Result.AddChunk(CodeCompletionString::CK_Comma);
2427 // Add the placeholder string.
2428 Result.AddPlaceholderChunk(
2429 Result.getAllocator().CopyString(PlaceholderStr));
2433 /// \brief Add a qualifier to the given code-completion string, if the
2434 /// provided nested-name-specifier is non-NULL.
2436 AddQualifierToCompletionString(CodeCompletionBuilder &Result,
2437 NestedNameSpecifier *Qualifier,
2438 bool QualifierIsInformative,
2439 ASTContext &Context,
2440 const PrintingPolicy &Policy) {
2444 std::string PrintedNNS;
2446 llvm::raw_string_ostream OS(PrintedNNS);
2447 Qualifier->print(OS, Policy);
2449 if (QualifierIsInformative)
2450 Result.AddInformativeChunk(Result.getAllocator().CopyString(PrintedNNS));
2452 Result.AddTextChunk(Result.getAllocator().CopyString(PrintedNNS));
2456 AddFunctionTypeQualsToCompletionString(CodeCompletionBuilder &Result,
2457 const FunctionDecl *Function) {
2458 const FunctionProtoType *Proto
2459 = Function->getType()->getAs<FunctionProtoType>();
2460 if (!Proto || !Proto->getTypeQuals())
2463 // FIXME: Add ref-qualifier!
2465 // Handle single qualifiers without copying
2466 if (Proto->getTypeQuals() == Qualifiers::Const) {
2467 Result.AddInformativeChunk(" const");
2471 if (Proto->getTypeQuals() == Qualifiers::Volatile) {
2472 Result.AddInformativeChunk(" volatile");
2476 if (Proto->getTypeQuals() == Qualifiers::Restrict) {
2477 Result.AddInformativeChunk(" restrict");
2481 // Handle multiple qualifiers.
2482 std::string QualsStr;
2483 if (Proto->isConst())
2484 QualsStr += " const";
2485 if (Proto->isVolatile())
2486 QualsStr += " volatile";
2487 if (Proto->isRestrict())
2488 QualsStr += " restrict";
2489 Result.AddInformativeChunk(Result.getAllocator().CopyString(QualsStr));
2492 /// \brief Add the name of the given declaration
2493 static void AddTypedNameChunk(ASTContext &Context, const PrintingPolicy &Policy,
2494 const NamedDecl *ND,
2495 CodeCompletionBuilder &Result) {
2496 DeclarationName Name = ND->getDeclName();
2500 switch (Name.getNameKind()) {
2501 case DeclarationName::CXXOperatorName: {
2502 const char *OperatorName = nullptr;
2503 switch (Name.getCXXOverloadedOperator()) {
2505 case OO_Conditional:
2506 case NUM_OVERLOADED_OPERATORS:
2507 OperatorName = "operator";
2510 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2511 case OO_##Name: OperatorName = "operator" Spelling; break;
2512 #define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
2513 #include "clang/Basic/OperatorKinds.def"
2515 case OO_New: OperatorName = "operator new"; break;
2516 case OO_Delete: OperatorName = "operator delete"; break;
2517 case OO_Array_New: OperatorName = "operator new[]"; break;
2518 case OO_Array_Delete: OperatorName = "operator delete[]"; break;
2519 case OO_Call: OperatorName = "operator()"; break;
2520 case OO_Subscript: OperatorName = "operator[]"; break;
2522 Result.AddTypedTextChunk(OperatorName);
2526 case DeclarationName::Identifier:
2527 case DeclarationName::CXXConversionFunctionName:
2528 case DeclarationName::CXXDestructorName:
2529 case DeclarationName::CXXLiteralOperatorName:
2530 Result.AddTypedTextChunk(
2531 Result.getAllocator().CopyString(ND->getNameAsString()));
2534 case DeclarationName::CXXUsingDirective:
2535 case DeclarationName::ObjCZeroArgSelector:
2536 case DeclarationName::ObjCOneArgSelector:
2537 case DeclarationName::ObjCMultiArgSelector:
2540 case DeclarationName::CXXConstructorName: {
2541 CXXRecordDecl *Record = nullptr;
2542 QualType Ty = Name.getCXXNameType();
2543 if (const RecordType *RecordTy = Ty->getAs<RecordType>())
2544 Record = cast<CXXRecordDecl>(RecordTy->getDecl());
2545 else if (const InjectedClassNameType *InjectedTy
2546 = Ty->getAs<InjectedClassNameType>())
2547 Record = InjectedTy->getDecl();
2549 Result.AddTypedTextChunk(
2550 Result.getAllocator().CopyString(ND->getNameAsString()));
2554 Result.AddTypedTextChunk(
2555 Result.getAllocator().CopyString(Record->getNameAsString()));
2556 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) {
2557 Result.AddChunk(CodeCompletionString::CK_LeftAngle);
2558 AddTemplateParameterChunks(Context, Policy, Template, Result);
2559 Result.AddChunk(CodeCompletionString::CK_RightAngle);
2566 CodeCompletionString *CodeCompletionResult::CreateCodeCompletionString(Sema &S,
2567 const CodeCompletionContext &CCContext,
2568 CodeCompletionAllocator &Allocator,
2569 CodeCompletionTUInfo &CCTUInfo,
2570 bool IncludeBriefComments) {
2571 return CreateCodeCompletionString(S.Context, S.PP, CCContext, Allocator,
2572 CCTUInfo, IncludeBriefComments);
2575 /// \brief If possible, create a new code completion string for the given
2578 /// \returns Either a new, heap-allocated code completion string describing
2579 /// how to use this result, or NULL to indicate that the string or name of the
2580 /// result is all that is needed.
2581 CodeCompletionString *
2582 CodeCompletionResult::CreateCodeCompletionString(ASTContext &Ctx,
2584 const CodeCompletionContext &CCContext,
2585 CodeCompletionAllocator &Allocator,
2586 CodeCompletionTUInfo &CCTUInfo,
2587 bool IncludeBriefComments) {
2588 CodeCompletionBuilder Result(Allocator, CCTUInfo, Priority, Availability);
2590 PrintingPolicy Policy = getCompletionPrintingPolicy(Ctx, PP);
2591 if (Kind == RK_Pattern) {
2592 Pattern->Priority = Priority;
2593 Pattern->Availability = Availability;
2596 Result.addParentContext(Declaration->getDeclContext());
2597 Pattern->ParentName = Result.getParentName();
2598 // Provide code completion comment for self.GetterName where
2599 // GetterName is the getter method for a property with name
2600 // different from the property name (declared via a property
2601 // getter attribute.
2602 const NamedDecl *ND = Declaration;
2603 if (const ObjCMethodDecl *M = dyn_cast<ObjCMethodDecl>(ND))
2604 if (M->isPropertyAccessor())
2605 if (const ObjCPropertyDecl *PDecl = M->findPropertyDecl())
2606 if (PDecl->getGetterName() == M->getSelector() &&
2607 PDecl->getIdentifier() != M->getIdentifier()) {
2608 if (const RawComment *RC =
2609 Ctx.getRawCommentForAnyRedecl(M)) {
2610 Result.addBriefComment(RC->getBriefText(Ctx));
2611 Pattern->BriefComment = Result.getBriefComment();
2613 else if (const RawComment *RC =
2614 Ctx.getRawCommentForAnyRedecl(PDecl)) {
2615 Result.addBriefComment(RC->getBriefText(Ctx));
2616 Pattern->BriefComment = Result.getBriefComment();
2624 if (Kind == RK_Keyword) {
2625 Result.AddTypedTextChunk(Keyword);
2626 return Result.TakeString();
2629 if (Kind == RK_Macro) {
2630 const MacroInfo *MI = PP.getMacroInfo(Macro);
2631 Result.AddTypedTextChunk(
2632 Result.getAllocator().CopyString(Macro->getName()));
2634 if (!MI || !MI->isFunctionLike())
2635 return Result.TakeString();
2637 // Format a function-like macro with placeholders for the arguments.
2638 Result.AddChunk(CodeCompletionString::CK_LeftParen);
2639 MacroInfo::arg_iterator A = MI->arg_begin(), AEnd = MI->arg_end();
2641 // C99 variadic macros add __VA_ARGS__ at the end. Skip it.
2642 if (MI->isC99Varargs()) {
2646 Result.AddPlaceholderChunk("...");
2650 for (MacroInfo::arg_iterator A = MI->arg_begin(); A != AEnd; ++A) {
2651 if (A != MI->arg_begin())
2652 Result.AddChunk(CodeCompletionString::CK_Comma);
2654 if (MI->isVariadic() && (A+1) == AEnd) {
2655 SmallString<32> Arg = (*A)->getName();
2656 if (MI->isC99Varargs())
2660 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
2664 // Non-variadic macros are simple.
2665 Result.AddPlaceholderChunk(
2666 Result.getAllocator().CopyString((*A)->getName()));
2668 Result.AddChunk(CodeCompletionString::CK_RightParen);
2669 return Result.TakeString();
2672 assert(Kind == RK_Declaration && "Missed a result kind?");
2673 const NamedDecl *ND = Declaration;
2674 Result.addParentContext(ND->getDeclContext());
2676 if (IncludeBriefComments) {
2677 // Add documentation comment, if it exists.
2678 if (const RawComment *RC = Ctx.getRawCommentForAnyRedecl(ND)) {
2679 Result.addBriefComment(RC->getBriefText(Ctx));
2681 else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
2682 if (OMD->isPropertyAccessor())
2683 if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
2684 if (const RawComment *RC = Ctx.getRawCommentForAnyRedecl(PDecl))
2685 Result.addBriefComment(RC->getBriefText(Ctx));
2688 if (StartsNestedNameSpecifier) {
2689 Result.AddTypedTextChunk(
2690 Result.getAllocator().CopyString(ND->getNameAsString()));
2691 Result.AddTextChunk("::");
2692 return Result.TakeString();
2695 for (const auto *I : ND->specific_attrs<AnnotateAttr>())
2696 Result.AddAnnotation(Result.getAllocator().CopyString(I->getAnnotation()));
2698 AddResultTypeChunk(Ctx, Policy, ND, CCContext.getBaseType(), Result);
2700 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(ND)) {
2701 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2703 AddTypedNameChunk(Ctx, Policy, ND, Result);
2704 Result.AddChunk(CodeCompletionString::CK_LeftParen);
2705 AddFunctionParameterChunks(PP, Policy, Function, Result);
2706 Result.AddChunk(CodeCompletionString::CK_RightParen);
2707 AddFunctionTypeQualsToCompletionString(Result, Function);
2708 return Result.TakeString();
2711 if (const FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND)) {
2712 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2714 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
2715 AddTypedNameChunk(Ctx, Policy, Function, Result);
2717 // Figure out which template parameters are deduced (or have default
2719 llvm::SmallBitVector Deduced;
2720 Sema::MarkDeducedTemplateParameters(Ctx, FunTmpl, Deduced);
2721 unsigned LastDeducibleArgument;
2722 for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0;
2723 --LastDeducibleArgument) {
2724 if (!Deduced[LastDeducibleArgument - 1]) {
2725 // C++0x: Figure out if the template argument has a default. If so,
2726 // the user doesn't need to type this argument.
2727 // FIXME: We need to abstract template parameters better!
2728 bool HasDefaultArg = false;
2729 NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam(
2730 LastDeducibleArgument - 1);
2731 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2732 HasDefaultArg = TTP->hasDefaultArgument();
2733 else if (NonTypeTemplateParmDecl *NTTP
2734 = dyn_cast<NonTypeTemplateParmDecl>(Param))
2735 HasDefaultArg = NTTP->hasDefaultArgument();
2737 assert(isa<TemplateTemplateParmDecl>(Param));
2739 = cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument();
2747 if (LastDeducibleArgument) {
2748 // Some of the function template arguments cannot be deduced from a
2749 // function call, so we introduce an explicit template argument list
2750 // containing all of the arguments up to the first deducible argument.
2751 Result.AddChunk(CodeCompletionString::CK_LeftAngle);
2752 AddTemplateParameterChunks(Ctx, Policy, FunTmpl, Result,
2753 LastDeducibleArgument);
2754 Result.AddChunk(CodeCompletionString::CK_RightAngle);
2757 // Add the function parameters
2758 Result.AddChunk(CodeCompletionString::CK_LeftParen);
2759 AddFunctionParameterChunks(PP, Policy, Function, Result);
2760 Result.AddChunk(CodeCompletionString::CK_RightParen);
2761 AddFunctionTypeQualsToCompletionString(Result, Function);
2762 return Result.TakeString();
2765 if (const TemplateDecl *Template = dyn_cast<TemplateDecl>(ND)) {
2766 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2768 Result.AddTypedTextChunk(
2769 Result.getAllocator().CopyString(Template->getNameAsString()));
2770 Result.AddChunk(CodeCompletionString::CK_LeftAngle);
2771 AddTemplateParameterChunks(Ctx, Policy, Template, Result);
2772 Result.AddChunk(CodeCompletionString::CK_RightAngle);
2773 return Result.TakeString();
2776 if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND)) {
2777 Selector Sel = Method->getSelector();
2778 if (Sel.isUnarySelector()) {
2779 Result.AddTypedTextChunk(Result.getAllocator().CopyString(
2780 Sel.getNameForSlot(0)));
2781 return Result.TakeString();
2784 std::string SelName = Sel.getNameForSlot(0).str();
2786 if (StartParameter == 0)
2787 Result.AddTypedTextChunk(Result.getAllocator().CopyString(SelName));
2789 Result.AddInformativeChunk(Result.getAllocator().CopyString(SelName));
2791 // If there is only one parameter, and we're past it, add an empty
2792 // typed-text chunk since there is nothing to type.
2793 if (Method->param_size() == 1)
2794 Result.AddTypedTextChunk("");
2797 for (ObjCMethodDecl::param_const_iterator P = Method->param_begin(),
2798 PEnd = Method->param_end();
2799 P != PEnd; (void)++P, ++Idx) {
2801 std::string Keyword;
2802 if (Idx > StartParameter)
2803 Result.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2804 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(Idx))
2805 Keyword += II->getName();
2807 if (Idx < StartParameter || AllParametersAreInformative)
2808 Result.AddInformativeChunk(Result.getAllocator().CopyString(Keyword));
2810 Result.AddTypedTextChunk(Result.getAllocator().CopyString(Keyword));
2813 // If we're before the starting parameter, skip the placeholder.
2814 if (Idx < StartParameter)
2818 QualType ParamType = (*P)->getType();
2819 Optional<ArrayRef<QualType>> ObjCSubsts;
2820 if (!CCContext.getBaseType().isNull())
2821 ObjCSubsts = CCContext.getBaseType()->getObjCSubstitutions(Method);
2823 if (ParamType->isBlockPointerType() && !DeclaringEntity)
2824 Arg = FormatFunctionParameter(Policy, *P, true,
2825 /*SuppressBlock=*/false,
2829 ParamType = ParamType.substObjCTypeArgs(Ctx, *ObjCSubsts,
2830 ObjCSubstitutionContext::Parameter);
2831 Arg = "(" + formatObjCParamQualifiers((*P)->getObjCDeclQualifier(),
2833 Arg += ParamType.getAsString(Policy) + ")";
2834 if (IdentifierInfo *II = (*P)->getIdentifier())
2835 if (DeclaringEntity || AllParametersAreInformative)
2836 Arg += II->getName();
2839 if (Method->isVariadic() && (P + 1) == PEnd)
2842 if (DeclaringEntity)
2843 Result.AddTextChunk(Result.getAllocator().CopyString(Arg));
2844 else if (AllParametersAreInformative)
2845 Result.AddInformativeChunk(Result.getAllocator().CopyString(Arg));
2847 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
2850 if (Method->isVariadic()) {
2851 if (Method->param_size() == 0) {
2852 if (DeclaringEntity)
2853 Result.AddTextChunk(", ...");
2854 else if (AllParametersAreInformative)
2855 Result.AddInformativeChunk(", ...");
2857 Result.AddPlaceholderChunk(", ...");
2860 MaybeAddSentinel(PP, Method, Result);
2863 return Result.TakeString();
2867 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2870 Result.AddTypedTextChunk(
2871 Result.getAllocator().CopyString(ND->getNameAsString()));
2872 return Result.TakeString();
2875 /// \brief Add function overload parameter chunks to the given code completion
2877 static void AddOverloadParameterChunks(ASTContext &Context,
2878 const PrintingPolicy &Policy,
2879 const FunctionDecl *Function,
2880 const FunctionProtoType *Prototype,
2881 CodeCompletionBuilder &Result,
2882 unsigned CurrentArg,
2884 bool InOptional = false) {
2885 bool FirstParameter = true;
2886 unsigned NumParams = Function ? Function->getNumParams()
2887 : Prototype->getNumParams();
2889 for (unsigned P = Start; P != NumParams; ++P) {
2890 if (Function && Function->getParamDecl(P)->hasDefaultArg() && !InOptional) {
2891 // When we see an optional default argument, put that argument and
2892 // the remaining default arguments into a new, optional string.
2893 CodeCompletionBuilder Opt(Result.getAllocator(),
2894 Result.getCodeCompletionTUInfo());
2895 if (!FirstParameter)
2896 Opt.AddChunk(CodeCompletionString::CK_Comma);
2897 // Optional sections are nested.
2898 AddOverloadParameterChunks(Context, Policy, Function, Prototype, Opt,
2899 CurrentArg, P, /*InOptional=*/true);
2900 Result.AddOptionalChunk(Opt.TakeString());
2905 FirstParameter = false;
2907 Result.AddChunk(CodeCompletionString::CK_Comma);
2911 // Format the placeholder string.
2912 std::string Placeholder;
2914 Placeholder = FormatFunctionParameter(Policy, Function->getParamDecl(P));
2916 Placeholder = Prototype->getParamType(P).getAsString(Policy);
2918 if (P == CurrentArg)
2919 Result.AddCurrentParameterChunk(
2920 Result.getAllocator().CopyString(Placeholder));
2922 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Placeholder));
2925 if (Prototype && Prototype->isVariadic()) {
2926 CodeCompletionBuilder Opt(Result.getAllocator(),
2927 Result.getCodeCompletionTUInfo());
2928 if (!FirstParameter)
2929 Opt.AddChunk(CodeCompletionString::CK_Comma);
2931 if (CurrentArg < NumParams)
2932 Opt.AddPlaceholderChunk("...");
2934 Opt.AddCurrentParameterChunk("...");
2936 Result.AddOptionalChunk(Opt.TakeString());
2940 CodeCompletionString *
2941 CodeCompleteConsumer::OverloadCandidate::CreateSignatureString(
2942 unsigned CurrentArg, Sema &S,
2943 CodeCompletionAllocator &Allocator,
2944 CodeCompletionTUInfo &CCTUInfo,
2945 bool IncludeBriefComments) const {
2946 PrintingPolicy Policy = getCompletionPrintingPolicy(S);
2948 // FIXME: Set priority, availability appropriately.
2949 CodeCompletionBuilder Result(Allocator,CCTUInfo, 1, CXAvailability_Available);
2950 FunctionDecl *FDecl = getFunction();
2951 const FunctionProtoType *Proto
2952 = dyn_cast<FunctionProtoType>(getFunctionType());
2953 if (!FDecl && !Proto) {
2954 // Function without a prototype. Just give the return type and a
2955 // highlighted ellipsis.
2956 const FunctionType *FT = getFunctionType();
2957 Result.AddResultTypeChunk(Result.getAllocator().CopyString(
2958 FT->getReturnType().getAsString(Policy)));
2959 Result.AddChunk(CodeCompletionString::CK_LeftParen);
2960 Result.AddChunk(CodeCompletionString::CK_CurrentParameter, "...");
2961 Result.AddChunk(CodeCompletionString::CK_RightParen);
2962 return Result.TakeString();
2966 if (IncludeBriefComments && CurrentArg < FDecl->getNumParams())
2967 if (auto RC = S.getASTContext().getRawCommentForAnyRedecl(
2968 FDecl->getParamDecl(CurrentArg)))
2969 Result.addBriefComment(RC->getBriefText(S.getASTContext()));
2970 AddResultTypeChunk(S.Context, Policy, FDecl, QualType(), Result);
2971 Result.AddTextChunk(
2972 Result.getAllocator().CopyString(FDecl->getNameAsString()));
2974 Result.AddResultTypeChunk(
2975 Result.getAllocator().CopyString(
2976 Proto->getReturnType().getAsString(Policy)));
2979 Result.AddChunk(CodeCompletionString::CK_LeftParen);
2980 AddOverloadParameterChunks(S.getASTContext(), Policy, FDecl, Proto, Result,
2982 Result.AddChunk(CodeCompletionString::CK_RightParen);
2984 return Result.TakeString();
2987 unsigned clang::getMacroUsagePriority(StringRef MacroName,
2988 const LangOptions &LangOpts,
2989 bool PreferredTypeIsPointer) {
2990 unsigned Priority = CCP_Macro;
2992 // Treat the "nil", "Nil" and "NULL" macros as null pointer constants.
2993 if (MacroName.equals("nil") || MacroName.equals("NULL") ||
2994 MacroName.equals("Nil")) {
2995 Priority = CCP_Constant;
2996 if (PreferredTypeIsPointer)
2997 Priority = Priority / CCF_SimilarTypeMatch;
2999 // Treat "YES", "NO", "true", and "false" as constants.
3000 else if (MacroName.equals("YES") || MacroName.equals("NO") ||
3001 MacroName.equals("true") || MacroName.equals("false"))
3002 Priority = CCP_Constant;
3003 // Treat "bool" as a type.
3004 else if (MacroName.equals("bool"))
3005 Priority = CCP_Type + (LangOpts.ObjC1? CCD_bool_in_ObjC : 0);
3011 CXCursorKind clang::getCursorKindForDecl(const Decl *D) {
3013 return CXCursor_UnexposedDecl;
3015 switch (D->getKind()) {
3016 case Decl::Enum: return CXCursor_EnumDecl;
3017 case Decl::EnumConstant: return CXCursor_EnumConstantDecl;
3018 case Decl::Field: return CXCursor_FieldDecl;
3019 case Decl::Function:
3020 return CXCursor_FunctionDecl;
3021 case Decl::ObjCCategory: return CXCursor_ObjCCategoryDecl;
3022 case Decl::ObjCCategoryImpl: return CXCursor_ObjCCategoryImplDecl;
3023 case Decl::ObjCImplementation: return CXCursor_ObjCImplementationDecl;
3025 case Decl::ObjCInterface: return CXCursor_ObjCInterfaceDecl;
3026 case Decl::ObjCIvar: return CXCursor_ObjCIvarDecl;
3027 case Decl::ObjCMethod:
3028 return cast<ObjCMethodDecl>(D)->isInstanceMethod()
3029 ? CXCursor_ObjCInstanceMethodDecl : CXCursor_ObjCClassMethodDecl;
3030 case Decl::CXXMethod: return CXCursor_CXXMethod;
3031 case Decl::CXXConstructor: return CXCursor_Constructor;
3032 case Decl::CXXDestructor: return CXCursor_Destructor;
3033 case Decl::CXXConversion: return CXCursor_ConversionFunction;
3034 case Decl::ObjCProperty: return CXCursor_ObjCPropertyDecl;
3035 case Decl::ObjCProtocol: return CXCursor_ObjCProtocolDecl;
3036 case Decl::ParmVar: return CXCursor_ParmDecl;
3037 case Decl::Typedef: return CXCursor_TypedefDecl;
3038 case Decl::TypeAlias: return CXCursor_TypeAliasDecl;
3039 case Decl::Var: return CXCursor_VarDecl;
3040 case Decl::Namespace: return CXCursor_Namespace;
3041 case Decl::NamespaceAlias: return CXCursor_NamespaceAlias;
3042 case Decl::TemplateTypeParm: return CXCursor_TemplateTypeParameter;
3043 case Decl::NonTypeTemplateParm:return CXCursor_NonTypeTemplateParameter;
3044 case Decl::TemplateTemplateParm:return CXCursor_TemplateTemplateParameter;
3045 case Decl::FunctionTemplate: return CXCursor_FunctionTemplate;
3046 case Decl::ClassTemplate: return CXCursor_ClassTemplate;
3047 case Decl::AccessSpec: return CXCursor_CXXAccessSpecifier;
3048 case Decl::ClassTemplatePartialSpecialization:
3049 return CXCursor_ClassTemplatePartialSpecialization;
3050 case Decl::UsingDirective: return CXCursor_UsingDirective;
3051 case Decl::TranslationUnit: return CXCursor_TranslationUnit;
3054 case Decl::UnresolvedUsingValue:
3055 case Decl::UnresolvedUsingTypename:
3056 return CXCursor_UsingDeclaration;
3058 case Decl::ObjCPropertyImpl:
3059 switch (cast<ObjCPropertyImplDecl>(D)->getPropertyImplementation()) {
3060 case ObjCPropertyImplDecl::Dynamic:
3061 return CXCursor_ObjCDynamicDecl;
3063 case ObjCPropertyImplDecl::Synthesize:
3064 return CXCursor_ObjCSynthesizeDecl;
3068 return CXCursor_ModuleImportDecl;
3070 case Decl::ObjCTypeParam: return CXCursor_TemplateTypeParameter;
3073 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
3074 switch (TD->getTagKind()) {
3075 case TTK_Interface: // fall through
3076 case TTK_Struct: return CXCursor_StructDecl;
3077 case TTK_Class: return CXCursor_ClassDecl;
3078 case TTK_Union: return CXCursor_UnionDecl;
3079 case TTK_Enum: return CXCursor_EnumDecl;
3084 return CXCursor_UnexposedDecl;
3087 static void AddMacroResults(Preprocessor &PP, ResultBuilder &Results,
3088 bool IncludeUndefined,
3089 bool TargetTypeIsPointer = false) {
3090 typedef CodeCompletionResult Result;
3092 Results.EnterNewScope();
3094 for (Preprocessor::macro_iterator M = PP.macro_begin(),
3095 MEnd = PP.macro_end();
3097 auto MD = PP.getMacroDefinition(M->first);
3098 if (IncludeUndefined || MD) {
3099 if (MacroInfo *MI = MD.getMacroInfo())
3100 if (MI->isUsedForHeaderGuard())
3103 Results.AddResult(Result(M->first,
3104 getMacroUsagePriority(M->first->getName(),
3106 TargetTypeIsPointer)));
3110 Results.ExitScope();
3114 static void AddPrettyFunctionResults(const LangOptions &LangOpts,
3115 ResultBuilder &Results) {
3116 typedef CodeCompletionResult Result;
3118 Results.EnterNewScope();
3120 Results.AddResult(Result("__PRETTY_FUNCTION__", CCP_Constant));
3121 Results.AddResult(Result("__FUNCTION__", CCP_Constant));
3122 if (LangOpts.C99 || LangOpts.CPlusPlus11)
3123 Results.AddResult(Result("__func__", CCP_Constant));
3124 Results.ExitScope();
3127 static void HandleCodeCompleteResults(Sema *S,
3128 CodeCompleteConsumer *CodeCompleter,
3129 CodeCompletionContext Context,
3130 CodeCompletionResult *Results,
3131 unsigned NumResults) {
3133 CodeCompleter->ProcessCodeCompleteResults(*S, Context, Results, NumResults);
3136 static enum CodeCompletionContext::Kind mapCodeCompletionContext(Sema &S,
3137 Sema::ParserCompletionContext PCC) {
3139 case Sema::PCC_Namespace:
3140 return CodeCompletionContext::CCC_TopLevel;
3142 case Sema::PCC_Class:
3143 return CodeCompletionContext::CCC_ClassStructUnion;
3145 case Sema::PCC_ObjCInterface:
3146 return CodeCompletionContext::CCC_ObjCInterface;
3148 case Sema::PCC_ObjCImplementation:
3149 return CodeCompletionContext::CCC_ObjCImplementation;
3151 case Sema::PCC_ObjCInstanceVariableList:
3152 return CodeCompletionContext::CCC_ObjCIvarList;
3154 case Sema::PCC_Template:
3155 case Sema::PCC_MemberTemplate:
3156 if (S.CurContext->isFileContext())
3157 return CodeCompletionContext::CCC_TopLevel;
3158 if (S.CurContext->isRecord())
3159 return CodeCompletionContext::CCC_ClassStructUnion;
3160 return CodeCompletionContext::CCC_Other;
3162 case Sema::PCC_RecoveryInFunction:
3163 return CodeCompletionContext::CCC_Recovery;
3165 case Sema::PCC_ForInit:
3166 if (S.getLangOpts().CPlusPlus || S.getLangOpts().C99 ||
3167 S.getLangOpts().ObjC1)
3168 return CodeCompletionContext::CCC_ParenthesizedExpression;
3170 return CodeCompletionContext::CCC_Expression;
3172 case Sema::PCC_Expression:
3173 case Sema::PCC_Condition:
3174 return CodeCompletionContext::CCC_Expression;
3176 case Sema::PCC_Statement:
3177 return CodeCompletionContext::CCC_Statement;
3179 case Sema::PCC_Type:
3180 return CodeCompletionContext::CCC_Type;
3182 case Sema::PCC_ParenthesizedExpression:
3183 return CodeCompletionContext::CCC_ParenthesizedExpression;
3185 case Sema::PCC_LocalDeclarationSpecifiers:
3186 return CodeCompletionContext::CCC_Type;
3189 llvm_unreachable("Invalid ParserCompletionContext!");
3192 /// \brief If we're in a C++ virtual member function, add completion results
3193 /// that invoke the functions we override, since it's common to invoke the
3194 /// overridden function as well as adding new functionality.
3196 /// \param S The semantic analysis object for which we are generating results.
3198 /// \param InContext This context in which the nested-name-specifier preceding
3199 /// the code-completion point
3200 static void MaybeAddOverrideCalls(Sema &S, DeclContext *InContext,
3201 ResultBuilder &Results) {
3202 // Look through blocks.
3203 DeclContext *CurContext = S.CurContext;
3204 while (isa<BlockDecl>(CurContext))
3205 CurContext = CurContext->getParent();
3208 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(CurContext);
3209 if (!Method || !Method->isVirtual())
3212 // We need to have names for all of the parameters, if we're going to
3213 // generate a forwarding call.
3214 for (auto P : Method->params())
3215 if (!P->getDeclName())
3218 PrintingPolicy Policy = getCompletionPrintingPolicy(S);
3219 for (CXXMethodDecl::method_iterator M = Method->begin_overridden_methods(),
3220 MEnd = Method->end_overridden_methods();
3222 CodeCompletionBuilder Builder(Results.getAllocator(),
3223 Results.getCodeCompletionTUInfo());
3224 const CXXMethodDecl *Overridden = *M;
3225 if (Overridden->getCanonicalDecl() == Method->getCanonicalDecl())
3228 // If we need a nested-name-specifier, add one now.
3230 NestedNameSpecifier *NNS
3231 = getRequiredQualification(S.Context, CurContext,
3232 Overridden->getDeclContext());
3235 llvm::raw_string_ostream OS(Str);
3236 NNS->print(OS, Policy);
3237 Builder.AddTextChunk(Results.getAllocator().CopyString(OS.str()));
3239 } else if (!InContext->Equals(Overridden->getDeclContext()))
3242 Builder.AddTypedTextChunk(Results.getAllocator().CopyString(
3243 Overridden->getNameAsString()));
3244 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
3245 bool FirstParam = true;
3246 for (auto P : Method->params()) {
3250 Builder.AddChunk(CodeCompletionString::CK_Comma);
3252 Builder.AddPlaceholderChunk(
3253 Results.getAllocator().CopyString(P->getIdentifier()->getName()));
3255 Builder.AddChunk(CodeCompletionString::CK_RightParen);
3256 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
3257 CCP_SuperCompletion,
3259 CXAvailability_Available,
3261 Results.Ignore(Overridden);
3265 void Sema::CodeCompleteModuleImport(SourceLocation ImportLoc,
3266 ModuleIdPath Path) {
3267 typedef CodeCompletionResult Result;
3268 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3269 CodeCompleter->getCodeCompletionTUInfo(),
3270 CodeCompletionContext::CCC_Other);
3271 Results.EnterNewScope();
3273 CodeCompletionAllocator &Allocator = Results.getAllocator();
3274 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
3275 typedef CodeCompletionResult Result;
3277 // Enumerate all top-level modules.
3278 SmallVector<Module *, 8> Modules;
3279 PP.getHeaderSearchInfo().collectAllModules(Modules);
3280 for (unsigned I = 0, N = Modules.size(); I != N; ++I) {
3281 Builder.AddTypedTextChunk(
3282 Builder.getAllocator().CopyString(Modules[I]->Name));
3283 Results.AddResult(Result(Builder.TakeString(),
3285 CXCursor_ModuleImportDecl,
3286 Modules[I]->isAvailable()
3287 ? CXAvailability_Available
3288 : CXAvailability_NotAvailable));
3290 } else if (getLangOpts().Modules) {
3291 // Load the named module.
3292 Module *Mod = PP.getModuleLoader().loadModule(ImportLoc, Path,
3294 /*IsInclusionDirective=*/false);
3295 // Enumerate submodules.
3297 for (Module::submodule_iterator Sub = Mod->submodule_begin(),
3298 SubEnd = Mod->submodule_end();
3299 Sub != SubEnd; ++Sub) {
3301 Builder.AddTypedTextChunk(
3302 Builder.getAllocator().CopyString((*Sub)->Name));
3303 Results.AddResult(Result(Builder.TakeString(),
3305 CXCursor_ModuleImportDecl,
3306 (*Sub)->isAvailable()
3307 ? CXAvailability_Available
3308 : CXAvailability_NotAvailable));
3312 Results.ExitScope();
3313 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
3314 Results.data(),Results.size());
3317 void Sema::CodeCompleteOrdinaryName(Scope *S,
3318 ParserCompletionContext CompletionContext) {
3319 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3320 CodeCompleter->getCodeCompletionTUInfo(),
3321 mapCodeCompletionContext(*this, CompletionContext));
3322 Results.EnterNewScope();
3324 // Determine how to filter results, e.g., so that the names of
3325 // values (functions, enumerators, function templates, etc.) are
3326 // only allowed where we can have an expression.
3327 switch (CompletionContext) {
3330 case PCC_ObjCInterface:
3331 case PCC_ObjCImplementation:
3332 case PCC_ObjCInstanceVariableList:
3334 case PCC_MemberTemplate:
3336 case PCC_LocalDeclarationSpecifiers:
3337 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
3341 case PCC_ParenthesizedExpression:
3342 case PCC_Expression:
3345 if (WantTypesInContext(CompletionContext, getLangOpts()))
3346 Results.setFilter(&ResultBuilder::IsOrdinaryName);
3348 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
3350 if (getLangOpts().CPlusPlus)
3351 MaybeAddOverrideCalls(*this, /*InContext=*/nullptr, Results);
3354 case PCC_RecoveryInFunction:
3359 // If we are in a C++ non-static member function, check the qualifiers on
3360 // the member function to filter/prioritize the results list.
3361 if (CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext))
3362 if (CurMethod->isInstance())
3363 Results.setObjectTypeQualifiers(
3364 Qualifiers::fromCVRMask(CurMethod->getTypeQualifiers()));
3366 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3367 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3368 CodeCompleter->includeGlobals());
3370 AddOrdinaryNameResults(CompletionContext, S, *this, Results);
3371 Results.ExitScope();
3373 switch (CompletionContext) {
3374 case PCC_ParenthesizedExpression:
3375 case PCC_Expression:
3377 case PCC_RecoveryInFunction:
3378 if (S->getFnParent())
3379 AddPrettyFunctionResults(PP.getLangOpts(), Results);
3384 case PCC_ObjCInterface:
3385 case PCC_ObjCImplementation:
3386 case PCC_ObjCInstanceVariableList:
3388 case PCC_MemberTemplate:
3392 case PCC_LocalDeclarationSpecifiers:
3396 if (CodeCompleter->includeMacros())
3397 AddMacroResults(PP, Results, false);
3399 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
3400 Results.data(),Results.size());
3403 static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
3404 ParsedType Receiver,
3405 ArrayRef<IdentifierInfo *> SelIdents,
3406 bool AtArgumentExpression,
3408 ResultBuilder &Results);
3410 void Sema::CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
3411 bool AllowNonIdentifiers,
3412 bool AllowNestedNameSpecifiers) {
3413 typedef CodeCompletionResult Result;
3414 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3415 CodeCompleter->getCodeCompletionTUInfo(),
3416 AllowNestedNameSpecifiers
3417 ? CodeCompletionContext::CCC_PotentiallyQualifiedName
3418 : CodeCompletionContext::CCC_Name);
3419 Results.EnterNewScope();
3421 // Type qualifiers can come after names.
3422 Results.AddResult(Result("const"));
3423 Results.AddResult(Result("volatile"));
3424 if (getLangOpts().C99)
3425 Results.AddResult(Result("restrict"));
3427 if (getLangOpts().CPlusPlus) {
3428 if (AllowNonIdentifiers) {
3429 Results.AddResult(Result("operator"));
3432 // Add nested-name-specifiers.
3433 if (AllowNestedNameSpecifiers) {
3434 Results.allowNestedNameSpecifiers();
3435 Results.setFilter(&ResultBuilder::IsImpossibleToSatisfy);
3436 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3437 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer,
3438 CodeCompleter->includeGlobals());
3439 Results.setFilter(nullptr);
3442 Results.ExitScope();
3444 // If we're in a context where we might have an expression (rather than a
3445 // declaration), and what we've seen so far is an Objective-C type that could
3446 // be a receiver of a class message, this may be a class message send with
3447 // the initial opening bracket '[' missing. Add appropriate completions.
3448 if (AllowNonIdentifiers && !AllowNestedNameSpecifiers &&
3449 DS.getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier &&
3450 DS.getTypeSpecType() == DeclSpec::TST_typename &&
3451 DS.getTypeSpecComplex() == DeclSpec::TSC_unspecified &&
3452 DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
3453 !DS.isTypeAltiVecVector() &&
3455 (S->getFlags() & Scope::DeclScope) != 0 &&
3456 (S->getFlags() & (Scope::ClassScope | Scope::TemplateParamScope |
3457 Scope::FunctionPrototypeScope |
3458 Scope::AtCatchScope)) == 0) {
3459 ParsedType T = DS.getRepAsType();
3460 if (!T.get().isNull() && T.get()->isObjCObjectOrInterfaceType())
3461 AddClassMessageCompletions(*this, S, T, None, false, false, Results);
3464 // Note that we intentionally suppress macro results here, since we do not
3465 // encourage using macros to produce the names of entities.
3467 HandleCodeCompleteResults(this, CodeCompleter,
3468 Results.getCompletionContext(),
3469 Results.data(), Results.size());
3472 struct Sema::CodeCompleteExpressionData {
3473 CodeCompleteExpressionData(QualType PreferredType = QualType())
3474 : PreferredType(PreferredType), IntegralConstantExpression(false),
3475 ObjCCollection(false) { }
3477 QualType PreferredType;
3478 bool IntegralConstantExpression;
3479 bool ObjCCollection;
3480 SmallVector<Decl *, 4> IgnoreDecls;
3483 /// \brief Perform code-completion in an expression context when we know what
3484 /// type we're looking for.
3485 void Sema::CodeCompleteExpression(Scope *S,
3486 const CodeCompleteExpressionData &Data) {
3487 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3488 CodeCompleter->getCodeCompletionTUInfo(),
3489 CodeCompletionContext::CCC_Expression);
3490 if (Data.ObjCCollection)
3491 Results.setFilter(&ResultBuilder::IsObjCCollection);
3492 else if (Data.IntegralConstantExpression)
3493 Results.setFilter(&ResultBuilder::IsIntegralConstantValue);
3494 else if (WantTypesInContext(PCC_Expression, getLangOpts()))
3495 Results.setFilter(&ResultBuilder::IsOrdinaryName);
3497 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
3499 if (!Data.PreferredType.isNull())
3500 Results.setPreferredType(Data.PreferredType.getNonReferenceType());
3502 // Ignore any declarations that we were told that we don't care about.
3503 for (unsigned I = 0, N = Data.IgnoreDecls.size(); I != N; ++I)
3504 Results.Ignore(Data.IgnoreDecls[I]);
3506 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3507 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3508 CodeCompleter->includeGlobals());
3510 Results.EnterNewScope();
3511 AddOrdinaryNameResults(PCC_Expression, S, *this, Results);
3512 Results.ExitScope();
3514 bool PreferredTypeIsPointer = false;
3515 if (!Data.PreferredType.isNull())
3516 PreferredTypeIsPointer = Data.PreferredType->isAnyPointerType()
3517 || Data.PreferredType->isMemberPointerType()
3518 || Data.PreferredType->isBlockPointerType();
3520 if (S->getFnParent() &&
3521 !Data.ObjCCollection &&
3522 !Data.IntegralConstantExpression)
3523 AddPrettyFunctionResults(PP.getLangOpts(), Results);
3525 if (CodeCompleter->includeMacros())
3526 AddMacroResults(PP, Results, false, PreferredTypeIsPointer);
3527 HandleCodeCompleteResults(this, CodeCompleter,
3528 CodeCompletionContext(CodeCompletionContext::CCC_Expression,
3529 Data.PreferredType),
3530 Results.data(),Results.size());
3533 void Sema::CodeCompletePostfixExpression(Scope *S, ExprResult E) {
3535 CodeCompleteOrdinaryName(S, PCC_RecoveryInFunction);
3536 else if (getLangOpts().ObjC1)
3537 CodeCompleteObjCInstanceMessage(S, E.get(), None, false);
3540 /// \brief The set of properties that have already been added, referenced by
3542 typedef llvm::SmallPtrSet<IdentifierInfo*, 16> AddedPropertiesSet;
3544 /// \brief Retrieve the container definition, if any?
3545 static ObjCContainerDecl *getContainerDef(ObjCContainerDecl *Container) {
3546 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
3547 if (Interface->hasDefinition())
3548 return Interface->getDefinition();
3553 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
3554 if (Protocol->hasDefinition())
3555 return Protocol->getDefinition();
3562 static void AddObjCProperties(const CodeCompletionContext &CCContext,
3563 ObjCContainerDecl *Container,
3564 bool AllowCategories,
3565 bool AllowNullaryMethods,
3566 DeclContext *CurContext,
3567 AddedPropertiesSet &AddedProperties,
3568 ResultBuilder &Results) {
3569 typedef CodeCompletionResult Result;
3571 // Retrieve the definition.
3572 Container = getContainerDef(Container);
3574 // Add properties in this container.
3575 for (const auto *P : Container->properties())
3576 if (AddedProperties.insert(P->getIdentifier()).second)
3577 Results.MaybeAddResult(Result(P, Results.getBasePriority(P), nullptr),
3580 // Add nullary methods
3581 if (AllowNullaryMethods) {
3582 ASTContext &Context = Container->getASTContext();
3583 PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema());
3584 for (auto *M : Container->methods()) {
3585 if (M->getSelector().isUnarySelector())
3586 if (IdentifierInfo *Name = M->getSelector().getIdentifierInfoForSlot(0))
3587 if (AddedProperties.insert(Name).second) {
3588 CodeCompletionBuilder Builder(Results.getAllocator(),
3589 Results.getCodeCompletionTUInfo());
3590 AddResultTypeChunk(Context, Policy, M, CCContext.getBaseType(),
3592 Builder.AddTypedTextChunk(
3593 Results.getAllocator().CopyString(Name->getName()));
3595 Results.MaybeAddResult(Result(Builder.TakeString(), M,
3596 CCP_MemberDeclaration + CCD_MethodAsProperty),
3603 // Add properties in referenced protocols.
3604 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
3605 for (auto *P : Protocol->protocols())
3606 AddObjCProperties(CCContext, P, AllowCategories, AllowNullaryMethods,
3607 CurContext, AddedProperties, Results);
3608 } else if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)){
3609 if (AllowCategories) {
3610 // Look through categories.
3611 for (auto *Cat : IFace->known_categories())
3612 AddObjCProperties(CCContext, Cat, AllowCategories, AllowNullaryMethods,
3613 CurContext, AddedProperties, Results);
3616 // Look through protocols.
3617 for (auto *I : IFace->all_referenced_protocols())
3618 AddObjCProperties(CCContext, I, AllowCategories, AllowNullaryMethods,
3619 CurContext, AddedProperties, Results);
3621 // Look in the superclass.
3622 if (IFace->getSuperClass())
3623 AddObjCProperties(CCContext, IFace->getSuperClass(), AllowCategories,
3624 AllowNullaryMethods, CurContext,
3625 AddedProperties, Results);
3626 } else if (const ObjCCategoryDecl *Category
3627 = dyn_cast<ObjCCategoryDecl>(Container)) {
3628 // Look through protocols.
3629 for (auto *P : Category->protocols())
3630 AddObjCProperties(CCContext, P, AllowCategories, AllowNullaryMethods,
3631 CurContext, AddedProperties, Results);
3635 void Sema::CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base,
3636 SourceLocation OpLoc,
3638 if (!Base || !CodeCompleter)
3641 ExprResult ConvertedBase = PerformMemberExprBaseConversion(Base, IsArrow);
3642 if (ConvertedBase.isInvalid())
3644 Base = ConvertedBase.get();
3646 typedef CodeCompletionResult Result;
3648 QualType BaseType = Base->getType();
3651 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
3652 BaseType = Ptr->getPointeeType();
3653 else if (BaseType->isObjCObjectPointerType())
3659 enum CodeCompletionContext::Kind contextKind;
3662 contextKind = CodeCompletionContext::CCC_ArrowMemberAccess;
3665 if (BaseType->isObjCObjectPointerType() ||
3666 BaseType->isObjCObjectOrInterfaceType()) {
3667 contextKind = CodeCompletionContext::CCC_ObjCPropertyAccess;
3670 contextKind = CodeCompletionContext::CCC_DotMemberAccess;
3674 CodeCompletionContext CCContext(contextKind, BaseType);
3675 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3676 CodeCompleter->getCodeCompletionTUInfo(),
3678 &ResultBuilder::IsMember);
3679 Results.EnterNewScope();
3680 if (const RecordType *Record = BaseType->getAs<RecordType>()) {
3681 // Indicate that we are performing a member access, and the cv-qualifiers
3682 // for the base object type.
3683 Results.setObjectTypeQualifiers(BaseType.getQualifiers());
3685 // Access to a C/C++ class, struct, or union.
3686 Results.allowNestedNameSpecifiers();
3687 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3688 LookupVisibleDecls(Record->getDecl(), LookupMemberName, Consumer,
3689 CodeCompleter->includeGlobals());
3691 if (getLangOpts().CPlusPlus) {
3692 if (!Results.empty()) {
3693 // The "template" keyword can follow "->" or "." in the grammar.
3694 // However, we only want to suggest the template keyword if something
3696 bool IsDependent = BaseType->isDependentType();
3698 for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent())
3699 if (DeclContext *Ctx = DepScope->getEntity()) {
3700 IsDependent = Ctx->isDependentContext();
3706 Results.AddResult(Result("template"));
3709 } else if (!IsArrow && BaseType->getAsObjCInterfacePointerType()) {
3710 // Objective-C property reference.
3711 AddedPropertiesSet AddedProperties;
3713 // Add property results based on our interface.
3714 const ObjCObjectPointerType *ObjCPtr
3715 = BaseType->getAsObjCInterfacePointerType();
3716 assert(ObjCPtr && "Non-NULL pointer guaranteed above!");
3717 AddObjCProperties(CCContext, ObjCPtr->getInterfaceDecl(), true,
3718 /*AllowNullaryMethods=*/true, CurContext,
3719 AddedProperties, Results);
3721 // Add properties from the protocols in a qualified interface.
3722 for (auto *I : ObjCPtr->quals())
3723 AddObjCProperties(CCContext, I, true, /*AllowNullaryMethods=*/true,
3724 CurContext, AddedProperties, Results);
3725 } else if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
3726 (!IsArrow && BaseType->isObjCObjectType())) {
3727 // Objective-C instance variable access.
3728 ObjCInterfaceDecl *Class = nullptr;
3729 if (const ObjCObjectPointerType *ObjCPtr
3730 = BaseType->getAs<ObjCObjectPointerType>())
3731 Class = ObjCPtr->getInterfaceDecl();
3733 Class = BaseType->getAs<ObjCObjectType>()->getInterface();
3735 // Add all ivars from this class and its superclasses.
3737 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3738 Results.setFilter(&ResultBuilder::IsObjCIvar);
3739 LookupVisibleDecls(Class, LookupMemberName, Consumer,
3740 CodeCompleter->includeGlobals());
3744 // FIXME: How do we cope with isa?
3746 Results.ExitScope();
3748 // Hand off the results found for code completion.
3749 HandleCodeCompleteResults(this, CodeCompleter,
3750 Results.getCompletionContext(),
3751 Results.data(),Results.size());
3754 void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) {
3758 ResultBuilder::LookupFilter Filter = nullptr;
3759 enum CodeCompletionContext::Kind ContextKind
3760 = CodeCompletionContext::CCC_Other;
3761 switch ((DeclSpec::TST)TagSpec) {
3762 case DeclSpec::TST_enum:
3763 Filter = &ResultBuilder::IsEnum;
3764 ContextKind = CodeCompletionContext::CCC_EnumTag;
3767 case DeclSpec::TST_union:
3768 Filter = &ResultBuilder::IsUnion;
3769 ContextKind = CodeCompletionContext::CCC_UnionTag;
3772 case DeclSpec::TST_struct:
3773 case DeclSpec::TST_class:
3774 case DeclSpec::TST_interface:
3775 Filter = &ResultBuilder::IsClassOrStruct;
3776 ContextKind = CodeCompletionContext::CCC_ClassOrStructTag;
3780 llvm_unreachable("Unknown type specifier kind in CodeCompleteTag");
3783 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3784 CodeCompleter->getCodeCompletionTUInfo(), ContextKind);
3785 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3787 // First pass: look for tags.
3788 Results.setFilter(Filter);
3789 LookupVisibleDecls(S, LookupTagName, Consumer,
3790 CodeCompleter->includeGlobals());
3792 if (CodeCompleter->includeGlobals()) {
3793 // Second pass: look for nested name specifiers.
3794 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
3795 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer);
3798 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
3799 Results.data(),Results.size());
3802 void Sema::CodeCompleteTypeQualifiers(DeclSpec &DS) {
3803 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3804 CodeCompleter->getCodeCompletionTUInfo(),
3805 CodeCompletionContext::CCC_TypeQualifiers);
3806 Results.EnterNewScope();
3807 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_const))
3808 Results.AddResult("const");
3809 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_volatile))
3810 Results.AddResult("volatile");
3811 if (getLangOpts().C99 &&
3812 !(DS.getTypeQualifiers() & DeclSpec::TQ_restrict))
3813 Results.AddResult("restrict");
3814 if (getLangOpts().C11 &&
3815 !(DS.getTypeQualifiers() & DeclSpec::TQ_atomic))
3816 Results.AddResult("_Atomic");
3817 Results.ExitScope();
3818 HandleCodeCompleteResults(this, CodeCompleter,
3819 Results.getCompletionContext(),
3820 Results.data(), Results.size());
3823 void Sema::CodeCompleteCase(Scope *S) {
3824 if (getCurFunction()->SwitchStack.empty() || !CodeCompleter)
3827 SwitchStmt *Switch = getCurFunction()->SwitchStack.back();
3828 QualType type = Switch->getCond()->IgnoreImplicit()->getType();
3829 if (!type->isEnumeralType()) {
3830 CodeCompleteExpressionData Data(type);
3831 Data.IntegralConstantExpression = true;
3832 CodeCompleteExpression(S, Data);
3836 // Code-complete the cases of a switch statement over an enumeration type
3837 // by providing the list of
3838 EnumDecl *Enum = type->castAs<EnumType>()->getDecl();
3839 if (EnumDecl *Def = Enum->getDefinition())
3842 // Determine which enumerators we have already seen in the switch statement.
3843 // FIXME: Ideally, we would also be able to look *past* the code-completion
3844 // token, in case we are code-completing in the middle of the switch and not
3845 // at the end. However, we aren't able to do so at the moment.
3846 llvm::SmallPtrSet<EnumConstantDecl *, 8> EnumeratorsSeen;
3847 NestedNameSpecifier *Qualifier = nullptr;
3848 for (SwitchCase *SC = Switch->getSwitchCaseList(); SC;
3849 SC = SC->getNextSwitchCase()) {
3850 CaseStmt *Case = dyn_cast<CaseStmt>(SC);
3854 Expr *CaseVal = Case->getLHS()->IgnoreParenCasts();
3855 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseVal))
3856 if (EnumConstantDecl *Enumerator
3857 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
3858 // We look into the AST of the case statement to determine which
3859 // enumerator was named. Alternatively, we could compute the value of
3860 // the integral constant expression, then compare it against the
3861 // values of each enumerator. However, value-based approach would not
3862 // work as well with C++ templates where enumerators declared within a
3863 // template are type- and value-dependent.
3864 EnumeratorsSeen.insert(Enumerator);
3866 // If this is a qualified-id, keep track of the nested-name-specifier
3867 // so that we can reproduce it as part of code completion, e.g.,
3869 // switch (TagD.getKind()) {
3870 // case TagDecl::TK_enum:
3874 // At the XXX, our completions are TagDecl::TK_union,
3875 // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
3876 // TK_struct, and TK_class.
3877 Qualifier = DRE->getQualifier();
3881 if (getLangOpts().CPlusPlus && !Qualifier && EnumeratorsSeen.empty()) {
3882 // If there are no prior enumerators in C++, check whether we have to
3883 // qualify the names of the enumerators that we suggest, because they
3884 // may not be visible in this scope.
3885 Qualifier = getRequiredQualification(Context, CurContext, Enum);
3888 // Add any enumerators that have not yet been mentioned.
3889 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3890 CodeCompleter->getCodeCompletionTUInfo(),
3891 CodeCompletionContext::CCC_Expression);
3892 Results.EnterNewScope();
3893 for (auto *E : Enum->enumerators()) {
3894 if (EnumeratorsSeen.count(E))
3897 CodeCompletionResult R(E, CCP_EnumInCase, Qualifier);
3898 Results.AddResult(R, CurContext, nullptr, false);
3900 Results.ExitScope();
3902 //We need to make sure we're setting the right context,
3903 //so only say we include macros if the code completer says we do
3904 enum CodeCompletionContext::Kind kind = CodeCompletionContext::CCC_Other;
3905 if (CodeCompleter->includeMacros()) {
3906 AddMacroResults(PP, Results, false);
3907 kind = CodeCompletionContext::CCC_OtherWithMacros;
3910 HandleCodeCompleteResults(this, CodeCompleter,
3912 Results.data(),Results.size());
3915 static bool anyNullArguments(ArrayRef<Expr *> Args) {
3916 if (Args.size() && !Args.data())
3919 for (unsigned I = 0; I != Args.size(); ++I)
3926 typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate;
3928 static void mergeCandidatesWithResults(Sema &SemaRef,
3929 SmallVectorImpl<ResultCandidate> &Results,
3930 OverloadCandidateSet &CandidateSet,
3931 SourceLocation Loc) {
3932 if (!CandidateSet.empty()) {
3933 // Sort the overload candidate set by placing the best overloads first.
3935 CandidateSet.begin(), CandidateSet.end(),
3936 [&](const OverloadCandidate &X, const OverloadCandidate &Y) {
3937 return isBetterOverloadCandidate(SemaRef, X, Y, Loc);
3940 // Add the remaining viable overload candidates as code-completion results.
3941 for (auto &Candidate : CandidateSet)
3942 if (Candidate.Viable)
3943 Results.push_back(ResultCandidate(Candidate.Function));
3947 /// \brief Get the type of the Nth parameter from a given set of overload
3949 static QualType getParamType(Sema &SemaRef,
3950 ArrayRef<ResultCandidate> Candidates,
3953 // Given the overloads 'Candidates' for a function call matching all arguments
3954 // up to N, return the type of the Nth parameter if it is the same for all
3955 // overload candidates.
3957 for (auto &Candidate : Candidates) {
3958 if (auto FType = Candidate.getFunctionType())
3959 if (auto Proto = dyn_cast<FunctionProtoType>(FType))
3960 if (N < Proto->getNumParams()) {
3961 if (ParamType.isNull())
3962 ParamType = Proto->getParamType(N);
3963 else if (!SemaRef.Context.hasSameUnqualifiedType(
3964 ParamType.getNonReferenceType(),
3965 Proto->getParamType(N).getNonReferenceType()))
3966 // Otherwise return a default-constructed QualType.
3974 static void CodeCompleteOverloadResults(Sema &SemaRef, Scope *S,
3975 MutableArrayRef<ResultCandidate> Candidates,
3976 unsigned CurrentArg,
3977 bool CompleteExpressionWithCurrentArg = true) {
3979 if (CompleteExpressionWithCurrentArg)
3980 ParamType = getParamType(SemaRef, Candidates, CurrentArg);
3982 if (ParamType.isNull())
3983 SemaRef.CodeCompleteOrdinaryName(S, Sema::PCC_Expression);
3985 SemaRef.CodeCompleteExpression(S, ParamType);
3987 if (!Candidates.empty())
3988 SemaRef.CodeCompleter->ProcessOverloadCandidates(SemaRef, CurrentArg,
3993 void Sema::CodeCompleteCall(Scope *S, Expr *Fn, ArrayRef<Expr *> Args) {
3997 // When we're code-completing for a call, we fall back to ordinary
3998 // name code-completion whenever we can't produce specific
3999 // results. We may want to revisit this strategy in the future,
4000 // e.g., by merging the two kinds of results.
4002 // FIXME: Provide support for variadic template functions.
4004 // Ignore type-dependent call expressions entirely.
4005 if (!Fn || Fn->isTypeDependent() || anyNullArguments(Args) ||
4006 Expr::hasAnyTypeDependentArguments(Args)) {
4007 CodeCompleteOrdinaryName(S, PCC_Expression);
4011 // Build an overload candidate set based on the functions we find.
4012 SourceLocation Loc = Fn->getExprLoc();
4013 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
4015 SmallVector<ResultCandidate, 8> Results;
4017 Expr *NakedFn = Fn->IgnoreParenCasts();
4018 if (auto ULE = dyn_cast<UnresolvedLookupExpr>(NakedFn))
4019 AddOverloadedCallCandidates(ULE, Args, CandidateSet,
4020 /*PartialOverloading=*/true);
4021 else if (auto UME = dyn_cast<UnresolvedMemberExpr>(NakedFn)) {
4022 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
4023 if (UME->hasExplicitTemplateArgs()) {
4024 UME->copyTemplateArgumentsInto(TemplateArgsBuffer);
4025 TemplateArgs = &TemplateArgsBuffer;
4027 SmallVector<Expr *, 12> ArgExprs(1, UME->getBase());
4028 ArgExprs.append(Args.begin(), Args.end());
4029 UnresolvedSet<8> Decls;
4030 Decls.append(UME->decls_begin(), UME->decls_end());
4031 AddFunctionCandidates(Decls, ArgExprs, CandidateSet, TemplateArgs,
4032 /*SuppressUsedConversions=*/false,
4033 /*PartialOverloading=*/true);
4035 FunctionDecl *FD = nullptr;
4036 if (auto MCE = dyn_cast<MemberExpr>(NakedFn))
4037 FD = dyn_cast<FunctionDecl>(MCE->getMemberDecl());
4038 else if (auto DRE = dyn_cast<DeclRefExpr>(NakedFn))
4039 FD = dyn_cast<FunctionDecl>(DRE->getDecl());
4040 if (FD) { // We check whether it's a resolved function declaration.
4041 if (!getLangOpts().CPlusPlus ||
4042 !FD->getType()->getAs<FunctionProtoType>())
4043 Results.push_back(ResultCandidate(FD));
4045 AddOverloadCandidate(FD, DeclAccessPair::make(FD, FD->getAccess()),
4047 /*SuppressUsedConversions=*/false,
4048 /*PartialOverloading=*/true);
4050 } else if (auto DC = NakedFn->getType()->getAsCXXRecordDecl()) {
4051 // If expression's type is CXXRecordDecl, it may overload the function
4052 // call operator, so we check if it does and add them as candidates.
4053 // A complete type is needed to lookup for member function call operators.
4054 if (!RequireCompleteType(Loc, NakedFn->getType(), 0)) {
4055 DeclarationName OpName = Context.DeclarationNames
4056 .getCXXOperatorName(OO_Call);
4057 LookupResult R(*this, OpName, Loc, LookupOrdinaryName);
4058 LookupQualifiedName(R, DC);
4059 R.suppressDiagnostics();
4060 SmallVector<Expr *, 12> ArgExprs(1, NakedFn);
4061 ArgExprs.append(Args.begin(), Args.end());
4062 AddFunctionCandidates(R.asUnresolvedSet(), ArgExprs, CandidateSet,
4063 /*ExplicitArgs=*/nullptr,
4064 /*SuppressUsedConversions=*/false,
4065 /*PartialOverloading=*/true);
4068 // Lastly we check whether expression's type is function pointer or
4070 QualType T = NakedFn->getType();
4071 if (!T->getPointeeType().isNull())
4072 T = T->getPointeeType();
4074 if (auto FP = T->getAs<FunctionProtoType>()) {
4075 if (!TooManyArguments(FP->getNumParams(), Args.size(),
4076 /*PartialOverloading=*/true) ||
4078 Results.push_back(ResultCandidate(FP));
4079 } else if (auto FT = T->getAs<FunctionType>())
4080 // No prototype and declaration, it may be a K & R style function.
4081 Results.push_back(ResultCandidate(FT));
4085 mergeCandidatesWithResults(*this, Results, CandidateSet, Loc);
4086 CodeCompleteOverloadResults(*this, S, Results, Args.size(),
4087 !CandidateSet.empty());
4090 void Sema::CodeCompleteConstructor(Scope *S, QualType Type, SourceLocation Loc,
4091 ArrayRef<Expr *> Args) {
4095 // A complete type is needed to lookup for constructors.
4096 if (RequireCompleteType(Loc, Type, 0))
4099 CXXRecordDecl *RD = Type->getAsCXXRecordDecl();
4101 CodeCompleteExpression(S, Type);
4105 // FIXME: Provide support for member initializers.
4106 // FIXME: Provide support for variadic template constructors.
4108 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
4110 for (auto C : LookupConstructors(RD)) {
4111 if (auto FD = dyn_cast<FunctionDecl>(C)) {
4112 AddOverloadCandidate(FD, DeclAccessPair::make(FD, C->getAccess()),
4114 /*SuppressUsedConversions=*/false,
4115 /*PartialOverloading=*/true);
4116 } else if (auto FTD = dyn_cast<FunctionTemplateDecl>(C)) {
4117 AddTemplateOverloadCandidate(FTD,
4118 DeclAccessPair::make(FTD, C->getAccess()),
4119 /*ExplicitTemplateArgs=*/nullptr,
4121 /*SuppressUsedConversions=*/false,
4122 /*PartialOverloading=*/true);
4126 SmallVector<ResultCandidate, 8> Results;
4127 mergeCandidatesWithResults(*this, Results, CandidateSet, Loc);
4128 CodeCompleteOverloadResults(*this, S, Results, Args.size());
4131 void Sema::CodeCompleteInitializer(Scope *S, Decl *D) {
4132 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
4134 CodeCompleteOrdinaryName(S, PCC_Expression);
4138 CodeCompleteExpression(S, VD->getType());
4141 void Sema::CodeCompleteReturn(Scope *S) {
4142 QualType ResultType;
4143 if (isa<BlockDecl>(CurContext)) {
4144 if (BlockScopeInfo *BSI = getCurBlock())
4145 ResultType = BSI->ReturnType;
4146 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(CurContext))
4147 ResultType = Function->getReturnType();
4148 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(CurContext))
4149 ResultType = Method->getReturnType();
4151 if (ResultType.isNull())
4152 CodeCompleteOrdinaryName(S, PCC_Expression);
4154 CodeCompleteExpression(S, ResultType);
4157 void Sema::CodeCompleteAfterIf(Scope *S) {
4158 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4159 CodeCompleter->getCodeCompletionTUInfo(),
4160 mapCodeCompletionContext(*this, PCC_Statement));
4161 Results.setFilter(&ResultBuilder::IsOrdinaryName);
4162 Results.EnterNewScope();
4164 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4165 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4166 CodeCompleter->includeGlobals());
4168 AddOrdinaryNameResults(PCC_Statement, S, *this, Results);
4171 CodeCompletionBuilder Builder(Results.getAllocator(),
4172 Results.getCodeCompletionTUInfo());
4173 Builder.AddTypedTextChunk("else");
4174 if (Results.includeCodePatterns()) {
4175 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4176 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4177 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
4178 Builder.AddPlaceholderChunk("statements");
4179 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
4180 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4182 Results.AddResult(Builder.TakeString());
4185 Builder.AddTypedTextChunk("else");
4186 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4187 Builder.AddTextChunk("if");
4188 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4189 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4190 if (getLangOpts().CPlusPlus)
4191 Builder.AddPlaceholderChunk("condition");
4193 Builder.AddPlaceholderChunk("expression");
4194 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4195 if (Results.includeCodePatterns()) {
4196 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4197 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4198 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
4199 Builder.AddPlaceholderChunk("statements");
4200 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
4201 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4203 Results.AddResult(Builder.TakeString());
4205 Results.ExitScope();
4207 if (S->getFnParent())
4208 AddPrettyFunctionResults(PP.getLangOpts(), Results);
4210 if (CodeCompleter->includeMacros())
4211 AddMacroResults(PP, Results, false);
4213 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4214 Results.data(),Results.size());
4217 void Sema::CodeCompleteAssignmentRHS(Scope *S, Expr *LHS) {
4219 CodeCompleteExpression(S, static_cast<Expr *>(LHS)->getType());
4221 CodeCompleteOrdinaryName(S, PCC_Expression);
4224 void Sema::CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
4225 bool EnteringContext) {
4226 if (!SS.getScopeRep() || !CodeCompleter)
4229 DeclContext *Ctx = computeDeclContext(SS, EnteringContext);
4233 // Try to instantiate any non-dependent declaration contexts before
4235 if (!isDependentScopeSpecifier(SS) && RequireCompleteDeclContext(SS, Ctx))
4238 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4239 CodeCompleter->getCodeCompletionTUInfo(),
4240 CodeCompletionContext::CCC_Name);
4241 Results.EnterNewScope();
4243 // The "template" keyword can follow "::" in the grammar, but only
4244 // put it into the grammar if the nested-name-specifier is dependent.
4245 NestedNameSpecifier *NNS = SS.getScopeRep();
4246 if (!Results.empty() && NNS->isDependent())
4247 Results.AddResult("template");
4249 // Add calls to overridden virtual functions, if there are any.
4251 // FIXME: This isn't wonderful, because we don't know whether we're actually
4252 // in a context that permits expressions. This is a general issue with
4253 // qualified-id completions.
4254 if (!EnteringContext)
4255 MaybeAddOverrideCalls(*this, Ctx, Results);
4256 Results.ExitScope();
4258 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4259 LookupVisibleDecls(Ctx, LookupOrdinaryName, Consumer);
4261 HandleCodeCompleteResults(this, CodeCompleter,
4262 Results.getCompletionContext(),
4263 Results.data(),Results.size());
4266 void Sema::CodeCompleteUsing(Scope *S) {
4270 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4271 CodeCompleter->getCodeCompletionTUInfo(),
4272 CodeCompletionContext::CCC_PotentiallyQualifiedName,
4273 &ResultBuilder::IsNestedNameSpecifier);
4274 Results.EnterNewScope();
4276 // If we aren't in class scope, we could see the "namespace" keyword.
4277 if (!S->isClassScope())
4278 Results.AddResult(CodeCompletionResult("namespace"));
4280 // After "using", we can see anything that would start a
4281 // nested-name-specifier.
4282 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4283 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4284 CodeCompleter->includeGlobals());
4285 Results.ExitScope();
4287 HandleCodeCompleteResults(this, CodeCompleter,
4288 CodeCompletionContext::CCC_PotentiallyQualifiedName,
4289 Results.data(),Results.size());
4292 void Sema::CodeCompleteUsingDirective(Scope *S) {
4296 // After "using namespace", we expect to see a namespace name or namespace
4298 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4299 CodeCompleter->getCodeCompletionTUInfo(),
4300 CodeCompletionContext::CCC_Namespace,
4301 &ResultBuilder::IsNamespaceOrAlias);
4302 Results.EnterNewScope();
4303 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4304 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4305 CodeCompleter->includeGlobals());
4306 Results.ExitScope();
4307 HandleCodeCompleteResults(this, CodeCompleter,
4308 CodeCompletionContext::CCC_Namespace,
4309 Results.data(),Results.size());
4312 void Sema::CodeCompleteNamespaceDecl(Scope *S) {
4316 DeclContext *Ctx = S->getEntity();
4317 if (!S->getParent())
4318 Ctx = Context.getTranslationUnitDecl();
4320 bool SuppressedGlobalResults
4321 = Ctx && !CodeCompleter->includeGlobals() && isa<TranslationUnitDecl>(Ctx);
4323 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4324 CodeCompleter->getCodeCompletionTUInfo(),
4325 SuppressedGlobalResults
4326 ? CodeCompletionContext::CCC_Namespace
4327 : CodeCompletionContext::CCC_Other,
4328 &ResultBuilder::IsNamespace);
4330 if (Ctx && Ctx->isFileContext() && !SuppressedGlobalResults) {
4331 // We only want to see those namespaces that have already been defined
4332 // within this scope, because its likely that the user is creating an
4333 // extended namespace declaration. Keep track of the most recent
4334 // definition of each namespace.
4335 std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest;
4336 for (DeclContext::specific_decl_iterator<NamespaceDecl>
4337 NS(Ctx->decls_begin()), NSEnd(Ctx->decls_end());
4339 OrigToLatest[NS->getOriginalNamespace()] = *NS;
4341 // Add the most recent definition (or extended definition) of each
4342 // namespace to the list of results.
4343 Results.EnterNewScope();
4344 for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator
4345 NS = OrigToLatest.begin(),
4346 NSEnd = OrigToLatest.end();
4348 Results.AddResult(CodeCompletionResult(
4349 NS->second, Results.getBasePriority(NS->second),
4351 CurContext, nullptr, false);
4352 Results.ExitScope();
4355 HandleCodeCompleteResults(this, CodeCompleter,
4356 Results.getCompletionContext(),
4357 Results.data(),Results.size());
4360 void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) {
4364 // After "namespace", we expect to see a namespace or alias.
4365 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4366 CodeCompleter->getCodeCompletionTUInfo(),
4367 CodeCompletionContext::CCC_Namespace,
4368 &ResultBuilder::IsNamespaceOrAlias);
4369 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4370 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4371 CodeCompleter->includeGlobals());
4372 HandleCodeCompleteResults(this, CodeCompleter,
4373 Results.getCompletionContext(),
4374 Results.data(),Results.size());
4377 void Sema::CodeCompleteOperatorName(Scope *S) {
4381 typedef CodeCompletionResult Result;
4382 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4383 CodeCompleter->getCodeCompletionTUInfo(),
4384 CodeCompletionContext::CCC_Type,
4385 &ResultBuilder::IsType);
4386 Results.EnterNewScope();
4388 // Add the names of overloadable operators.
4389 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
4390 if (std::strcmp(Spelling, "?")) \
4391 Results.AddResult(Result(Spelling));
4392 #include "clang/Basic/OperatorKinds.def"
4394 // Add any type names visible from the current scope
4395 Results.allowNestedNameSpecifiers();
4396 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4397 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4398 CodeCompleter->includeGlobals());
4400 // Add any type specifiers
4401 AddTypeSpecifierResults(getLangOpts(), Results);
4402 Results.ExitScope();
4404 HandleCodeCompleteResults(this, CodeCompleter,
4405 CodeCompletionContext::CCC_Type,
4406 Results.data(),Results.size());
4409 void Sema::CodeCompleteConstructorInitializer(
4411 ArrayRef <CXXCtorInitializer *> Initializers) {
4415 AdjustDeclIfTemplate(ConstructorD);
4417 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ConstructorD);
4421 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4422 CodeCompleter->getCodeCompletionTUInfo(),
4423 CodeCompletionContext::CCC_PotentiallyQualifiedName);
4424 Results.EnterNewScope();
4426 // Fill in any already-initialized fields or base classes.
4427 llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields;
4428 llvm::SmallPtrSet<CanQualType, 4> InitializedBases;
4429 for (unsigned I = 0, E = Initializers.size(); I != E; ++I) {
4430 if (Initializers[I]->isBaseInitializer())
4431 InitializedBases.insert(
4432 Context.getCanonicalType(QualType(Initializers[I]->getBaseClass(), 0)));
4434 InitializedFields.insert(cast<FieldDecl>(
4435 Initializers[I]->getAnyMember()));
4438 // Add completions for base classes.
4439 CodeCompletionBuilder Builder(Results.getAllocator(),
4440 Results.getCodeCompletionTUInfo());
4441 PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
4442 bool SawLastInitializer = Initializers.empty();
4443 CXXRecordDecl *ClassDecl = Constructor->getParent();
4444 for (const auto &Base : ClassDecl->bases()) {
4445 if (!InitializedBases.insert(Context.getCanonicalType(Base.getType()))
4448 = !Initializers.empty() &&
4449 Initializers.back()->isBaseInitializer() &&
4450 Context.hasSameUnqualifiedType(Base.getType(),
4451 QualType(Initializers.back()->getBaseClass(), 0));
4455 Builder.AddTypedTextChunk(
4456 Results.getAllocator().CopyString(
4457 Base.getType().getAsString(Policy)));
4458 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4459 Builder.AddPlaceholderChunk("args");
4460 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4461 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
4462 SawLastInitializer? CCP_NextInitializer
4463 : CCP_MemberDeclaration));
4464 SawLastInitializer = false;
4467 // Add completions for virtual base classes.
4468 for (const auto &Base : ClassDecl->vbases()) {
4469 if (!InitializedBases.insert(Context.getCanonicalType(Base.getType()))
4472 = !Initializers.empty() &&
4473 Initializers.back()->isBaseInitializer() &&
4474 Context.hasSameUnqualifiedType(Base.getType(),
4475 QualType(Initializers.back()->getBaseClass(), 0));
4479 Builder.AddTypedTextChunk(
4480 Builder.getAllocator().CopyString(
4481 Base.getType().getAsString(Policy)));
4482 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4483 Builder.AddPlaceholderChunk("args");
4484 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4485 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
4486 SawLastInitializer? CCP_NextInitializer
4487 : CCP_MemberDeclaration));
4488 SawLastInitializer = false;
4491 // Add completions for members.
4492 for (auto *Field : ClassDecl->fields()) {
4493 if (!InitializedFields.insert(cast<FieldDecl>(Field->getCanonicalDecl()))
4496 = !Initializers.empty() &&
4497 Initializers.back()->isAnyMemberInitializer() &&
4498 Initializers.back()->getAnyMember() == Field;
4502 if (!Field->getDeclName())
4505 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
4506 Field->getIdentifier()->getName()));
4507 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4508 Builder.AddPlaceholderChunk("args");
4509 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4510 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
4511 SawLastInitializer? CCP_NextInitializer
4512 : CCP_MemberDeclaration,
4514 CXAvailability_Available,
4516 SawLastInitializer = false;
4518 Results.ExitScope();
4520 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4521 Results.data(), Results.size());
4524 /// \brief Determine whether this scope denotes a namespace.
4525 static bool isNamespaceScope(Scope *S) {
4526 DeclContext *DC = S->getEntity();
4530 return DC->isFileContext();
4533 void Sema::CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro,
4534 bool AfterAmpersand) {
4535 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4536 CodeCompleter->getCodeCompletionTUInfo(),
4537 CodeCompletionContext::CCC_Other);
4538 Results.EnterNewScope();
4540 // Note what has already been captured.
4541 llvm::SmallPtrSet<IdentifierInfo *, 4> Known;
4542 bool IncludedThis = false;
4543 for (const auto &C : Intro.Captures) {
4544 if (C.Kind == LCK_This) {
4545 IncludedThis = true;
4552 // Look for other capturable variables.
4553 for (; S && !isNamespaceScope(S); S = S->getParent()) {
4554 for (const auto *D : S->decls()) {
4555 const auto *Var = dyn_cast<VarDecl>(D);
4557 !Var->hasLocalStorage() ||
4558 Var->hasAttr<BlocksAttr>())
4561 if (Known.insert(Var->getIdentifier()).second)
4562 Results.AddResult(CodeCompletionResult(Var, CCP_LocalDeclaration),
4563 CurContext, nullptr, false);
4567 // Add 'this', if it would be valid.
4568 if (!IncludedThis && !AfterAmpersand && Intro.Default != LCD_ByCopy)
4569 addThisCompletion(*this, Results);
4571 Results.ExitScope();
4573 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4574 Results.data(), Results.size());
4577 /// Macro that optionally prepends an "@" to the string literal passed in via
4578 /// Keyword, depending on whether NeedAt is true or false.
4579 #define OBJC_AT_KEYWORD_NAME(NeedAt,Keyword) ((NeedAt)? "@" Keyword : Keyword)
4581 static void AddObjCImplementationResults(const LangOptions &LangOpts,
4582 ResultBuilder &Results,
4584 typedef CodeCompletionResult Result;
4585 // Since we have an implementation, we can end it.
4586 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"end")));
4588 CodeCompletionBuilder Builder(Results.getAllocator(),
4589 Results.getCodeCompletionTUInfo());
4590 if (LangOpts.ObjC2) {
4592 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"dynamic"));
4593 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4594 Builder.AddPlaceholderChunk("property");
4595 Results.AddResult(Result(Builder.TakeString()));
4598 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"synthesize"));
4599 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4600 Builder.AddPlaceholderChunk("property");
4601 Results.AddResult(Result(Builder.TakeString()));
4605 static void AddObjCInterfaceResults(const LangOptions &LangOpts,
4606 ResultBuilder &Results,
4608 typedef CodeCompletionResult Result;
4610 // Since we have an interface or protocol, we can end it.
4611 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"end")));
4613 if (LangOpts.ObjC2) {
4615 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"property")));
4618 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"required")));
4621 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"optional")));
4625 static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt) {
4626 typedef CodeCompletionResult Result;
4627 CodeCompletionBuilder Builder(Results.getAllocator(),
4628 Results.getCodeCompletionTUInfo());
4631 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"class"));
4632 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4633 Builder.AddPlaceholderChunk("name");
4634 Results.AddResult(Result(Builder.TakeString()));
4636 if (Results.includeCodePatterns()) {
4638 // FIXME: Could introduce the whole pattern, including superclasses and
4640 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"interface"));
4641 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4642 Builder.AddPlaceholderChunk("class");
4643 Results.AddResult(Result(Builder.TakeString()));
4646 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"protocol"));
4647 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4648 Builder.AddPlaceholderChunk("protocol");
4649 Results.AddResult(Result(Builder.TakeString()));
4651 // @implementation name
4652 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"implementation"));
4653 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4654 Builder.AddPlaceholderChunk("class");
4655 Results.AddResult(Result(Builder.TakeString()));
4658 // @compatibility_alias name
4659 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"compatibility_alias"));
4660 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4661 Builder.AddPlaceholderChunk("alias");
4662 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4663 Builder.AddPlaceholderChunk("class");
4664 Results.AddResult(Result(Builder.TakeString()));
4666 if (Results.getSema().getLangOpts().Modules) {
4668 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "import"));
4669 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4670 Builder.AddPlaceholderChunk("module");
4671 Results.AddResult(Result(Builder.TakeString()));
4675 void Sema::CodeCompleteObjCAtDirective(Scope *S) {
4676 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4677 CodeCompleter->getCodeCompletionTUInfo(),
4678 CodeCompletionContext::CCC_Other);
4679 Results.EnterNewScope();
4680 if (isa<ObjCImplDecl>(CurContext))
4681 AddObjCImplementationResults(getLangOpts(), Results, false);
4682 else if (CurContext->isObjCContainer())
4683 AddObjCInterfaceResults(getLangOpts(), Results, false);
4685 AddObjCTopLevelResults(Results, false);
4686 Results.ExitScope();
4687 HandleCodeCompleteResults(this, CodeCompleter,
4688 CodeCompletionContext::CCC_Other,
4689 Results.data(),Results.size());
4692 static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt) {
4693 typedef CodeCompletionResult Result;
4694 CodeCompletionBuilder Builder(Results.getAllocator(),
4695 Results.getCodeCompletionTUInfo());
4697 // @encode ( type-name )
4698 const char *EncodeType = "char[]";
4699 if (Results.getSema().getLangOpts().CPlusPlus ||
4700 Results.getSema().getLangOpts().ConstStrings)
4701 EncodeType = "const char[]";
4702 Builder.AddResultTypeChunk(EncodeType);
4703 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"encode"));
4704 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4705 Builder.AddPlaceholderChunk("type-name");
4706 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4707 Results.AddResult(Result(Builder.TakeString()));
4709 // @protocol ( protocol-name )
4710 Builder.AddResultTypeChunk("Protocol *");
4711 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"protocol"));
4712 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4713 Builder.AddPlaceholderChunk("protocol-name");
4714 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4715 Results.AddResult(Result(Builder.TakeString()));
4717 // @selector ( selector )
4718 Builder.AddResultTypeChunk("SEL");
4719 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"selector"));
4720 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4721 Builder.AddPlaceholderChunk("selector");
4722 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4723 Results.AddResult(Result(Builder.TakeString()));
4726 Builder.AddResultTypeChunk("NSString *");
4727 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"\""));
4728 Builder.AddPlaceholderChunk("string");
4729 Builder.AddTextChunk("\"");
4730 Results.AddResult(Result(Builder.TakeString()));
4733 Builder.AddResultTypeChunk("NSArray *");
4734 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"["));
4735 Builder.AddPlaceholderChunk("objects, ...");
4736 Builder.AddChunk(CodeCompletionString::CK_RightBracket);
4737 Results.AddResult(Result(Builder.TakeString()));
4739 // @{key : object, ...}
4740 Builder.AddResultTypeChunk("NSDictionary *");
4741 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"{"));
4742 Builder.AddPlaceholderChunk("key");
4743 Builder.AddChunk(CodeCompletionString::CK_Colon);
4744 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4745 Builder.AddPlaceholderChunk("object, ...");
4746 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4747 Results.AddResult(Result(Builder.TakeString()));
4750 Builder.AddResultTypeChunk("id");
4751 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "("));
4752 Builder.AddPlaceholderChunk("expression");
4753 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4754 Results.AddResult(Result(Builder.TakeString()));
4757 static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt) {
4758 typedef CodeCompletionResult Result;
4759 CodeCompletionBuilder Builder(Results.getAllocator(),
4760 Results.getCodeCompletionTUInfo());
4762 if (Results.includeCodePatterns()) {
4763 // @try { statements } @catch ( declaration ) { statements } @finally
4765 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"try"));
4766 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4767 Builder.AddPlaceholderChunk("statements");
4768 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4769 Builder.AddTextChunk("@catch");
4770 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4771 Builder.AddPlaceholderChunk("parameter");
4772 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4773 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4774 Builder.AddPlaceholderChunk("statements");
4775 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4776 Builder.AddTextChunk("@finally");
4777 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4778 Builder.AddPlaceholderChunk("statements");
4779 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4780 Results.AddResult(Result(Builder.TakeString()));
4784 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"throw"));
4785 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4786 Builder.AddPlaceholderChunk("expression");
4787 Results.AddResult(Result(Builder.TakeString()));
4789 if (Results.includeCodePatterns()) {
4790 // @synchronized ( expression ) { statements }
4791 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"synchronized"));
4792 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4793 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4794 Builder.AddPlaceholderChunk("expression");
4795 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4796 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4797 Builder.AddPlaceholderChunk("statements");
4798 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4799 Results.AddResult(Result(Builder.TakeString()));
4803 static void AddObjCVisibilityResults(const LangOptions &LangOpts,
4804 ResultBuilder &Results,
4806 typedef CodeCompletionResult Result;
4807 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"private")));
4808 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"protected")));
4809 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"public")));
4811 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"package")));
4814 void Sema::CodeCompleteObjCAtVisibility(Scope *S) {
4815 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4816 CodeCompleter->getCodeCompletionTUInfo(),
4817 CodeCompletionContext::CCC_Other);
4818 Results.EnterNewScope();
4819 AddObjCVisibilityResults(getLangOpts(), Results, false);
4820 Results.ExitScope();
4821 HandleCodeCompleteResults(this, CodeCompleter,
4822 CodeCompletionContext::CCC_Other,
4823 Results.data(),Results.size());
4826 void Sema::CodeCompleteObjCAtStatement(Scope *S) {
4827 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4828 CodeCompleter->getCodeCompletionTUInfo(),
4829 CodeCompletionContext::CCC_Other);
4830 Results.EnterNewScope();
4831 AddObjCStatementResults(Results, false);
4832 AddObjCExpressionResults(Results, false);
4833 Results.ExitScope();
4834 HandleCodeCompleteResults(this, CodeCompleter,
4835 CodeCompletionContext::CCC_Other,
4836 Results.data(),Results.size());
4839 void Sema::CodeCompleteObjCAtExpression(Scope *S) {
4840 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4841 CodeCompleter->getCodeCompletionTUInfo(),
4842 CodeCompletionContext::CCC_Other);
4843 Results.EnterNewScope();
4844 AddObjCExpressionResults(Results, false);
4845 Results.ExitScope();
4846 HandleCodeCompleteResults(this, CodeCompleter,
4847 CodeCompletionContext::CCC_Other,
4848 Results.data(),Results.size());
4851 /// \brief Determine whether the addition of the given flag to an Objective-C
4852 /// property's attributes will cause a conflict.
4853 static bool ObjCPropertyFlagConflicts(unsigned Attributes, unsigned NewFlag) {
4854 // Check if we've already added this flag.
4855 if (Attributes & NewFlag)
4858 Attributes |= NewFlag;
4860 // Check for collisions with "readonly".
4861 if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
4862 (Attributes & ObjCDeclSpec::DQ_PR_readwrite))
4865 // Check for more than one of { assign, copy, retain, strong, weak }.
4866 unsigned AssignCopyRetMask = Attributes & (ObjCDeclSpec::DQ_PR_assign |
4867 ObjCDeclSpec::DQ_PR_unsafe_unretained |
4868 ObjCDeclSpec::DQ_PR_copy |
4869 ObjCDeclSpec::DQ_PR_retain |
4870 ObjCDeclSpec::DQ_PR_strong |
4871 ObjCDeclSpec::DQ_PR_weak);
4872 if (AssignCopyRetMask &&
4873 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_assign &&
4874 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_unsafe_unretained &&
4875 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_copy &&
4876 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_retain &&
4877 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_strong &&
4878 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_weak)
4884 void Sema::CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS) {
4888 unsigned Attributes = ODS.getPropertyAttributes();
4890 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4891 CodeCompleter->getCodeCompletionTUInfo(),
4892 CodeCompletionContext::CCC_Other);
4893 Results.EnterNewScope();
4894 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readonly))
4895 Results.AddResult(CodeCompletionResult("readonly"));
4896 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_assign))
4897 Results.AddResult(CodeCompletionResult("assign"));
4898 if (!ObjCPropertyFlagConflicts(Attributes,
4899 ObjCDeclSpec::DQ_PR_unsafe_unretained))
4900 Results.AddResult(CodeCompletionResult("unsafe_unretained"));
4901 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readwrite))
4902 Results.AddResult(CodeCompletionResult("readwrite"));
4903 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_retain))
4904 Results.AddResult(CodeCompletionResult("retain"));
4905 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_strong))
4906 Results.AddResult(CodeCompletionResult("strong"));
4907 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_copy))
4908 Results.AddResult(CodeCompletionResult("copy"));
4909 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nonatomic))
4910 Results.AddResult(CodeCompletionResult("nonatomic"));
4911 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_atomic))
4912 Results.AddResult(CodeCompletionResult("atomic"));
4914 // Only suggest "weak" if we're compiling for ARC-with-weak-references or GC.
4915 if (getLangOpts().ObjCARCWeak || getLangOpts().getGC() != LangOptions::NonGC)
4916 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_weak))
4917 Results.AddResult(CodeCompletionResult("weak"));
4919 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_setter)) {
4920 CodeCompletionBuilder Setter(Results.getAllocator(),
4921 Results.getCodeCompletionTUInfo());
4922 Setter.AddTypedTextChunk("setter");
4923 Setter.AddTextChunk("=");
4924 Setter.AddPlaceholderChunk("method");
4925 Results.AddResult(CodeCompletionResult(Setter.TakeString()));
4927 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_getter)) {
4928 CodeCompletionBuilder Getter(Results.getAllocator(),
4929 Results.getCodeCompletionTUInfo());
4930 Getter.AddTypedTextChunk("getter");
4931 Getter.AddTextChunk("=");
4932 Getter.AddPlaceholderChunk("method");
4933 Results.AddResult(CodeCompletionResult(Getter.TakeString()));
4935 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nullability)) {
4936 Results.AddResult(CodeCompletionResult("nonnull"));
4937 Results.AddResult(CodeCompletionResult("nullable"));
4938 Results.AddResult(CodeCompletionResult("null_unspecified"));
4939 Results.AddResult(CodeCompletionResult("null_resettable"));
4941 Results.ExitScope();
4942 HandleCodeCompleteResults(this, CodeCompleter,
4943 CodeCompletionContext::CCC_Other,
4944 Results.data(),Results.size());
4947 /// \brief Describes the kind of Objective-C method that we want to find
4948 /// via code completion.
4949 enum ObjCMethodKind {
4950 MK_Any, ///< Any kind of method, provided it means other specified criteria.
4951 MK_ZeroArgSelector, ///< Zero-argument (unary) selector.
4952 MK_OneArgSelector ///< One-argument selector.
4955 static bool isAcceptableObjCSelector(Selector Sel,
4956 ObjCMethodKind WantKind,
4957 ArrayRef<IdentifierInfo *> SelIdents,
4958 bool AllowSameLength = true) {
4959 unsigned NumSelIdents = SelIdents.size();
4960 if (NumSelIdents > Sel.getNumArgs())
4965 case MK_ZeroArgSelector: return Sel.isUnarySelector();
4966 case MK_OneArgSelector: return Sel.getNumArgs() == 1;
4969 if (!AllowSameLength && NumSelIdents && NumSelIdents == Sel.getNumArgs())
4972 for (unsigned I = 0; I != NumSelIdents; ++I)
4973 if (SelIdents[I] != Sel.getIdentifierInfoForSlot(I))
4979 static bool isAcceptableObjCMethod(ObjCMethodDecl *Method,
4980 ObjCMethodKind WantKind,
4981 ArrayRef<IdentifierInfo *> SelIdents,
4982 bool AllowSameLength = true) {
4983 return isAcceptableObjCSelector(Method->getSelector(), WantKind, SelIdents,
4988 /// \brief A set of selectors, which is used to avoid introducing multiple
4989 /// completions with the same selector into the result set.
4990 typedef llvm::SmallPtrSet<Selector, 16> VisitedSelectorSet;
4993 /// \brief Add all of the Objective-C methods in the given Objective-C
4994 /// container to the set of results.
4996 /// The container will be a class, protocol, category, or implementation of
4997 /// any of the above. This mether will recurse to include methods from
4998 /// the superclasses of classes along with their categories, protocols, and
4999 /// implementations.
5001 /// \param Container the container in which we'll look to find methods.
5003 /// \param WantInstanceMethods Whether to add instance methods (only); if
5004 /// false, this routine will add factory methods (only).
5006 /// \param CurContext the context in which we're performing the lookup that
5009 /// \param AllowSameLength Whether we allow a method to be added to the list
5010 /// when it has the same number of parameters as we have selector identifiers.
5012 /// \param Results the structure into which we'll add results.
5013 static void AddObjCMethods(ObjCContainerDecl *Container,
5014 bool WantInstanceMethods,
5015 ObjCMethodKind WantKind,
5016 ArrayRef<IdentifierInfo *> SelIdents,
5017 DeclContext *CurContext,
5018 VisitedSelectorSet &Selectors,
5019 bool AllowSameLength,
5020 ResultBuilder &Results,
5021 bool InOriginalClass = true) {
5022 typedef CodeCompletionResult Result;
5023 Container = getContainerDef(Container);
5024 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container);
5025 bool isRootClass = IFace && !IFace->getSuperClass();
5026 for (auto *M : Container->methods()) {
5027 // The instance methods on the root class can be messaged via the
5029 if (M->isInstanceMethod() == WantInstanceMethods ||
5030 (isRootClass && !WantInstanceMethods)) {
5031 // Check whether the selector identifiers we've been given are a
5032 // subset of the identifiers for this particular method.
5033 if (!isAcceptableObjCMethod(M, WantKind, SelIdents, AllowSameLength))
5036 if (!Selectors.insert(M->getSelector()).second)
5039 Result R = Result(M, Results.getBasePriority(M), nullptr);
5040 R.StartParameter = SelIdents.size();
5041 R.AllParametersAreInformative = (WantKind != MK_Any);
5042 if (!InOriginalClass)
5043 R.Priority += CCD_InBaseClass;
5044 Results.MaybeAddResult(R, CurContext);
5048 // Visit the protocols of protocols.
5049 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
5050 if (Protocol->hasDefinition()) {
5051 const ObjCList<ObjCProtocolDecl> &Protocols
5052 = Protocol->getReferencedProtocols();
5053 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
5054 E = Protocols.end();
5056 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents,
5057 CurContext, Selectors, AllowSameLength, Results, false);
5061 if (!IFace || !IFace->hasDefinition())
5064 // Add methods in protocols.
5065 for (auto *I : IFace->protocols())
5066 AddObjCMethods(I, WantInstanceMethods, WantKind, SelIdents,
5067 CurContext, Selectors, AllowSameLength, Results, false);
5069 // Add methods in categories.
5070 for (auto *CatDecl : IFace->known_categories()) {
5071 AddObjCMethods(CatDecl, WantInstanceMethods, WantKind, SelIdents,
5072 CurContext, Selectors, AllowSameLength,
5073 Results, InOriginalClass);
5075 // Add a categories protocol methods.
5076 const ObjCList<ObjCProtocolDecl> &Protocols
5077 = CatDecl->getReferencedProtocols();
5078 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
5079 E = Protocols.end();
5081 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents,
5082 CurContext, Selectors, AllowSameLength,
5085 // Add methods in category implementations.
5086 if (ObjCCategoryImplDecl *Impl = CatDecl->getImplementation())
5087 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
5088 CurContext, Selectors, AllowSameLength,
5089 Results, InOriginalClass);
5092 // Add methods in superclass.
5093 if (IFace->getSuperClass())
5094 AddObjCMethods(IFace->getSuperClass(), WantInstanceMethods, WantKind,
5095 SelIdents, CurContext, Selectors,
5096 AllowSameLength, Results, false);
5098 // Add methods in our implementation, if any.
5099 if (ObjCImplementationDecl *Impl = IFace->getImplementation())
5100 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
5101 CurContext, Selectors, AllowSameLength,
5102 Results, InOriginalClass);
5106 void Sema::CodeCompleteObjCPropertyGetter(Scope *S) {
5107 // Try to find the interface where getters might live.
5108 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext);
5110 if (ObjCCategoryDecl *Category
5111 = dyn_cast_or_null<ObjCCategoryDecl>(CurContext))
5112 Class = Category->getClassInterface();
5118 // Find all of the potential getters.
5119 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5120 CodeCompleter->getCodeCompletionTUInfo(),
5121 CodeCompletionContext::CCC_Other);
5122 Results.EnterNewScope();
5124 VisitedSelectorSet Selectors;
5125 AddObjCMethods(Class, true, MK_ZeroArgSelector, None, CurContext, Selectors,
5126 /*AllowSameLength=*/true, Results);
5127 Results.ExitScope();
5128 HandleCodeCompleteResults(this, CodeCompleter,
5129 CodeCompletionContext::CCC_Other,
5130 Results.data(),Results.size());
5133 void Sema::CodeCompleteObjCPropertySetter(Scope *S) {
5134 // Try to find the interface where setters might live.
5135 ObjCInterfaceDecl *Class
5136 = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext);
5138 if (ObjCCategoryDecl *Category
5139 = dyn_cast_or_null<ObjCCategoryDecl>(CurContext))
5140 Class = Category->getClassInterface();
5146 // Find all of the potential getters.
5147 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5148 CodeCompleter->getCodeCompletionTUInfo(),
5149 CodeCompletionContext::CCC_Other);
5150 Results.EnterNewScope();
5152 VisitedSelectorSet Selectors;
5153 AddObjCMethods(Class, true, MK_OneArgSelector, None, CurContext,
5154 Selectors, /*AllowSameLength=*/true, Results);
5156 Results.ExitScope();
5157 HandleCodeCompleteResults(this, CodeCompleter,
5158 CodeCompletionContext::CCC_Other,
5159 Results.data(),Results.size());
5162 void Sema::CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
5164 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5165 CodeCompleter->getCodeCompletionTUInfo(),
5166 CodeCompletionContext::CCC_Type);
5167 Results.EnterNewScope();
5169 // Add context-sensitive, Objective-C parameter-passing keywords.
5170 bool AddedInOut = false;
5171 if ((DS.getObjCDeclQualifier() &
5172 (ObjCDeclSpec::DQ_In | ObjCDeclSpec::DQ_Inout)) == 0) {
5173 Results.AddResult("in");
5174 Results.AddResult("inout");
5177 if ((DS.getObjCDeclQualifier() &
5178 (ObjCDeclSpec::DQ_Out | ObjCDeclSpec::DQ_Inout)) == 0) {
5179 Results.AddResult("out");
5181 Results.AddResult("inout");
5183 if ((DS.getObjCDeclQualifier() &
5184 (ObjCDeclSpec::DQ_Bycopy | ObjCDeclSpec::DQ_Byref |
5185 ObjCDeclSpec::DQ_Oneway)) == 0) {
5186 Results.AddResult("bycopy");
5187 Results.AddResult("byref");
5188 Results.AddResult("oneway");
5190 if ((DS.getObjCDeclQualifier() & ObjCDeclSpec::DQ_CSNullability) == 0) {
5191 Results.AddResult("nonnull");
5192 Results.AddResult("nullable");
5193 Results.AddResult("null_unspecified");
5196 // If we're completing the return type of an Objective-C method and the
5197 // identifier IBAction refers to a macro, provide a completion item for
5199 // IBAction)<#selector#>:(id)sender
5200 if (DS.getObjCDeclQualifier() == 0 && !IsParameter &&
5201 PP.isMacroDefined("IBAction")) {
5202 CodeCompletionBuilder Builder(Results.getAllocator(),
5203 Results.getCodeCompletionTUInfo(),
5204 CCP_CodePattern, CXAvailability_Available);
5205 Builder.AddTypedTextChunk("IBAction");
5206 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5207 Builder.AddPlaceholderChunk("selector");
5208 Builder.AddChunk(CodeCompletionString::CK_Colon);
5209 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
5210 Builder.AddTextChunk("id");
5211 Builder.AddChunk(CodeCompletionString::CK_RightParen);
5212 Builder.AddTextChunk("sender");
5213 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
5216 // If we're completing the return type, provide 'instancetype'.
5218 Results.AddResult(CodeCompletionResult("instancetype"));
5221 // Add various builtin type names and specifiers.
5222 AddOrdinaryNameResults(PCC_Type, S, *this, Results);
5223 Results.ExitScope();
5225 // Add the various type names
5226 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
5227 CodeCompletionDeclConsumer Consumer(Results, CurContext);
5228 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
5229 CodeCompleter->includeGlobals());
5231 if (CodeCompleter->includeMacros())
5232 AddMacroResults(PP, Results, false);
5234 HandleCodeCompleteResults(this, CodeCompleter,
5235 CodeCompletionContext::CCC_Type,
5236 Results.data(), Results.size());
5239 /// \brief When we have an expression with type "id", we may assume
5240 /// that it has some more-specific class type based on knowledge of
5241 /// common uses of Objective-C. This routine returns that class type,
5242 /// or NULL if no better result could be determined.
5243 static ObjCInterfaceDecl *GetAssumedMessageSendExprType(Expr *E) {
5244 ObjCMessageExpr *Msg = dyn_cast_or_null<ObjCMessageExpr>(E);
5248 Selector Sel = Msg->getSelector();
5252 IdentifierInfo *Id = Sel.getIdentifierInfoForSlot(0);
5256 ObjCMethodDecl *Method = Msg->getMethodDecl();
5260 // Determine the class that we're sending the message to.
5261 ObjCInterfaceDecl *IFace = nullptr;
5262 switch (Msg->getReceiverKind()) {
5263 case ObjCMessageExpr::Class:
5264 if (const ObjCObjectType *ObjType
5265 = Msg->getClassReceiver()->getAs<ObjCObjectType>())
5266 IFace = ObjType->getInterface();
5269 case ObjCMessageExpr::Instance: {
5270 QualType T = Msg->getInstanceReceiver()->getType();
5271 if (const ObjCObjectPointerType *Ptr = T->getAs<ObjCObjectPointerType>())
5272 IFace = Ptr->getInterfaceDecl();
5276 case ObjCMessageExpr::SuperInstance:
5277 case ObjCMessageExpr::SuperClass:
5284 ObjCInterfaceDecl *Super = IFace->getSuperClass();
5285 if (Method->isInstanceMethod())
5286 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
5287 .Case("retain", IFace)
5288 .Case("strong", IFace)
5289 .Case("autorelease", IFace)
5290 .Case("copy", IFace)
5291 .Case("copyWithZone", IFace)
5292 .Case("mutableCopy", IFace)
5293 .Case("mutableCopyWithZone", IFace)
5294 .Case("awakeFromCoder", IFace)
5295 .Case("replacementObjectFromCoder", IFace)
5296 .Case("class", IFace)
5297 .Case("classForCoder", IFace)
5298 .Case("superclass", Super)
5301 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
5303 .Case("alloc", IFace)
5304 .Case("allocWithZone", IFace)
5305 .Case("class", IFace)
5306 .Case("superclass", Super)
5310 // Add a special completion for a message send to "super", which fills in the
5311 // most likely case of forwarding all of our arguments to the superclass
5314 /// \param S The semantic analysis object.
5316 /// \param NeedSuperKeyword Whether we need to prefix this completion with
5317 /// the "super" keyword. Otherwise, we just need to provide the arguments.
5319 /// \param SelIdents The identifiers in the selector that have already been
5320 /// provided as arguments for a send to "super".
5322 /// \param Results The set of results to augment.
5324 /// \returns the Objective-C method declaration that would be invoked by
5325 /// this "super" completion. If NULL, no completion was added.
5326 static ObjCMethodDecl *AddSuperSendCompletion(
5327 Sema &S, bool NeedSuperKeyword,
5328 ArrayRef<IdentifierInfo *> SelIdents,
5329 ResultBuilder &Results) {
5330 ObjCMethodDecl *CurMethod = S.getCurMethodDecl();
5334 ObjCInterfaceDecl *Class = CurMethod->getClassInterface();
5338 // Try to find a superclass method with the same selector.
5339 ObjCMethodDecl *SuperMethod = nullptr;
5340 while ((Class = Class->getSuperClass()) && !SuperMethod) {
5341 // Check in the class
5342 SuperMethod = Class->getMethod(CurMethod->getSelector(),
5343 CurMethod->isInstanceMethod());
5345 // Check in categories or class extensions.
5347 for (const auto *Cat : Class->known_categories()) {
5348 if ((SuperMethod = Cat->getMethod(CurMethod->getSelector(),
5349 CurMethod->isInstanceMethod())))
5358 // Check whether the superclass method has the same signature.
5359 if (CurMethod->param_size() != SuperMethod->param_size() ||
5360 CurMethod->isVariadic() != SuperMethod->isVariadic())
5363 for (ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin(),
5364 CurPEnd = CurMethod->param_end(),
5365 SuperP = SuperMethod->param_begin();
5366 CurP != CurPEnd; ++CurP, ++SuperP) {
5367 // Make sure the parameter types are compatible.
5368 if (!S.Context.hasSameUnqualifiedType((*CurP)->getType(),
5369 (*SuperP)->getType()))
5372 // Make sure we have a parameter name to forward!
5373 if (!(*CurP)->getIdentifier())
5377 // We have a superclass method. Now, form the send-to-super completion.
5378 CodeCompletionBuilder Builder(Results.getAllocator(),
5379 Results.getCodeCompletionTUInfo());
5381 // Give this completion a return type.
5382 AddResultTypeChunk(S.Context, getCompletionPrintingPolicy(S), SuperMethod,
5383 Results.getCompletionContext().getBaseType(),
5386 // If we need the "super" keyword, add it (plus some spacing).
5387 if (NeedSuperKeyword) {
5388 Builder.AddTypedTextChunk("super");
5389 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5392 Selector Sel = CurMethod->getSelector();
5393 if (Sel.isUnarySelector()) {
5394 if (NeedSuperKeyword)
5395 Builder.AddTextChunk(Builder.getAllocator().CopyString(
5396 Sel.getNameForSlot(0)));
5398 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
5399 Sel.getNameForSlot(0)));
5401 ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin();
5402 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I, ++CurP) {
5403 if (I > SelIdents.size())
5404 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5406 if (I < SelIdents.size())
5407 Builder.AddInformativeChunk(
5408 Builder.getAllocator().CopyString(
5409 Sel.getNameForSlot(I) + ":"));
5410 else if (NeedSuperKeyword || I > SelIdents.size()) {
5411 Builder.AddTextChunk(
5412 Builder.getAllocator().CopyString(
5413 Sel.getNameForSlot(I) + ":"));
5414 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
5415 (*CurP)->getIdentifier()->getName()));
5417 Builder.AddTypedTextChunk(
5418 Builder.getAllocator().CopyString(
5419 Sel.getNameForSlot(I) + ":"));
5420 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
5421 (*CurP)->getIdentifier()->getName()));
5426 Results.AddResult(CodeCompletionResult(Builder.TakeString(), SuperMethod,
5427 CCP_SuperCompletion));
5431 void Sema::CodeCompleteObjCMessageReceiver(Scope *S) {
5432 typedef CodeCompletionResult Result;
5433 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5434 CodeCompleter->getCodeCompletionTUInfo(),
5435 CodeCompletionContext::CCC_ObjCMessageReceiver,
5436 getLangOpts().CPlusPlus11
5437 ? &ResultBuilder::IsObjCMessageReceiverOrLambdaCapture
5438 : &ResultBuilder::IsObjCMessageReceiver);
5440 CodeCompletionDeclConsumer Consumer(Results, CurContext);
5441 Results.EnterNewScope();
5442 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
5443 CodeCompleter->includeGlobals());
5445 // If we are in an Objective-C method inside a class that has a superclass,
5446 // add "super" as an option.
5447 if (ObjCMethodDecl *Method = getCurMethodDecl())
5448 if (ObjCInterfaceDecl *Iface = Method->getClassInterface())
5449 if (Iface->getSuperClass()) {
5450 Results.AddResult(Result("super"));
5452 AddSuperSendCompletion(*this, /*NeedSuperKeyword=*/true, None, Results);
5455 if (getLangOpts().CPlusPlus11)
5456 addThisCompletion(*this, Results);
5458 Results.ExitScope();
5460 if (CodeCompleter->includeMacros())
5461 AddMacroResults(PP, Results, false);
5462 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
5463 Results.data(), Results.size());
5467 void Sema::CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
5468 ArrayRef<IdentifierInfo *> SelIdents,
5469 bool AtArgumentExpression) {
5470 ObjCInterfaceDecl *CDecl = nullptr;
5471 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
5472 // Figure out which interface we're in.
5473 CDecl = CurMethod->getClassInterface();
5477 // Find the superclass of this class.
5478 CDecl = CDecl->getSuperClass();
5482 if (CurMethod->isInstanceMethod()) {
5483 // We are inside an instance method, which means that the message
5484 // send [super ...] is actually calling an instance method on the
5486 return CodeCompleteObjCInstanceMessage(S, nullptr, SelIdents,
5487 AtArgumentExpression,
5491 // Fall through to send to the superclass in CDecl.
5493 // "super" may be the name of a type or variable. Figure out which
5495 IdentifierInfo *Super = getSuperIdentifier();
5496 NamedDecl *ND = LookupSingleName(S, Super, SuperLoc,
5497 LookupOrdinaryName);
5498 if ((CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(ND))) {
5499 // "super" names an interface. Use it.
5500 } else if (TypeDecl *TD = dyn_cast_or_null<TypeDecl>(ND)) {
5501 if (const ObjCObjectType *Iface
5502 = Context.getTypeDeclType(TD)->getAs<ObjCObjectType>())
5503 CDecl = Iface->getInterface();
5504 } else if (ND && isa<UnresolvedUsingTypenameDecl>(ND)) {
5505 // "super" names an unresolved type; we can't be more specific.
5507 // Assume that "super" names some kind of value and parse that way.
5509 SourceLocation TemplateKWLoc;
5511 id.setIdentifier(Super, SuperLoc);
5512 ExprResult SuperExpr = ActOnIdExpression(S, SS, TemplateKWLoc, id,
5514 return CodeCompleteObjCInstanceMessage(S, (Expr *)SuperExpr.get(),
5516 AtArgumentExpression);
5522 ParsedType Receiver;
5524 Receiver = ParsedType::make(Context.getObjCInterfaceType(CDecl));
5525 return CodeCompleteObjCClassMessage(S, Receiver, SelIdents,
5526 AtArgumentExpression,
5530 /// \brief Given a set of code-completion results for the argument of a message
5531 /// send, determine the preferred type (if any) for that argument expression.
5532 static QualType getPreferredArgumentTypeForMessageSend(ResultBuilder &Results,
5533 unsigned NumSelIdents) {
5534 typedef CodeCompletionResult Result;
5535 ASTContext &Context = Results.getSema().Context;
5537 QualType PreferredType;
5538 unsigned BestPriority = CCP_Unlikely * 2;
5539 Result *ResultsData = Results.data();
5540 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
5541 Result &R = ResultsData[I];
5542 if (R.Kind == Result::RK_Declaration &&
5543 isa<ObjCMethodDecl>(R.Declaration)) {
5544 if (R.Priority <= BestPriority) {
5545 const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(R.Declaration);
5546 if (NumSelIdents <= Method->param_size()) {
5547 QualType MyPreferredType = Method->parameters()[NumSelIdents - 1]
5549 if (R.Priority < BestPriority || PreferredType.isNull()) {
5550 BestPriority = R.Priority;
5551 PreferredType = MyPreferredType;
5552 } else if (!Context.hasSameUnqualifiedType(PreferredType,
5554 PreferredType = QualType();
5561 return PreferredType;
5564 static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
5565 ParsedType Receiver,
5566 ArrayRef<IdentifierInfo *> SelIdents,
5567 bool AtArgumentExpression,
5569 ResultBuilder &Results) {
5570 typedef CodeCompletionResult Result;
5571 ObjCInterfaceDecl *CDecl = nullptr;
5573 // If the given name refers to an interface type, retrieve the
5574 // corresponding declaration.
5576 QualType T = SemaRef.GetTypeFromParser(Receiver, nullptr);
5578 if (const ObjCObjectType *Interface = T->getAs<ObjCObjectType>())
5579 CDecl = Interface->getInterface();
5582 // Add all of the factory methods in this Objective-C class, its protocols,
5583 // superclasses, categories, implementation, etc.
5584 Results.EnterNewScope();
5586 // If this is a send-to-super, try to add the special "super" send
5589 if (ObjCMethodDecl *SuperMethod
5590 = AddSuperSendCompletion(SemaRef, false, SelIdents, Results))
5591 Results.Ignore(SuperMethod);
5594 // If we're inside an Objective-C method definition, prefer its selector to
5596 if (ObjCMethodDecl *CurMethod = SemaRef.getCurMethodDecl())
5597 Results.setPreferredSelector(CurMethod->getSelector());
5599 VisitedSelectorSet Selectors;
5601 AddObjCMethods(CDecl, false, MK_Any, SelIdents,
5602 SemaRef.CurContext, Selectors, AtArgumentExpression,
5605 // We're messaging "id" as a type; provide all class/factory methods.
5607 // If we have an external source, load the entire class method
5608 // pool from the AST file.
5609 if (SemaRef.getExternalSource()) {
5610 for (uint32_t I = 0,
5611 N = SemaRef.getExternalSource()->GetNumExternalSelectors();
5613 Selector Sel = SemaRef.getExternalSource()->GetExternalSelector(I);
5614 if (Sel.isNull() || SemaRef.MethodPool.count(Sel))
5617 SemaRef.ReadMethodPool(Sel);
5621 for (Sema::GlobalMethodPool::iterator M = SemaRef.MethodPool.begin(),
5622 MEnd = SemaRef.MethodPool.end();
5624 for (ObjCMethodList *MethList = &M->second.second;
5625 MethList && MethList->getMethod();
5626 MethList = MethList->getNext()) {
5627 if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents))
5630 Result R(MethList->getMethod(),
5631 Results.getBasePriority(MethList->getMethod()), nullptr);
5632 R.StartParameter = SelIdents.size();
5633 R.AllParametersAreInformative = false;
5634 Results.MaybeAddResult(R, SemaRef.CurContext);
5639 Results.ExitScope();
5642 void Sema::CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
5643 ArrayRef<IdentifierInfo *> SelIdents,
5644 bool AtArgumentExpression,
5647 QualType T = this->GetTypeFromParser(Receiver);
5649 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5650 CodeCompleter->getCodeCompletionTUInfo(),
5651 CodeCompletionContext(CodeCompletionContext::CCC_ObjCClassMessage,
5654 AddClassMessageCompletions(*this, S, Receiver, SelIdents,
5655 AtArgumentExpression, IsSuper, Results);
5657 // If we're actually at the argument expression (rather than prior to the
5658 // selector), we're actually performing code completion for an expression.
5659 // Determine whether we have a single, best method. If so, we can
5660 // code-complete the expression using the corresponding parameter type as
5661 // our preferred type, improving completion results.
5662 if (AtArgumentExpression) {
5663 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results,
5665 if (PreferredType.isNull())
5666 CodeCompleteOrdinaryName(S, PCC_Expression);
5668 CodeCompleteExpression(S, PreferredType);
5672 HandleCodeCompleteResults(this, CodeCompleter,
5673 Results.getCompletionContext(),
5674 Results.data(), Results.size());
5677 void Sema::CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
5678 ArrayRef<IdentifierInfo *> SelIdents,
5679 bool AtArgumentExpression,
5680 ObjCInterfaceDecl *Super) {
5681 typedef CodeCompletionResult Result;
5683 Expr *RecExpr = static_cast<Expr *>(Receiver);
5685 // If necessary, apply function/array conversion to the receiver.
5686 // C99 6.7.5.3p[7,8].
5688 ExprResult Conv = DefaultFunctionArrayLvalueConversion(RecExpr);
5689 if (Conv.isInvalid()) // conversion failed. bail.
5691 RecExpr = Conv.get();
5693 QualType ReceiverType = RecExpr? RecExpr->getType()
5694 : Super? Context.getObjCObjectPointerType(
5695 Context.getObjCInterfaceType(Super))
5696 : Context.getObjCIdType();
5698 // If we're messaging an expression with type "id" or "Class", check
5699 // whether we know something special about the receiver that allows
5700 // us to assume a more-specific receiver type.
5701 if (ReceiverType->isObjCIdType() || ReceiverType->isObjCClassType()) {
5702 if (ObjCInterfaceDecl *IFace = GetAssumedMessageSendExprType(RecExpr)) {
5703 if (ReceiverType->isObjCClassType())
5704 return CodeCompleteObjCClassMessage(S,
5705 ParsedType::make(Context.getObjCInterfaceType(IFace)),
5707 AtArgumentExpression, Super);
5709 ReceiverType = Context.getObjCObjectPointerType(
5710 Context.getObjCInterfaceType(IFace));
5712 } else if (RecExpr && getLangOpts().CPlusPlus) {
5713 ExprResult Conv = PerformContextuallyConvertToObjCPointer(RecExpr);
5714 if (Conv.isUsable()) {
5715 RecExpr = Conv.get();
5716 ReceiverType = RecExpr->getType();
5720 // Build the set of methods we can see.
5721 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5722 CodeCompleter->getCodeCompletionTUInfo(),
5723 CodeCompletionContext(CodeCompletionContext::CCC_ObjCInstanceMessage,
5724 ReceiverType, SelIdents));
5726 Results.EnterNewScope();
5728 // If this is a send-to-super, try to add the special "super" send
5731 if (ObjCMethodDecl *SuperMethod
5732 = AddSuperSendCompletion(*this, false, SelIdents, Results))
5733 Results.Ignore(SuperMethod);
5736 // If we're inside an Objective-C method definition, prefer its selector to
5738 if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
5739 Results.setPreferredSelector(CurMethod->getSelector());
5741 // Keep track of the selectors we've already added.
5742 VisitedSelectorSet Selectors;
5744 // Handle messages to Class. This really isn't a message to an instance
5745 // method, so we treat it the same way we would treat a message send to a
5747 if (ReceiverType->isObjCClassType() ||
5748 ReceiverType->isObjCQualifiedClassType()) {
5749 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
5750 if (ObjCInterfaceDecl *ClassDecl = CurMethod->getClassInterface())
5751 AddObjCMethods(ClassDecl, false, MK_Any, SelIdents,
5752 CurContext, Selectors, AtArgumentExpression, Results);
5755 // Handle messages to a qualified ID ("id<foo>").
5756 else if (const ObjCObjectPointerType *QualID
5757 = ReceiverType->getAsObjCQualifiedIdType()) {
5758 // Search protocols for instance methods.
5759 for (auto *I : QualID->quals())
5760 AddObjCMethods(I, true, MK_Any, SelIdents, CurContext,
5761 Selectors, AtArgumentExpression, Results);
5763 // Handle messages to a pointer to interface type.
5764 else if (const ObjCObjectPointerType *IFacePtr
5765 = ReceiverType->getAsObjCInterfacePointerType()) {
5766 // Search the class, its superclasses, etc., for instance methods.
5767 AddObjCMethods(IFacePtr->getInterfaceDecl(), true, MK_Any, SelIdents,
5768 CurContext, Selectors, AtArgumentExpression,
5771 // Search protocols for instance methods.
5772 for (auto *I : IFacePtr->quals())
5773 AddObjCMethods(I, true, MK_Any, SelIdents, CurContext,
5774 Selectors, AtArgumentExpression, Results);
5776 // Handle messages to "id".
5777 else if (ReceiverType->isObjCIdType()) {
5778 // We're messaging "id", so provide all instance methods we know
5779 // about as code-completion results.
5781 // If we have an external source, load the entire class method
5782 // pool from the AST file.
5783 if (ExternalSource) {
5784 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
5786 Selector Sel = ExternalSource->GetExternalSelector(I);
5787 if (Sel.isNull() || MethodPool.count(Sel))
5790 ReadMethodPool(Sel);
5794 for (GlobalMethodPool::iterator M = MethodPool.begin(),
5795 MEnd = MethodPool.end();
5797 for (ObjCMethodList *MethList = &M->second.first;
5798 MethList && MethList->getMethod();
5799 MethList = MethList->getNext()) {
5800 if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents))
5803 if (!Selectors.insert(MethList->getMethod()->getSelector()).second)
5806 Result R(MethList->getMethod(),
5807 Results.getBasePriority(MethList->getMethod()), nullptr);
5808 R.StartParameter = SelIdents.size();
5809 R.AllParametersAreInformative = false;
5810 Results.MaybeAddResult(R, CurContext);
5814 Results.ExitScope();
5817 // If we're actually at the argument expression (rather than prior to the
5818 // selector), we're actually performing code completion for an expression.
5819 // Determine whether we have a single, best method. If so, we can
5820 // code-complete the expression using the corresponding parameter type as
5821 // our preferred type, improving completion results.
5822 if (AtArgumentExpression) {
5823 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results,
5825 if (PreferredType.isNull())
5826 CodeCompleteOrdinaryName(S, PCC_Expression);
5828 CodeCompleteExpression(S, PreferredType);
5832 HandleCodeCompleteResults(this, CodeCompleter,
5833 Results.getCompletionContext(),
5834 Results.data(),Results.size());
5837 void Sema::CodeCompleteObjCForCollection(Scope *S,
5838 DeclGroupPtrTy IterationVar) {
5839 CodeCompleteExpressionData Data;
5840 Data.ObjCCollection = true;
5842 if (IterationVar.getAsOpaquePtr()) {
5843 DeclGroupRef DG = IterationVar.get();
5844 for (DeclGroupRef::iterator I = DG.begin(), End = DG.end(); I != End; ++I) {
5846 Data.IgnoreDecls.push_back(*I);
5850 CodeCompleteExpression(S, Data);
5853 void Sema::CodeCompleteObjCSelector(Scope *S,
5854 ArrayRef<IdentifierInfo *> SelIdents) {
5855 // If we have an external source, load the entire class method
5856 // pool from the AST file.
5857 if (ExternalSource) {
5858 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
5860 Selector Sel = ExternalSource->GetExternalSelector(I);
5861 if (Sel.isNull() || MethodPool.count(Sel))
5864 ReadMethodPool(Sel);
5868 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5869 CodeCompleter->getCodeCompletionTUInfo(),
5870 CodeCompletionContext::CCC_SelectorName);
5871 Results.EnterNewScope();
5872 for (GlobalMethodPool::iterator M = MethodPool.begin(),
5873 MEnd = MethodPool.end();
5876 Selector Sel = M->first;
5877 if (!isAcceptableObjCSelector(Sel, MK_Any, SelIdents))
5880 CodeCompletionBuilder Builder(Results.getAllocator(),
5881 Results.getCodeCompletionTUInfo());
5882 if (Sel.isUnarySelector()) {
5883 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
5884 Sel.getNameForSlot(0)));
5885 Results.AddResult(Builder.TakeString());
5889 std::string Accumulator;
5890 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I) {
5891 if (I == SelIdents.size()) {
5892 if (!Accumulator.empty()) {
5893 Builder.AddInformativeChunk(Builder.getAllocator().CopyString(
5895 Accumulator.clear();
5899 Accumulator += Sel.getNameForSlot(I);
5902 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString( Accumulator));
5903 Results.AddResult(Builder.TakeString());
5905 Results.ExitScope();
5907 HandleCodeCompleteResults(this, CodeCompleter,
5908 CodeCompletionContext::CCC_SelectorName,
5909 Results.data(), Results.size());
5912 /// \brief Add all of the protocol declarations that we find in the given
5913 /// (translation unit) context.
5914 static void AddProtocolResults(DeclContext *Ctx, DeclContext *CurContext,
5915 bool OnlyForwardDeclarations,
5916 ResultBuilder &Results) {
5917 typedef CodeCompletionResult Result;
5919 for (const auto *D : Ctx->decls()) {
5920 // Record any protocols we find.
5921 if (const auto *Proto = dyn_cast<ObjCProtocolDecl>(D))
5922 if (!OnlyForwardDeclarations || !Proto->hasDefinition())
5923 Results.AddResult(Result(Proto, Results.getBasePriority(Proto),nullptr),
5924 CurContext, nullptr, false);
5928 void Sema::CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols,
5929 unsigned NumProtocols) {
5930 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5931 CodeCompleter->getCodeCompletionTUInfo(),
5932 CodeCompletionContext::CCC_ObjCProtocolName);
5934 if (CodeCompleter && CodeCompleter->includeGlobals()) {
5935 Results.EnterNewScope();
5937 // Tell the result set to ignore all of the protocols we have
5939 // FIXME: This doesn't work when caching code-completion results.
5940 for (unsigned I = 0; I != NumProtocols; ++I)
5941 if (ObjCProtocolDecl *Protocol = LookupProtocol(Protocols[I].first,
5942 Protocols[I].second))
5943 Results.Ignore(Protocol);
5945 // Add all protocols.
5946 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, false,
5949 Results.ExitScope();
5952 HandleCodeCompleteResults(this, CodeCompleter,
5953 CodeCompletionContext::CCC_ObjCProtocolName,
5954 Results.data(),Results.size());
5957 void Sema::CodeCompleteObjCProtocolDecl(Scope *) {
5958 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5959 CodeCompleter->getCodeCompletionTUInfo(),
5960 CodeCompletionContext::CCC_ObjCProtocolName);
5962 if (CodeCompleter && CodeCompleter->includeGlobals()) {
5963 Results.EnterNewScope();
5965 // Add all protocols.
5966 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, true,
5969 Results.ExitScope();
5972 HandleCodeCompleteResults(this, CodeCompleter,
5973 CodeCompletionContext::CCC_ObjCProtocolName,
5974 Results.data(),Results.size());
5977 /// \brief Add all of the Objective-C interface declarations that we find in
5978 /// the given (translation unit) context.
5979 static void AddInterfaceResults(DeclContext *Ctx, DeclContext *CurContext,
5980 bool OnlyForwardDeclarations,
5981 bool OnlyUnimplemented,
5982 ResultBuilder &Results) {
5983 typedef CodeCompletionResult Result;
5985 for (const auto *D : Ctx->decls()) {
5986 // Record any interfaces we find.
5987 if (const auto *Class = dyn_cast<ObjCInterfaceDecl>(D))
5988 if ((!OnlyForwardDeclarations || !Class->hasDefinition()) &&
5989 (!OnlyUnimplemented || !Class->getImplementation()))
5990 Results.AddResult(Result(Class, Results.getBasePriority(Class),nullptr),
5991 CurContext, nullptr, false);
5995 void Sema::CodeCompleteObjCInterfaceDecl(Scope *S) {
5996 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5997 CodeCompleter->getCodeCompletionTUInfo(),
5998 CodeCompletionContext::CCC_Other);
5999 Results.EnterNewScope();
6001 if (CodeCompleter->includeGlobals()) {
6003 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
6007 Results.ExitScope();
6009 HandleCodeCompleteResults(this, CodeCompleter,
6010 CodeCompletionContext::CCC_ObjCInterfaceName,
6011 Results.data(),Results.size());
6014 void Sema::CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName,
6015 SourceLocation ClassNameLoc) {
6016 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6017 CodeCompleter->getCodeCompletionTUInfo(),
6018 CodeCompletionContext::CCC_ObjCInterfaceName);
6019 Results.EnterNewScope();
6021 // Make sure that we ignore the class we're currently defining.
6023 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
6024 if (CurClass && isa<ObjCInterfaceDecl>(CurClass))
6025 Results.Ignore(CurClass);
6027 if (CodeCompleter->includeGlobals()) {
6029 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
6033 Results.ExitScope();
6035 HandleCodeCompleteResults(this, CodeCompleter,
6036 CodeCompletionContext::CCC_ObjCInterfaceName,
6037 Results.data(),Results.size());
6040 void Sema::CodeCompleteObjCImplementationDecl(Scope *S) {
6041 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6042 CodeCompleter->getCodeCompletionTUInfo(),
6043 CodeCompletionContext::CCC_Other);
6044 Results.EnterNewScope();
6046 if (CodeCompleter->includeGlobals()) {
6047 // Add all unimplemented classes.
6048 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
6052 Results.ExitScope();
6054 HandleCodeCompleteResults(this, CodeCompleter,
6055 CodeCompletionContext::CCC_ObjCInterfaceName,
6056 Results.data(),Results.size());
6059 void Sema::CodeCompleteObjCInterfaceCategory(Scope *S,
6060 IdentifierInfo *ClassName,
6061 SourceLocation ClassNameLoc) {
6062 typedef CodeCompletionResult Result;
6064 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6065 CodeCompleter->getCodeCompletionTUInfo(),
6066 CodeCompletionContext::CCC_ObjCCategoryName);
6068 // Ignore any categories we find that have already been implemented by this
6070 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
6072 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
6073 if (ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass)){
6074 for (const auto *Cat : Class->visible_categories())
6075 CategoryNames.insert(Cat->getIdentifier());
6078 // Add all of the categories we know about.
6079 Results.EnterNewScope();
6080 TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
6081 for (const auto *D : TU->decls())
6082 if (const auto *Category = dyn_cast<ObjCCategoryDecl>(D))
6083 if (CategoryNames.insert(Category->getIdentifier()).second)
6084 Results.AddResult(Result(Category, Results.getBasePriority(Category),
6086 CurContext, nullptr, false);
6087 Results.ExitScope();
6089 HandleCodeCompleteResults(this, CodeCompleter,
6090 CodeCompletionContext::CCC_ObjCCategoryName,
6091 Results.data(),Results.size());
6094 void Sema::CodeCompleteObjCImplementationCategory(Scope *S,
6095 IdentifierInfo *ClassName,
6096 SourceLocation ClassNameLoc) {
6097 typedef CodeCompletionResult Result;
6099 // Find the corresponding interface. If we couldn't find the interface, the
6100 // program itself is ill-formed. However, we'll try to be helpful still by
6101 // providing the list of all of the categories we know about.
6103 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
6104 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass);
6106 return CodeCompleteObjCInterfaceCategory(S, ClassName, ClassNameLoc);
6108 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6109 CodeCompleter->getCodeCompletionTUInfo(),
6110 CodeCompletionContext::CCC_ObjCCategoryName);
6112 // Add all of the categories that have have corresponding interface
6113 // declarations in this class and any of its superclasses, except for
6114 // already-implemented categories in the class itself.
6115 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
6116 Results.EnterNewScope();
6117 bool IgnoreImplemented = true;
6119 for (const auto *Cat : Class->visible_categories()) {
6120 if ((!IgnoreImplemented || !Cat->getImplementation()) &&
6121 CategoryNames.insert(Cat->getIdentifier()).second)
6122 Results.AddResult(Result(Cat, Results.getBasePriority(Cat), nullptr),
6123 CurContext, nullptr, false);
6126 Class = Class->getSuperClass();
6127 IgnoreImplemented = false;
6129 Results.ExitScope();
6131 HandleCodeCompleteResults(this, CodeCompleter,
6132 CodeCompletionContext::CCC_ObjCCategoryName,
6133 Results.data(),Results.size());
6136 void Sema::CodeCompleteObjCPropertyDefinition(Scope *S) {
6137 CodeCompletionContext CCContext(CodeCompletionContext::CCC_Other);
6138 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6139 CodeCompleter->getCodeCompletionTUInfo(),
6142 // Figure out where this @synthesize lives.
6143 ObjCContainerDecl *Container
6144 = dyn_cast_or_null<ObjCContainerDecl>(CurContext);
6146 (!isa<ObjCImplementationDecl>(Container) &&
6147 !isa<ObjCCategoryImplDecl>(Container)))
6150 // Ignore any properties that have already been implemented.
6151 Container = getContainerDef(Container);
6152 for (const auto *D : Container->decls())
6153 if (const auto *PropertyImpl = dyn_cast<ObjCPropertyImplDecl>(D))
6154 Results.Ignore(PropertyImpl->getPropertyDecl());
6156 // Add any properties that we find.
6157 AddedPropertiesSet AddedProperties;
6158 Results.EnterNewScope();
6159 if (ObjCImplementationDecl *ClassImpl
6160 = dyn_cast<ObjCImplementationDecl>(Container))
6161 AddObjCProperties(CCContext, ClassImpl->getClassInterface(), false,
6162 /*AllowNullaryMethods=*/false, CurContext,
6163 AddedProperties, Results);
6165 AddObjCProperties(CCContext,
6166 cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl(),
6167 false, /*AllowNullaryMethods=*/false, CurContext,
6168 AddedProperties, Results);
6169 Results.ExitScope();
6171 HandleCodeCompleteResults(this, CodeCompleter,
6172 CodeCompletionContext::CCC_Other,
6173 Results.data(),Results.size());
6176 void Sema::CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
6177 IdentifierInfo *PropertyName) {
6178 typedef CodeCompletionResult Result;
6179 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6180 CodeCompleter->getCodeCompletionTUInfo(),
6181 CodeCompletionContext::CCC_Other);
6183 // Figure out where this @synthesize lives.
6184 ObjCContainerDecl *Container
6185 = dyn_cast_or_null<ObjCContainerDecl>(CurContext);
6187 (!isa<ObjCImplementationDecl>(Container) &&
6188 !isa<ObjCCategoryImplDecl>(Container)))
6191 // Figure out which interface we're looking into.
6192 ObjCInterfaceDecl *Class = nullptr;
6193 if (ObjCImplementationDecl *ClassImpl
6194 = dyn_cast<ObjCImplementationDecl>(Container))
6195 Class = ClassImpl->getClassInterface();
6197 Class = cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl()
6198 ->getClassInterface();
6200 // Determine the type of the property we're synthesizing.
6201 QualType PropertyType = Context.getObjCIdType();
6203 if (ObjCPropertyDecl *Property
6204 = Class->FindPropertyDeclaration(PropertyName)) {
6206 = Property->getType().getNonReferenceType().getUnqualifiedType();
6208 // Give preference to ivars
6209 Results.setPreferredType(PropertyType);
6213 // Add all of the instance variables in this class and its superclasses.
6214 Results.EnterNewScope();
6215 bool SawSimilarlyNamedIvar = false;
6216 std::string NameWithPrefix;
6217 NameWithPrefix += '_';
6218 NameWithPrefix += PropertyName->getName();
6219 std::string NameWithSuffix = PropertyName->getName().str();
6220 NameWithSuffix += '_';
6221 for(; Class; Class = Class->getSuperClass()) {
6222 for (ObjCIvarDecl *Ivar = Class->all_declared_ivar_begin(); Ivar;
6223 Ivar = Ivar->getNextIvar()) {
6224 Results.AddResult(Result(Ivar, Results.getBasePriority(Ivar), nullptr),
6225 CurContext, nullptr, false);
6227 // Determine whether we've seen an ivar with a name similar to the
6229 if ((PropertyName == Ivar->getIdentifier() ||
6230 NameWithPrefix == Ivar->getName() ||
6231 NameWithSuffix == Ivar->getName())) {
6232 SawSimilarlyNamedIvar = true;
6234 // Reduce the priority of this result by one, to give it a slight
6235 // advantage over other results whose names don't match so closely.
6236 if (Results.size() &&
6237 Results.data()[Results.size() - 1].Kind
6238 == CodeCompletionResult::RK_Declaration &&
6239 Results.data()[Results.size() - 1].Declaration == Ivar)
6240 Results.data()[Results.size() - 1].Priority--;
6245 if (!SawSimilarlyNamedIvar) {
6246 // Create ivar result _propName, that the user can use to synthesize
6247 // an ivar of the appropriate type.
6248 unsigned Priority = CCP_MemberDeclaration + 1;
6249 typedef CodeCompletionResult Result;
6250 CodeCompletionAllocator &Allocator = Results.getAllocator();
6251 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo(),
6252 Priority,CXAvailability_Available);
6254 PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
6255 Builder.AddResultTypeChunk(GetCompletionTypeString(PropertyType, Context,
6256 Policy, Allocator));
6257 Builder.AddTypedTextChunk(Allocator.CopyString(NameWithPrefix));
6258 Results.AddResult(Result(Builder.TakeString(), Priority,
6259 CXCursor_ObjCIvarDecl));
6262 Results.ExitScope();
6264 HandleCodeCompleteResults(this, CodeCompleter,
6265 CodeCompletionContext::CCC_Other,
6266 Results.data(),Results.size());
6269 // Mapping from selectors to the methods that implement that selector, along
6270 // with the "in original class" flag.
6271 typedef llvm::DenseMap<
6272 Selector, llvm::PointerIntPair<ObjCMethodDecl *, 1, bool> > KnownMethodsMap;
6274 /// \brief Find all of the methods that reside in the given container
6275 /// (and its superclasses, protocols, etc.) that meet the given
6276 /// criteria. Insert those methods into the map of known methods,
6277 /// indexed by selector so they can be easily found.
6278 static void FindImplementableMethods(ASTContext &Context,
6279 ObjCContainerDecl *Container,
6280 bool WantInstanceMethods,
6281 QualType ReturnType,
6282 KnownMethodsMap &KnownMethods,
6283 bool InOriginalClass = true) {
6284 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)) {
6285 // Make sure we have a definition; that's what we'll walk.
6286 if (!IFace->hasDefinition())
6289 IFace = IFace->getDefinition();
6292 const ObjCList<ObjCProtocolDecl> &Protocols
6293 = IFace->getReferencedProtocols();
6294 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
6295 E = Protocols.end();
6297 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
6298 KnownMethods, InOriginalClass);
6300 // Add methods from any class extensions and categories.
6301 for (auto *Cat : IFace->visible_categories()) {
6302 FindImplementableMethods(Context, Cat, WantInstanceMethods, ReturnType,
6303 KnownMethods, false);
6306 // Visit the superclass.
6307 if (IFace->getSuperClass())
6308 FindImplementableMethods(Context, IFace->getSuperClass(),
6309 WantInstanceMethods, ReturnType,
6310 KnownMethods, false);
6313 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
6314 // Recurse into protocols.
6315 const ObjCList<ObjCProtocolDecl> &Protocols
6316 = Category->getReferencedProtocols();
6317 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
6318 E = Protocols.end();
6320 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
6321 KnownMethods, InOriginalClass);
6323 // If this category is the original class, jump to the interface.
6324 if (InOriginalClass && Category->getClassInterface())
6325 FindImplementableMethods(Context, Category->getClassInterface(),
6326 WantInstanceMethods, ReturnType, KnownMethods,
6330 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
6331 // Make sure we have a definition; that's what we'll walk.
6332 if (!Protocol->hasDefinition())
6334 Protocol = Protocol->getDefinition();
6335 Container = Protocol;
6337 // Recurse into protocols.
6338 const ObjCList<ObjCProtocolDecl> &Protocols
6339 = Protocol->getReferencedProtocols();
6340 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
6341 E = Protocols.end();
6343 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
6344 KnownMethods, false);
6347 // Add methods in this container. This operation occurs last because
6348 // we want the methods from this container to override any methods
6349 // we've previously seen with the same selector.
6350 for (auto *M : Container->methods()) {
6351 if (M->isInstanceMethod() == WantInstanceMethods) {
6352 if (!ReturnType.isNull() &&
6353 !Context.hasSameUnqualifiedType(ReturnType, M->getReturnType()))
6356 KnownMethods[M->getSelector()] =
6357 KnownMethodsMap::mapped_type(M, InOriginalClass);
6362 /// \brief Add the parenthesized return or parameter type chunk to a code
6363 /// completion string.
6364 static void AddObjCPassingTypeChunk(QualType Type,
6365 unsigned ObjCDeclQuals,
6366 ASTContext &Context,
6367 const PrintingPolicy &Policy,
6368 CodeCompletionBuilder &Builder) {
6369 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6370 std::string Quals = formatObjCParamQualifiers(ObjCDeclQuals, Type);
6372 Builder.AddTextChunk(Builder.getAllocator().CopyString(Quals));
6373 Builder.AddTextChunk(GetCompletionTypeString(Type, Context, Policy,
6374 Builder.getAllocator()));
6375 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6378 /// \brief Determine whether the given class is or inherits from a class by
6380 static bool InheritsFromClassNamed(ObjCInterfaceDecl *Class,
6385 if (Class->getIdentifier() && Class->getIdentifier()->getName() == Name)
6388 return InheritsFromClassNamed(Class->getSuperClass(), Name);
6391 /// \brief Add code completions for Objective-C Key-Value Coding (KVC) and
6392 /// Key-Value Observing (KVO).
6393 static void AddObjCKeyValueCompletions(ObjCPropertyDecl *Property,
6394 bool IsInstanceMethod,
6395 QualType ReturnType,
6396 ASTContext &Context,
6397 VisitedSelectorSet &KnownSelectors,
6398 ResultBuilder &Results) {
6399 IdentifierInfo *PropName = Property->getIdentifier();
6400 if (!PropName || PropName->getLength() == 0)
6403 PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema());
6405 // Builder that will create each code completion.
6406 typedef CodeCompletionResult Result;
6407 CodeCompletionAllocator &Allocator = Results.getAllocator();
6408 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
6410 // The selector table.
6411 SelectorTable &Selectors = Context.Selectors;
6413 // The property name, copied into the code completion allocation region
6416 CodeCompletionAllocator &Allocator;
6418 const char *CopiedKey;
6420 KeyHolder(CodeCompletionAllocator &Allocator, StringRef Key)
6421 : Allocator(Allocator), Key(Key), CopiedKey(nullptr) {}
6423 operator const char *() {
6427 return CopiedKey = Allocator.CopyString(Key);
6429 } Key(Allocator, PropName->getName());
6431 // The uppercased name of the property name.
6432 std::string UpperKey = PropName->getName();
6433 if (!UpperKey.empty())
6434 UpperKey[0] = toUppercase(UpperKey[0]);
6436 bool ReturnTypeMatchesProperty = ReturnType.isNull() ||
6437 Context.hasSameUnqualifiedType(ReturnType.getNonReferenceType(),
6438 Property->getType());
6439 bool ReturnTypeMatchesVoid
6440 = ReturnType.isNull() || ReturnType->isVoidType();
6442 // Add the normal accessor -(type)key.
6443 if (IsInstanceMethod &&
6444 KnownSelectors.insert(Selectors.getNullarySelector(PropName)).second &&
6445 ReturnTypeMatchesProperty && !Property->getGetterMethodDecl()) {
6446 if (ReturnType.isNull())
6447 AddObjCPassingTypeChunk(Property->getType(), /*Quals=*/0,
6448 Context, Policy, Builder);
6450 Builder.AddTypedTextChunk(Key);
6451 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6452 CXCursor_ObjCInstanceMethodDecl));
6455 // If we have an integral or boolean property (or the user has provided
6456 // an integral or boolean return type), add the accessor -(type)isKey.
6457 if (IsInstanceMethod &&
6458 ((!ReturnType.isNull() &&
6459 (ReturnType->isIntegerType() || ReturnType->isBooleanType())) ||
6460 (ReturnType.isNull() &&
6461 (Property->getType()->isIntegerType() ||
6462 Property->getType()->isBooleanType())))) {
6463 std::string SelectorName = (Twine("is") + UpperKey).str();
6464 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6465 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
6467 if (ReturnType.isNull()) {
6468 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6469 Builder.AddTextChunk("BOOL");
6470 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6473 Builder.AddTypedTextChunk(
6474 Allocator.CopyString(SelectorId->getName()));
6475 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6476 CXCursor_ObjCInstanceMethodDecl));
6480 // Add the normal mutator.
6481 if (IsInstanceMethod && ReturnTypeMatchesVoid &&
6482 !Property->getSetterMethodDecl()) {
6483 std::string SelectorName = (Twine("set") + UpperKey).str();
6484 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6485 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
6486 if (ReturnType.isNull()) {
6487 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6488 Builder.AddTextChunk("void");
6489 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6492 Builder.AddTypedTextChunk(
6493 Allocator.CopyString(SelectorId->getName()));
6494 Builder.AddTypedTextChunk(":");
6495 AddObjCPassingTypeChunk(Property->getType(), /*Quals=*/0,
6496 Context, Policy, Builder);
6497 Builder.AddTextChunk(Key);
6498 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6499 CXCursor_ObjCInstanceMethodDecl));
6503 // Indexed and unordered accessors
6504 unsigned IndexedGetterPriority = CCP_CodePattern;
6505 unsigned IndexedSetterPriority = CCP_CodePattern;
6506 unsigned UnorderedGetterPriority = CCP_CodePattern;
6507 unsigned UnorderedSetterPriority = CCP_CodePattern;
6508 if (const ObjCObjectPointerType *ObjCPointer
6509 = Property->getType()->getAs<ObjCObjectPointerType>()) {
6510 if (ObjCInterfaceDecl *IFace = ObjCPointer->getInterfaceDecl()) {
6511 // If this interface type is not provably derived from a known
6512 // collection, penalize the corresponding completions.
6513 if (!InheritsFromClassNamed(IFace, "NSMutableArray")) {
6514 IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
6515 if (!InheritsFromClassNamed(IFace, "NSArray"))
6516 IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
6519 if (!InheritsFromClassNamed(IFace, "NSMutableSet")) {
6520 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
6521 if (!InheritsFromClassNamed(IFace, "NSSet"))
6522 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
6526 IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
6527 IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
6528 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
6529 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
6532 // Add -(NSUInteger)countOf<key>
6533 if (IsInstanceMethod &&
6534 (ReturnType.isNull() || ReturnType->isIntegerType())) {
6535 std::string SelectorName = (Twine("countOf") + UpperKey).str();
6536 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6537 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
6539 if (ReturnType.isNull()) {
6540 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6541 Builder.AddTextChunk("NSUInteger");
6542 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6545 Builder.AddTypedTextChunk(
6546 Allocator.CopyString(SelectorId->getName()));
6547 Results.AddResult(Result(Builder.TakeString(),
6548 std::min(IndexedGetterPriority,
6549 UnorderedGetterPriority),
6550 CXCursor_ObjCInstanceMethodDecl));
6555 // Add -(id)objectInKeyAtIndex:(NSUInteger)index
6556 if (IsInstanceMethod &&
6557 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
6558 std::string SelectorName
6559 = (Twine("objectIn") + UpperKey + "AtIndex").str();
6560 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6561 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
6562 if (ReturnType.isNull()) {
6563 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6564 Builder.AddTextChunk("id");
6565 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6568 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6569 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6570 Builder.AddTextChunk("NSUInteger");
6571 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6572 Builder.AddTextChunk("index");
6573 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
6574 CXCursor_ObjCInstanceMethodDecl));
6578 // Add -(NSArray *)keyAtIndexes:(NSIndexSet *)indexes
6579 if (IsInstanceMethod &&
6580 (ReturnType.isNull() ||
6581 (ReturnType->isObjCObjectPointerType() &&
6582 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6583 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6584 ->getName() == "NSArray"))) {
6585 std::string SelectorName
6586 = (Twine(Property->getName()) + "AtIndexes").str();
6587 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6588 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
6589 if (ReturnType.isNull()) {
6590 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6591 Builder.AddTextChunk("NSArray *");
6592 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6595 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6596 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6597 Builder.AddTextChunk("NSIndexSet *");
6598 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6599 Builder.AddTextChunk("indexes");
6600 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
6601 CXCursor_ObjCInstanceMethodDecl));
6605 // Add -(void)getKey:(type **)buffer range:(NSRange)inRange
6606 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
6607 std::string SelectorName = (Twine("get") + UpperKey).str();
6608 IdentifierInfo *SelectorIds[2] = {
6609 &Context.Idents.get(SelectorName),
6610 &Context.Idents.get("range")
6613 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
6614 if (ReturnType.isNull()) {
6615 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6616 Builder.AddTextChunk("void");
6617 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6620 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6621 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6622 Builder.AddPlaceholderChunk("object-type");
6623 Builder.AddTextChunk(" **");
6624 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6625 Builder.AddTextChunk("buffer");
6626 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6627 Builder.AddTypedTextChunk("range:");
6628 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6629 Builder.AddTextChunk("NSRange");
6630 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6631 Builder.AddTextChunk("inRange");
6632 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
6633 CXCursor_ObjCInstanceMethodDecl));
6637 // Mutable indexed accessors
6639 // - (void)insertObject:(type *)object inKeyAtIndex:(NSUInteger)index
6640 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
6641 std::string SelectorName = (Twine("in") + UpperKey + "AtIndex").str();
6642 IdentifierInfo *SelectorIds[2] = {
6643 &Context.Idents.get("insertObject"),
6644 &Context.Idents.get(SelectorName)
6647 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
6648 if (ReturnType.isNull()) {
6649 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6650 Builder.AddTextChunk("void");
6651 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6654 Builder.AddTypedTextChunk("insertObject:");
6655 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6656 Builder.AddPlaceholderChunk("object-type");
6657 Builder.AddTextChunk(" *");
6658 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6659 Builder.AddTextChunk("object");
6660 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6661 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6662 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6663 Builder.AddPlaceholderChunk("NSUInteger");
6664 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6665 Builder.AddTextChunk("index");
6666 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6667 CXCursor_ObjCInstanceMethodDecl));
6671 // - (void)insertKey:(NSArray *)array atIndexes:(NSIndexSet *)indexes
6672 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
6673 std::string SelectorName = (Twine("insert") + UpperKey).str();
6674 IdentifierInfo *SelectorIds[2] = {
6675 &Context.Idents.get(SelectorName),
6676 &Context.Idents.get("atIndexes")
6679 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
6680 if (ReturnType.isNull()) {
6681 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6682 Builder.AddTextChunk("void");
6683 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6686 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6687 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6688 Builder.AddTextChunk("NSArray *");
6689 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6690 Builder.AddTextChunk("array");
6691 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6692 Builder.AddTypedTextChunk("atIndexes:");
6693 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6694 Builder.AddPlaceholderChunk("NSIndexSet *");
6695 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6696 Builder.AddTextChunk("indexes");
6697 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6698 CXCursor_ObjCInstanceMethodDecl));
6702 // -(void)removeObjectFromKeyAtIndex:(NSUInteger)index
6703 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
6704 std::string SelectorName
6705 = (Twine("removeObjectFrom") + UpperKey + "AtIndex").str();
6706 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6707 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
6708 if (ReturnType.isNull()) {
6709 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6710 Builder.AddTextChunk("void");
6711 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6714 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6715 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6716 Builder.AddTextChunk("NSUInteger");
6717 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6718 Builder.AddTextChunk("index");
6719 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6720 CXCursor_ObjCInstanceMethodDecl));
6724 // -(void)removeKeyAtIndexes:(NSIndexSet *)indexes
6725 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
6726 std::string SelectorName
6727 = (Twine("remove") + UpperKey + "AtIndexes").str();
6728 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6729 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
6730 if (ReturnType.isNull()) {
6731 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6732 Builder.AddTextChunk("void");
6733 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6736 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6737 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6738 Builder.AddTextChunk("NSIndexSet *");
6739 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6740 Builder.AddTextChunk("indexes");
6741 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6742 CXCursor_ObjCInstanceMethodDecl));
6746 // - (void)replaceObjectInKeyAtIndex:(NSUInteger)index withObject:(id)object
6747 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
6748 std::string SelectorName
6749 = (Twine("replaceObjectIn") + UpperKey + "AtIndex").str();
6750 IdentifierInfo *SelectorIds[2] = {
6751 &Context.Idents.get(SelectorName),
6752 &Context.Idents.get("withObject")
6755 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
6756 if (ReturnType.isNull()) {
6757 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6758 Builder.AddTextChunk("void");
6759 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6762 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6763 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6764 Builder.AddPlaceholderChunk("NSUInteger");
6765 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6766 Builder.AddTextChunk("index");
6767 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6768 Builder.AddTypedTextChunk("withObject:");
6769 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6770 Builder.AddTextChunk("id");
6771 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6772 Builder.AddTextChunk("object");
6773 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6774 CXCursor_ObjCInstanceMethodDecl));
6778 // - (void)replaceKeyAtIndexes:(NSIndexSet *)indexes withKey:(NSArray *)array
6779 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
6780 std::string SelectorName1
6781 = (Twine("replace") + UpperKey + "AtIndexes").str();
6782 std::string SelectorName2 = (Twine("with") + UpperKey).str();
6783 IdentifierInfo *SelectorIds[2] = {
6784 &Context.Idents.get(SelectorName1),
6785 &Context.Idents.get(SelectorName2)
6788 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
6789 if (ReturnType.isNull()) {
6790 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6791 Builder.AddTextChunk("void");
6792 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6795 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName1 + ":"));
6796 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6797 Builder.AddPlaceholderChunk("NSIndexSet *");
6798 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6799 Builder.AddTextChunk("indexes");
6800 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6801 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName2 + ":"));
6802 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6803 Builder.AddTextChunk("NSArray *");
6804 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6805 Builder.AddTextChunk("array");
6806 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6807 CXCursor_ObjCInstanceMethodDecl));
6811 // Unordered getters
6812 // - (NSEnumerator *)enumeratorOfKey
6813 if (IsInstanceMethod &&
6814 (ReturnType.isNull() ||
6815 (ReturnType->isObjCObjectPointerType() &&
6816 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6817 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6818 ->getName() == "NSEnumerator"))) {
6819 std::string SelectorName = (Twine("enumeratorOf") + UpperKey).str();
6820 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6821 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
6823 if (ReturnType.isNull()) {
6824 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6825 Builder.AddTextChunk("NSEnumerator *");
6826 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6829 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6830 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
6831 CXCursor_ObjCInstanceMethodDecl));
6835 // - (type *)memberOfKey:(type *)object
6836 if (IsInstanceMethod &&
6837 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
6838 std::string SelectorName = (Twine("memberOf") + UpperKey).str();
6839 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6840 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
6841 if (ReturnType.isNull()) {
6842 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6843 Builder.AddPlaceholderChunk("object-type");
6844 Builder.AddTextChunk(" *");
6845 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6848 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6849 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6850 if (ReturnType.isNull()) {
6851 Builder.AddPlaceholderChunk("object-type");
6852 Builder.AddTextChunk(" *");
6854 Builder.AddTextChunk(GetCompletionTypeString(ReturnType, Context,
6856 Builder.getAllocator()));
6858 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6859 Builder.AddTextChunk("object");
6860 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
6861 CXCursor_ObjCInstanceMethodDecl));
6865 // Mutable unordered accessors
6866 // - (void)addKeyObject:(type *)object
6867 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
6868 std::string SelectorName
6869 = (Twine("add") + UpperKey + Twine("Object")).str();
6870 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6871 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
6872 if (ReturnType.isNull()) {
6873 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6874 Builder.AddTextChunk("void");
6875 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6878 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6879 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6880 Builder.AddPlaceholderChunk("object-type");
6881 Builder.AddTextChunk(" *");
6882 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6883 Builder.AddTextChunk("object");
6884 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6885 CXCursor_ObjCInstanceMethodDecl));
6889 // - (void)addKey:(NSSet *)objects
6890 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
6891 std::string SelectorName = (Twine("add") + UpperKey).str();
6892 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6893 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
6894 if (ReturnType.isNull()) {
6895 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6896 Builder.AddTextChunk("void");
6897 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6900 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6901 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6902 Builder.AddTextChunk("NSSet *");
6903 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6904 Builder.AddTextChunk("objects");
6905 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6906 CXCursor_ObjCInstanceMethodDecl));
6910 // - (void)removeKeyObject:(type *)object
6911 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
6912 std::string SelectorName
6913 = (Twine("remove") + UpperKey + Twine("Object")).str();
6914 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6915 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
6916 if (ReturnType.isNull()) {
6917 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6918 Builder.AddTextChunk("void");
6919 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6922 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6923 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6924 Builder.AddPlaceholderChunk("object-type");
6925 Builder.AddTextChunk(" *");
6926 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6927 Builder.AddTextChunk("object");
6928 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6929 CXCursor_ObjCInstanceMethodDecl));
6933 // - (void)removeKey:(NSSet *)objects
6934 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
6935 std::string SelectorName = (Twine("remove") + UpperKey).str();
6936 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6937 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
6938 if (ReturnType.isNull()) {
6939 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6940 Builder.AddTextChunk("void");
6941 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6944 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6945 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6946 Builder.AddTextChunk("NSSet *");
6947 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6948 Builder.AddTextChunk("objects");
6949 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6950 CXCursor_ObjCInstanceMethodDecl));
6954 // - (void)intersectKey:(NSSet *)objects
6955 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
6956 std::string SelectorName = (Twine("intersect") + UpperKey).str();
6957 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6958 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
6959 if (ReturnType.isNull()) {
6960 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6961 Builder.AddTextChunk("void");
6962 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6965 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6966 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6967 Builder.AddTextChunk("NSSet *");
6968 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6969 Builder.AddTextChunk("objects");
6970 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6971 CXCursor_ObjCInstanceMethodDecl));
6975 // Key-Value Observing
6976 // + (NSSet *)keyPathsForValuesAffectingKey
6977 if (!IsInstanceMethod &&
6978 (ReturnType.isNull() ||
6979 (ReturnType->isObjCObjectPointerType() &&
6980 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6981 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6982 ->getName() == "NSSet"))) {
6983 std::string SelectorName
6984 = (Twine("keyPathsForValuesAffecting") + UpperKey).str();
6985 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6986 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
6988 if (ReturnType.isNull()) {
6989 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6990 Builder.AddTextChunk("NSSet *");
6991 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6994 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6995 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6996 CXCursor_ObjCClassMethodDecl));
7000 // + (BOOL)automaticallyNotifiesObserversForKey
7001 if (!IsInstanceMethod &&
7002 (ReturnType.isNull() ||
7003 ReturnType->isIntegerType() ||
7004 ReturnType->isBooleanType())) {
7005 std::string SelectorName
7006 = (Twine("automaticallyNotifiesObserversOf") + UpperKey).str();
7007 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
7008 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
7010 if (ReturnType.isNull()) {
7011 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7012 Builder.AddTextChunk("BOOL");
7013 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7016 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
7017 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
7018 CXCursor_ObjCClassMethodDecl));
7023 void Sema::CodeCompleteObjCMethodDecl(Scope *S,
7024 bool IsInstanceMethod,
7025 ParsedType ReturnTy) {
7026 // Determine the return type of the method we're declaring, if
7028 QualType ReturnType = GetTypeFromParser(ReturnTy);
7029 Decl *IDecl = nullptr;
7030 if (CurContext->isObjCContainer()) {
7031 ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext);
7032 IDecl = cast<Decl>(OCD);
7034 // Determine where we should start searching for methods.
7035 ObjCContainerDecl *SearchDecl = nullptr;
7036 bool IsInImplementation = false;
7037 if (Decl *D = IDecl) {
7038 if (ObjCImplementationDecl *Impl = dyn_cast<ObjCImplementationDecl>(D)) {
7039 SearchDecl = Impl->getClassInterface();
7040 IsInImplementation = true;
7041 } else if (ObjCCategoryImplDecl *CatImpl
7042 = dyn_cast<ObjCCategoryImplDecl>(D)) {
7043 SearchDecl = CatImpl->getCategoryDecl();
7044 IsInImplementation = true;
7046 SearchDecl = dyn_cast<ObjCContainerDecl>(D);
7049 if (!SearchDecl && S) {
7050 if (DeclContext *DC = S->getEntity())
7051 SearchDecl = dyn_cast<ObjCContainerDecl>(DC);
7055 HandleCodeCompleteResults(this, CodeCompleter,
7056 CodeCompletionContext::CCC_Other,
7061 // Find all of the methods that we could declare/implement here.
7062 KnownMethodsMap KnownMethods;
7063 FindImplementableMethods(Context, SearchDecl, IsInstanceMethod,
7064 ReturnType, KnownMethods);
7066 // Add declarations or definitions for each of the known methods.
7067 typedef CodeCompletionResult Result;
7068 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
7069 CodeCompleter->getCodeCompletionTUInfo(),
7070 CodeCompletionContext::CCC_Other);
7071 Results.EnterNewScope();
7072 PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
7073 for (KnownMethodsMap::iterator M = KnownMethods.begin(),
7074 MEnd = KnownMethods.end();
7076 ObjCMethodDecl *Method = M->second.getPointer();
7077 CodeCompletionBuilder Builder(Results.getAllocator(),
7078 Results.getCodeCompletionTUInfo());
7080 // If the result type was not already provided, add it to the
7081 // pattern as (type).
7082 if (ReturnType.isNull())
7083 AddObjCPassingTypeChunk(Method->getSendResultType()
7084 .stripObjCKindOfType(Context),
7085 Method->getObjCDeclQualifier(), Context, Policy,
7088 Selector Sel = Method->getSelector();
7090 // Add the first part of the selector to the pattern.
7091 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
7092 Sel.getNameForSlot(0)));
7094 // Add parameters to the pattern.
7096 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
7097 PEnd = Method->param_end();
7098 P != PEnd; (void)++P, ++I) {
7099 // Add the part of the selector name.
7101 Builder.AddTypedTextChunk(":");
7102 else if (I < Sel.getNumArgs()) {
7103 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7104 Builder.AddTypedTextChunk(
7105 Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":"));
7109 // Add the parameter type.
7111 if ((*P)->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
7112 ParamType = (*P)->getType();
7114 ParamType = (*P)->getOriginalType();
7115 ParamType = ParamType.substObjCTypeArgs(Context, {},
7116 ObjCSubstitutionContext::Parameter);
7117 AddObjCPassingTypeChunk(ParamType,
7118 (*P)->getObjCDeclQualifier(),
7122 if (IdentifierInfo *Id = (*P)->getIdentifier())
7123 Builder.AddTextChunk(Builder.getAllocator().CopyString( Id->getName()));
7126 if (Method->isVariadic()) {
7127 if (Method->param_size() > 0)
7128 Builder.AddChunk(CodeCompletionString::CK_Comma);
7129 Builder.AddTextChunk("...");
7132 if (IsInImplementation && Results.includeCodePatterns()) {
7133 // We will be defining the method here, so add a compound statement.
7134 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7135 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
7136 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
7137 if (!Method->getReturnType()->isVoidType()) {
7138 // If the result type is not void, add a return clause.
7139 Builder.AddTextChunk("return");
7140 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7141 Builder.AddPlaceholderChunk("expression");
7142 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
7144 Builder.AddPlaceholderChunk("statements");
7146 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
7147 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
7150 unsigned Priority = CCP_CodePattern;
7151 if (!M->second.getInt())
7152 Priority += CCD_InBaseClass;
7154 Results.AddResult(Result(Builder.TakeString(), Method, Priority));
7157 // Add Key-Value-Coding and Key-Value-Observing accessor methods for all of
7158 // the properties in this class and its categories.
7159 if (Context.getLangOpts().ObjC2) {
7160 SmallVector<ObjCContainerDecl *, 4> Containers;
7161 Containers.push_back(SearchDecl);
7163 VisitedSelectorSet KnownSelectors;
7164 for (KnownMethodsMap::iterator M = KnownMethods.begin(),
7165 MEnd = KnownMethods.end();
7167 KnownSelectors.insert(M->first);
7170 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(SearchDecl);
7172 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(SearchDecl))
7173 IFace = Category->getClassInterface();
7176 for (auto *Cat : IFace->visible_categories())
7177 Containers.push_back(Cat);
7179 for (unsigned I = 0, N = Containers.size(); I != N; ++I)
7180 for (auto *P : Containers[I]->properties())
7181 AddObjCKeyValueCompletions(P, IsInstanceMethod, ReturnType, Context,
7182 KnownSelectors, Results);
7185 Results.ExitScope();
7187 HandleCodeCompleteResults(this, CodeCompleter,
7188 CodeCompletionContext::CCC_Other,
7189 Results.data(),Results.size());
7192 void Sema::CodeCompleteObjCMethodDeclSelector(Scope *S,
7193 bool IsInstanceMethod,
7194 bool AtParameterName,
7195 ParsedType ReturnTy,
7196 ArrayRef<IdentifierInfo *> SelIdents) {
7197 // If we have an external source, load the entire class method
7198 // pool from the AST file.
7199 if (ExternalSource) {
7200 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
7202 Selector Sel = ExternalSource->GetExternalSelector(I);
7203 if (Sel.isNull() || MethodPool.count(Sel))
7206 ReadMethodPool(Sel);
7210 // Build the set of methods we can see.
7211 typedef CodeCompletionResult Result;
7212 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
7213 CodeCompleter->getCodeCompletionTUInfo(),
7214 CodeCompletionContext::CCC_Other);
7217 Results.setPreferredType(GetTypeFromParser(ReturnTy).getNonReferenceType());
7219 Results.EnterNewScope();
7220 for (GlobalMethodPool::iterator M = MethodPool.begin(),
7221 MEnd = MethodPool.end();
7223 for (ObjCMethodList *MethList = IsInstanceMethod ? &M->second.first :
7225 MethList && MethList->getMethod();
7226 MethList = MethList->getNext()) {
7227 if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents))
7230 if (AtParameterName) {
7231 // Suggest parameter names we've seen before.
7232 unsigned NumSelIdents = SelIdents.size();
7234 NumSelIdents <= MethList->getMethod()->param_size()) {
7235 ParmVarDecl *Param =
7236 MethList->getMethod()->parameters()[NumSelIdents - 1];
7237 if (Param->getIdentifier()) {
7238 CodeCompletionBuilder Builder(Results.getAllocator(),
7239 Results.getCodeCompletionTUInfo());
7240 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
7241 Param->getIdentifier()->getName()));
7242 Results.AddResult(Builder.TakeString());
7249 Result R(MethList->getMethod(),
7250 Results.getBasePriority(MethList->getMethod()), nullptr);
7251 R.StartParameter = SelIdents.size();
7252 R.AllParametersAreInformative = false;
7253 R.DeclaringEntity = true;
7254 Results.MaybeAddResult(R, CurContext);
7258 Results.ExitScope();
7259 HandleCodeCompleteResults(this, CodeCompleter,
7260 CodeCompletionContext::CCC_Other,
7261 Results.data(),Results.size());
7264 void Sema::CodeCompletePreprocessorDirective(bool InConditional) {
7265 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
7266 CodeCompleter->getCodeCompletionTUInfo(),
7267 CodeCompletionContext::CCC_PreprocessorDirective);
7268 Results.EnterNewScope();
7271 CodeCompletionBuilder Builder(Results.getAllocator(),
7272 Results.getCodeCompletionTUInfo());
7273 Builder.AddTypedTextChunk("if");
7274 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7275 Builder.AddPlaceholderChunk("condition");
7276 Results.AddResult(Builder.TakeString());
7279 Builder.AddTypedTextChunk("ifdef");
7280 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7281 Builder.AddPlaceholderChunk("macro");
7282 Results.AddResult(Builder.TakeString());
7285 Builder.AddTypedTextChunk("ifndef");
7286 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7287 Builder.AddPlaceholderChunk("macro");
7288 Results.AddResult(Builder.TakeString());
7290 if (InConditional) {
7291 // #elif <condition>
7292 Builder.AddTypedTextChunk("elif");
7293 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7294 Builder.AddPlaceholderChunk("condition");
7295 Results.AddResult(Builder.TakeString());
7298 Builder.AddTypedTextChunk("else");
7299 Results.AddResult(Builder.TakeString());
7302 Builder.AddTypedTextChunk("endif");
7303 Results.AddResult(Builder.TakeString());
7306 // #include "header"
7307 Builder.AddTypedTextChunk("include");
7308 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7309 Builder.AddTextChunk("\"");
7310 Builder.AddPlaceholderChunk("header");
7311 Builder.AddTextChunk("\"");
7312 Results.AddResult(Builder.TakeString());
7314 // #include <header>
7315 Builder.AddTypedTextChunk("include");
7316 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7317 Builder.AddTextChunk("<");
7318 Builder.AddPlaceholderChunk("header");
7319 Builder.AddTextChunk(">");
7320 Results.AddResult(Builder.TakeString());
7323 Builder.AddTypedTextChunk("define");
7324 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7325 Builder.AddPlaceholderChunk("macro");
7326 Results.AddResult(Builder.TakeString());
7328 // #define <macro>(<args>)
7329 Builder.AddTypedTextChunk("define");
7330 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7331 Builder.AddPlaceholderChunk("macro");
7332 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7333 Builder.AddPlaceholderChunk("args");
7334 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7335 Results.AddResult(Builder.TakeString());
7338 Builder.AddTypedTextChunk("undef");
7339 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7340 Builder.AddPlaceholderChunk("macro");
7341 Results.AddResult(Builder.TakeString());
7344 Builder.AddTypedTextChunk("line");
7345 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7346 Builder.AddPlaceholderChunk("number");
7347 Results.AddResult(Builder.TakeString());
7349 // #line <number> "filename"
7350 Builder.AddTypedTextChunk("line");
7351 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7352 Builder.AddPlaceholderChunk("number");
7353 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7354 Builder.AddTextChunk("\"");
7355 Builder.AddPlaceholderChunk("filename");
7356 Builder.AddTextChunk("\"");
7357 Results.AddResult(Builder.TakeString());
7360 Builder.AddTypedTextChunk("error");
7361 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7362 Builder.AddPlaceholderChunk("message");
7363 Results.AddResult(Builder.TakeString());
7365 // #pragma <arguments>
7366 Builder.AddTypedTextChunk("pragma");
7367 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7368 Builder.AddPlaceholderChunk("arguments");
7369 Results.AddResult(Builder.TakeString());
7371 if (getLangOpts().ObjC1) {
7373 Builder.AddTypedTextChunk("import");
7374 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7375 Builder.AddTextChunk("\"");
7376 Builder.AddPlaceholderChunk("header");
7377 Builder.AddTextChunk("\"");
7378 Results.AddResult(Builder.TakeString());
7381 Builder.AddTypedTextChunk("import");
7382 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7383 Builder.AddTextChunk("<");
7384 Builder.AddPlaceholderChunk("header");
7385 Builder.AddTextChunk(">");
7386 Results.AddResult(Builder.TakeString());
7389 // #include_next "header"
7390 Builder.AddTypedTextChunk("include_next");
7391 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7392 Builder.AddTextChunk("\"");
7393 Builder.AddPlaceholderChunk("header");
7394 Builder.AddTextChunk("\"");
7395 Results.AddResult(Builder.TakeString());
7397 // #include_next <header>
7398 Builder.AddTypedTextChunk("include_next");
7399 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7400 Builder.AddTextChunk("<");
7401 Builder.AddPlaceholderChunk("header");
7402 Builder.AddTextChunk(">");
7403 Results.AddResult(Builder.TakeString());
7405 // #warning <message>
7406 Builder.AddTypedTextChunk("warning");
7407 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7408 Builder.AddPlaceholderChunk("message");
7409 Results.AddResult(Builder.TakeString());
7411 // Note: #ident and #sccs are such crazy anachronisms that we don't provide
7412 // completions for them. And __include_macros is a Clang-internal extension
7413 // that we don't want to encourage anyone to use.
7415 // FIXME: we don't support #assert or #unassert, so don't suggest them.
7416 Results.ExitScope();
7418 HandleCodeCompleteResults(this, CodeCompleter,
7419 CodeCompletionContext::CCC_PreprocessorDirective,
7420 Results.data(), Results.size());
7423 void Sema::CodeCompleteInPreprocessorConditionalExclusion(Scope *S) {
7424 CodeCompleteOrdinaryName(S,
7425 S->getFnParent()? Sema::PCC_RecoveryInFunction
7426 : Sema::PCC_Namespace);
7429 void Sema::CodeCompletePreprocessorMacroName(bool IsDefinition) {
7430 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
7431 CodeCompleter->getCodeCompletionTUInfo(),
7432 IsDefinition? CodeCompletionContext::CCC_MacroName
7433 : CodeCompletionContext::CCC_MacroNameUse);
7434 if (!IsDefinition && (!CodeCompleter || CodeCompleter->includeMacros())) {
7435 // Add just the names of macros, not their arguments.
7436 CodeCompletionBuilder Builder(Results.getAllocator(),
7437 Results.getCodeCompletionTUInfo());
7438 Results.EnterNewScope();
7439 for (Preprocessor::macro_iterator M = PP.macro_begin(),
7440 MEnd = PP.macro_end();
7442 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
7443 M->first->getName()));
7444 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
7446 CXCursor_MacroDefinition));
7448 Results.ExitScope();
7449 } else if (IsDefinition) {
7450 // FIXME: Can we detect when the user just wrote an include guard above?
7453 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
7454 Results.data(), Results.size());
7457 void Sema::CodeCompletePreprocessorExpression() {
7458 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
7459 CodeCompleter->getCodeCompletionTUInfo(),
7460 CodeCompletionContext::CCC_PreprocessorExpression);
7462 if (!CodeCompleter || CodeCompleter->includeMacros())
7463 AddMacroResults(PP, Results, true);
7465 // defined (<macro>)
7466 Results.EnterNewScope();
7467 CodeCompletionBuilder Builder(Results.getAllocator(),
7468 Results.getCodeCompletionTUInfo());
7469 Builder.AddTypedTextChunk("defined");
7470 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7471 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7472 Builder.AddPlaceholderChunk("macro");
7473 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7474 Results.AddResult(Builder.TakeString());
7475 Results.ExitScope();
7477 HandleCodeCompleteResults(this, CodeCompleter,
7478 CodeCompletionContext::CCC_PreprocessorExpression,
7479 Results.data(), Results.size());
7482 void Sema::CodeCompletePreprocessorMacroArgument(Scope *S,
7483 IdentifierInfo *Macro,
7484 MacroInfo *MacroInfo,
7485 unsigned Argument) {
7486 // FIXME: In the future, we could provide "overload" results, much like we
7487 // do for function calls.
7489 // Now just ignore this. There will be another code-completion callback
7490 // for the expanded tokens.
7493 void Sema::CodeCompleteNaturalLanguage() {
7494 HandleCodeCompleteResults(this, CodeCompleter,
7495 CodeCompletionContext::CCC_NaturalLanguage,
7499 void Sema::GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
7500 CodeCompletionTUInfo &CCTUInfo,
7501 SmallVectorImpl<CodeCompletionResult> &Results) {
7502 ResultBuilder Builder(*this, Allocator, CCTUInfo,
7503 CodeCompletionContext::CCC_Recovery);
7504 if (!CodeCompleter || CodeCompleter->includeGlobals()) {
7505 CodeCompletionDeclConsumer Consumer(Builder,
7506 Context.getTranslationUnitDecl());
7507 LookupVisibleDecls(Context.getTranslationUnitDecl(), LookupAnyName,
7511 if (!CodeCompleter || CodeCompleter->includeMacros())
7512 AddMacroResults(PP, Builder, true);
7515 Results.insert(Results.end(),
7516 Builder.data(), Builder.data() + Builder.size());