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/Sema/Lookup.h"
15 #include "clang/Sema/Overload.h"
16 #include "clang/Sema/CodeCompleteConsumer.h"
17 #include "clang/Sema/ExternalSemaSource.h"
18 #include "clang/Sema/Scope.h"
19 #include "clang/Sema/ScopeInfo.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/ExprCXX.h"
22 #include "clang/AST/ExprObjC.h"
23 #include "clang/Lex/HeaderSearch.h"
24 #include "clang/Lex/MacroInfo.h"
25 #include "clang/Lex/Preprocessor.h"
26 #include "llvm/ADT/DenseSet.h"
27 #include "llvm/ADT/SmallBitVector.h"
28 #include "llvm/ADT/SmallPtrSet.h"
29 #include "llvm/ADT/SmallString.h"
30 #include "llvm/ADT/StringExtras.h"
31 #include "llvm/ADT/StringSwitch.h"
32 #include "llvm/ADT/Twine.h"
37 using namespace clang;
41 /// \brief A container of code-completion results.
44 /// \brief The type of a name-lookup filter, which can be provided to the
45 /// name-lookup routines to specify which declarations should be included in
46 /// the result set (when it returns true) and which declarations should be
47 /// filtered out (returns false).
48 typedef bool (ResultBuilder::*LookupFilter)(NamedDecl *) const;
50 typedef CodeCompletionResult Result;
53 /// \brief The actual results we have found.
54 std::vector<Result> Results;
56 /// \brief A record of all of the declarations we have found and placed
57 /// into the result set, used to ensure that no declaration ever gets into
58 /// the result set twice.
59 llvm::SmallPtrSet<Decl*, 16> AllDeclsFound;
61 typedef std::pair<NamedDecl *, unsigned> DeclIndexPair;
63 /// \brief An entry in the shadow map, which is optimized to store
64 /// a single (declaration, index) mapping (the common case) but
65 /// can also store a list of (declaration, index) mappings.
66 class ShadowMapEntry {
67 typedef SmallVector<DeclIndexPair, 4> DeclIndexPairVector;
69 /// \brief Contains either the solitary NamedDecl * or a vector
70 /// of (declaration, index) pairs.
71 llvm::PointerUnion<NamedDecl *, DeclIndexPairVector*> DeclOrVector;
73 /// \brief When the entry contains a single declaration, this is
74 /// the index associated with that entry.
75 unsigned SingleDeclIndex;
78 ShadowMapEntry() : DeclOrVector(), SingleDeclIndex(0) { }
80 void Add(NamedDecl *ND, unsigned Index) {
81 if (DeclOrVector.isNull()) {
82 // 0 - > 1 elements: just set the single element information.
84 SingleDeclIndex = Index;
88 if (NamedDecl *PrevND = DeclOrVector.dyn_cast<NamedDecl *>()) {
89 // 1 -> 2 elements: create the vector of results and push in the
90 // existing declaration.
91 DeclIndexPairVector *Vec = new DeclIndexPairVector;
92 Vec->push_back(DeclIndexPair(PrevND, SingleDeclIndex));
96 // Add the new element to the end of the vector.
97 DeclOrVector.get<DeclIndexPairVector*>()->push_back(
98 DeclIndexPair(ND, Index));
102 if (DeclIndexPairVector *Vec
103 = DeclOrVector.dyn_cast<DeclIndexPairVector *>()) {
105 DeclOrVector = ((NamedDecl *)0);
111 iterator begin() const;
112 iterator end() const;
115 /// \brief A mapping from declaration names to the declarations that have
116 /// this name within a particular scope and their index within the list of
118 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
120 /// \brief The semantic analysis object for which results are being
124 /// \brief The allocator used to allocate new code-completion strings.
125 CodeCompletionAllocator &Allocator;
127 CodeCompletionTUInfo &CCTUInfo;
129 /// \brief If non-NULL, a filter function used to remove any code-completion
130 /// results that are not desirable.
133 /// \brief Whether we should allow declarations as
134 /// nested-name-specifiers that would otherwise be filtered out.
135 bool AllowNestedNameSpecifiers;
137 /// \brief If set, the type that we would prefer our resulting value
138 /// declarations to have.
140 /// Closely matching the preferred type gives a boost to a result's
142 CanQualType PreferredType;
144 /// \brief A list of shadow maps, which is used to model name hiding at
145 /// different levels of, e.g., the inheritance hierarchy.
146 std::list<ShadowMap> ShadowMaps;
148 /// \brief If we're potentially referring to a C++ member function, the set
149 /// of qualifiers applied to the object type.
150 Qualifiers ObjectTypeQualifiers;
152 /// \brief Whether the \p ObjectTypeQualifiers field is active.
153 bool HasObjectTypeQualifiers;
155 /// \brief The selector that we prefer.
156 Selector PreferredSelector;
158 /// \brief The completion context in which we are gathering results.
159 CodeCompletionContext CompletionContext;
161 /// \brief If we are in an instance method definition, the @implementation
163 ObjCImplementationDecl *ObjCImplementation;
165 void AdjustResultPriorityForDecl(Result &R);
167 void MaybeAddConstructorResults(Result R);
170 explicit ResultBuilder(Sema &SemaRef, CodeCompletionAllocator &Allocator,
171 CodeCompletionTUInfo &CCTUInfo,
172 const CodeCompletionContext &CompletionContext,
173 LookupFilter Filter = 0)
174 : SemaRef(SemaRef), Allocator(Allocator), CCTUInfo(CCTUInfo),
176 AllowNestedNameSpecifiers(false), HasObjectTypeQualifiers(false),
177 CompletionContext(CompletionContext),
178 ObjCImplementation(0)
180 // If this is an Objective-C instance method definition, dig out the
181 // corresponding implementation.
182 switch (CompletionContext.getKind()) {
183 case CodeCompletionContext::CCC_Expression:
184 case CodeCompletionContext::CCC_ObjCMessageReceiver:
185 case CodeCompletionContext::CCC_ParenthesizedExpression:
186 case CodeCompletionContext::CCC_Statement:
187 case CodeCompletionContext::CCC_Recovery:
188 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl())
189 if (Method->isInstanceMethod())
190 if (ObjCInterfaceDecl *Interface = Method->getClassInterface())
191 ObjCImplementation = Interface->getImplementation();
199 /// \brief Whether we should include code patterns in the completion
201 bool includeCodePatterns() const {
202 return SemaRef.CodeCompleter &&
203 SemaRef.CodeCompleter->includeCodePatterns();
206 /// \brief Set the filter used for code-completion results.
207 void setFilter(LookupFilter Filter) {
208 this->Filter = Filter;
211 Result *data() { return Results.empty()? 0 : &Results.front(); }
212 unsigned size() const { return Results.size(); }
213 bool empty() const { return Results.empty(); }
215 /// \brief Specify the preferred type.
216 void setPreferredType(QualType T) {
217 PreferredType = SemaRef.Context.getCanonicalType(T);
220 /// \brief Set the cv-qualifiers on the object type, for us in filtering
221 /// calls to member functions.
223 /// When there are qualifiers in this set, they will be used to filter
224 /// out member functions that aren't available (because there will be a
225 /// cv-qualifier mismatch) or prefer functions with an exact qualifier
227 void setObjectTypeQualifiers(Qualifiers Quals) {
228 ObjectTypeQualifiers = Quals;
229 HasObjectTypeQualifiers = true;
232 /// \brief Set the preferred selector.
234 /// When an Objective-C method declaration result is added, and that
235 /// method's selector matches this preferred selector, we give that method
236 /// a slight priority boost.
237 void setPreferredSelector(Selector Sel) {
238 PreferredSelector = Sel;
241 /// \brief Retrieve the code-completion context for which results are
243 const CodeCompletionContext &getCompletionContext() const {
244 return CompletionContext;
247 /// \brief Specify whether nested-name-specifiers are allowed.
248 void allowNestedNameSpecifiers(bool Allow = true) {
249 AllowNestedNameSpecifiers = Allow;
252 /// \brief Return the semantic analysis object for which we are collecting
253 /// code completion results.
254 Sema &getSema() const { return SemaRef; }
256 /// \brief Retrieve the allocator used to allocate code completion strings.
257 CodeCompletionAllocator &getAllocator() const { return Allocator; }
259 CodeCompletionTUInfo &getCodeCompletionTUInfo() const { return CCTUInfo; }
261 /// \brief Determine whether the given declaration is at all interesting
262 /// as a code-completion result.
264 /// \param ND the declaration that we are inspecting.
266 /// \param AsNestedNameSpecifier will be set true if this declaration is
267 /// only interesting when it is a nested-name-specifier.
268 bool isInterestingDecl(NamedDecl *ND, bool &AsNestedNameSpecifier) const;
270 /// \brief Check whether the result is hidden by the Hiding declaration.
272 /// \returns true if the result is hidden and cannot be found, false if
273 /// the hidden result could still be found. When false, \p R may be
274 /// modified to describe how the result can be found (e.g., via extra
276 bool CheckHiddenResult(Result &R, DeclContext *CurContext,
279 /// \brief Add a new result to this result set (if it isn't already in one
280 /// of the shadow maps), or replace an existing result (for, e.g., a
283 /// \param R the result to add (if it is unique).
285 /// \param CurContext the context in which this result will be named.
286 void MaybeAddResult(Result R, DeclContext *CurContext = 0);
288 /// \brief Add a new result to this result set, where we already know
289 /// the hiding declation (if any).
291 /// \param R the result to add (if it is unique).
293 /// \param CurContext the context in which this result will be named.
295 /// \param Hiding the declaration that hides the result.
297 /// \param InBaseClass whether the result was found in a base
298 /// class of the searched context.
299 void AddResult(Result R, DeclContext *CurContext, NamedDecl *Hiding,
302 /// \brief Add a new non-declaration result to this result set.
303 void AddResult(Result R);
305 /// \brief Enter into a new scope.
306 void EnterNewScope();
308 /// \brief Exit from the current scope.
311 /// \brief Ignore this declaration, if it is seen again.
312 void Ignore(Decl *D) { AllDeclsFound.insert(D->getCanonicalDecl()); }
314 /// \name Name lookup predicates
316 /// These predicates can be passed to the name lookup functions to filter the
317 /// results of name lookup. All of the predicates have the same type, so that
320 bool IsOrdinaryName(NamedDecl *ND) const;
321 bool IsOrdinaryNonTypeName(NamedDecl *ND) const;
322 bool IsIntegralConstantValue(NamedDecl *ND) const;
323 bool IsOrdinaryNonValueName(NamedDecl *ND) const;
324 bool IsNestedNameSpecifier(NamedDecl *ND) const;
325 bool IsEnum(NamedDecl *ND) const;
326 bool IsClassOrStruct(NamedDecl *ND) const;
327 bool IsUnion(NamedDecl *ND) const;
328 bool IsNamespace(NamedDecl *ND) const;
329 bool IsNamespaceOrAlias(NamedDecl *ND) const;
330 bool IsType(NamedDecl *ND) const;
331 bool IsMember(NamedDecl *ND) const;
332 bool IsObjCIvar(NamedDecl *ND) const;
333 bool IsObjCMessageReceiver(NamedDecl *ND) const;
334 bool IsObjCMessageReceiverOrLambdaCapture(NamedDecl *ND) const;
335 bool IsObjCCollection(NamedDecl *ND) const;
336 bool IsImpossibleToSatisfy(NamedDecl *ND) const;
341 class ResultBuilder::ShadowMapEntry::iterator {
342 llvm::PointerUnion<NamedDecl*, const DeclIndexPair*> DeclOrIterator;
343 unsigned SingleDeclIndex;
346 typedef DeclIndexPair value_type;
347 typedef value_type reference;
348 typedef std::ptrdiff_t difference_type;
349 typedef std::input_iterator_tag iterator_category;
355 pointer(const DeclIndexPair &Value) : Value(Value) { }
357 const DeclIndexPair *operator->() const {
362 iterator() : DeclOrIterator((NamedDecl *)0), SingleDeclIndex(0) { }
364 iterator(NamedDecl *SingleDecl, unsigned Index)
365 : DeclOrIterator(SingleDecl), SingleDeclIndex(Index) { }
367 iterator(const DeclIndexPair *Iterator)
368 : DeclOrIterator(Iterator), SingleDeclIndex(0) { }
370 iterator &operator++() {
371 if (DeclOrIterator.is<NamedDecl *>()) {
372 DeclOrIterator = (NamedDecl *)0;
377 const DeclIndexPair *I = DeclOrIterator.get<const DeclIndexPair*>();
383 /*iterator operator++(int) {
389 reference operator*() const {
390 if (NamedDecl *ND = DeclOrIterator.dyn_cast<NamedDecl *>())
391 return reference(ND, SingleDeclIndex);
393 return *DeclOrIterator.get<const DeclIndexPair*>();
396 pointer operator->() const {
397 return pointer(**this);
400 friend bool operator==(const iterator &X, const iterator &Y) {
401 return X.DeclOrIterator.getOpaqueValue()
402 == Y.DeclOrIterator.getOpaqueValue() &&
403 X.SingleDeclIndex == Y.SingleDeclIndex;
406 friend bool operator!=(const iterator &X, const iterator &Y) {
411 ResultBuilder::ShadowMapEntry::iterator
412 ResultBuilder::ShadowMapEntry::begin() const {
413 if (DeclOrVector.isNull())
416 if (NamedDecl *ND = DeclOrVector.dyn_cast<NamedDecl *>())
417 return iterator(ND, SingleDeclIndex);
419 return iterator(DeclOrVector.get<DeclIndexPairVector *>()->begin());
422 ResultBuilder::ShadowMapEntry::iterator
423 ResultBuilder::ShadowMapEntry::end() const {
424 if (DeclOrVector.is<NamedDecl *>() || DeclOrVector.isNull())
427 return iterator(DeclOrVector.get<DeclIndexPairVector *>()->end());
430 /// \brief Compute the qualification required to get from the current context
431 /// (\p CurContext) to the target context (\p TargetContext).
433 /// \param Context the AST context in which the qualification will be used.
435 /// \param CurContext the context where an entity is being named, which is
436 /// typically based on the current scope.
438 /// \param TargetContext the context in which the named entity actually
441 /// \returns a nested name specifier that refers into the target context, or
442 /// NULL if no qualification is needed.
443 static NestedNameSpecifier *
444 getRequiredQualification(ASTContext &Context,
445 DeclContext *CurContext,
446 DeclContext *TargetContext) {
447 SmallVector<DeclContext *, 4> TargetParents;
449 for (DeclContext *CommonAncestor = TargetContext;
450 CommonAncestor && !CommonAncestor->Encloses(CurContext);
451 CommonAncestor = CommonAncestor->getLookupParent()) {
452 if (CommonAncestor->isTransparentContext() ||
453 CommonAncestor->isFunctionOrMethod())
456 TargetParents.push_back(CommonAncestor);
459 NestedNameSpecifier *Result = 0;
460 while (!TargetParents.empty()) {
461 DeclContext *Parent = TargetParents.back();
462 TargetParents.pop_back();
464 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Parent)) {
465 if (!Namespace->getIdentifier())
468 Result = NestedNameSpecifier::Create(Context, Result, Namespace);
470 else if (TagDecl *TD = dyn_cast<TagDecl>(Parent))
471 Result = NestedNameSpecifier::Create(Context, Result,
473 Context.getTypeDeclType(TD).getTypePtr());
478 bool ResultBuilder::isInterestingDecl(NamedDecl *ND,
479 bool &AsNestedNameSpecifier) const {
480 AsNestedNameSpecifier = false;
482 ND = ND->getUnderlyingDecl();
483 unsigned IDNS = ND->getIdentifierNamespace();
485 // Skip unnamed entities.
486 if (!ND->getDeclName())
489 // Friend declarations and declarations introduced due to friends are never
491 if (IDNS & (Decl::IDNS_OrdinaryFriend | Decl::IDNS_TagFriend))
494 // Class template (partial) specializations are never added as results.
495 if (isa<ClassTemplateSpecializationDecl>(ND) ||
496 isa<ClassTemplatePartialSpecializationDecl>(ND))
499 // Using declarations themselves are never added as results.
500 if (isa<UsingDecl>(ND))
503 // Some declarations have reserved names that we don't want to ever show.
504 if (const IdentifierInfo *Id = ND->getIdentifier()) {
505 // __va_list_tag is a freak of nature. Find it and skip it.
506 if (Id->isStr("__va_list_tag") || Id->isStr("__builtin_va_list"))
509 // Filter out names reserved for the implementation (C99 7.1.3,
510 // C++ [lib.global.names]) if they come from a system header.
512 // FIXME: Add predicate for this.
513 if (Id->getLength() >= 2) {
514 const char *Name = Id->getNameStart();
515 if (Name[0] == '_' &&
516 (Name[1] == '_' || (Name[1] >= 'A' && Name[1] <= 'Z')) &&
517 (ND->getLocation().isInvalid() ||
518 SemaRef.SourceMgr.isInSystemHeader(
519 SemaRef.SourceMgr.getSpellingLoc(ND->getLocation()))))
524 if (Filter == &ResultBuilder::IsNestedNameSpecifier ||
525 ((isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) &&
526 Filter != &ResultBuilder::IsNamespace &&
527 Filter != &ResultBuilder::IsNamespaceOrAlias &&
529 AsNestedNameSpecifier = true;
531 // Filter out any unwanted results.
532 if (Filter && !(this->*Filter)(ND)) {
533 // Check whether it is interesting as a nested-name-specifier.
534 if (AllowNestedNameSpecifiers && SemaRef.getLangOpts().CPlusPlus &&
535 IsNestedNameSpecifier(ND) &&
536 (Filter != &ResultBuilder::IsMember ||
537 (isa<CXXRecordDecl>(ND) &&
538 cast<CXXRecordDecl>(ND)->isInjectedClassName()))) {
539 AsNestedNameSpecifier = true;
545 // ... then it must be interesting!
549 bool ResultBuilder::CheckHiddenResult(Result &R, DeclContext *CurContext,
551 // In C, there is no way to refer to a hidden name.
552 // FIXME: This isn't true; we can find a tag name hidden by an ordinary
553 // name if we introduce the tag type.
554 if (!SemaRef.getLangOpts().CPlusPlus)
557 DeclContext *HiddenCtx = R.Declaration->getDeclContext()->getRedeclContext();
559 // There is no way to qualify a name declared in a function or method.
560 if (HiddenCtx->isFunctionOrMethod())
563 if (HiddenCtx == Hiding->getDeclContext()->getRedeclContext())
566 // We can refer to the result with the appropriate qualification. Do it.
568 R.QualifierIsInformative = false;
571 R.Qualifier = getRequiredQualification(SemaRef.Context,
573 R.Declaration->getDeclContext());
577 /// \brief A simplified classification of types used to determine whether two
578 /// types are "similar enough" when adjusting priorities.
579 SimplifiedTypeClass clang::getSimplifiedTypeClass(CanQualType T) {
580 switch (T->getTypeClass()) {
582 switch (cast<BuiltinType>(T)->getKind()) {
583 case BuiltinType::Void:
586 case BuiltinType::NullPtr:
589 case BuiltinType::Overload:
590 case BuiltinType::Dependent:
593 case BuiltinType::ObjCId:
594 case BuiltinType::ObjCClass:
595 case BuiltinType::ObjCSel:
596 return STC_ObjectiveC;
599 return STC_Arithmetic;
603 return STC_Arithmetic;
608 case Type::BlockPointer:
611 case Type::LValueReference:
612 case Type::RValueReference:
613 return getSimplifiedTypeClass(T->getAs<ReferenceType>()->getPointeeType());
615 case Type::ConstantArray:
616 case Type::IncompleteArray:
617 case Type::VariableArray:
618 case Type::DependentSizedArray:
621 case Type::DependentSizedExtVector:
623 case Type::ExtVector:
624 return STC_Arithmetic;
626 case Type::FunctionProto:
627 case Type::FunctionNoProto:
634 return STC_Arithmetic;
636 case Type::ObjCObject:
637 case Type::ObjCInterface:
638 case Type::ObjCObjectPointer:
639 return STC_ObjectiveC;
646 /// \brief Get the type that a given expression will have if this declaration
647 /// is used as an expression in its "typical" code-completion form.
648 QualType clang::getDeclUsageType(ASTContext &C, NamedDecl *ND) {
649 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
651 if (TypeDecl *Type = dyn_cast<TypeDecl>(ND))
652 return C.getTypeDeclType(Type);
653 if (ObjCInterfaceDecl *Iface = dyn_cast<ObjCInterfaceDecl>(ND))
654 return C.getObjCInterfaceType(Iface);
657 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND))
658 T = Function->getCallResultType();
659 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND))
660 T = Method->getSendResultType();
661 else if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND))
662 T = FunTmpl->getTemplatedDecl()->getCallResultType();
663 else if (EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND))
664 T = C.getTypeDeclType(cast<EnumDecl>(Enumerator->getDeclContext()));
665 else if (ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND))
666 T = Property->getType();
667 else if (ValueDecl *Value = dyn_cast<ValueDecl>(ND))
668 T = Value->getType();
672 // Dig through references, function pointers, and block pointers to
673 // get down to the likely type of an expression when the entity is
676 if (const ReferenceType *Ref = T->getAs<ReferenceType>()) {
677 T = Ref->getPointeeType();
681 if (const PointerType *Pointer = T->getAs<PointerType>()) {
682 if (Pointer->getPointeeType()->isFunctionType()) {
683 T = Pointer->getPointeeType();
690 if (const BlockPointerType *Block = T->getAs<BlockPointerType>()) {
691 T = Block->getPointeeType();
695 if (const FunctionType *Function = T->getAs<FunctionType>()) {
696 T = Function->getResultType();
706 void ResultBuilder::AdjustResultPriorityForDecl(Result &R) {
707 // If this is an Objective-C method declaration whose selector matches our
708 // preferred selector, give it a priority boost.
709 if (!PreferredSelector.isNull())
710 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(R.Declaration))
711 if (PreferredSelector == Method->getSelector())
712 R.Priority += CCD_SelectorMatch;
714 // If we have a preferred type, adjust the priority for results with exactly-
715 // matching or nearly-matching types.
716 if (!PreferredType.isNull()) {
717 QualType T = getDeclUsageType(SemaRef.Context, R.Declaration);
719 CanQualType TC = SemaRef.Context.getCanonicalType(T);
720 // Check for exactly-matching types (modulo qualifiers).
721 if (SemaRef.Context.hasSameUnqualifiedType(PreferredType, TC))
722 R.Priority /= CCF_ExactTypeMatch;
723 // Check for nearly-matching types, based on classification of each.
724 else if ((getSimplifiedTypeClass(PreferredType)
725 == getSimplifiedTypeClass(TC)) &&
726 !(PreferredType->isEnumeralType() && TC->isEnumeralType()))
727 R.Priority /= CCF_SimilarTypeMatch;
732 void ResultBuilder::MaybeAddConstructorResults(Result R) {
733 if (!SemaRef.getLangOpts().CPlusPlus || !R.Declaration ||
734 !CompletionContext.wantConstructorResults())
737 ASTContext &Context = SemaRef.Context;
738 NamedDecl *D = R.Declaration;
739 CXXRecordDecl *Record = 0;
740 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D))
741 Record = ClassTemplate->getTemplatedDecl();
742 else if ((Record = dyn_cast<CXXRecordDecl>(D))) {
743 // Skip specializations and partial specializations.
744 if (isa<ClassTemplateSpecializationDecl>(Record))
747 // There are no constructors here.
751 Record = Record->getDefinition();
756 QualType RecordTy = Context.getTypeDeclType(Record);
757 DeclarationName ConstructorName
758 = Context.DeclarationNames.getCXXConstructorName(
759 Context.getCanonicalType(RecordTy));
760 for (DeclContext::lookup_result Ctors = Record->lookup(ConstructorName);
761 Ctors.first != Ctors.second; ++Ctors.first) {
762 R.Declaration = *Ctors.first;
763 R.CursorKind = getCursorKindForDecl(R.Declaration);
764 Results.push_back(R);
768 void ResultBuilder::MaybeAddResult(Result R, DeclContext *CurContext) {
769 assert(!ShadowMaps.empty() && "Must enter into a results scope");
771 if (R.Kind != Result::RK_Declaration) {
772 // For non-declaration results, just add the result.
773 Results.push_back(R);
777 // Look through using declarations.
778 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
779 MaybeAddResult(Result(Using->getTargetDecl(), R.Qualifier), CurContext);
783 Decl *CanonDecl = R.Declaration->getCanonicalDecl();
784 unsigned IDNS = CanonDecl->getIdentifierNamespace();
786 bool AsNestedNameSpecifier = false;
787 if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
790 // C++ constructors are never found by name lookup.
791 if (isa<CXXConstructorDecl>(R.Declaration))
794 ShadowMap &SMap = ShadowMaps.back();
795 ShadowMapEntry::iterator I, IEnd;
796 ShadowMap::iterator NamePos = SMap.find(R.Declaration->getDeclName());
797 if (NamePos != SMap.end()) {
798 I = NamePos->second.begin();
799 IEnd = NamePos->second.end();
802 for (; I != IEnd; ++I) {
803 NamedDecl *ND = I->first;
804 unsigned Index = I->second;
805 if (ND->getCanonicalDecl() == CanonDecl) {
806 // This is a redeclaration. Always pick the newer declaration.
807 Results[Index].Declaration = R.Declaration;
814 // This is a new declaration in this scope. However, check whether this
815 // declaration name is hidden by a similarly-named declaration in an outer
817 std::list<ShadowMap>::iterator SM, SMEnd = ShadowMaps.end();
819 for (SM = ShadowMaps.begin(); SM != SMEnd; ++SM) {
820 ShadowMapEntry::iterator I, IEnd;
821 ShadowMap::iterator NamePos = SM->find(R.Declaration->getDeclName());
822 if (NamePos != SM->end()) {
823 I = NamePos->second.begin();
824 IEnd = NamePos->second.end();
826 for (; I != IEnd; ++I) {
827 // A tag declaration does not hide a non-tag declaration.
828 if (I->first->hasTagIdentifierNamespace() &&
829 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
830 Decl::IDNS_ObjCProtocol)))
833 // Protocols are in distinct namespaces from everything else.
834 if (((I->first->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
835 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
836 I->first->getIdentifierNamespace() != IDNS)
839 // The newly-added result is hidden by an entry in the shadow map.
840 if (CheckHiddenResult(R, CurContext, I->first))
847 // Make sure that any given declaration only shows up in the result set once.
848 if (!AllDeclsFound.insert(CanonDecl))
851 // If the filter is for nested-name-specifiers, then this result starts a
852 // nested-name-specifier.
853 if (AsNestedNameSpecifier) {
854 R.StartsNestedNameSpecifier = true;
855 R.Priority = CCP_NestedNameSpecifier;
857 AdjustResultPriorityForDecl(R);
859 // If this result is supposed to have an informative qualifier, add one.
860 if (R.QualifierIsInformative && !R.Qualifier &&
861 !R.StartsNestedNameSpecifier) {
862 DeclContext *Ctx = R.Declaration->getDeclContext();
863 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
864 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, Namespace);
865 else if (TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
866 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, false,
867 SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
869 R.QualifierIsInformative = false;
872 // Insert this result into the set of results and into the current shadow
874 SMap[R.Declaration->getDeclName()].Add(R.Declaration, Results.size());
875 Results.push_back(R);
877 if (!AsNestedNameSpecifier)
878 MaybeAddConstructorResults(R);
881 void ResultBuilder::AddResult(Result R, DeclContext *CurContext,
882 NamedDecl *Hiding, bool InBaseClass = false) {
883 if (R.Kind != Result::RK_Declaration) {
884 // For non-declaration results, just add the result.
885 Results.push_back(R);
889 // Look through using declarations.
890 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
891 AddResult(Result(Using->getTargetDecl(), R.Qualifier), CurContext, Hiding);
895 bool AsNestedNameSpecifier = false;
896 if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
899 // C++ constructors are never found by name lookup.
900 if (isa<CXXConstructorDecl>(R.Declaration))
903 if (Hiding && CheckHiddenResult(R, CurContext, Hiding))
906 // Make sure that any given declaration only shows up in the result set once.
907 if (!AllDeclsFound.insert(R.Declaration->getCanonicalDecl()))
910 // If the filter is for nested-name-specifiers, then this result starts a
911 // nested-name-specifier.
912 if (AsNestedNameSpecifier) {
913 R.StartsNestedNameSpecifier = true;
914 R.Priority = CCP_NestedNameSpecifier;
916 else if (Filter == &ResultBuilder::IsMember && !R.Qualifier && InBaseClass &&
917 isa<CXXRecordDecl>(R.Declaration->getDeclContext()
918 ->getRedeclContext()))
919 R.QualifierIsInformative = true;
921 // If this result is supposed to have an informative qualifier, add one.
922 if (R.QualifierIsInformative && !R.Qualifier &&
923 !R.StartsNestedNameSpecifier) {
924 DeclContext *Ctx = R.Declaration->getDeclContext();
925 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
926 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, Namespace);
927 else if (TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
928 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, false,
929 SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
931 R.QualifierIsInformative = false;
934 // Adjust the priority if this result comes from a base class.
936 R.Priority += CCD_InBaseClass;
938 AdjustResultPriorityForDecl(R);
940 if (HasObjectTypeQualifiers)
941 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(R.Declaration))
942 if (Method->isInstance()) {
943 Qualifiers MethodQuals
944 = Qualifiers::fromCVRMask(Method->getTypeQualifiers());
945 if (ObjectTypeQualifiers == MethodQuals)
946 R.Priority += CCD_ObjectQualifierMatch;
947 else if (ObjectTypeQualifiers - MethodQuals) {
948 // The method cannot be invoked, because doing so would drop
954 // Insert this result into the set of results.
955 Results.push_back(R);
957 if (!AsNestedNameSpecifier)
958 MaybeAddConstructorResults(R);
961 void ResultBuilder::AddResult(Result R) {
962 assert(R.Kind != Result::RK_Declaration &&
963 "Declaration results need more context");
964 Results.push_back(R);
967 /// \brief Enter into a new scope.
968 void ResultBuilder::EnterNewScope() {
969 ShadowMaps.push_back(ShadowMap());
972 /// \brief Exit from the current scope.
973 void ResultBuilder::ExitScope() {
974 for (ShadowMap::iterator E = ShadowMaps.back().begin(),
975 EEnd = ShadowMaps.back().end();
980 ShadowMaps.pop_back();
983 /// \brief Determines whether this given declaration will be found by
984 /// ordinary name lookup.
985 bool ResultBuilder::IsOrdinaryName(NamedDecl *ND) const {
986 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
988 unsigned IDNS = Decl::IDNS_Ordinary;
989 if (SemaRef.getLangOpts().CPlusPlus)
990 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
991 else if (SemaRef.getLangOpts().ObjC1) {
992 if (isa<ObjCIvarDecl>(ND))
996 return ND->getIdentifierNamespace() & IDNS;
999 /// \brief Determines whether this given declaration will be found by
1000 /// ordinary name lookup but is not a type name.
1001 bool ResultBuilder::IsOrdinaryNonTypeName(NamedDecl *ND) const {
1002 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
1003 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND))
1006 unsigned IDNS = Decl::IDNS_Ordinary;
1007 if (SemaRef.getLangOpts().CPlusPlus)
1008 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
1009 else if (SemaRef.getLangOpts().ObjC1) {
1010 if (isa<ObjCIvarDecl>(ND))
1014 return ND->getIdentifierNamespace() & IDNS;
1017 bool ResultBuilder::IsIntegralConstantValue(NamedDecl *ND) const {
1018 if (!IsOrdinaryNonTypeName(ND))
1021 if (ValueDecl *VD = dyn_cast<ValueDecl>(ND->getUnderlyingDecl()))
1022 if (VD->getType()->isIntegralOrEnumerationType())
1028 /// \brief Determines whether this given declaration will be found by
1029 /// ordinary name lookup.
1030 bool ResultBuilder::IsOrdinaryNonValueName(NamedDecl *ND) const {
1031 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
1033 unsigned IDNS = Decl::IDNS_Ordinary;
1034 if (SemaRef.getLangOpts().CPlusPlus)
1035 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace;
1037 return (ND->getIdentifierNamespace() & IDNS) &&
1038 !isa<ValueDecl>(ND) && !isa<FunctionTemplateDecl>(ND) &&
1039 !isa<ObjCPropertyDecl>(ND);
1042 /// \brief Determines whether the given declaration is suitable as the
1043 /// start of a C++ nested-name-specifier, e.g., a class or namespace.
1044 bool ResultBuilder::IsNestedNameSpecifier(NamedDecl *ND) const {
1045 // Allow us to find class templates, too.
1046 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
1047 ND = ClassTemplate->getTemplatedDecl();
1049 return SemaRef.isAcceptableNestedNameSpecifier(ND);
1052 /// \brief Determines whether the given declaration is an enumeration.
1053 bool ResultBuilder::IsEnum(NamedDecl *ND) const {
1054 return isa<EnumDecl>(ND);
1057 /// \brief Determines whether the given declaration is a class or struct.
1058 bool ResultBuilder::IsClassOrStruct(NamedDecl *ND) const {
1059 // Allow us to find class templates, too.
1060 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
1061 ND = ClassTemplate->getTemplatedDecl();
1063 if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
1064 return RD->getTagKind() == TTK_Class ||
1065 RD->getTagKind() == TTK_Struct;
1070 /// \brief Determines whether the given declaration is a union.
1071 bool ResultBuilder::IsUnion(NamedDecl *ND) const {
1072 // Allow us to find class templates, too.
1073 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
1074 ND = ClassTemplate->getTemplatedDecl();
1076 if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
1077 return RD->getTagKind() == TTK_Union;
1082 /// \brief Determines whether the given declaration is a namespace.
1083 bool ResultBuilder::IsNamespace(NamedDecl *ND) const {
1084 return isa<NamespaceDecl>(ND);
1087 /// \brief Determines whether the given declaration is a namespace or
1088 /// namespace alias.
1089 bool ResultBuilder::IsNamespaceOrAlias(NamedDecl *ND) const {
1090 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
1093 /// \brief Determines whether the given declaration is a type.
1094 bool ResultBuilder::IsType(NamedDecl *ND) const {
1095 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(ND))
1096 ND = Using->getTargetDecl();
1098 return isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
1101 /// \brief Determines which members of a class should be visible via
1102 /// "." or "->". Only value declarations, nested name specifiers, and
1103 /// using declarations thereof should show up.
1104 bool ResultBuilder::IsMember(NamedDecl *ND) const {
1105 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(ND))
1106 ND = Using->getTargetDecl();
1108 return isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND) ||
1109 isa<ObjCPropertyDecl>(ND);
1112 static bool isObjCReceiverType(ASTContext &C, QualType T) {
1113 T = C.getCanonicalType(T);
1114 switch (T->getTypeClass()) {
1115 case Type::ObjCObject:
1116 case Type::ObjCInterface:
1117 case Type::ObjCObjectPointer:
1121 switch (cast<BuiltinType>(T)->getKind()) {
1122 case BuiltinType::ObjCId:
1123 case BuiltinType::ObjCClass:
1124 case BuiltinType::ObjCSel:
1136 if (!C.getLangOpts().CPlusPlus)
1139 // FIXME: We could perform more analysis here to determine whether a
1140 // particular class type has any conversions to Objective-C types. For now,
1141 // just accept all class types.
1142 return T->isDependentType() || T->isRecordType();
1145 bool ResultBuilder::IsObjCMessageReceiver(NamedDecl *ND) const {
1146 QualType T = getDeclUsageType(SemaRef.Context, ND);
1150 T = SemaRef.Context.getBaseElementType(T);
1151 return isObjCReceiverType(SemaRef.Context, T);
1154 bool ResultBuilder::IsObjCMessageReceiverOrLambdaCapture(NamedDecl *ND) const {
1155 if (IsObjCMessageReceiver(ND))
1158 VarDecl *Var = dyn_cast<VarDecl>(ND);
1162 return Var->hasLocalStorage() && !Var->hasAttr<BlocksAttr>();
1165 bool ResultBuilder::IsObjCCollection(NamedDecl *ND) const {
1166 if ((SemaRef.getLangOpts().CPlusPlus && !IsOrdinaryName(ND)) ||
1167 (!SemaRef.getLangOpts().CPlusPlus && !IsOrdinaryNonTypeName(ND)))
1170 QualType T = getDeclUsageType(SemaRef.Context, ND);
1174 T = SemaRef.Context.getBaseElementType(T);
1175 return T->isObjCObjectType() || T->isObjCObjectPointerType() ||
1176 T->isObjCIdType() ||
1177 (SemaRef.getLangOpts().CPlusPlus && T->isRecordType());
1180 bool ResultBuilder::IsImpossibleToSatisfy(NamedDecl *ND) const {
1184 /// \rief Determines whether the given declaration is an Objective-C
1185 /// instance variable.
1186 bool ResultBuilder::IsObjCIvar(NamedDecl *ND) const {
1187 return isa<ObjCIvarDecl>(ND);
1191 /// \brief Visible declaration consumer that adds a code-completion result
1192 /// for each visible declaration.
1193 class CodeCompletionDeclConsumer : public VisibleDeclConsumer {
1194 ResultBuilder &Results;
1195 DeclContext *CurContext;
1198 CodeCompletionDeclConsumer(ResultBuilder &Results, DeclContext *CurContext)
1199 : Results(Results), CurContext(CurContext) { }
1201 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
1203 bool Accessible = true;
1205 Accessible = Results.getSema().IsSimplyAccessible(ND, Ctx);
1207 ResultBuilder::Result Result(ND, 0, false, Accessible);
1208 Results.AddResult(Result, CurContext, Hiding, InBaseClass);
1213 /// \brief Add type specifiers for the current language as keyword results.
1214 static void AddTypeSpecifierResults(const LangOptions &LangOpts,
1215 ResultBuilder &Results) {
1216 typedef CodeCompletionResult Result;
1217 Results.AddResult(Result("short", CCP_Type));
1218 Results.AddResult(Result("long", CCP_Type));
1219 Results.AddResult(Result("signed", CCP_Type));
1220 Results.AddResult(Result("unsigned", CCP_Type));
1221 Results.AddResult(Result("void", CCP_Type));
1222 Results.AddResult(Result("char", CCP_Type));
1223 Results.AddResult(Result("int", CCP_Type));
1224 Results.AddResult(Result("float", CCP_Type));
1225 Results.AddResult(Result("double", CCP_Type));
1226 Results.AddResult(Result("enum", CCP_Type));
1227 Results.AddResult(Result("struct", CCP_Type));
1228 Results.AddResult(Result("union", CCP_Type));
1229 Results.AddResult(Result("const", CCP_Type));
1230 Results.AddResult(Result("volatile", CCP_Type));
1234 Results.AddResult(Result("_Complex", CCP_Type));
1235 Results.AddResult(Result("_Imaginary", CCP_Type));
1236 Results.AddResult(Result("_Bool", CCP_Type));
1237 Results.AddResult(Result("restrict", CCP_Type));
1240 CodeCompletionBuilder Builder(Results.getAllocator(),
1241 Results.getCodeCompletionTUInfo());
1242 if (LangOpts.CPlusPlus) {
1244 Results.AddResult(Result("bool", CCP_Type +
1245 (LangOpts.ObjC1? CCD_bool_in_ObjC : 0)));
1246 Results.AddResult(Result("class", CCP_Type));
1247 Results.AddResult(Result("wchar_t", CCP_Type));
1249 // typename qualified-id
1250 Builder.AddTypedTextChunk("typename");
1251 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1252 Builder.AddPlaceholderChunk("qualifier");
1253 Builder.AddTextChunk("::");
1254 Builder.AddPlaceholderChunk("name");
1255 Results.AddResult(Result(Builder.TakeString()));
1257 if (LangOpts.CPlusPlus0x) {
1258 Results.AddResult(Result("auto", CCP_Type));
1259 Results.AddResult(Result("char16_t", CCP_Type));
1260 Results.AddResult(Result("char32_t", CCP_Type));
1262 Builder.AddTypedTextChunk("decltype");
1263 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1264 Builder.AddPlaceholderChunk("expression");
1265 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1266 Results.AddResult(Result(Builder.TakeString()));
1271 if (LangOpts.GNUMode) {
1272 // FIXME: Enable when we actually support decimal floating point.
1273 // Results.AddResult(Result("_Decimal32"));
1274 // Results.AddResult(Result("_Decimal64"));
1275 // Results.AddResult(Result("_Decimal128"));
1277 Builder.AddTypedTextChunk("typeof");
1278 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1279 Builder.AddPlaceholderChunk("expression");
1280 Results.AddResult(Result(Builder.TakeString()));
1282 Builder.AddTypedTextChunk("typeof");
1283 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1284 Builder.AddPlaceholderChunk("type");
1285 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1286 Results.AddResult(Result(Builder.TakeString()));
1290 static void AddStorageSpecifiers(Sema::ParserCompletionContext CCC,
1291 const LangOptions &LangOpts,
1292 ResultBuilder &Results) {
1293 typedef CodeCompletionResult Result;
1294 // Note: we don't suggest either "auto" or "register", because both
1295 // are pointless as storage specifiers. Elsewhere, we suggest "auto"
1296 // in C++0x as a type specifier.
1297 Results.AddResult(Result("extern"));
1298 Results.AddResult(Result("static"));
1301 static void AddFunctionSpecifiers(Sema::ParserCompletionContext CCC,
1302 const LangOptions &LangOpts,
1303 ResultBuilder &Results) {
1304 typedef CodeCompletionResult Result;
1306 case Sema::PCC_Class:
1307 case Sema::PCC_MemberTemplate:
1308 if (LangOpts.CPlusPlus) {
1309 Results.AddResult(Result("explicit"));
1310 Results.AddResult(Result("friend"));
1311 Results.AddResult(Result("mutable"));
1312 Results.AddResult(Result("virtual"));
1316 case Sema::PCC_ObjCInterface:
1317 case Sema::PCC_ObjCImplementation:
1318 case Sema::PCC_Namespace:
1319 case Sema::PCC_Template:
1320 if (LangOpts.CPlusPlus || LangOpts.C99)
1321 Results.AddResult(Result("inline"));
1324 case Sema::PCC_ObjCInstanceVariableList:
1325 case Sema::PCC_Expression:
1326 case Sema::PCC_Statement:
1327 case Sema::PCC_ForInit:
1328 case Sema::PCC_Condition:
1329 case Sema::PCC_RecoveryInFunction:
1330 case Sema::PCC_Type:
1331 case Sema::PCC_ParenthesizedExpression:
1332 case Sema::PCC_LocalDeclarationSpecifiers:
1337 static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt);
1338 static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt);
1339 static void AddObjCVisibilityResults(const LangOptions &LangOpts,
1340 ResultBuilder &Results,
1342 static void AddObjCImplementationResults(const LangOptions &LangOpts,
1343 ResultBuilder &Results,
1345 static void AddObjCInterfaceResults(const LangOptions &LangOpts,
1346 ResultBuilder &Results,
1348 static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt);
1350 static void AddTypedefResult(ResultBuilder &Results) {
1351 CodeCompletionBuilder Builder(Results.getAllocator(),
1352 Results.getCodeCompletionTUInfo());
1353 Builder.AddTypedTextChunk("typedef");
1354 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1355 Builder.AddPlaceholderChunk("type");
1356 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1357 Builder.AddPlaceholderChunk("name");
1358 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
1361 static bool WantTypesInContext(Sema::ParserCompletionContext CCC,
1362 const LangOptions &LangOpts) {
1364 case Sema::PCC_Namespace:
1365 case Sema::PCC_Class:
1366 case Sema::PCC_ObjCInstanceVariableList:
1367 case Sema::PCC_Template:
1368 case Sema::PCC_MemberTemplate:
1369 case Sema::PCC_Statement:
1370 case Sema::PCC_RecoveryInFunction:
1371 case Sema::PCC_Type:
1372 case Sema::PCC_ParenthesizedExpression:
1373 case Sema::PCC_LocalDeclarationSpecifiers:
1376 case Sema::PCC_Expression:
1377 case Sema::PCC_Condition:
1378 return LangOpts.CPlusPlus;
1380 case Sema::PCC_ObjCInterface:
1381 case Sema::PCC_ObjCImplementation:
1384 case Sema::PCC_ForInit:
1385 return LangOpts.CPlusPlus || LangOpts.ObjC1 || LangOpts.C99;
1388 llvm_unreachable("Invalid ParserCompletionContext!");
1391 static PrintingPolicy getCompletionPrintingPolicy(const ASTContext &Context,
1392 const Preprocessor &PP) {
1393 PrintingPolicy Policy = Sema::getPrintingPolicy(Context, PP);
1394 Policy.AnonymousTagLocations = false;
1395 Policy.SuppressStrongLifetime = true;
1396 Policy.SuppressUnwrittenScope = true;
1400 /// \brief Retrieve a printing policy suitable for code completion.
1401 static PrintingPolicy getCompletionPrintingPolicy(Sema &S) {
1402 return getCompletionPrintingPolicy(S.Context, S.PP);
1405 /// \brief Retrieve the string representation of the given type as a string
1406 /// that has the appropriate lifetime for code completion.
1408 /// This routine provides a fast path where we provide constant strings for
1409 /// common type names.
1410 static const char *GetCompletionTypeString(QualType T,
1411 ASTContext &Context,
1412 const PrintingPolicy &Policy,
1413 CodeCompletionAllocator &Allocator) {
1414 if (!T.getLocalQualifiers()) {
1415 // Built-in type names are constant strings.
1416 if (const BuiltinType *BT = dyn_cast<BuiltinType>(T))
1417 return BT->getName(Policy);
1419 // Anonymous tag types are constant strings.
1420 if (const TagType *TagT = dyn_cast<TagType>(T))
1421 if (TagDecl *Tag = TagT->getDecl())
1422 if (!Tag->getIdentifier() && !Tag->getTypedefNameForAnonDecl()) {
1423 switch (Tag->getTagKind()) {
1424 case TTK_Struct: return "struct <anonymous>";
1425 case TTK_Class: return "class <anonymous>";
1426 case TTK_Union: return "union <anonymous>";
1427 case TTK_Enum: return "enum <anonymous>";
1432 // Slow path: format the type as a string.
1434 T.getAsStringInternal(Result, Policy);
1435 return Allocator.CopyString(Result);
1438 /// \brief Add a completion for "this", if we're in a member function.
1439 static void addThisCompletion(Sema &S, ResultBuilder &Results) {
1440 QualType ThisTy = S.getCurrentThisType();
1441 if (ThisTy.isNull())
1444 CodeCompletionAllocator &Allocator = Results.getAllocator();
1445 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
1446 PrintingPolicy Policy = getCompletionPrintingPolicy(S);
1447 Builder.AddResultTypeChunk(GetCompletionTypeString(ThisTy,
1451 Builder.AddTypedTextChunk("this");
1452 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
1455 /// \brief Add language constructs that show up for "ordinary" names.
1456 static void AddOrdinaryNameResults(Sema::ParserCompletionContext CCC,
1459 ResultBuilder &Results) {
1460 CodeCompletionAllocator &Allocator = Results.getAllocator();
1461 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
1462 PrintingPolicy Policy = getCompletionPrintingPolicy(SemaRef);
1464 typedef CodeCompletionResult Result;
1466 case Sema::PCC_Namespace:
1467 if (SemaRef.getLangOpts().CPlusPlus) {
1468 if (Results.includeCodePatterns()) {
1469 // namespace <identifier> { declarations }
1470 Builder.AddTypedTextChunk("namespace");
1471 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1472 Builder.AddPlaceholderChunk("identifier");
1473 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1474 Builder.AddPlaceholderChunk("declarations");
1475 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1476 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1477 Results.AddResult(Result(Builder.TakeString()));
1480 // namespace identifier = identifier ;
1481 Builder.AddTypedTextChunk("namespace");
1482 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1483 Builder.AddPlaceholderChunk("name");
1484 Builder.AddChunk(CodeCompletionString::CK_Equal);
1485 Builder.AddPlaceholderChunk("namespace");
1486 Results.AddResult(Result(Builder.TakeString()));
1489 Builder.AddTypedTextChunk("using");
1490 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1491 Builder.AddTextChunk("namespace");
1492 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1493 Builder.AddPlaceholderChunk("identifier");
1494 Results.AddResult(Result(Builder.TakeString()));
1496 // asm(string-literal)
1497 Builder.AddTypedTextChunk("asm");
1498 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1499 Builder.AddPlaceholderChunk("string-literal");
1500 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1501 Results.AddResult(Result(Builder.TakeString()));
1503 if (Results.includeCodePatterns()) {
1504 // Explicit template instantiation
1505 Builder.AddTypedTextChunk("template");
1506 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1507 Builder.AddPlaceholderChunk("declaration");
1508 Results.AddResult(Result(Builder.TakeString()));
1512 if (SemaRef.getLangOpts().ObjC1)
1513 AddObjCTopLevelResults(Results, true);
1515 AddTypedefResult(Results);
1518 case Sema::PCC_Class:
1519 if (SemaRef.getLangOpts().CPlusPlus) {
1520 // Using declaration
1521 Builder.AddTypedTextChunk("using");
1522 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1523 Builder.AddPlaceholderChunk("qualifier");
1524 Builder.AddTextChunk("::");
1525 Builder.AddPlaceholderChunk("name");
1526 Results.AddResult(Result(Builder.TakeString()));
1528 // using typename qualifier::name (only in a dependent context)
1529 if (SemaRef.CurContext->isDependentContext()) {
1530 Builder.AddTypedTextChunk("using");
1531 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1532 Builder.AddTextChunk("typename");
1533 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1534 Builder.AddPlaceholderChunk("qualifier");
1535 Builder.AddTextChunk("::");
1536 Builder.AddPlaceholderChunk("name");
1537 Results.AddResult(Result(Builder.TakeString()));
1540 if (CCC == Sema::PCC_Class) {
1541 AddTypedefResult(Results);
1544 Builder.AddTypedTextChunk("public");
1545 if (Results.includeCodePatterns())
1546 Builder.AddChunk(CodeCompletionString::CK_Colon);
1547 Results.AddResult(Result(Builder.TakeString()));
1550 Builder.AddTypedTextChunk("protected");
1551 if (Results.includeCodePatterns())
1552 Builder.AddChunk(CodeCompletionString::CK_Colon);
1553 Results.AddResult(Result(Builder.TakeString()));
1556 Builder.AddTypedTextChunk("private");
1557 if (Results.includeCodePatterns())
1558 Builder.AddChunk(CodeCompletionString::CK_Colon);
1559 Results.AddResult(Result(Builder.TakeString()));
1564 case Sema::PCC_Template:
1565 case Sema::PCC_MemberTemplate:
1566 if (SemaRef.getLangOpts().CPlusPlus && Results.includeCodePatterns()) {
1567 // template < parameters >
1568 Builder.AddTypedTextChunk("template");
1569 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1570 Builder.AddPlaceholderChunk("parameters");
1571 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1572 Results.AddResult(Result(Builder.TakeString()));
1575 AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
1576 AddFunctionSpecifiers(CCC, SemaRef.getLangOpts(), Results);
1579 case Sema::PCC_ObjCInterface:
1580 AddObjCInterfaceResults(SemaRef.getLangOpts(), Results, true);
1581 AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
1582 AddFunctionSpecifiers(CCC, SemaRef.getLangOpts(), Results);
1585 case Sema::PCC_ObjCImplementation:
1586 AddObjCImplementationResults(SemaRef.getLangOpts(), Results, true);
1587 AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
1588 AddFunctionSpecifiers(CCC, SemaRef.getLangOpts(), Results);
1591 case Sema::PCC_ObjCInstanceVariableList:
1592 AddObjCVisibilityResults(SemaRef.getLangOpts(), Results, true);
1595 case Sema::PCC_RecoveryInFunction:
1596 case Sema::PCC_Statement: {
1597 AddTypedefResult(Results);
1599 if (SemaRef.getLangOpts().CPlusPlus && Results.includeCodePatterns() &&
1600 SemaRef.getLangOpts().CXXExceptions) {
1601 Builder.AddTypedTextChunk("try");
1602 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1603 Builder.AddPlaceholderChunk("statements");
1604 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1605 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1606 Builder.AddTextChunk("catch");
1607 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1608 Builder.AddPlaceholderChunk("declaration");
1609 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1610 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1611 Builder.AddPlaceholderChunk("statements");
1612 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1613 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1614 Results.AddResult(Result(Builder.TakeString()));
1616 if (SemaRef.getLangOpts().ObjC1)
1617 AddObjCStatementResults(Results, true);
1619 if (Results.includeCodePatterns()) {
1620 // if (condition) { statements }
1621 Builder.AddTypedTextChunk("if");
1622 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1623 if (SemaRef.getLangOpts().CPlusPlus)
1624 Builder.AddPlaceholderChunk("condition");
1626 Builder.AddPlaceholderChunk("expression");
1627 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1628 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1629 Builder.AddPlaceholderChunk("statements");
1630 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1631 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1632 Results.AddResult(Result(Builder.TakeString()));
1634 // switch (condition) { }
1635 Builder.AddTypedTextChunk("switch");
1636 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1637 if (SemaRef.getLangOpts().CPlusPlus)
1638 Builder.AddPlaceholderChunk("condition");
1640 Builder.AddPlaceholderChunk("expression");
1641 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1642 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1643 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1644 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1645 Results.AddResult(Result(Builder.TakeString()));
1648 // Switch-specific statements.
1649 if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
1651 Builder.AddTypedTextChunk("case");
1652 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1653 Builder.AddPlaceholderChunk("expression");
1654 Builder.AddChunk(CodeCompletionString::CK_Colon);
1655 Results.AddResult(Result(Builder.TakeString()));
1658 Builder.AddTypedTextChunk("default");
1659 Builder.AddChunk(CodeCompletionString::CK_Colon);
1660 Results.AddResult(Result(Builder.TakeString()));
1663 if (Results.includeCodePatterns()) {
1664 /// while (condition) { statements }
1665 Builder.AddTypedTextChunk("while");
1666 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1667 if (SemaRef.getLangOpts().CPlusPlus)
1668 Builder.AddPlaceholderChunk("condition");
1670 Builder.AddPlaceholderChunk("expression");
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 // do { statements } while ( expression );
1679 Builder.AddTypedTextChunk("do");
1680 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1681 Builder.AddPlaceholderChunk("statements");
1682 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1683 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1684 Builder.AddTextChunk("while");
1685 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1686 Builder.AddPlaceholderChunk("expression");
1687 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1688 Results.AddResult(Result(Builder.TakeString()));
1690 // for ( for-init-statement ; condition ; expression ) { statements }
1691 Builder.AddTypedTextChunk("for");
1692 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1693 if (SemaRef.getLangOpts().CPlusPlus || SemaRef.getLangOpts().C99)
1694 Builder.AddPlaceholderChunk("init-statement");
1696 Builder.AddPlaceholderChunk("init-expression");
1697 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
1698 Builder.AddPlaceholderChunk("condition");
1699 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
1700 Builder.AddPlaceholderChunk("inc-expression");
1701 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1702 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
1703 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1704 Builder.AddPlaceholderChunk("statements");
1705 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
1706 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
1707 Results.AddResult(Result(Builder.TakeString()));
1710 if (S->getContinueParent()) {
1712 Builder.AddTypedTextChunk("continue");
1713 Results.AddResult(Result(Builder.TakeString()));
1716 if (S->getBreakParent()) {
1718 Builder.AddTypedTextChunk("break");
1719 Results.AddResult(Result(Builder.TakeString()));
1722 // "return expression ;" or "return ;", depending on whether we
1723 // know the function is void or not.
1724 bool isVoid = false;
1725 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(SemaRef.CurContext))
1726 isVoid = Function->getResultType()->isVoidType();
1727 else if (ObjCMethodDecl *Method
1728 = dyn_cast<ObjCMethodDecl>(SemaRef.CurContext))
1729 isVoid = Method->getResultType()->isVoidType();
1730 else if (SemaRef.getCurBlock() &&
1731 !SemaRef.getCurBlock()->ReturnType.isNull())
1732 isVoid = SemaRef.getCurBlock()->ReturnType->isVoidType();
1733 Builder.AddTypedTextChunk("return");
1735 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1736 Builder.AddPlaceholderChunk("expression");
1738 Results.AddResult(Result(Builder.TakeString()));
1740 // goto identifier ;
1741 Builder.AddTypedTextChunk("goto");
1742 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1743 Builder.AddPlaceholderChunk("label");
1744 Results.AddResult(Result(Builder.TakeString()));
1747 Builder.AddTypedTextChunk("using");
1748 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1749 Builder.AddTextChunk("namespace");
1750 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1751 Builder.AddPlaceholderChunk("identifier");
1752 Results.AddResult(Result(Builder.TakeString()));
1755 // Fall through (for statement expressions).
1756 case Sema::PCC_ForInit:
1757 case Sema::PCC_Condition:
1758 AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
1759 // Fall through: conditions and statements can have expressions.
1761 case Sema::PCC_ParenthesizedExpression:
1762 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
1763 CCC == Sema::PCC_ParenthesizedExpression) {
1764 // (__bridge <type>)<expression>
1765 Builder.AddTypedTextChunk("__bridge");
1766 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1767 Builder.AddPlaceholderChunk("type");
1768 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1769 Builder.AddPlaceholderChunk("expression");
1770 Results.AddResult(Result(Builder.TakeString()));
1772 // (__bridge_transfer <Objective-C type>)<expression>
1773 Builder.AddTypedTextChunk("__bridge_transfer");
1774 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1775 Builder.AddPlaceholderChunk("Objective-C type");
1776 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1777 Builder.AddPlaceholderChunk("expression");
1778 Results.AddResult(Result(Builder.TakeString()));
1780 // (__bridge_retained <CF type>)<expression>
1781 Builder.AddTypedTextChunk("__bridge_retained");
1782 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1783 Builder.AddPlaceholderChunk("CF type");
1784 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1785 Builder.AddPlaceholderChunk("expression");
1786 Results.AddResult(Result(Builder.TakeString()));
1790 case Sema::PCC_Expression: {
1791 if (SemaRef.getLangOpts().CPlusPlus) {
1792 // 'this', if we're in a non-static member function.
1793 addThisCompletion(SemaRef, Results);
1796 Builder.AddResultTypeChunk("bool");
1797 Builder.AddTypedTextChunk("true");
1798 Results.AddResult(Result(Builder.TakeString()));
1801 Builder.AddResultTypeChunk("bool");
1802 Builder.AddTypedTextChunk("false");
1803 Results.AddResult(Result(Builder.TakeString()));
1805 if (SemaRef.getLangOpts().RTTI) {
1806 // dynamic_cast < type-id > ( expression )
1807 Builder.AddTypedTextChunk("dynamic_cast");
1808 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1809 Builder.AddPlaceholderChunk("type");
1810 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1811 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1812 Builder.AddPlaceholderChunk("expression");
1813 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1814 Results.AddResult(Result(Builder.TakeString()));
1817 // static_cast < type-id > ( expression )
1818 Builder.AddTypedTextChunk("static_cast");
1819 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1820 Builder.AddPlaceholderChunk("type");
1821 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1822 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1823 Builder.AddPlaceholderChunk("expression");
1824 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1825 Results.AddResult(Result(Builder.TakeString()));
1827 // reinterpret_cast < type-id > ( expression )
1828 Builder.AddTypedTextChunk("reinterpret_cast");
1829 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1830 Builder.AddPlaceholderChunk("type");
1831 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1832 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1833 Builder.AddPlaceholderChunk("expression");
1834 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1835 Results.AddResult(Result(Builder.TakeString()));
1837 // const_cast < type-id > ( expression )
1838 Builder.AddTypedTextChunk("const_cast");
1839 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
1840 Builder.AddPlaceholderChunk("type");
1841 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
1842 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1843 Builder.AddPlaceholderChunk("expression");
1844 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1845 Results.AddResult(Result(Builder.TakeString()));
1847 if (SemaRef.getLangOpts().RTTI) {
1848 // typeid ( expression-or-type )
1849 Builder.AddResultTypeChunk("std::type_info");
1850 Builder.AddTypedTextChunk("typeid");
1851 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1852 Builder.AddPlaceholderChunk("expression-or-type");
1853 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1854 Results.AddResult(Result(Builder.TakeString()));
1858 Builder.AddTypedTextChunk("new");
1859 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1860 Builder.AddPlaceholderChunk("type");
1861 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1862 Builder.AddPlaceholderChunk("expressions");
1863 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1864 Results.AddResult(Result(Builder.TakeString()));
1866 // new T [ ] ( ... )
1867 Builder.AddTypedTextChunk("new");
1868 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1869 Builder.AddPlaceholderChunk("type");
1870 Builder.AddChunk(CodeCompletionString::CK_LeftBracket);
1871 Builder.AddPlaceholderChunk("size");
1872 Builder.AddChunk(CodeCompletionString::CK_RightBracket);
1873 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1874 Builder.AddPlaceholderChunk("expressions");
1875 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1876 Results.AddResult(Result(Builder.TakeString()));
1878 // delete expression
1879 Builder.AddResultTypeChunk("void");
1880 Builder.AddTypedTextChunk("delete");
1881 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1882 Builder.AddPlaceholderChunk("expression");
1883 Results.AddResult(Result(Builder.TakeString()));
1885 // delete [] expression
1886 Builder.AddResultTypeChunk("void");
1887 Builder.AddTypedTextChunk("delete");
1888 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1889 Builder.AddChunk(CodeCompletionString::CK_LeftBracket);
1890 Builder.AddChunk(CodeCompletionString::CK_RightBracket);
1891 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1892 Builder.AddPlaceholderChunk("expression");
1893 Results.AddResult(Result(Builder.TakeString()));
1895 if (SemaRef.getLangOpts().CXXExceptions) {
1897 Builder.AddResultTypeChunk("void");
1898 Builder.AddTypedTextChunk("throw");
1899 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1900 Builder.AddPlaceholderChunk("expression");
1901 Results.AddResult(Result(Builder.TakeString()));
1906 if (SemaRef.getLangOpts().CPlusPlus0x) {
1908 Builder.AddResultTypeChunk("std::nullptr_t");
1909 Builder.AddTypedTextChunk("nullptr");
1910 Results.AddResult(Result(Builder.TakeString()));
1913 Builder.AddResultTypeChunk("size_t");
1914 Builder.AddTypedTextChunk("alignof");
1915 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1916 Builder.AddPlaceholderChunk("type");
1917 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1918 Results.AddResult(Result(Builder.TakeString()));
1921 Builder.AddResultTypeChunk("bool");
1922 Builder.AddTypedTextChunk("noexcept");
1923 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1924 Builder.AddPlaceholderChunk("expression");
1925 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1926 Results.AddResult(Result(Builder.TakeString()));
1928 // sizeof... expression
1929 Builder.AddResultTypeChunk("size_t");
1930 Builder.AddTypedTextChunk("sizeof...");
1931 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1932 Builder.AddPlaceholderChunk("parameter-pack");
1933 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1934 Results.AddResult(Result(Builder.TakeString()));
1938 if (SemaRef.getLangOpts().ObjC1) {
1939 // Add "super", if we're in an Objective-C class with a superclass.
1940 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
1941 // The interface can be NULL.
1942 if (ObjCInterfaceDecl *ID = Method->getClassInterface())
1943 if (ID->getSuperClass()) {
1944 std::string SuperType;
1945 SuperType = ID->getSuperClass()->getNameAsString();
1946 if (Method->isInstanceMethod())
1949 Builder.AddResultTypeChunk(Allocator.CopyString(SuperType));
1950 Builder.AddTypedTextChunk("super");
1951 Results.AddResult(Result(Builder.TakeString()));
1955 AddObjCExpressionResults(Results, true);
1958 // sizeof expression
1959 Builder.AddResultTypeChunk("size_t");
1960 Builder.AddTypedTextChunk("sizeof");
1961 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1962 Builder.AddPlaceholderChunk("expression-or-type");
1963 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1964 Results.AddResult(Result(Builder.TakeString()));
1968 case Sema::PCC_Type:
1969 case Sema::PCC_LocalDeclarationSpecifiers:
1973 if (WantTypesInContext(CCC, SemaRef.getLangOpts()))
1974 AddTypeSpecifierResults(SemaRef.getLangOpts(), Results);
1976 if (SemaRef.getLangOpts().CPlusPlus && CCC != Sema::PCC_Type)
1977 Results.AddResult(Result("operator"));
1980 /// \brief If the given declaration has an associated type, add it as a result
1982 static void AddResultTypeChunk(ASTContext &Context,
1983 const PrintingPolicy &Policy,
1985 CodeCompletionBuilder &Result) {
1989 // Skip constructors and conversion functions, which have their return types
1990 // built into their names.
1991 if (isa<CXXConstructorDecl>(ND) || isa<CXXConversionDecl>(ND))
1994 // Determine the type of the declaration (if it has a type).
1996 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND))
1997 T = Function->getResultType();
1998 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND))
1999 T = Method->getResultType();
2000 else if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND))
2001 T = FunTmpl->getTemplatedDecl()->getResultType();
2002 else if (EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND))
2003 T = Context.getTypeDeclType(cast<TypeDecl>(Enumerator->getDeclContext()));
2004 else if (isa<UnresolvedUsingValueDecl>(ND)) {
2005 /* Do nothing: ignore unresolved using declarations*/
2006 } else if (ValueDecl *Value = dyn_cast<ValueDecl>(ND)) {
2007 T = Value->getType();
2008 } else if (ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND))
2009 T = Property->getType();
2011 if (T.isNull() || Context.hasSameType(T, Context.DependentTy))
2014 Result.AddResultTypeChunk(GetCompletionTypeString(T, Context, Policy,
2015 Result.getAllocator()));
2018 static void MaybeAddSentinel(ASTContext &Context, NamedDecl *FunctionOrMethod,
2019 CodeCompletionBuilder &Result) {
2020 if (SentinelAttr *Sentinel = FunctionOrMethod->getAttr<SentinelAttr>())
2021 if (Sentinel->getSentinel() == 0) {
2022 if (Context.getLangOpts().ObjC1 &&
2023 Context.Idents.get("nil").hasMacroDefinition())
2024 Result.AddTextChunk(", nil");
2025 else if (Context.Idents.get("NULL").hasMacroDefinition())
2026 Result.AddTextChunk(", NULL");
2028 Result.AddTextChunk(", (void*)0");
2032 static std::string formatObjCParamQualifiers(unsigned ObjCQuals) {
2034 if (ObjCQuals & Decl::OBJC_TQ_In)
2036 else if (ObjCQuals & Decl::OBJC_TQ_Inout)
2038 else if (ObjCQuals & Decl::OBJC_TQ_Out)
2040 if (ObjCQuals & Decl::OBJC_TQ_Bycopy)
2041 Result += "bycopy ";
2042 else if (ObjCQuals & Decl::OBJC_TQ_Byref)
2044 if (ObjCQuals & Decl::OBJC_TQ_Oneway)
2045 Result += "oneway ";
2049 static std::string FormatFunctionParameter(ASTContext &Context,
2050 const PrintingPolicy &Policy,
2052 bool SuppressName = false,
2053 bool SuppressBlock = false) {
2054 bool ObjCMethodParam = isa<ObjCMethodDecl>(Param->getDeclContext());
2055 if (Param->getType()->isDependentType() ||
2056 !Param->getType()->isBlockPointerType()) {
2057 // The argument for a dependent or non-block parameter is a placeholder
2058 // containing that parameter's type.
2061 if (Param->getIdentifier() && !ObjCMethodParam && !SuppressName)
2062 Result = Param->getIdentifier()->getName();
2064 Param->getType().getAsStringInternal(Result, Policy);
2066 if (ObjCMethodParam) {
2067 Result = "(" + formatObjCParamQualifiers(Param->getObjCDeclQualifier())
2069 if (Param->getIdentifier() && !SuppressName)
2070 Result += Param->getIdentifier()->getName();
2075 // The argument for a block pointer parameter is a block literal with
2076 // the appropriate type.
2077 FunctionTypeLoc *Block = 0;
2078 FunctionProtoTypeLoc *BlockProto = 0;
2080 if (TypeSourceInfo *TSInfo = Param->getTypeSourceInfo()) {
2081 TL = TSInfo->getTypeLoc().getUnqualifiedLoc();
2083 // Look through typedefs.
2084 if (!SuppressBlock) {
2085 if (TypedefTypeLoc *TypedefTL = dyn_cast<TypedefTypeLoc>(&TL)) {
2086 if (TypeSourceInfo *InnerTSInfo
2087 = TypedefTL->getTypedefNameDecl()->getTypeSourceInfo()) {
2088 TL = InnerTSInfo->getTypeLoc().getUnqualifiedLoc();
2093 // Look through qualified types
2094 if (QualifiedTypeLoc *QualifiedTL = dyn_cast<QualifiedTypeLoc>(&TL)) {
2095 TL = QualifiedTL->getUnqualifiedLoc();
2100 // Try to get the function prototype behind the block pointer type,
2102 if (BlockPointerTypeLoc *BlockPtr
2103 = dyn_cast<BlockPointerTypeLoc>(&TL)) {
2104 TL = BlockPtr->getPointeeLoc().IgnoreParens();
2105 Block = dyn_cast<FunctionTypeLoc>(&TL);
2106 BlockProto = dyn_cast<FunctionProtoTypeLoc>(&TL);
2113 // We were unable to find a FunctionProtoTypeLoc with parameter names
2114 // for the block; just use the parameter type as a placeholder.
2116 if (!ObjCMethodParam && Param->getIdentifier())
2117 Result = Param->getIdentifier()->getName();
2119 Param->getType().getUnqualifiedType().getAsStringInternal(Result, Policy);
2121 if (ObjCMethodParam) {
2122 Result = "(" + formatObjCParamQualifiers(Param->getObjCDeclQualifier())
2124 if (Param->getIdentifier())
2125 Result += Param->getIdentifier()->getName();
2131 // We have the function prototype behind the block pointer type, as it was
2132 // written in the source.
2134 QualType ResultType = Block->getTypePtr()->getResultType();
2135 if (!ResultType->isVoidType() || SuppressBlock)
2136 ResultType.getAsStringInternal(Result, Policy);
2138 // Format the parameter list.
2140 if (!BlockProto || Block->getNumArgs() == 0) {
2141 if (BlockProto && BlockProto->getTypePtr()->isVariadic())
2147 for (unsigned I = 0, N = Block->getNumArgs(); I != N; ++I) {
2150 Params += FormatFunctionParameter(Context, Policy, Block->getArg(I),
2151 /*SuppressName=*/false,
2152 /*SuppressBlock=*/true);
2154 if (I == N - 1 && BlockProto->getTypePtr()->isVariadic())
2160 if (SuppressBlock) {
2161 // Format as a parameter.
2162 Result = Result + " (^";
2163 if (Param->getIdentifier())
2164 Result += Param->getIdentifier()->getName();
2168 // Format as a block literal argument.
2169 Result = '^' + Result;
2172 if (Param->getIdentifier())
2173 Result += Param->getIdentifier()->getName();
2179 /// \brief Add function parameter chunks to the given code completion string.
2180 static void AddFunctionParameterChunks(ASTContext &Context,
2181 const PrintingPolicy &Policy,
2182 FunctionDecl *Function,
2183 CodeCompletionBuilder &Result,
2185 bool InOptional = false) {
2186 bool FirstParameter = true;
2188 for (unsigned P = Start, N = Function->getNumParams(); P != N; ++P) {
2189 ParmVarDecl *Param = Function->getParamDecl(P);
2191 if (Param->hasDefaultArg() && !InOptional) {
2192 // When we see an optional default argument, put that argument and
2193 // the remaining default arguments into a new, optional string.
2194 CodeCompletionBuilder Opt(Result.getAllocator(),
2195 Result.getCodeCompletionTUInfo());
2196 if (!FirstParameter)
2197 Opt.AddChunk(CodeCompletionString::CK_Comma);
2198 AddFunctionParameterChunks(Context, Policy, Function, Opt, P, true);
2199 Result.AddOptionalChunk(Opt.TakeString());
2204 FirstParameter = false;
2206 Result.AddChunk(CodeCompletionString::CK_Comma);
2210 // Format the placeholder string.
2211 std::string PlaceholderStr = FormatFunctionParameter(Context, Policy,
2214 if (Function->isVariadic() && P == N - 1)
2215 PlaceholderStr += ", ...";
2217 // Add the placeholder string.
2218 Result.AddPlaceholderChunk(
2219 Result.getAllocator().CopyString(PlaceholderStr));
2222 if (const FunctionProtoType *Proto
2223 = Function->getType()->getAs<FunctionProtoType>())
2224 if (Proto->isVariadic()) {
2225 if (Proto->getNumArgs() == 0)
2226 Result.AddPlaceholderChunk("...");
2228 MaybeAddSentinel(Context, Function, Result);
2232 /// \brief Add template parameter chunks to the given code completion string.
2233 static void AddTemplateParameterChunks(ASTContext &Context,
2234 const PrintingPolicy &Policy,
2235 TemplateDecl *Template,
2236 CodeCompletionBuilder &Result,
2237 unsigned MaxParameters = 0,
2239 bool InDefaultArg = false) {
2240 bool FirstParameter = true;
2242 TemplateParameterList *Params = Template->getTemplateParameters();
2243 TemplateParameterList::iterator PEnd = Params->end();
2245 PEnd = Params->begin() + MaxParameters;
2246 for (TemplateParameterList::iterator P = Params->begin() + Start;
2248 bool HasDefaultArg = false;
2249 std::string PlaceholderStr;
2250 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
2251 if (TTP->wasDeclaredWithTypename())
2252 PlaceholderStr = "typename";
2254 PlaceholderStr = "class";
2256 if (TTP->getIdentifier()) {
2257 PlaceholderStr += ' ';
2258 PlaceholderStr += TTP->getIdentifier()->getName();
2261 HasDefaultArg = TTP->hasDefaultArgument();
2262 } else if (NonTypeTemplateParmDecl *NTTP
2263 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
2264 if (NTTP->getIdentifier())
2265 PlaceholderStr = NTTP->getIdentifier()->getName();
2266 NTTP->getType().getAsStringInternal(PlaceholderStr, Policy);
2267 HasDefaultArg = NTTP->hasDefaultArgument();
2269 assert(isa<TemplateTemplateParmDecl>(*P));
2270 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
2272 // Since putting the template argument list into the placeholder would
2273 // be very, very long, we just use an abbreviation.
2274 PlaceholderStr = "template<...> class";
2275 if (TTP->getIdentifier()) {
2276 PlaceholderStr += ' ';
2277 PlaceholderStr += TTP->getIdentifier()->getName();
2280 HasDefaultArg = TTP->hasDefaultArgument();
2283 if (HasDefaultArg && !InDefaultArg) {
2284 // When we see an optional default argument, put that argument and
2285 // the remaining default arguments into a new, optional string.
2286 CodeCompletionBuilder Opt(Result.getAllocator(),
2287 Result.getCodeCompletionTUInfo());
2288 if (!FirstParameter)
2289 Opt.AddChunk(CodeCompletionString::CK_Comma);
2290 AddTemplateParameterChunks(Context, Policy, Template, Opt, MaxParameters,
2291 P - Params->begin(), true);
2292 Result.AddOptionalChunk(Opt.TakeString());
2296 InDefaultArg = false;
2299 FirstParameter = false;
2301 Result.AddChunk(CodeCompletionString::CK_Comma);
2303 // Add the placeholder string.
2304 Result.AddPlaceholderChunk(
2305 Result.getAllocator().CopyString(PlaceholderStr));
2309 /// \brief Add a qualifier to the given code-completion string, if the
2310 /// provided nested-name-specifier is non-NULL.
2312 AddQualifierToCompletionString(CodeCompletionBuilder &Result,
2313 NestedNameSpecifier *Qualifier,
2314 bool QualifierIsInformative,
2315 ASTContext &Context,
2316 const PrintingPolicy &Policy) {
2320 std::string PrintedNNS;
2322 llvm::raw_string_ostream OS(PrintedNNS);
2323 Qualifier->print(OS, Policy);
2325 if (QualifierIsInformative)
2326 Result.AddInformativeChunk(Result.getAllocator().CopyString(PrintedNNS));
2328 Result.AddTextChunk(Result.getAllocator().CopyString(PrintedNNS));
2332 AddFunctionTypeQualsToCompletionString(CodeCompletionBuilder &Result,
2333 FunctionDecl *Function) {
2334 const FunctionProtoType *Proto
2335 = Function->getType()->getAs<FunctionProtoType>();
2336 if (!Proto || !Proto->getTypeQuals())
2339 // FIXME: Add ref-qualifier!
2341 // Handle single qualifiers without copying
2342 if (Proto->getTypeQuals() == Qualifiers::Const) {
2343 Result.AddInformativeChunk(" const");
2347 if (Proto->getTypeQuals() == Qualifiers::Volatile) {
2348 Result.AddInformativeChunk(" volatile");
2352 if (Proto->getTypeQuals() == Qualifiers::Restrict) {
2353 Result.AddInformativeChunk(" restrict");
2357 // Handle multiple qualifiers.
2358 std::string QualsStr;
2359 if (Proto->getTypeQuals() & Qualifiers::Const)
2360 QualsStr += " const";
2361 if (Proto->getTypeQuals() & Qualifiers::Volatile)
2362 QualsStr += " volatile";
2363 if (Proto->getTypeQuals() & Qualifiers::Restrict)
2364 QualsStr += " restrict";
2365 Result.AddInformativeChunk(Result.getAllocator().CopyString(QualsStr));
2368 /// \brief Add the name of the given declaration
2369 static void AddTypedNameChunk(ASTContext &Context, const PrintingPolicy &Policy,
2370 NamedDecl *ND, CodeCompletionBuilder &Result) {
2371 DeclarationName Name = ND->getDeclName();
2375 switch (Name.getNameKind()) {
2376 case DeclarationName::CXXOperatorName: {
2377 const char *OperatorName = 0;
2378 switch (Name.getCXXOverloadedOperator()) {
2380 case OO_Conditional:
2381 case NUM_OVERLOADED_OPERATORS:
2382 OperatorName = "operator";
2385 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2386 case OO_##Name: OperatorName = "operator" Spelling; break;
2387 #define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
2388 #include "clang/Basic/OperatorKinds.def"
2390 case OO_New: OperatorName = "operator new"; break;
2391 case OO_Delete: OperatorName = "operator delete"; break;
2392 case OO_Array_New: OperatorName = "operator new[]"; break;
2393 case OO_Array_Delete: OperatorName = "operator delete[]"; break;
2394 case OO_Call: OperatorName = "operator()"; break;
2395 case OO_Subscript: OperatorName = "operator[]"; break;
2397 Result.AddTypedTextChunk(OperatorName);
2401 case DeclarationName::Identifier:
2402 case DeclarationName::CXXConversionFunctionName:
2403 case DeclarationName::CXXDestructorName:
2404 case DeclarationName::CXXLiteralOperatorName:
2405 Result.AddTypedTextChunk(
2406 Result.getAllocator().CopyString(ND->getNameAsString()));
2409 case DeclarationName::CXXUsingDirective:
2410 case DeclarationName::ObjCZeroArgSelector:
2411 case DeclarationName::ObjCOneArgSelector:
2412 case DeclarationName::ObjCMultiArgSelector:
2415 case DeclarationName::CXXConstructorName: {
2416 CXXRecordDecl *Record = 0;
2417 QualType Ty = Name.getCXXNameType();
2418 if (const RecordType *RecordTy = Ty->getAs<RecordType>())
2419 Record = cast<CXXRecordDecl>(RecordTy->getDecl());
2420 else if (const InjectedClassNameType *InjectedTy
2421 = Ty->getAs<InjectedClassNameType>())
2422 Record = InjectedTy->getDecl();
2424 Result.AddTypedTextChunk(
2425 Result.getAllocator().CopyString(ND->getNameAsString()));
2429 Result.AddTypedTextChunk(
2430 Result.getAllocator().CopyString(Record->getNameAsString()));
2431 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) {
2432 Result.AddChunk(CodeCompletionString::CK_LeftAngle);
2433 AddTemplateParameterChunks(Context, Policy, Template, Result);
2434 Result.AddChunk(CodeCompletionString::CK_RightAngle);
2441 CodeCompletionString *CodeCompletionResult::CreateCodeCompletionString(Sema &S,
2442 CodeCompletionAllocator &Allocator,
2443 CodeCompletionTUInfo &CCTUInfo) {
2444 return CreateCodeCompletionString(S.Context, S.PP, Allocator, CCTUInfo);
2447 /// \brief If possible, create a new code completion string for the given
2450 /// \returns Either a new, heap-allocated code completion string describing
2451 /// how to use this result, or NULL to indicate that the string or name of the
2452 /// result is all that is needed.
2453 CodeCompletionString *
2454 CodeCompletionResult::CreateCodeCompletionString(ASTContext &Ctx,
2456 CodeCompletionAllocator &Allocator,
2457 CodeCompletionTUInfo &CCTUInfo) {
2458 CodeCompletionBuilder Result(Allocator, CCTUInfo, Priority, Availability);
2460 PrintingPolicy Policy = getCompletionPrintingPolicy(Ctx, PP);
2461 if (Kind == RK_Pattern) {
2462 Pattern->Priority = Priority;
2463 Pattern->Availability = Availability;
2466 Result.addParentContext(Declaration->getDeclContext());
2467 Pattern->ParentKind = Result.getParentKind();
2468 Pattern->ParentName = Result.getParentName();
2474 if (Kind == RK_Keyword) {
2475 Result.AddTypedTextChunk(Keyword);
2476 return Result.TakeString();
2479 if (Kind == RK_Macro) {
2480 MacroInfo *MI = PP.getMacroInfo(Macro);
2481 assert(MI && "Not a macro?");
2483 Result.AddTypedTextChunk(
2484 Result.getAllocator().CopyString(Macro->getName()));
2486 if (!MI->isFunctionLike())
2487 return Result.TakeString();
2489 // Format a function-like macro with placeholders for the arguments.
2490 Result.AddChunk(CodeCompletionString::CK_LeftParen);
2491 MacroInfo::arg_iterator A = MI->arg_begin(), AEnd = MI->arg_end();
2493 // C99 variadic macros add __VA_ARGS__ at the end. Skip it.
2494 if (MI->isC99Varargs()) {
2498 Result.AddPlaceholderChunk("...");
2502 for (MacroInfo::arg_iterator A = MI->arg_begin(); A != AEnd; ++A) {
2503 if (A != MI->arg_begin())
2504 Result.AddChunk(CodeCompletionString::CK_Comma);
2506 if (MI->isVariadic() && (A+1) == AEnd) {
2507 SmallString<32> Arg = (*A)->getName();
2508 if (MI->isC99Varargs())
2512 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
2516 // Non-variadic macros are simple.
2517 Result.AddPlaceholderChunk(
2518 Result.getAllocator().CopyString((*A)->getName()));
2520 Result.AddChunk(CodeCompletionString::CK_RightParen);
2521 return Result.TakeString();
2524 assert(Kind == RK_Declaration && "Missed a result kind?");
2525 NamedDecl *ND = Declaration;
2526 Result.addParentContext(ND->getDeclContext());
2528 if (StartsNestedNameSpecifier) {
2529 Result.AddTypedTextChunk(
2530 Result.getAllocator().CopyString(ND->getNameAsString()));
2531 Result.AddTextChunk("::");
2532 return Result.TakeString();
2535 for (Decl::attr_iterator i = ND->attr_begin(); i != ND->attr_end(); ++i) {
2536 if (AnnotateAttr *Attr = dyn_cast_or_null<AnnotateAttr>(*i)) {
2537 Result.AddAnnotation(Result.getAllocator().CopyString(Attr->getAnnotation()));
2541 AddResultTypeChunk(Ctx, Policy, ND, Result);
2543 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND)) {
2544 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2546 AddTypedNameChunk(Ctx, Policy, ND, Result);
2547 Result.AddChunk(CodeCompletionString::CK_LeftParen);
2548 AddFunctionParameterChunks(Ctx, Policy, Function, Result);
2549 Result.AddChunk(CodeCompletionString::CK_RightParen);
2550 AddFunctionTypeQualsToCompletionString(Result, Function);
2551 return Result.TakeString();
2554 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND)) {
2555 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2557 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
2558 AddTypedNameChunk(Ctx, Policy, Function, Result);
2560 // Figure out which template parameters are deduced (or have default
2562 llvm::SmallBitVector Deduced;
2563 Sema::MarkDeducedTemplateParameters(Ctx, FunTmpl, Deduced);
2564 unsigned LastDeducibleArgument;
2565 for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0;
2566 --LastDeducibleArgument) {
2567 if (!Deduced[LastDeducibleArgument - 1]) {
2568 // C++0x: Figure out if the template argument has a default. If so,
2569 // the user doesn't need to type this argument.
2570 // FIXME: We need to abstract template parameters better!
2571 bool HasDefaultArg = false;
2572 NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam(
2573 LastDeducibleArgument - 1);
2574 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2575 HasDefaultArg = TTP->hasDefaultArgument();
2576 else if (NonTypeTemplateParmDecl *NTTP
2577 = dyn_cast<NonTypeTemplateParmDecl>(Param))
2578 HasDefaultArg = NTTP->hasDefaultArgument();
2580 assert(isa<TemplateTemplateParmDecl>(Param));
2582 = cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument();
2590 if (LastDeducibleArgument) {
2591 // Some of the function template arguments cannot be deduced from a
2592 // function call, so we introduce an explicit template argument list
2593 // containing all of the arguments up to the first deducible argument.
2594 Result.AddChunk(CodeCompletionString::CK_LeftAngle);
2595 AddTemplateParameterChunks(Ctx, Policy, FunTmpl, Result,
2596 LastDeducibleArgument);
2597 Result.AddChunk(CodeCompletionString::CK_RightAngle);
2600 // Add the function parameters
2601 Result.AddChunk(CodeCompletionString::CK_LeftParen);
2602 AddFunctionParameterChunks(Ctx, Policy, Function, Result);
2603 Result.AddChunk(CodeCompletionString::CK_RightParen);
2604 AddFunctionTypeQualsToCompletionString(Result, Function);
2605 return Result.TakeString();
2608 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(ND)) {
2609 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2611 Result.AddTypedTextChunk(
2612 Result.getAllocator().CopyString(Template->getNameAsString()));
2613 Result.AddChunk(CodeCompletionString::CK_LeftAngle);
2614 AddTemplateParameterChunks(Ctx, Policy, Template, Result);
2615 Result.AddChunk(CodeCompletionString::CK_RightAngle);
2616 return Result.TakeString();
2619 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND)) {
2620 Selector Sel = Method->getSelector();
2621 if (Sel.isUnarySelector()) {
2622 Result.AddTypedTextChunk(Result.getAllocator().CopyString(
2623 Sel.getNameForSlot(0)));
2624 return Result.TakeString();
2627 std::string SelName = Sel.getNameForSlot(0).str();
2629 if (StartParameter == 0)
2630 Result.AddTypedTextChunk(Result.getAllocator().CopyString(SelName));
2632 Result.AddInformativeChunk(Result.getAllocator().CopyString(SelName));
2634 // If there is only one parameter, and we're past it, add an empty
2635 // typed-text chunk since there is nothing to type.
2636 if (Method->param_size() == 1)
2637 Result.AddTypedTextChunk("");
2640 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
2641 PEnd = Method->param_end();
2642 P != PEnd; (void)++P, ++Idx) {
2644 std::string Keyword;
2645 if (Idx > StartParameter)
2646 Result.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2647 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(Idx))
2648 Keyword += II->getName();
2650 if (Idx < StartParameter || AllParametersAreInformative)
2651 Result.AddInformativeChunk(Result.getAllocator().CopyString(Keyword));
2653 Result.AddTypedTextChunk(Result.getAllocator().CopyString(Keyword));
2656 // If we're before the starting parameter, skip the placeholder.
2657 if (Idx < StartParameter)
2662 if ((*P)->getType()->isBlockPointerType() && !DeclaringEntity)
2663 Arg = FormatFunctionParameter(Ctx, Policy, *P, true);
2665 (*P)->getType().getAsStringInternal(Arg, Policy);
2666 Arg = "(" + formatObjCParamQualifiers((*P)->getObjCDeclQualifier())
2668 if (IdentifierInfo *II = (*P)->getIdentifier())
2669 if (DeclaringEntity || AllParametersAreInformative)
2670 Arg += II->getName();
2673 if (Method->isVariadic() && (P + 1) == PEnd)
2676 if (DeclaringEntity)
2677 Result.AddTextChunk(Result.getAllocator().CopyString(Arg));
2678 else if (AllParametersAreInformative)
2679 Result.AddInformativeChunk(Result.getAllocator().CopyString(Arg));
2681 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
2684 if (Method->isVariadic()) {
2685 if (Method->param_size() == 0) {
2686 if (DeclaringEntity)
2687 Result.AddTextChunk(", ...");
2688 else if (AllParametersAreInformative)
2689 Result.AddInformativeChunk(", ...");
2691 Result.AddPlaceholderChunk(", ...");
2694 MaybeAddSentinel(Ctx, Method, Result);
2697 return Result.TakeString();
2701 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2704 Result.AddTypedTextChunk(
2705 Result.getAllocator().CopyString(ND->getNameAsString()));
2706 return Result.TakeString();
2709 CodeCompletionString *
2710 CodeCompleteConsumer::OverloadCandidate::CreateSignatureString(
2711 unsigned CurrentArg,
2713 CodeCompletionAllocator &Allocator,
2714 CodeCompletionTUInfo &CCTUInfo) const {
2715 PrintingPolicy Policy = getCompletionPrintingPolicy(S);
2717 // FIXME: Set priority, availability appropriately.
2718 CodeCompletionBuilder Result(Allocator,CCTUInfo, 1, CXAvailability_Available);
2719 FunctionDecl *FDecl = getFunction();
2720 AddResultTypeChunk(S.Context, Policy, FDecl, Result);
2721 const FunctionProtoType *Proto
2722 = dyn_cast<FunctionProtoType>(getFunctionType());
2723 if (!FDecl && !Proto) {
2724 // Function without a prototype. Just give the return type and a
2725 // highlighted ellipsis.
2726 const FunctionType *FT = getFunctionType();
2727 Result.AddTextChunk(GetCompletionTypeString(FT->getResultType(),
2729 Result.getAllocator()));
2730 Result.AddChunk(CodeCompletionString::CK_LeftParen);
2731 Result.AddChunk(CodeCompletionString::CK_CurrentParameter, "...");
2732 Result.AddChunk(CodeCompletionString::CK_RightParen);
2733 return Result.TakeString();
2737 Result.AddTextChunk(
2738 Result.getAllocator().CopyString(FDecl->getNameAsString()));
2740 Result.AddTextChunk(
2741 Result.getAllocator().CopyString(
2742 Proto->getResultType().getAsString(Policy)));
2744 Result.AddChunk(CodeCompletionString::CK_LeftParen);
2745 unsigned NumParams = FDecl? FDecl->getNumParams() : Proto->getNumArgs();
2746 for (unsigned I = 0; I != NumParams; ++I) {
2748 Result.AddChunk(CodeCompletionString::CK_Comma);
2750 std::string ArgString;
2754 ArgString = FDecl->getParamDecl(I)->getNameAsString();
2755 ArgType = FDecl->getParamDecl(I)->getOriginalType();
2757 ArgType = Proto->getArgType(I);
2760 ArgType.getAsStringInternal(ArgString, Policy);
2762 if (I == CurrentArg)
2763 Result.AddChunk(CodeCompletionString::CK_CurrentParameter,
2764 Result.getAllocator().CopyString(ArgString));
2766 Result.AddTextChunk(Result.getAllocator().CopyString(ArgString));
2769 if (Proto && Proto->isVariadic()) {
2770 Result.AddChunk(CodeCompletionString::CK_Comma);
2771 if (CurrentArg < NumParams)
2772 Result.AddTextChunk("...");
2774 Result.AddChunk(CodeCompletionString::CK_CurrentParameter, "...");
2776 Result.AddChunk(CodeCompletionString::CK_RightParen);
2778 return Result.TakeString();
2781 unsigned clang::getMacroUsagePriority(StringRef MacroName,
2782 const LangOptions &LangOpts,
2783 bool PreferredTypeIsPointer) {
2784 unsigned Priority = CCP_Macro;
2786 // Treat the "nil", "Nil" and "NULL" macros as null pointer constants.
2787 if (MacroName.equals("nil") || MacroName.equals("NULL") ||
2788 MacroName.equals("Nil")) {
2789 Priority = CCP_Constant;
2790 if (PreferredTypeIsPointer)
2791 Priority = Priority / CCF_SimilarTypeMatch;
2793 // Treat "YES", "NO", "true", and "false" as constants.
2794 else if (MacroName.equals("YES") || MacroName.equals("NO") ||
2795 MacroName.equals("true") || MacroName.equals("false"))
2796 Priority = CCP_Constant;
2797 // Treat "bool" as a type.
2798 else if (MacroName.equals("bool"))
2799 Priority = CCP_Type + (LangOpts.ObjC1? CCD_bool_in_ObjC : 0);
2805 CXCursorKind clang::getCursorKindForDecl(Decl *D) {
2807 return CXCursor_UnexposedDecl;
2809 switch (D->getKind()) {
2810 case Decl::Enum: return CXCursor_EnumDecl;
2811 case Decl::EnumConstant: return CXCursor_EnumConstantDecl;
2812 case Decl::Field: return CXCursor_FieldDecl;
2813 case Decl::Function:
2814 return CXCursor_FunctionDecl;
2815 case Decl::ObjCCategory: return CXCursor_ObjCCategoryDecl;
2816 case Decl::ObjCCategoryImpl: return CXCursor_ObjCCategoryImplDecl;
2817 case Decl::ObjCImplementation: return CXCursor_ObjCImplementationDecl;
2819 case Decl::ObjCInterface: return CXCursor_ObjCInterfaceDecl;
2820 case Decl::ObjCIvar: return CXCursor_ObjCIvarDecl;
2821 case Decl::ObjCMethod:
2822 return cast<ObjCMethodDecl>(D)->isInstanceMethod()
2823 ? CXCursor_ObjCInstanceMethodDecl : CXCursor_ObjCClassMethodDecl;
2824 case Decl::CXXMethod: return CXCursor_CXXMethod;
2825 case Decl::CXXConstructor: return CXCursor_Constructor;
2826 case Decl::CXXDestructor: return CXCursor_Destructor;
2827 case Decl::CXXConversion: return CXCursor_ConversionFunction;
2828 case Decl::ObjCProperty: return CXCursor_ObjCPropertyDecl;
2829 case Decl::ObjCProtocol: return CXCursor_ObjCProtocolDecl;
2830 case Decl::ParmVar: return CXCursor_ParmDecl;
2831 case Decl::Typedef: return CXCursor_TypedefDecl;
2832 case Decl::TypeAlias: return CXCursor_TypeAliasDecl;
2833 case Decl::Var: return CXCursor_VarDecl;
2834 case Decl::Namespace: return CXCursor_Namespace;
2835 case Decl::NamespaceAlias: return CXCursor_NamespaceAlias;
2836 case Decl::TemplateTypeParm: return CXCursor_TemplateTypeParameter;
2837 case Decl::NonTypeTemplateParm:return CXCursor_NonTypeTemplateParameter;
2838 case Decl::TemplateTemplateParm:return CXCursor_TemplateTemplateParameter;
2839 case Decl::FunctionTemplate: return CXCursor_FunctionTemplate;
2840 case Decl::ClassTemplate: return CXCursor_ClassTemplate;
2841 case Decl::AccessSpec: return CXCursor_CXXAccessSpecifier;
2842 case Decl::ClassTemplatePartialSpecialization:
2843 return CXCursor_ClassTemplatePartialSpecialization;
2844 case Decl::UsingDirective: return CXCursor_UsingDirective;
2847 case Decl::UnresolvedUsingValue:
2848 case Decl::UnresolvedUsingTypename:
2849 return CXCursor_UsingDeclaration;
2851 case Decl::ObjCPropertyImpl:
2852 switch (cast<ObjCPropertyImplDecl>(D)->getPropertyImplementation()) {
2853 case ObjCPropertyImplDecl::Dynamic:
2854 return CXCursor_ObjCDynamicDecl;
2856 case ObjCPropertyImplDecl::Synthesize:
2857 return CXCursor_ObjCSynthesizeDecl;
2861 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
2862 switch (TD->getTagKind()) {
2863 case TTK_Struct: return CXCursor_StructDecl;
2864 case TTK_Class: return CXCursor_ClassDecl;
2865 case TTK_Union: return CXCursor_UnionDecl;
2866 case TTK_Enum: return CXCursor_EnumDecl;
2871 return CXCursor_UnexposedDecl;
2874 static void AddMacroResults(Preprocessor &PP, ResultBuilder &Results,
2875 bool TargetTypeIsPointer = false) {
2876 typedef CodeCompletionResult Result;
2878 Results.EnterNewScope();
2880 for (Preprocessor::macro_iterator M = PP.macro_begin(),
2881 MEnd = PP.macro_end();
2883 Results.AddResult(Result(M->first,
2884 getMacroUsagePriority(M->first->getName(),
2886 TargetTypeIsPointer)));
2889 Results.ExitScope();
2893 static void AddPrettyFunctionResults(const LangOptions &LangOpts,
2894 ResultBuilder &Results) {
2895 typedef CodeCompletionResult Result;
2897 Results.EnterNewScope();
2899 Results.AddResult(Result("__PRETTY_FUNCTION__", CCP_Constant));
2900 Results.AddResult(Result("__FUNCTION__", CCP_Constant));
2901 if (LangOpts.C99 || LangOpts.CPlusPlus0x)
2902 Results.AddResult(Result("__func__", CCP_Constant));
2903 Results.ExitScope();
2906 static void HandleCodeCompleteResults(Sema *S,
2907 CodeCompleteConsumer *CodeCompleter,
2908 CodeCompletionContext Context,
2909 CodeCompletionResult *Results,
2910 unsigned NumResults) {
2912 CodeCompleter->ProcessCodeCompleteResults(*S, Context, Results, NumResults);
2915 static enum CodeCompletionContext::Kind mapCodeCompletionContext(Sema &S,
2916 Sema::ParserCompletionContext PCC) {
2918 case Sema::PCC_Namespace:
2919 return CodeCompletionContext::CCC_TopLevel;
2921 case Sema::PCC_Class:
2922 return CodeCompletionContext::CCC_ClassStructUnion;
2924 case Sema::PCC_ObjCInterface:
2925 return CodeCompletionContext::CCC_ObjCInterface;
2927 case Sema::PCC_ObjCImplementation:
2928 return CodeCompletionContext::CCC_ObjCImplementation;
2930 case Sema::PCC_ObjCInstanceVariableList:
2931 return CodeCompletionContext::CCC_ObjCIvarList;
2933 case Sema::PCC_Template:
2934 case Sema::PCC_MemberTemplate:
2935 if (S.CurContext->isFileContext())
2936 return CodeCompletionContext::CCC_TopLevel;
2937 if (S.CurContext->isRecord())
2938 return CodeCompletionContext::CCC_ClassStructUnion;
2939 return CodeCompletionContext::CCC_Other;
2941 case Sema::PCC_RecoveryInFunction:
2942 return CodeCompletionContext::CCC_Recovery;
2944 case Sema::PCC_ForInit:
2945 if (S.getLangOpts().CPlusPlus || S.getLangOpts().C99 ||
2946 S.getLangOpts().ObjC1)
2947 return CodeCompletionContext::CCC_ParenthesizedExpression;
2949 return CodeCompletionContext::CCC_Expression;
2951 case Sema::PCC_Expression:
2952 case Sema::PCC_Condition:
2953 return CodeCompletionContext::CCC_Expression;
2955 case Sema::PCC_Statement:
2956 return CodeCompletionContext::CCC_Statement;
2958 case Sema::PCC_Type:
2959 return CodeCompletionContext::CCC_Type;
2961 case Sema::PCC_ParenthesizedExpression:
2962 return CodeCompletionContext::CCC_ParenthesizedExpression;
2964 case Sema::PCC_LocalDeclarationSpecifiers:
2965 return CodeCompletionContext::CCC_Type;
2968 llvm_unreachable("Invalid ParserCompletionContext!");
2971 /// \brief If we're in a C++ virtual member function, add completion results
2972 /// that invoke the functions we override, since it's common to invoke the
2973 /// overridden function as well as adding new functionality.
2975 /// \param S The semantic analysis object for which we are generating results.
2977 /// \param InContext This context in which the nested-name-specifier preceding
2978 /// the code-completion point
2979 static void MaybeAddOverrideCalls(Sema &S, DeclContext *InContext,
2980 ResultBuilder &Results) {
2981 // Look through blocks.
2982 DeclContext *CurContext = S.CurContext;
2983 while (isa<BlockDecl>(CurContext))
2984 CurContext = CurContext->getParent();
2987 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(CurContext);
2988 if (!Method || !Method->isVirtual())
2991 // We need to have names for all of the parameters, if we're going to
2992 // generate a forwarding call.
2993 for (CXXMethodDecl::param_iterator P = Method->param_begin(),
2994 PEnd = Method->param_end();
2997 if (!(*P)->getDeclName())
3001 PrintingPolicy Policy = getCompletionPrintingPolicy(S);
3002 for (CXXMethodDecl::method_iterator M = Method->begin_overridden_methods(),
3003 MEnd = Method->end_overridden_methods();
3005 CodeCompletionBuilder Builder(Results.getAllocator(),
3006 Results.getCodeCompletionTUInfo());
3007 CXXMethodDecl *Overridden = const_cast<CXXMethodDecl *>(*M);
3008 if (Overridden->getCanonicalDecl() == Method->getCanonicalDecl())
3011 // If we need a nested-name-specifier, add one now.
3013 NestedNameSpecifier *NNS
3014 = getRequiredQualification(S.Context, CurContext,
3015 Overridden->getDeclContext());
3018 llvm::raw_string_ostream OS(Str);
3019 NNS->print(OS, Policy);
3020 Builder.AddTextChunk(Results.getAllocator().CopyString(OS.str()));
3022 } else if (!InContext->Equals(Overridden->getDeclContext()))
3025 Builder.AddTypedTextChunk(Results.getAllocator().CopyString(
3026 Overridden->getNameAsString()));
3027 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
3028 bool FirstParam = true;
3029 for (CXXMethodDecl::param_iterator P = Method->param_begin(),
3030 PEnd = Method->param_end();
3035 Builder.AddChunk(CodeCompletionString::CK_Comma);
3037 Builder.AddPlaceholderChunk(Results.getAllocator().CopyString(
3038 (*P)->getIdentifier()->getName()));
3040 Builder.AddChunk(CodeCompletionString::CK_RightParen);
3041 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
3042 CCP_SuperCompletion,
3044 CXAvailability_Available,
3046 Results.Ignore(Overridden);
3050 void Sema::CodeCompleteModuleImport(SourceLocation ImportLoc,
3051 ModuleIdPath Path) {
3052 typedef CodeCompletionResult Result;
3053 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3054 CodeCompleter->getCodeCompletionTUInfo(),
3055 CodeCompletionContext::CCC_Other);
3056 Results.EnterNewScope();
3058 CodeCompletionAllocator &Allocator = Results.getAllocator();
3059 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
3060 typedef CodeCompletionResult Result;
3062 // Enumerate all top-level modules.
3063 llvm::SmallVector<Module *, 8> Modules;
3064 PP.getHeaderSearchInfo().collectAllModules(Modules);
3065 for (unsigned I = 0, N = Modules.size(); I != N; ++I) {
3066 Builder.AddTypedTextChunk(
3067 Builder.getAllocator().CopyString(Modules[I]->Name));
3068 Results.AddResult(Result(Builder.TakeString(),
3070 CXCursor_NotImplemented,
3071 Modules[I]->isAvailable()
3072 ? CXAvailability_Available
3073 : CXAvailability_NotAvailable));
3076 // Load the named module.
3077 Module *Mod = PP.getModuleLoader().loadModule(ImportLoc, Path,
3079 /*IsInclusionDirective=*/false);
3080 // Enumerate submodules.
3082 for (Module::submodule_iterator Sub = Mod->submodule_begin(),
3083 SubEnd = Mod->submodule_end();
3084 Sub != SubEnd; ++Sub) {
3086 Builder.AddTypedTextChunk(
3087 Builder.getAllocator().CopyString((*Sub)->Name));
3088 Results.AddResult(Result(Builder.TakeString(),
3090 CXCursor_NotImplemented,
3091 (*Sub)->isAvailable()
3092 ? CXAvailability_Available
3093 : CXAvailability_NotAvailable));
3097 Results.ExitScope();
3098 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
3099 Results.data(),Results.size());
3102 void Sema::CodeCompleteOrdinaryName(Scope *S,
3103 ParserCompletionContext CompletionContext) {
3104 typedef CodeCompletionResult Result;
3105 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3106 CodeCompleter->getCodeCompletionTUInfo(),
3107 mapCodeCompletionContext(*this, CompletionContext));
3108 Results.EnterNewScope();
3110 // Determine how to filter results, e.g., so that the names of
3111 // values (functions, enumerators, function templates, etc.) are
3112 // only allowed where we can have an expression.
3113 switch (CompletionContext) {
3116 case PCC_ObjCInterface:
3117 case PCC_ObjCImplementation:
3118 case PCC_ObjCInstanceVariableList:
3120 case PCC_MemberTemplate:
3122 case PCC_LocalDeclarationSpecifiers:
3123 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
3127 case PCC_ParenthesizedExpression:
3128 case PCC_Expression:
3131 if (WantTypesInContext(CompletionContext, getLangOpts()))
3132 Results.setFilter(&ResultBuilder::IsOrdinaryName);
3134 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
3136 if (getLangOpts().CPlusPlus)
3137 MaybeAddOverrideCalls(*this, /*InContext=*/0, Results);
3140 case PCC_RecoveryInFunction:
3145 // If we are in a C++ non-static member function, check the qualifiers on
3146 // the member function to filter/prioritize the results list.
3147 if (CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext))
3148 if (CurMethod->isInstance())
3149 Results.setObjectTypeQualifiers(
3150 Qualifiers::fromCVRMask(CurMethod->getTypeQualifiers()));
3152 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3153 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3154 CodeCompleter->includeGlobals());
3156 AddOrdinaryNameResults(CompletionContext, S, *this, Results);
3157 Results.ExitScope();
3159 switch (CompletionContext) {
3160 case PCC_ParenthesizedExpression:
3161 case PCC_Expression:
3163 case PCC_RecoveryInFunction:
3164 if (S->getFnParent())
3165 AddPrettyFunctionResults(PP.getLangOpts(), Results);
3170 case PCC_ObjCInterface:
3171 case PCC_ObjCImplementation:
3172 case PCC_ObjCInstanceVariableList:
3174 case PCC_MemberTemplate:
3178 case PCC_LocalDeclarationSpecifiers:
3182 if (CodeCompleter->includeMacros())
3183 AddMacroResults(PP, Results);
3185 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
3186 Results.data(),Results.size());
3189 static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
3190 ParsedType Receiver,
3191 IdentifierInfo **SelIdents,
3192 unsigned NumSelIdents,
3193 bool AtArgumentExpression,
3195 ResultBuilder &Results);
3197 void Sema::CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
3198 bool AllowNonIdentifiers,
3199 bool AllowNestedNameSpecifiers) {
3200 typedef CodeCompletionResult Result;
3201 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3202 CodeCompleter->getCodeCompletionTUInfo(),
3203 AllowNestedNameSpecifiers
3204 ? CodeCompletionContext::CCC_PotentiallyQualifiedName
3205 : CodeCompletionContext::CCC_Name);
3206 Results.EnterNewScope();
3208 // Type qualifiers can come after names.
3209 Results.AddResult(Result("const"));
3210 Results.AddResult(Result("volatile"));
3211 if (getLangOpts().C99)
3212 Results.AddResult(Result("restrict"));
3214 if (getLangOpts().CPlusPlus) {
3215 if (AllowNonIdentifiers) {
3216 Results.AddResult(Result("operator"));
3219 // Add nested-name-specifiers.
3220 if (AllowNestedNameSpecifiers) {
3221 Results.allowNestedNameSpecifiers();
3222 Results.setFilter(&ResultBuilder::IsImpossibleToSatisfy);
3223 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3224 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer,
3225 CodeCompleter->includeGlobals());
3226 Results.setFilter(0);
3229 Results.ExitScope();
3231 // If we're in a context where we might have an expression (rather than a
3232 // declaration), and what we've seen so far is an Objective-C type that could
3233 // be a receiver of a class message, this may be a class message send with
3234 // the initial opening bracket '[' missing. Add appropriate completions.
3235 if (AllowNonIdentifiers && !AllowNestedNameSpecifiers &&
3236 DS.getTypeSpecType() == DeclSpec::TST_typename &&
3237 DS.getStorageClassSpecAsWritten() == DeclSpec::SCS_unspecified &&
3238 !DS.isThreadSpecified() && !DS.isExternInLinkageSpec() &&
3239 DS.getTypeSpecComplex() == DeclSpec::TSC_unspecified &&
3240 DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
3241 DS.getTypeQualifiers() == 0 &&
3243 (S->getFlags() & Scope::DeclScope) != 0 &&
3244 (S->getFlags() & (Scope::ClassScope | Scope::TemplateParamScope |
3245 Scope::FunctionPrototypeScope |
3246 Scope::AtCatchScope)) == 0) {
3247 ParsedType T = DS.getRepAsType();
3248 if (!T.get().isNull() && T.get()->isObjCObjectOrInterfaceType())
3249 AddClassMessageCompletions(*this, S, T, 0, 0, false, false, Results);
3252 // Note that we intentionally suppress macro results here, since we do not
3253 // encourage using macros to produce the names of entities.
3255 HandleCodeCompleteResults(this, CodeCompleter,
3256 Results.getCompletionContext(),
3257 Results.data(), Results.size());
3260 struct Sema::CodeCompleteExpressionData {
3261 CodeCompleteExpressionData(QualType PreferredType = QualType())
3262 : PreferredType(PreferredType), IntegralConstantExpression(false),
3263 ObjCCollection(false) { }
3265 QualType PreferredType;
3266 bool IntegralConstantExpression;
3267 bool ObjCCollection;
3268 SmallVector<Decl *, 4> IgnoreDecls;
3271 /// \brief Perform code-completion in an expression context when we know what
3272 /// type we're looking for.
3274 /// \param IntegralConstantExpression Only permit integral constant
3276 void Sema::CodeCompleteExpression(Scope *S,
3277 const CodeCompleteExpressionData &Data) {
3278 typedef CodeCompletionResult Result;
3279 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3280 CodeCompleter->getCodeCompletionTUInfo(),
3281 CodeCompletionContext::CCC_Expression);
3282 if (Data.ObjCCollection)
3283 Results.setFilter(&ResultBuilder::IsObjCCollection);
3284 else if (Data.IntegralConstantExpression)
3285 Results.setFilter(&ResultBuilder::IsIntegralConstantValue);
3286 else if (WantTypesInContext(PCC_Expression, getLangOpts()))
3287 Results.setFilter(&ResultBuilder::IsOrdinaryName);
3289 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
3291 if (!Data.PreferredType.isNull())
3292 Results.setPreferredType(Data.PreferredType.getNonReferenceType());
3294 // Ignore any declarations that we were told that we don't care about.
3295 for (unsigned I = 0, N = Data.IgnoreDecls.size(); I != N; ++I)
3296 Results.Ignore(Data.IgnoreDecls[I]);
3298 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3299 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3300 CodeCompleter->includeGlobals());
3302 Results.EnterNewScope();
3303 AddOrdinaryNameResults(PCC_Expression, S, *this, Results);
3304 Results.ExitScope();
3306 bool PreferredTypeIsPointer = false;
3307 if (!Data.PreferredType.isNull())
3308 PreferredTypeIsPointer = Data.PreferredType->isAnyPointerType()
3309 || Data.PreferredType->isMemberPointerType()
3310 || Data.PreferredType->isBlockPointerType();
3312 if (S->getFnParent() &&
3313 !Data.ObjCCollection &&
3314 !Data.IntegralConstantExpression)
3315 AddPrettyFunctionResults(PP.getLangOpts(), Results);
3317 if (CodeCompleter->includeMacros())
3318 AddMacroResults(PP, Results, PreferredTypeIsPointer);
3319 HandleCodeCompleteResults(this, CodeCompleter,
3320 CodeCompletionContext(CodeCompletionContext::CCC_Expression,
3321 Data.PreferredType),
3322 Results.data(),Results.size());
3325 void Sema::CodeCompletePostfixExpression(Scope *S, ExprResult E) {
3327 CodeCompleteOrdinaryName(S, PCC_RecoveryInFunction);
3328 else if (getLangOpts().ObjC1)
3329 CodeCompleteObjCInstanceMessage(S, E.take(), 0, 0, false);
3332 /// \brief The set of properties that have already been added, referenced by
3334 typedef llvm::SmallPtrSet<IdentifierInfo*, 16> AddedPropertiesSet;
3336 static void AddObjCProperties(ObjCContainerDecl *Container,
3337 bool AllowCategories,
3338 bool AllowNullaryMethods,
3339 DeclContext *CurContext,
3340 AddedPropertiesSet &AddedProperties,
3341 ResultBuilder &Results) {
3342 typedef CodeCompletionResult Result;
3344 // Add properties in this container.
3345 for (ObjCContainerDecl::prop_iterator P = Container->prop_begin(),
3346 PEnd = Container->prop_end();
3349 if (AddedProperties.insert(P->getIdentifier()))
3350 Results.MaybeAddResult(Result(*P, 0), CurContext);
3353 // Add nullary methods
3354 if (AllowNullaryMethods) {
3355 ASTContext &Context = Container->getASTContext();
3356 PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema());
3357 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
3358 MEnd = Container->meth_end();
3360 if (M->getSelector().isUnarySelector())
3361 if (IdentifierInfo *Name = M->getSelector().getIdentifierInfoForSlot(0))
3362 if (AddedProperties.insert(Name)) {
3363 CodeCompletionBuilder Builder(Results.getAllocator(),
3364 Results.getCodeCompletionTUInfo());
3365 AddResultTypeChunk(Context, Policy, *M, Builder);
3366 Builder.AddTypedTextChunk(
3367 Results.getAllocator().CopyString(Name->getName()));
3369 Results.MaybeAddResult(Result(Builder.TakeString(), *M,
3370 CCP_MemberDeclaration + CCD_MethodAsProperty),
3377 // Add properties in referenced protocols.
3378 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
3379 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
3380 PEnd = Protocol->protocol_end();
3382 AddObjCProperties(*P, AllowCategories, AllowNullaryMethods, CurContext,
3383 AddedProperties, Results);
3384 } else if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)){
3385 if (AllowCategories) {
3386 // Look through categories.
3387 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
3388 Category; Category = Category->getNextClassCategory())
3389 AddObjCProperties(Category, AllowCategories, AllowNullaryMethods,
3390 CurContext, AddedProperties, Results);
3393 // Look through protocols.
3394 for (ObjCInterfaceDecl::all_protocol_iterator
3395 I = IFace->all_referenced_protocol_begin(),
3396 E = IFace->all_referenced_protocol_end(); I != E; ++I)
3397 AddObjCProperties(*I, AllowCategories, AllowNullaryMethods, CurContext,
3398 AddedProperties, Results);
3400 // Look in the superclass.
3401 if (IFace->getSuperClass())
3402 AddObjCProperties(IFace->getSuperClass(), AllowCategories,
3403 AllowNullaryMethods, CurContext,
3404 AddedProperties, Results);
3405 } else if (const ObjCCategoryDecl *Category
3406 = dyn_cast<ObjCCategoryDecl>(Container)) {
3407 // Look through protocols.
3408 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
3409 PEnd = Category->protocol_end();
3411 AddObjCProperties(*P, AllowCategories, AllowNullaryMethods, CurContext,
3412 AddedProperties, Results);
3416 void Sema::CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base,
3417 SourceLocation OpLoc,
3419 if (!Base || !CodeCompleter)
3422 ExprResult ConvertedBase = PerformMemberExprBaseConversion(Base, IsArrow);
3423 if (ConvertedBase.isInvalid())
3425 Base = ConvertedBase.get();
3427 typedef CodeCompletionResult Result;
3429 QualType BaseType = Base->getType();
3432 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
3433 BaseType = Ptr->getPointeeType();
3434 else if (BaseType->isObjCObjectPointerType())
3440 enum CodeCompletionContext::Kind contextKind;
3443 contextKind = CodeCompletionContext::CCC_ArrowMemberAccess;
3446 if (BaseType->isObjCObjectPointerType() ||
3447 BaseType->isObjCObjectOrInterfaceType()) {
3448 contextKind = CodeCompletionContext::CCC_ObjCPropertyAccess;
3451 contextKind = CodeCompletionContext::CCC_DotMemberAccess;
3455 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3456 CodeCompleter->getCodeCompletionTUInfo(),
3457 CodeCompletionContext(contextKind,
3459 &ResultBuilder::IsMember);
3460 Results.EnterNewScope();
3461 if (const RecordType *Record = BaseType->getAs<RecordType>()) {
3462 // Indicate that we are performing a member access, and the cv-qualifiers
3463 // for the base object type.
3464 Results.setObjectTypeQualifiers(BaseType.getQualifiers());
3466 // Access to a C/C++ class, struct, or union.
3467 Results.allowNestedNameSpecifiers();
3468 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3469 LookupVisibleDecls(Record->getDecl(), LookupMemberName, Consumer,
3470 CodeCompleter->includeGlobals());
3472 if (getLangOpts().CPlusPlus) {
3473 if (!Results.empty()) {
3474 // The "template" keyword can follow "->" or "." in the grammar.
3475 // However, we only want to suggest the template keyword if something
3477 bool IsDependent = BaseType->isDependentType();
3479 for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent())
3480 if (DeclContext *Ctx = (DeclContext *)DepScope->getEntity()) {
3481 IsDependent = Ctx->isDependentContext();
3487 Results.AddResult(Result("template"));
3490 } else if (!IsArrow && BaseType->getAsObjCInterfacePointerType()) {
3491 // Objective-C property reference.
3492 AddedPropertiesSet AddedProperties;
3494 // Add property results based on our interface.
3495 const ObjCObjectPointerType *ObjCPtr
3496 = BaseType->getAsObjCInterfacePointerType();
3497 assert(ObjCPtr && "Non-NULL pointer guaranteed above!");
3498 AddObjCProperties(ObjCPtr->getInterfaceDecl(), true,
3499 /*AllowNullaryMethods=*/true, CurContext,
3500 AddedProperties, Results);
3502 // Add properties from the protocols in a qualified interface.
3503 for (ObjCObjectPointerType::qual_iterator I = ObjCPtr->qual_begin(),
3504 E = ObjCPtr->qual_end();
3506 AddObjCProperties(*I, true, /*AllowNullaryMethods=*/true, CurContext,
3507 AddedProperties, Results);
3508 } else if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
3509 (!IsArrow && BaseType->isObjCObjectType())) {
3510 // Objective-C instance variable access.
3511 ObjCInterfaceDecl *Class = 0;
3512 if (const ObjCObjectPointerType *ObjCPtr
3513 = BaseType->getAs<ObjCObjectPointerType>())
3514 Class = ObjCPtr->getInterfaceDecl();
3516 Class = BaseType->getAs<ObjCObjectType>()->getInterface();
3518 // Add all ivars from this class and its superclasses.
3520 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3521 Results.setFilter(&ResultBuilder::IsObjCIvar);
3522 LookupVisibleDecls(Class, LookupMemberName, Consumer,
3523 CodeCompleter->includeGlobals());
3527 // FIXME: How do we cope with isa?
3529 Results.ExitScope();
3531 // Hand off the results found for code completion.
3532 HandleCodeCompleteResults(this, CodeCompleter,
3533 Results.getCompletionContext(),
3534 Results.data(),Results.size());
3537 void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) {
3541 typedef CodeCompletionResult Result;
3542 ResultBuilder::LookupFilter Filter = 0;
3543 enum CodeCompletionContext::Kind ContextKind
3544 = CodeCompletionContext::CCC_Other;
3545 switch ((DeclSpec::TST)TagSpec) {
3546 case DeclSpec::TST_enum:
3547 Filter = &ResultBuilder::IsEnum;
3548 ContextKind = CodeCompletionContext::CCC_EnumTag;
3551 case DeclSpec::TST_union:
3552 Filter = &ResultBuilder::IsUnion;
3553 ContextKind = CodeCompletionContext::CCC_UnionTag;
3556 case DeclSpec::TST_struct:
3557 case DeclSpec::TST_class:
3558 Filter = &ResultBuilder::IsClassOrStruct;
3559 ContextKind = CodeCompletionContext::CCC_ClassOrStructTag;
3563 llvm_unreachable("Unknown type specifier kind in CodeCompleteTag");
3566 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3567 CodeCompleter->getCodeCompletionTUInfo(), ContextKind);
3568 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3570 // First pass: look for tags.
3571 Results.setFilter(Filter);
3572 LookupVisibleDecls(S, LookupTagName, Consumer,
3573 CodeCompleter->includeGlobals());
3575 if (CodeCompleter->includeGlobals()) {
3576 // Second pass: look for nested name specifiers.
3577 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
3578 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer);
3581 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
3582 Results.data(),Results.size());
3585 void Sema::CodeCompleteTypeQualifiers(DeclSpec &DS) {
3586 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3587 CodeCompleter->getCodeCompletionTUInfo(),
3588 CodeCompletionContext::CCC_TypeQualifiers);
3589 Results.EnterNewScope();
3590 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_const))
3591 Results.AddResult("const");
3592 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_volatile))
3593 Results.AddResult("volatile");
3594 if (getLangOpts().C99 &&
3595 !(DS.getTypeQualifiers() & DeclSpec::TQ_restrict))
3596 Results.AddResult("restrict");
3597 Results.ExitScope();
3598 HandleCodeCompleteResults(this, CodeCompleter,
3599 Results.getCompletionContext(),
3600 Results.data(), Results.size());
3603 void Sema::CodeCompleteCase(Scope *S) {
3604 if (getCurFunction()->SwitchStack.empty() || !CodeCompleter)
3607 SwitchStmt *Switch = getCurFunction()->SwitchStack.back();
3608 QualType type = Switch->getCond()->IgnoreImplicit()->getType();
3609 if (!type->isEnumeralType()) {
3610 CodeCompleteExpressionData Data(type);
3611 Data.IntegralConstantExpression = true;
3612 CodeCompleteExpression(S, Data);
3616 // Code-complete the cases of a switch statement over an enumeration type
3617 // by providing the list of
3618 EnumDecl *Enum = type->castAs<EnumType>()->getDecl();
3620 // Determine which enumerators we have already seen in the switch statement.
3621 // FIXME: Ideally, we would also be able to look *past* the code-completion
3622 // token, in case we are code-completing in the middle of the switch and not
3623 // at the end. However, we aren't able to do so at the moment.
3624 llvm::SmallPtrSet<EnumConstantDecl *, 8> EnumeratorsSeen;
3625 NestedNameSpecifier *Qualifier = 0;
3626 for (SwitchCase *SC = Switch->getSwitchCaseList(); SC;
3627 SC = SC->getNextSwitchCase()) {
3628 CaseStmt *Case = dyn_cast<CaseStmt>(SC);
3632 Expr *CaseVal = Case->getLHS()->IgnoreParenCasts();
3633 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseVal))
3634 if (EnumConstantDecl *Enumerator
3635 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
3636 // We look into the AST of the case statement to determine which
3637 // enumerator was named. Alternatively, we could compute the value of
3638 // the integral constant expression, then compare it against the
3639 // values of each enumerator. However, value-based approach would not
3640 // work as well with C++ templates where enumerators declared within a
3641 // template are type- and value-dependent.
3642 EnumeratorsSeen.insert(Enumerator);
3644 // If this is a qualified-id, keep track of the nested-name-specifier
3645 // so that we can reproduce it as part of code completion, e.g.,
3647 // switch (TagD.getKind()) {
3648 // case TagDecl::TK_enum:
3652 // At the XXX, our completions are TagDecl::TK_union,
3653 // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
3654 // TK_struct, and TK_class.
3655 Qualifier = DRE->getQualifier();
3659 if (getLangOpts().CPlusPlus && !Qualifier && EnumeratorsSeen.empty()) {
3660 // If there are no prior enumerators in C++, check whether we have to
3661 // qualify the names of the enumerators that we suggest, because they
3662 // may not be visible in this scope.
3663 Qualifier = getRequiredQualification(Context, CurContext, Enum);
3666 // Add any enumerators that have not yet been mentioned.
3667 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3668 CodeCompleter->getCodeCompletionTUInfo(),
3669 CodeCompletionContext::CCC_Expression);
3670 Results.EnterNewScope();
3671 for (EnumDecl::enumerator_iterator E = Enum->enumerator_begin(),
3672 EEnd = Enum->enumerator_end();
3674 if (EnumeratorsSeen.count(*E))
3677 CodeCompletionResult R(*E, Qualifier);
3678 R.Priority = CCP_EnumInCase;
3679 Results.AddResult(R, CurContext, 0, false);
3681 Results.ExitScope();
3683 //We need to make sure we're setting the right context,
3684 //so only say we include macros if the code completer says we do
3685 enum CodeCompletionContext::Kind kind = CodeCompletionContext::CCC_Other;
3686 if (CodeCompleter->includeMacros()) {
3687 AddMacroResults(PP, Results);
3688 kind = CodeCompletionContext::CCC_OtherWithMacros;
3691 HandleCodeCompleteResults(this, CodeCompleter,
3693 Results.data(),Results.size());
3697 struct IsBetterOverloadCandidate {
3702 explicit IsBetterOverloadCandidate(Sema &S, SourceLocation Loc)
3703 : S(S), Loc(Loc) { }
3706 operator()(const OverloadCandidate &X, const OverloadCandidate &Y) const {
3707 return isBetterOverloadCandidate(S, X, Y, Loc);
3712 static bool anyNullArguments(llvm::ArrayRef<Expr*> Args) {
3713 if (Args.size() && !Args.data())
3716 for (unsigned I = 0; I != Args.size(); ++I)
3723 void Sema::CodeCompleteCall(Scope *S, Expr *FnIn,
3724 llvm::ArrayRef<Expr *> Args) {
3728 // When we're code-completing for a call, we fall back to ordinary
3729 // name code-completion whenever we can't produce specific
3730 // results. We may want to revisit this strategy in the future,
3731 // e.g., by merging the two kinds of results.
3733 Expr *Fn = (Expr *)FnIn;
3735 // Ignore type-dependent call expressions entirely.
3736 if (!Fn || Fn->isTypeDependent() || anyNullArguments(Args) ||
3737 Expr::hasAnyTypeDependentArguments(Args)) {
3738 CodeCompleteOrdinaryName(S, PCC_Expression);
3742 // Build an overload candidate set based on the functions we find.
3743 SourceLocation Loc = Fn->getExprLoc();
3744 OverloadCandidateSet CandidateSet(Loc);
3746 // FIXME: What if we're calling something that isn't a function declaration?
3747 // FIXME: What if we're calling a pseudo-destructor?
3748 // FIXME: What if we're calling a member function?
3750 typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate;
3751 SmallVector<ResultCandidate, 8> Results;
3753 Expr *NakedFn = Fn->IgnoreParenCasts();
3754 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(NakedFn))
3755 AddOverloadedCallCandidates(ULE, Args, CandidateSet,
3756 /*PartialOverloading=*/ true);
3757 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
3758 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl());
3760 if (!getLangOpts().CPlusPlus ||
3761 !FDecl->getType()->getAs<FunctionProtoType>())
3762 Results.push_back(ResultCandidate(FDecl));
3765 AddOverloadCandidate(FDecl, DeclAccessPair::make(FDecl, AS_none), Args,
3766 CandidateSet, false, /*PartialOverloading*/true);
3772 if (!CandidateSet.empty()) {
3773 // Sort the overload candidate set by placing the best overloads first.
3774 std::stable_sort(CandidateSet.begin(), CandidateSet.end(),
3775 IsBetterOverloadCandidate(*this, Loc));
3777 // Add the remaining viable overload candidates as code-completion reslults.
3778 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3779 CandEnd = CandidateSet.end();
3780 Cand != CandEnd; ++Cand) {
3782 Results.push_back(ResultCandidate(Cand->Function));
3785 // From the viable candidates, try to determine the type of this parameter.
3786 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
3787 if (const FunctionType *FType = Results[I].getFunctionType())
3788 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FType))
3789 if (Args.size() < Proto->getNumArgs()) {
3790 if (ParamType.isNull())
3791 ParamType = Proto->getArgType(Args.size());
3792 else if (!Context.hasSameUnqualifiedType(
3793 ParamType.getNonReferenceType(),
3794 Proto->getArgType(Args.size()).getNonReferenceType())) {
3795 ParamType = QualType();
3801 // Try to determine the parameter type from the type of the expression
3803 QualType FunctionType = Fn->getType();
3804 if (const PointerType *Ptr = FunctionType->getAs<PointerType>())
3805 FunctionType = Ptr->getPointeeType();
3806 else if (const BlockPointerType *BlockPtr
3807 = FunctionType->getAs<BlockPointerType>())
3808 FunctionType = BlockPtr->getPointeeType();
3809 else if (const MemberPointerType *MemPtr
3810 = FunctionType->getAs<MemberPointerType>())
3811 FunctionType = MemPtr->getPointeeType();
3813 if (const FunctionProtoType *Proto
3814 = FunctionType->getAs<FunctionProtoType>()) {
3815 if (Args.size() < Proto->getNumArgs())
3816 ParamType = Proto->getArgType(Args.size());
3820 if (ParamType.isNull())
3821 CodeCompleteOrdinaryName(S, PCC_Expression);
3823 CodeCompleteExpression(S, ParamType);
3825 if (!Results.empty())
3826 CodeCompleter->ProcessOverloadCandidates(*this, Args.size(), Results.data(),
3830 void Sema::CodeCompleteInitializer(Scope *S, Decl *D) {
3831 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
3833 CodeCompleteOrdinaryName(S, PCC_Expression);
3837 CodeCompleteExpression(S, VD->getType());
3840 void Sema::CodeCompleteReturn(Scope *S) {
3841 QualType ResultType;
3842 if (isa<BlockDecl>(CurContext)) {
3843 if (BlockScopeInfo *BSI = getCurBlock())
3844 ResultType = BSI->ReturnType;
3845 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(CurContext))
3846 ResultType = Function->getResultType();
3847 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(CurContext))
3848 ResultType = Method->getResultType();
3850 if (ResultType.isNull())
3851 CodeCompleteOrdinaryName(S, PCC_Expression);
3853 CodeCompleteExpression(S, ResultType);
3856 void Sema::CodeCompleteAfterIf(Scope *S) {
3857 typedef CodeCompletionResult Result;
3858 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3859 CodeCompleter->getCodeCompletionTUInfo(),
3860 mapCodeCompletionContext(*this, PCC_Statement));
3861 Results.setFilter(&ResultBuilder::IsOrdinaryName);
3862 Results.EnterNewScope();
3864 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3865 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3866 CodeCompleter->includeGlobals());
3868 AddOrdinaryNameResults(PCC_Statement, S, *this, Results);
3871 CodeCompletionBuilder Builder(Results.getAllocator(),
3872 Results.getCodeCompletionTUInfo());
3873 Builder.AddTypedTextChunk("else");
3874 if (Results.includeCodePatterns()) {
3875 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3876 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
3877 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
3878 Builder.AddPlaceholderChunk("statements");
3879 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
3880 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
3882 Results.AddResult(Builder.TakeString());
3885 Builder.AddTypedTextChunk("else");
3886 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3887 Builder.AddTextChunk("if");
3888 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3889 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
3890 if (getLangOpts().CPlusPlus)
3891 Builder.AddPlaceholderChunk("condition");
3893 Builder.AddPlaceholderChunk("expression");
3894 Builder.AddChunk(CodeCompletionString::CK_RightParen);
3895 if (Results.includeCodePatterns()) {
3896 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3897 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
3898 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
3899 Builder.AddPlaceholderChunk("statements");
3900 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
3901 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
3903 Results.AddResult(Builder.TakeString());
3905 Results.ExitScope();
3907 if (S->getFnParent())
3908 AddPrettyFunctionResults(PP.getLangOpts(), Results);
3910 if (CodeCompleter->includeMacros())
3911 AddMacroResults(PP, Results);
3913 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
3914 Results.data(),Results.size());
3917 void Sema::CodeCompleteAssignmentRHS(Scope *S, Expr *LHS) {
3919 CodeCompleteExpression(S, static_cast<Expr *>(LHS)->getType());
3921 CodeCompleteOrdinaryName(S, PCC_Expression);
3924 void Sema::CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
3925 bool EnteringContext) {
3926 if (!SS.getScopeRep() || !CodeCompleter)
3929 DeclContext *Ctx = computeDeclContext(SS, EnteringContext);
3933 // Try to instantiate any non-dependent declaration contexts before
3935 if (!isDependentScopeSpecifier(SS) && RequireCompleteDeclContext(SS, Ctx))
3938 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3939 CodeCompleter->getCodeCompletionTUInfo(),
3940 CodeCompletionContext::CCC_Name);
3941 Results.EnterNewScope();
3943 // The "template" keyword can follow "::" in the grammar, but only
3944 // put it into the grammar if the nested-name-specifier is dependent.
3945 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
3946 if (!Results.empty() && NNS->isDependent())
3947 Results.AddResult("template");
3949 // Add calls to overridden virtual functions, if there are any.
3951 // FIXME: This isn't wonderful, because we don't know whether we're actually
3952 // in a context that permits expressions. This is a general issue with
3953 // qualified-id completions.
3954 if (!EnteringContext)
3955 MaybeAddOverrideCalls(*this, Ctx, Results);
3956 Results.ExitScope();
3958 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3959 LookupVisibleDecls(Ctx, LookupOrdinaryName, Consumer);
3961 HandleCodeCompleteResults(this, CodeCompleter,
3962 Results.getCompletionContext(),
3963 Results.data(),Results.size());
3966 void Sema::CodeCompleteUsing(Scope *S) {
3970 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3971 CodeCompleter->getCodeCompletionTUInfo(),
3972 CodeCompletionContext::CCC_PotentiallyQualifiedName,
3973 &ResultBuilder::IsNestedNameSpecifier);
3974 Results.EnterNewScope();
3976 // If we aren't in class scope, we could see the "namespace" keyword.
3977 if (!S->isClassScope())
3978 Results.AddResult(CodeCompletionResult("namespace"));
3980 // After "using", we can see anything that would start a
3981 // nested-name-specifier.
3982 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3983 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3984 CodeCompleter->includeGlobals());
3985 Results.ExitScope();
3987 HandleCodeCompleteResults(this, CodeCompleter,
3988 CodeCompletionContext::CCC_PotentiallyQualifiedName,
3989 Results.data(),Results.size());
3992 void Sema::CodeCompleteUsingDirective(Scope *S) {
3996 // After "using namespace", we expect to see a namespace name or namespace
3998 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
3999 CodeCompleter->getCodeCompletionTUInfo(),
4000 CodeCompletionContext::CCC_Namespace,
4001 &ResultBuilder::IsNamespaceOrAlias);
4002 Results.EnterNewScope();
4003 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4004 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4005 CodeCompleter->includeGlobals());
4006 Results.ExitScope();
4007 HandleCodeCompleteResults(this, CodeCompleter,
4008 CodeCompletionContext::CCC_Namespace,
4009 Results.data(),Results.size());
4012 void Sema::CodeCompleteNamespaceDecl(Scope *S) {
4016 DeclContext *Ctx = (DeclContext *)S->getEntity();
4017 if (!S->getParent())
4018 Ctx = Context.getTranslationUnitDecl();
4020 bool SuppressedGlobalResults
4021 = Ctx && !CodeCompleter->includeGlobals() && isa<TranslationUnitDecl>(Ctx);
4023 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4024 CodeCompleter->getCodeCompletionTUInfo(),
4025 SuppressedGlobalResults
4026 ? CodeCompletionContext::CCC_Namespace
4027 : CodeCompletionContext::CCC_Other,
4028 &ResultBuilder::IsNamespace);
4030 if (Ctx && Ctx->isFileContext() && !SuppressedGlobalResults) {
4031 // We only want to see those namespaces that have already been defined
4032 // within this scope, because its likely that the user is creating an
4033 // extended namespace declaration. Keep track of the most recent
4034 // definition of each namespace.
4035 std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest;
4036 for (DeclContext::specific_decl_iterator<NamespaceDecl>
4037 NS(Ctx->decls_begin()), NSEnd(Ctx->decls_end());
4039 OrigToLatest[NS->getOriginalNamespace()] = *NS;
4041 // Add the most recent definition (or extended definition) of each
4042 // namespace to the list of results.
4043 Results.EnterNewScope();
4044 for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator
4045 NS = OrigToLatest.begin(),
4046 NSEnd = OrigToLatest.end();
4048 Results.AddResult(CodeCompletionResult(NS->second, 0),
4049 CurContext, 0, false);
4050 Results.ExitScope();
4053 HandleCodeCompleteResults(this, CodeCompleter,
4054 Results.getCompletionContext(),
4055 Results.data(),Results.size());
4058 void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) {
4062 // After "namespace", we expect to see a namespace or alias.
4063 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4064 CodeCompleter->getCodeCompletionTUInfo(),
4065 CodeCompletionContext::CCC_Namespace,
4066 &ResultBuilder::IsNamespaceOrAlias);
4067 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4068 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4069 CodeCompleter->includeGlobals());
4070 HandleCodeCompleteResults(this, CodeCompleter,
4071 Results.getCompletionContext(),
4072 Results.data(),Results.size());
4075 void Sema::CodeCompleteOperatorName(Scope *S) {
4079 typedef CodeCompletionResult Result;
4080 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4081 CodeCompleter->getCodeCompletionTUInfo(),
4082 CodeCompletionContext::CCC_Type,
4083 &ResultBuilder::IsType);
4084 Results.EnterNewScope();
4086 // Add the names of overloadable operators.
4087 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
4088 if (std::strcmp(Spelling, "?")) \
4089 Results.AddResult(Result(Spelling));
4090 #include "clang/Basic/OperatorKinds.def"
4092 // Add any type names visible from the current scope
4093 Results.allowNestedNameSpecifiers();
4094 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4095 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4096 CodeCompleter->includeGlobals());
4098 // Add any type specifiers
4099 AddTypeSpecifierResults(getLangOpts(), Results);
4100 Results.ExitScope();
4102 HandleCodeCompleteResults(this, CodeCompleter,
4103 CodeCompletionContext::CCC_Type,
4104 Results.data(),Results.size());
4107 void Sema::CodeCompleteConstructorInitializer(Decl *ConstructorD,
4108 CXXCtorInitializer** Initializers,
4109 unsigned NumInitializers) {
4110 PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
4111 CXXConstructorDecl *Constructor
4112 = static_cast<CXXConstructorDecl *>(ConstructorD);
4116 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4117 CodeCompleter->getCodeCompletionTUInfo(),
4118 CodeCompletionContext::CCC_PotentiallyQualifiedName);
4119 Results.EnterNewScope();
4121 // Fill in any already-initialized fields or base classes.
4122 llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields;
4123 llvm::SmallPtrSet<CanQualType, 4> InitializedBases;
4124 for (unsigned I = 0; I != NumInitializers; ++I) {
4125 if (Initializers[I]->isBaseInitializer())
4126 InitializedBases.insert(
4127 Context.getCanonicalType(QualType(Initializers[I]->getBaseClass(), 0)));
4129 InitializedFields.insert(cast<FieldDecl>(
4130 Initializers[I]->getAnyMember()));
4133 // Add completions for base classes.
4134 CodeCompletionBuilder Builder(Results.getAllocator(),
4135 Results.getCodeCompletionTUInfo());
4136 bool SawLastInitializer = (NumInitializers == 0);
4137 CXXRecordDecl *ClassDecl = Constructor->getParent();
4138 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4139 BaseEnd = ClassDecl->bases_end();
4140 Base != BaseEnd; ++Base) {
4141 if (!InitializedBases.insert(Context.getCanonicalType(Base->getType()))) {
4143 = NumInitializers > 0 &&
4144 Initializers[NumInitializers - 1]->isBaseInitializer() &&
4145 Context.hasSameUnqualifiedType(Base->getType(),
4146 QualType(Initializers[NumInitializers - 1]->getBaseClass(), 0));
4150 Builder.AddTypedTextChunk(
4151 Results.getAllocator().CopyString(
4152 Base->getType().getAsString(Policy)));
4153 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4154 Builder.AddPlaceholderChunk("args");
4155 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4156 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
4157 SawLastInitializer? CCP_NextInitializer
4158 : CCP_MemberDeclaration));
4159 SawLastInitializer = false;
4162 // Add completions for virtual base classes.
4163 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
4164 BaseEnd = ClassDecl->vbases_end();
4165 Base != BaseEnd; ++Base) {
4166 if (!InitializedBases.insert(Context.getCanonicalType(Base->getType()))) {
4168 = NumInitializers > 0 &&
4169 Initializers[NumInitializers - 1]->isBaseInitializer() &&
4170 Context.hasSameUnqualifiedType(Base->getType(),
4171 QualType(Initializers[NumInitializers - 1]->getBaseClass(), 0));
4175 Builder.AddTypedTextChunk(
4176 Builder.getAllocator().CopyString(
4177 Base->getType().getAsString(Policy)));
4178 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4179 Builder.AddPlaceholderChunk("args");
4180 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4181 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
4182 SawLastInitializer? CCP_NextInitializer
4183 : CCP_MemberDeclaration));
4184 SawLastInitializer = false;
4187 // Add completions for members.
4188 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4189 FieldEnd = ClassDecl->field_end();
4190 Field != FieldEnd; ++Field) {
4191 if (!InitializedFields.insert(cast<FieldDecl>(Field->getCanonicalDecl()))) {
4193 = NumInitializers > 0 &&
4194 Initializers[NumInitializers - 1]->isAnyMemberInitializer() &&
4195 Initializers[NumInitializers - 1]->getAnyMember() == *Field;
4199 if (!Field->getDeclName())
4202 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
4203 Field->getIdentifier()->getName()));
4204 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4205 Builder.AddPlaceholderChunk("args");
4206 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4207 Results.AddResult(CodeCompletionResult(Builder.TakeString(),
4208 SawLastInitializer? CCP_NextInitializer
4209 : CCP_MemberDeclaration,
4211 CXAvailability_Available,
4213 SawLastInitializer = false;
4215 Results.ExitScope();
4217 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4218 Results.data(), Results.size());
4221 /// \brief Determine whether this scope denotes a namespace.
4222 static bool isNamespaceScope(Scope *S) {
4223 DeclContext *DC = static_cast<DeclContext *>(S->getEntity());
4227 return DC->isFileContext();
4230 void Sema::CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro,
4231 bool AfterAmpersand) {
4232 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4233 CodeCompleter->getCodeCompletionTUInfo(),
4234 CodeCompletionContext::CCC_Other);
4235 Results.EnterNewScope();
4237 // Note what has already been captured.
4238 llvm::SmallPtrSet<IdentifierInfo *, 4> Known;
4239 bool IncludedThis = false;
4240 for (SmallVectorImpl<LambdaCapture>::iterator C = Intro.Captures.begin(),
4241 CEnd = Intro.Captures.end();
4243 if (C->Kind == LCK_This) {
4244 IncludedThis = true;
4248 Known.insert(C->Id);
4251 // Look for other capturable variables.
4252 for (; S && !isNamespaceScope(S); S = S->getParent()) {
4253 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
4255 VarDecl *Var = dyn_cast<VarDecl>(*D);
4257 !Var->hasLocalStorage() ||
4258 Var->hasAttr<BlocksAttr>())
4261 if (Known.insert(Var->getIdentifier()))
4262 Results.AddResult(CodeCompletionResult(Var), CurContext, 0, false);
4266 // Add 'this', if it would be valid.
4267 if (!IncludedThis && !AfterAmpersand && Intro.Default != LCD_ByCopy)
4268 addThisCompletion(*this, Results);
4270 Results.ExitScope();
4272 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4273 Results.data(), Results.size());
4276 // Macro that expands to @Keyword or Keyword, depending on whether NeedAt is
4278 #define OBJC_AT_KEYWORD_NAME(NeedAt,Keyword) NeedAt? "@" #Keyword : #Keyword
4279 static void AddObjCImplementationResults(const LangOptions &LangOpts,
4280 ResultBuilder &Results,
4282 typedef CodeCompletionResult Result;
4283 // Since we have an implementation, we can end it.
4284 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,end)));
4286 CodeCompletionBuilder Builder(Results.getAllocator(),
4287 Results.getCodeCompletionTUInfo());
4288 if (LangOpts.ObjC2) {
4290 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,dynamic));
4291 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4292 Builder.AddPlaceholderChunk("property");
4293 Results.AddResult(Result(Builder.TakeString()));
4296 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,synthesize));
4297 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4298 Builder.AddPlaceholderChunk("property");
4299 Results.AddResult(Result(Builder.TakeString()));
4303 static void AddObjCInterfaceResults(const LangOptions &LangOpts,
4304 ResultBuilder &Results,
4306 typedef CodeCompletionResult Result;
4308 // Since we have an interface or protocol, we can end it.
4309 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,end)));
4311 if (LangOpts.ObjC2) {
4313 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,property)));
4316 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,required)));
4319 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,optional)));
4323 static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt) {
4324 typedef CodeCompletionResult Result;
4325 CodeCompletionBuilder Builder(Results.getAllocator(),
4326 Results.getCodeCompletionTUInfo());
4329 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,class));
4330 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4331 Builder.AddPlaceholderChunk("name");
4332 Results.AddResult(Result(Builder.TakeString()));
4334 if (Results.includeCodePatterns()) {
4336 // FIXME: Could introduce the whole pattern, including superclasses and
4338 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,interface));
4339 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4340 Builder.AddPlaceholderChunk("class");
4341 Results.AddResult(Result(Builder.TakeString()));
4344 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,protocol));
4345 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4346 Builder.AddPlaceholderChunk("protocol");
4347 Results.AddResult(Result(Builder.TakeString()));
4349 // @implementation name
4350 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,implementation));
4351 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4352 Builder.AddPlaceholderChunk("class");
4353 Results.AddResult(Result(Builder.TakeString()));
4356 // @compatibility_alias name
4357 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,compatibility_alias));
4358 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4359 Builder.AddPlaceholderChunk("alias");
4360 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4361 Builder.AddPlaceholderChunk("class");
4362 Results.AddResult(Result(Builder.TakeString()));
4365 void Sema::CodeCompleteObjCAtDirective(Scope *S) {
4366 typedef CodeCompletionResult Result;
4367 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4368 CodeCompleter->getCodeCompletionTUInfo(),
4369 CodeCompletionContext::CCC_Other);
4370 Results.EnterNewScope();
4371 if (isa<ObjCImplDecl>(CurContext))
4372 AddObjCImplementationResults(getLangOpts(), Results, false);
4373 else if (CurContext->isObjCContainer())
4374 AddObjCInterfaceResults(getLangOpts(), Results, false);
4376 AddObjCTopLevelResults(Results, false);
4377 Results.ExitScope();
4378 HandleCodeCompleteResults(this, CodeCompleter,
4379 CodeCompletionContext::CCC_Other,
4380 Results.data(),Results.size());
4383 static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt) {
4384 typedef CodeCompletionResult Result;
4385 CodeCompletionBuilder Builder(Results.getAllocator(),
4386 Results.getCodeCompletionTUInfo());
4388 // @encode ( type-name )
4389 const char *EncodeType = "char[]";
4390 if (Results.getSema().getLangOpts().CPlusPlus ||
4391 Results.getSema().getLangOpts().ConstStrings)
4392 EncodeType = " const char[]";
4393 Builder.AddResultTypeChunk(EncodeType);
4394 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,encode));
4395 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4396 Builder.AddPlaceholderChunk("type-name");
4397 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4398 Results.AddResult(Result(Builder.TakeString()));
4400 // @protocol ( protocol-name )
4401 Builder.AddResultTypeChunk("Protocol *");
4402 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,protocol));
4403 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4404 Builder.AddPlaceholderChunk("protocol-name");
4405 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4406 Results.AddResult(Result(Builder.TakeString()));
4408 // @selector ( selector )
4409 Builder.AddResultTypeChunk("SEL");
4410 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,selector));
4411 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4412 Builder.AddPlaceholderChunk("selector");
4413 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4414 Results.AddResult(Result(Builder.TakeString()));
4416 // @[ objects, ... ]
4417 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,[));
4418 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4419 Builder.AddPlaceholderChunk("objects, ...");
4420 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4421 Builder.AddChunk(CodeCompletionString::CK_RightBracket);
4422 Results.AddResult(Result(Builder.TakeString()));
4424 // @{ key : object, ... }
4425 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,{));
4426 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4427 Builder.AddPlaceholderChunk("key");
4428 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4429 Builder.AddChunk(CodeCompletionString::CK_Colon);
4430 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4431 Builder.AddPlaceholderChunk("object, ...");
4432 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4433 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4434 Results.AddResult(Result(Builder.TakeString()));
4437 static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt) {
4438 typedef CodeCompletionResult Result;
4439 CodeCompletionBuilder Builder(Results.getAllocator(),
4440 Results.getCodeCompletionTUInfo());
4442 if (Results.includeCodePatterns()) {
4443 // @try { statements } @catch ( declaration ) { statements } @finally
4445 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,try));
4446 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4447 Builder.AddPlaceholderChunk("statements");
4448 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4449 Builder.AddTextChunk("@catch");
4450 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4451 Builder.AddPlaceholderChunk("parameter");
4452 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4453 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4454 Builder.AddPlaceholderChunk("statements");
4455 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4456 Builder.AddTextChunk("@finally");
4457 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4458 Builder.AddPlaceholderChunk("statements");
4459 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4460 Results.AddResult(Result(Builder.TakeString()));
4464 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,throw));
4465 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4466 Builder.AddPlaceholderChunk("expression");
4467 Results.AddResult(Result(Builder.TakeString()));
4469 if (Results.includeCodePatterns()) {
4470 // @synchronized ( expression ) { statements }
4471 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,synchronized));
4472 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4473 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4474 Builder.AddPlaceholderChunk("expression");
4475 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4476 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
4477 Builder.AddPlaceholderChunk("statements");
4478 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
4479 Results.AddResult(Result(Builder.TakeString()));
4483 static void AddObjCVisibilityResults(const LangOptions &LangOpts,
4484 ResultBuilder &Results,
4486 typedef CodeCompletionResult Result;
4487 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,private)));
4488 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,protected)));
4489 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,public)));
4491 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,package)));
4494 void Sema::CodeCompleteObjCAtVisibility(Scope *S) {
4495 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4496 CodeCompleter->getCodeCompletionTUInfo(),
4497 CodeCompletionContext::CCC_Other);
4498 Results.EnterNewScope();
4499 AddObjCVisibilityResults(getLangOpts(), Results, false);
4500 Results.ExitScope();
4501 HandleCodeCompleteResults(this, CodeCompleter,
4502 CodeCompletionContext::CCC_Other,
4503 Results.data(),Results.size());
4506 void Sema::CodeCompleteObjCAtStatement(Scope *S) {
4507 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4508 CodeCompleter->getCodeCompletionTUInfo(),
4509 CodeCompletionContext::CCC_Other);
4510 Results.EnterNewScope();
4511 AddObjCStatementResults(Results, false);
4512 AddObjCExpressionResults(Results, false);
4513 Results.ExitScope();
4514 HandleCodeCompleteResults(this, CodeCompleter,
4515 CodeCompletionContext::CCC_Other,
4516 Results.data(),Results.size());
4519 void Sema::CodeCompleteObjCAtExpression(Scope *S) {
4520 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4521 CodeCompleter->getCodeCompletionTUInfo(),
4522 CodeCompletionContext::CCC_Other);
4523 Results.EnterNewScope();
4524 AddObjCExpressionResults(Results, false);
4525 Results.ExitScope();
4526 HandleCodeCompleteResults(this, CodeCompleter,
4527 CodeCompletionContext::CCC_Other,
4528 Results.data(),Results.size());
4531 /// \brief Determine whether the addition of the given flag to an Objective-C
4532 /// property's attributes will cause a conflict.
4533 static bool ObjCPropertyFlagConflicts(unsigned Attributes, unsigned NewFlag) {
4534 // Check if we've already added this flag.
4535 if (Attributes & NewFlag)
4538 Attributes |= NewFlag;
4540 // Check for collisions with "readonly".
4541 if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
4542 (Attributes & (ObjCDeclSpec::DQ_PR_readwrite |
4543 ObjCDeclSpec::DQ_PR_assign |
4544 ObjCDeclSpec::DQ_PR_unsafe_unretained |
4545 ObjCDeclSpec::DQ_PR_copy |
4546 ObjCDeclSpec::DQ_PR_retain |
4547 ObjCDeclSpec::DQ_PR_strong)))
4550 // Check for more than one of { assign, copy, retain, strong }.
4551 unsigned AssignCopyRetMask = Attributes & (ObjCDeclSpec::DQ_PR_assign |
4552 ObjCDeclSpec::DQ_PR_unsafe_unretained |
4553 ObjCDeclSpec::DQ_PR_copy |
4554 ObjCDeclSpec::DQ_PR_retain|
4555 ObjCDeclSpec::DQ_PR_strong);
4556 if (AssignCopyRetMask &&
4557 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_assign &&
4558 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_unsafe_unretained &&
4559 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_copy &&
4560 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_retain &&
4561 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_strong)
4567 void Sema::CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS) {
4571 unsigned Attributes = ODS.getPropertyAttributes();
4573 typedef CodeCompletionResult Result;
4574 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4575 CodeCompleter->getCodeCompletionTUInfo(),
4576 CodeCompletionContext::CCC_Other);
4577 Results.EnterNewScope();
4578 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readonly))
4579 Results.AddResult(CodeCompletionResult("readonly"));
4580 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_assign))
4581 Results.AddResult(CodeCompletionResult("assign"));
4582 if (!ObjCPropertyFlagConflicts(Attributes,
4583 ObjCDeclSpec::DQ_PR_unsafe_unretained))
4584 Results.AddResult(CodeCompletionResult("unsafe_unretained"));
4585 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readwrite))
4586 Results.AddResult(CodeCompletionResult("readwrite"));
4587 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_retain))
4588 Results.AddResult(CodeCompletionResult("retain"));
4589 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_strong))
4590 Results.AddResult(CodeCompletionResult("strong"));
4591 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_copy))
4592 Results.AddResult(CodeCompletionResult("copy"));
4593 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nonatomic))
4594 Results.AddResult(CodeCompletionResult("nonatomic"));
4595 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_atomic))
4596 Results.AddResult(CodeCompletionResult("atomic"));
4597 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_setter)) {
4598 CodeCompletionBuilder Setter(Results.getAllocator(),
4599 Results.getCodeCompletionTUInfo());
4600 Setter.AddTypedTextChunk("setter");
4601 Setter.AddTextChunk(" = ");
4602 Setter.AddPlaceholderChunk("method");
4603 Results.AddResult(CodeCompletionResult(Setter.TakeString()));
4605 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_getter)) {
4606 CodeCompletionBuilder Getter(Results.getAllocator(),
4607 Results.getCodeCompletionTUInfo());
4608 Getter.AddTypedTextChunk("getter");
4609 Getter.AddTextChunk(" = ");
4610 Getter.AddPlaceholderChunk("method");
4611 Results.AddResult(CodeCompletionResult(Getter.TakeString()));
4613 Results.ExitScope();
4614 HandleCodeCompleteResults(this, CodeCompleter,
4615 CodeCompletionContext::CCC_Other,
4616 Results.data(),Results.size());
4619 /// \brief Descripts the kind of Objective-C method that we want to find
4620 /// via code completion.
4621 enum ObjCMethodKind {
4622 MK_Any, //< Any kind of method, provided it means other specified criteria.
4623 MK_ZeroArgSelector, //< Zero-argument (unary) selector.
4624 MK_OneArgSelector //< One-argument selector.
4627 static bool isAcceptableObjCSelector(Selector Sel,
4628 ObjCMethodKind WantKind,
4629 IdentifierInfo **SelIdents,
4630 unsigned NumSelIdents,
4631 bool AllowSameLength = true) {
4632 if (NumSelIdents > Sel.getNumArgs())
4637 case MK_ZeroArgSelector: return Sel.isUnarySelector();
4638 case MK_OneArgSelector: return Sel.getNumArgs() == 1;
4641 if (!AllowSameLength && NumSelIdents && NumSelIdents == Sel.getNumArgs())
4644 for (unsigned I = 0; I != NumSelIdents; ++I)
4645 if (SelIdents[I] != Sel.getIdentifierInfoForSlot(I))
4651 static bool isAcceptableObjCMethod(ObjCMethodDecl *Method,
4652 ObjCMethodKind WantKind,
4653 IdentifierInfo **SelIdents,
4654 unsigned NumSelIdents,
4655 bool AllowSameLength = true) {
4656 return isAcceptableObjCSelector(Method->getSelector(), WantKind, SelIdents,
4657 NumSelIdents, AllowSameLength);
4661 /// \brief A set of selectors, which is used to avoid introducing multiple
4662 /// completions with the same selector into the result set.
4663 typedef llvm::SmallPtrSet<Selector, 16> VisitedSelectorSet;
4666 /// \brief Add all of the Objective-C methods in the given Objective-C
4667 /// container to the set of results.
4669 /// The container will be a class, protocol, category, or implementation of
4670 /// any of the above. This mether will recurse to include methods from
4671 /// the superclasses of classes along with their categories, protocols, and
4672 /// implementations.
4674 /// \param Container the container in which we'll look to find methods.
4676 /// \param WantInstance whether to add instance methods (only); if false, this
4677 /// routine will add factory methods (only).
4679 /// \param CurContext the context in which we're performing the lookup that
4682 /// \param AllowSameLength Whether we allow a method to be added to the list
4683 /// when it has the same number of parameters as we have selector identifiers.
4685 /// \param Results the structure into which we'll add results.
4686 static void AddObjCMethods(ObjCContainerDecl *Container,
4687 bool WantInstanceMethods,
4688 ObjCMethodKind WantKind,
4689 IdentifierInfo **SelIdents,
4690 unsigned NumSelIdents,
4691 DeclContext *CurContext,
4692 VisitedSelectorSet &Selectors,
4693 bool AllowSameLength,
4694 ResultBuilder &Results,
4695 bool InOriginalClass = true) {
4696 typedef CodeCompletionResult Result;
4697 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
4698 MEnd = Container->meth_end();
4700 if ((*M)->isInstanceMethod() == WantInstanceMethods) {
4701 // Check whether the selector identifiers we've been given are a
4702 // subset of the identifiers for this particular method.
4703 if (!isAcceptableObjCMethod(*M, WantKind, SelIdents, NumSelIdents,
4707 if (!Selectors.insert((*M)->getSelector()))
4710 Result R = Result(*M, 0);
4711 R.StartParameter = NumSelIdents;
4712 R.AllParametersAreInformative = (WantKind != MK_Any);
4713 if (!InOriginalClass)
4714 R.Priority += CCD_InBaseClass;
4715 Results.MaybeAddResult(R, CurContext);
4719 // Visit the protocols of protocols.
4720 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4721 if (Protocol->hasDefinition()) {
4722 const ObjCList<ObjCProtocolDecl> &Protocols
4723 = Protocol->getReferencedProtocols();
4724 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4725 E = Protocols.end();
4727 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents,
4728 NumSelIdents, CurContext, Selectors, AllowSameLength,
4733 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container);
4734 if (!IFace || !IFace->hasDefinition())
4737 // Add methods in protocols.
4738 for (ObjCInterfaceDecl::protocol_iterator I = IFace->protocol_begin(),
4739 E = IFace->protocol_end();
4741 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, NumSelIdents,
4742 CurContext, Selectors, AllowSameLength, Results, false);
4744 // Add methods in categories.
4745 for (ObjCCategoryDecl *CatDecl = IFace->getCategoryList(); CatDecl;
4746 CatDecl = CatDecl->getNextClassCategory()) {
4747 AddObjCMethods(CatDecl, WantInstanceMethods, WantKind, SelIdents,
4748 NumSelIdents, CurContext, Selectors, AllowSameLength,
4749 Results, InOriginalClass);
4751 // Add a categories protocol methods.
4752 const ObjCList<ObjCProtocolDecl> &Protocols
4753 = CatDecl->getReferencedProtocols();
4754 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4755 E = Protocols.end();
4757 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents,
4758 NumSelIdents, CurContext, Selectors, AllowSameLength,
4761 // Add methods in category implementations.
4762 if (ObjCCategoryImplDecl *Impl = CatDecl->getImplementation())
4763 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
4764 NumSelIdents, CurContext, Selectors, AllowSameLength,
4765 Results, InOriginalClass);
4768 // Add methods in superclass.
4769 if (IFace->getSuperClass())
4770 AddObjCMethods(IFace->getSuperClass(), WantInstanceMethods, WantKind,
4771 SelIdents, NumSelIdents, CurContext, Selectors,
4772 AllowSameLength, Results, false);
4774 // Add methods in our implementation, if any.
4775 if (ObjCImplementationDecl *Impl = IFace->getImplementation())
4776 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
4777 NumSelIdents, CurContext, Selectors, AllowSameLength,
4778 Results, InOriginalClass);
4782 void Sema::CodeCompleteObjCPropertyGetter(Scope *S) {
4783 typedef CodeCompletionResult Result;
4785 // Try to find the interface where getters might live.
4786 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext);
4788 if (ObjCCategoryDecl *Category
4789 = dyn_cast_or_null<ObjCCategoryDecl>(CurContext))
4790 Class = Category->getClassInterface();
4796 // Find all of the potential getters.
4797 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4798 CodeCompleter->getCodeCompletionTUInfo(),
4799 CodeCompletionContext::CCC_Other);
4800 Results.EnterNewScope();
4802 VisitedSelectorSet Selectors;
4803 AddObjCMethods(Class, true, MK_ZeroArgSelector, 0, 0, CurContext, Selectors,
4804 /*AllowSameLength=*/true, Results);
4805 Results.ExitScope();
4806 HandleCodeCompleteResults(this, CodeCompleter,
4807 CodeCompletionContext::CCC_Other,
4808 Results.data(),Results.size());
4811 void Sema::CodeCompleteObjCPropertySetter(Scope *S) {
4812 typedef CodeCompletionResult Result;
4814 // Try to find the interface where setters might live.
4815 ObjCInterfaceDecl *Class
4816 = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext);
4818 if (ObjCCategoryDecl *Category
4819 = dyn_cast_or_null<ObjCCategoryDecl>(CurContext))
4820 Class = Category->getClassInterface();
4826 // Find all of the potential getters.
4827 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4828 CodeCompleter->getCodeCompletionTUInfo(),
4829 CodeCompletionContext::CCC_Other);
4830 Results.EnterNewScope();
4832 VisitedSelectorSet Selectors;
4833 AddObjCMethods(Class, true, MK_OneArgSelector, 0, 0, CurContext,
4834 Selectors, /*AllowSameLength=*/true, Results);
4836 Results.ExitScope();
4837 HandleCodeCompleteResults(this, CodeCompleter,
4838 CodeCompletionContext::CCC_Other,
4839 Results.data(),Results.size());
4842 void Sema::CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
4844 typedef CodeCompletionResult Result;
4845 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4846 CodeCompleter->getCodeCompletionTUInfo(),
4847 CodeCompletionContext::CCC_Type);
4848 Results.EnterNewScope();
4850 // Add context-sensitive, Objective-C parameter-passing keywords.
4851 bool AddedInOut = false;
4852 if ((DS.getObjCDeclQualifier() &
4853 (ObjCDeclSpec::DQ_In | ObjCDeclSpec::DQ_Inout)) == 0) {
4854 Results.AddResult("in");
4855 Results.AddResult("inout");
4858 if ((DS.getObjCDeclQualifier() &
4859 (ObjCDeclSpec::DQ_Out | ObjCDeclSpec::DQ_Inout)) == 0) {
4860 Results.AddResult("out");
4862 Results.AddResult("inout");
4864 if ((DS.getObjCDeclQualifier() &
4865 (ObjCDeclSpec::DQ_Bycopy | ObjCDeclSpec::DQ_Byref |
4866 ObjCDeclSpec::DQ_Oneway)) == 0) {
4867 Results.AddResult("bycopy");
4868 Results.AddResult("byref");
4869 Results.AddResult("oneway");
4872 // If we're completing the return type of an Objective-C method and the
4873 // identifier IBAction refers to a macro, provide a completion item for
4875 // IBAction)<#selector#>:(id)sender
4876 if (DS.getObjCDeclQualifier() == 0 && !IsParameter &&
4877 Context.Idents.get("IBAction").hasMacroDefinition()) {
4878 CodeCompletionBuilder Builder(Results.getAllocator(),
4879 Results.getCodeCompletionTUInfo(),
4880 CCP_CodePattern, CXAvailability_Available);
4881 Builder.AddTypedTextChunk("IBAction");
4882 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4883 Builder.AddPlaceholderChunk("selector");
4884 Builder.AddChunk(CodeCompletionString::CK_Colon);
4885 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4886 Builder.AddTextChunk("id");
4887 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4888 Builder.AddTextChunk("sender");
4889 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
4892 // Add various builtin type names and specifiers.
4893 AddOrdinaryNameResults(PCC_Type, S, *this, Results);
4894 Results.ExitScope();
4896 // Add the various type names
4897 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
4898 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4899 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4900 CodeCompleter->includeGlobals());
4902 if (CodeCompleter->includeMacros())
4903 AddMacroResults(PP, Results);
4905 HandleCodeCompleteResults(this, CodeCompleter,
4906 CodeCompletionContext::CCC_Type,
4907 Results.data(), Results.size());
4910 /// \brief When we have an expression with type "id", we may assume
4911 /// that it has some more-specific class type based on knowledge of
4912 /// common uses of Objective-C. This routine returns that class type,
4913 /// or NULL if no better result could be determined.
4914 static ObjCInterfaceDecl *GetAssumedMessageSendExprType(Expr *E) {
4915 ObjCMessageExpr *Msg = dyn_cast_or_null<ObjCMessageExpr>(E);
4919 Selector Sel = Msg->getSelector();
4923 IdentifierInfo *Id = Sel.getIdentifierInfoForSlot(0);
4927 ObjCMethodDecl *Method = Msg->getMethodDecl();
4931 // Determine the class that we're sending the message to.
4932 ObjCInterfaceDecl *IFace = 0;
4933 switch (Msg->getReceiverKind()) {
4934 case ObjCMessageExpr::Class:
4935 if (const ObjCObjectType *ObjType
4936 = Msg->getClassReceiver()->getAs<ObjCObjectType>())
4937 IFace = ObjType->getInterface();
4940 case ObjCMessageExpr::Instance: {
4941 QualType T = Msg->getInstanceReceiver()->getType();
4942 if (const ObjCObjectPointerType *Ptr = T->getAs<ObjCObjectPointerType>())
4943 IFace = Ptr->getInterfaceDecl();
4947 case ObjCMessageExpr::SuperInstance:
4948 case ObjCMessageExpr::SuperClass:
4955 ObjCInterfaceDecl *Super = IFace->getSuperClass();
4956 if (Method->isInstanceMethod())
4957 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
4958 .Case("retain", IFace)
4959 .Case("strong", IFace)
4960 .Case("autorelease", IFace)
4961 .Case("copy", IFace)
4962 .Case("copyWithZone", IFace)
4963 .Case("mutableCopy", IFace)
4964 .Case("mutableCopyWithZone", IFace)
4965 .Case("awakeFromCoder", IFace)
4966 .Case("replacementObjectFromCoder", IFace)
4967 .Case("class", IFace)
4968 .Case("classForCoder", IFace)
4969 .Case("superclass", Super)
4972 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
4974 .Case("alloc", IFace)
4975 .Case("allocWithZone", IFace)
4976 .Case("class", IFace)
4977 .Case("superclass", Super)
4981 // Add a special completion for a message send to "super", which fills in the
4982 // most likely case of forwarding all of our arguments to the superclass
4985 /// \param S The semantic analysis object.
4987 /// \param S NeedSuperKeyword Whether we need to prefix this completion with
4988 /// the "super" keyword. Otherwise, we just need to provide the arguments.
4990 /// \param SelIdents The identifiers in the selector that have already been
4991 /// provided as arguments for a send to "super".
4993 /// \param NumSelIdents The number of identifiers in \p SelIdents.
4995 /// \param Results The set of results to augment.
4997 /// \returns the Objective-C method declaration that would be invoked by
4998 /// this "super" completion. If NULL, no completion was added.
4999 static ObjCMethodDecl *AddSuperSendCompletion(Sema &S, bool NeedSuperKeyword,
5000 IdentifierInfo **SelIdents,
5001 unsigned NumSelIdents,
5002 ResultBuilder &Results) {
5003 ObjCMethodDecl *CurMethod = S.getCurMethodDecl();
5007 ObjCInterfaceDecl *Class = CurMethod->getClassInterface();
5011 // Try to find a superclass method with the same selector.
5012 ObjCMethodDecl *SuperMethod = 0;
5013 while ((Class = Class->getSuperClass()) && !SuperMethod) {
5014 // Check in the class
5015 SuperMethod = Class->getMethod(CurMethod->getSelector(),
5016 CurMethod->isInstanceMethod());
5018 // Check in categories or class extensions.
5020 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
5021 Category = Category->getNextClassCategory())
5022 if ((SuperMethod = Category->getMethod(CurMethod->getSelector(),
5023 CurMethod->isInstanceMethod())))
5031 // Check whether the superclass method has the same signature.
5032 if (CurMethod->param_size() != SuperMethod->param_size() ||
5033 CurMethod->isVariadic() != SuperMethod->isVariadic())
5036 for (ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin(),
5037 CurPEnd = CurMethod->param_end(),
5038 SuperP = SuperMethod->param_begin();
5039 CurP != CurPEnd; ++CurP, ++SuperP) {
5040 // Make sure the parameter types are compatible.
5041 if (!S.Context.hasSameUnqualifiedType((*CurP)->getType(),
5042 (*SuperP)->getType()))
5045 // Make sure we have a parameter name to forward!
5046 if (!(*CurP)->getIdentifier())
5050 // We have a superclass method. Now, form the send-to-super completion.
5051 CodeCompletionBuilder Builder(Results.getAllocator(),
5052 Results.getCodeCompletionTUInfo());
5054 // Give this completion a return type.
5055 AddResultTypeChunk(S.Context, getCompletionPrintingPolicy(S), SuperMethod,
5058 // If we need the "super" keyword, add it (plus some spacing).
5059 if (NeedSuperKeyword) {
5060 Builder.AddTypedTextChunk("super");
5061 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5064 Selector Sel = CurMethod->getSelector();
5065 if (Sel.isUnarySelector()) {
5066 if (NeedSuperKeyword)
5067 Builder.AddTextChunk(Builder.getAllocator().CopyString(
5068 Sel.getNameForSlot(0)));
5070 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
5071 Sel.getNameForSlot(0)));
5073 ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin();
5074 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I, ++CurP) {
5075 if (I > NumSelIdents)
5076 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
5078 if (I < NumSelIdents)
5079 Builder.AddInformativeChunk(
5080 Builder.getAllocator().CopyString(
5081 Sel.getNameForSlot(I) + ":"));
5082 else if (NeedSuperKeyword || I > NumSelIdents) {
5083 Builder.AddTextChunk(
5084 Builder.getAllocator().CopyString(
5085 Sel.getNameForSlot(I) + ":"));
5086 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
5087 (*CurP)->getIdentifier()->getName()));
5089 Builder.AddTypedTextChunk(
5090 Builder.getAllocator().CopyString(
5091 Sel.getNameForSlot(I) + ":"));
5092 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
5093 (*CurP)->getIdentifier()->getName()));
5098 Results.AddResult(CodeCompletionResult(Builder.TakeString(), SuperMethod,
5099 CCP_SuperCompletion));
5103 void Sema::CodeCompleteObjCMessageReceiver(Scope *S) {
5104 typedef CodeCompletionResult Result;
5105 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5106 CodeCompleter->getCodeCompletionTUInfo(),
5107 CodeCompletionContext::CCC_ObjCMessageReceiver,
5108 getLangOpts().CPlusPlus0x
5109 ? &ResultBuilder::IsObjCMessageReceiverOrLambdaCapture
5110 : &ResultBuilder::IsObjCMessageReceiver);
5112 CodeCompletionDeclConsumer Consumer(Results, CurContext);
5113 Results.EnterNewScope();
5114 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
5115 CodeCompleter->includeGlobals());
5117 // If we are in an Objective-C method inside a class that has a superclass,
5118 // add "super" as an option.
5119 if (ObjCMethodDecl *Method = getCurMethodDecl())
5120 if (ObjCInterfaceDecl *Iface = Method->getClassInterface())
5121 if (Iface->getSuperClass()) {
5122 Results.AddResult(Result("super"));
5124 AddSuperSendCompletion(*this, /*NeedSuperKeyword=*/true, 0, 0, Results);
5127 if (getLangOpts().CPlusPlus0x)
5128 addThisCompletion(*this, Results);
5130 Results.ExitScope();
5132 if (CodeCompleter->includeMacros())
5133 AddMacroResults(PP, Results);
5134 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
5135 Results.data(), Results.size());
5139 void Sema::CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
5140 IdentifierInfo **SelIdents,
5141 unsigned NumSelIdents,
5142 bool AtArgumentExpression) {
5143 ObjCInterfaceDecl *CDecl = 0;
5144 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
5145 // Figure out which interface we're in.
5146 CDecl = CurMethod->getClassInterface();
5150 // Find the superclass of this class.
5151 CDecl = CDecl->getSuperClass();
5155 if (CurMethod->isInstanceMethod()) {
5156 // We are inside an instance method, which means that the message
5157 // send [super ...] is actually calling an instance method on the
5159 return CodeCompleteObjCInstanceMessage(S, 0,
5160 SelIdents, NumSelIdents,
5161 AtArgumentExpression,
5165 // Fall through to send to the superclass in CDecl.
5167 // "super" may be the name of a type or variable. Figure out which
5169 IdentifierInfo *Super = &Context.Idents.get("super");
5170 NamedDecl *ND = LookupSingleName(S, Super, SuperLoc,
5171 LookupOrdinaryName);
5172 if ((CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(ND))) {
5173 // "super" names an interface. Use it.
5174 } else if (TypeDecl *TD = dyn_cast_or_null<TypeDecl>(ND)) {
5175 if (const ObjCObjectType *Iface
5176 = Context.getTypeDeclType(TD)->getAs<ObjCObjectType>())
5177 CDecl = Iface->getInterface();
5178 } else if (ND && isa<UnresolvedUsingTypenameDecl>(ND)) {
5179 // "super" names an unresolved type; we can't be more specific.
5181 // Assume that "super" names some kind of value and parse that way.
5183 SourceLocation TemplateKWLoc;
5185 id.setIdentifier(Super, SuperLoc);
5186 ExprResult SuperExpr = ActOnIdExpression(S, SS, TemplateKWLoc, id,
5188 return CodeCompleteObjCInstanceMessage(S, (Expr *)SuperExpr.get(),
5189 SelIdents, NumSelIdents,
5190 AtArgumentExpression);
5196 ParsedType Receiver;
5198 Receiver = ParsedType::make(Context.getObjCInterfaceType(CDecl));
5199 return CodeCompleteObjCClassMessage(S, Receiver, SelIdents,
5200 NumSelIdents, AtArgumentExpression,
5204 /// \brief Given a set of code-completion results for the argument of a message
5205 /// send, determine the preferred type (if any) for that argument expression.
5206 static QualType getPreferredArgumentTypeForMessageSend(ResultBuilder &Results,
5207 unsigned NumSelIdents) {
5208 typedef CodeCompletionResult Result;
5209 ASTContext &Context = Results.getSema().Context;
5211 QualType PreferredType;
5212 unsigned BestPriority = CCP_Unlikely * 2;
5213 Result *ResultsData = Results.data();
5214 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
5215 Result &R = ResultsData[I];
5216 if (R.Kind == Result::RK_Declaration &&
5217 isa<ObjCMethodDecl>(R.Declaration)) {
5218 if (R.Priority <= BestPriority) {
5219 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(R.Declaration);
5220 if (NumSelIdents <= Method->param_size()) {
5221 QualType MyPreferredType = Method->param_begin()[NumSelIdents - 1]
5223 if (R.Priority < BestPriority || PreferredType.isNull()) {
5224 BestPriority = R.Priority;
5225 PreferredType = MyPreferredType;
5226 } else if (!Context.hasSameUnqualifiedType(PreferredType,
5228 PreferredType = QualType();
5235 return PreferredType;
5238 static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
5239 ParsedType Receiver,
5240 IdentifierInfo **SelIdents,
5241 unsigned NumSelIdents,
5242 bool AtArgumentExpression,
5244 ResultBuilder &Results) {
5245 typedef CodeCompletionResult Result;
5246 ObjCInterfaceDecl *CDecl = 0;
5248 // If the given name refers to an interface type, retrieve the
5249 // corresponding declaration.
5251 QualType T = SemaRef.GetTypeFromParser(Receiver, 0);
5253 if (const ObjCObjectType *Interface = T->getAs<ObjCObjectType>())
5254 CDecl = Interface->getInterface();
5257 // Add all of the factory methods in this Objective-C class, its protocols,
5258 // superclasses, categories, implementation, etc.
5259 Results.EnterNewScope();
5261 // If this is a send-to-super, try to add the special "super" send
5264 if (ObjCMethodDecl *SuperMethod
5265 = AddSuperSendCompletion(SemaRef, false, SelIdents, NumSelIdents,
5267 Results.Ignore(SuperMethod);
5270 // If we're inside an Objective-C method definition, prefer its selector to
5272 if (ObjCMethodDecl *CurMethod = SemaRef.getCurMethodDecl())
5273 Results.setPreferredSelector(CurMethod->getSelector());
5275 VisitedSelectorSet Selectors;
5277 AddObjCMethods(CDecl, false, MK_Any, SelIdents, NumSelIdents,
5278 SemaRef.CurContext, Selectors, AtArgumentExpression,
5281 // We're messaging "id" as a type; provide all class/factory methods.
5283 // If we have an external source, load the entire class method
5284 // pool from the AST file.
5285 if (SemaRef.ExternalSource) {
5286 for (uint32_t I = 0,
5287 N = SemaRef.ExternalSource->GetNumExternalSelectors();
5289 Selector Sel = SemaRef.ExternalSource->GetExternalSelector(I);
5290 if (Sel.isNull() || SemaRef.MethodPool.count(Sel))
5293 SemaRef.ReadMethodPool(Sel);
5297 for (Sema::GlobalMethodPool::iterator M = SemaRef.MethodPool.begin(),
5298 MEnd = SemaRef.MethodPool.end();
5300 for (ObjCMethodList *MethList = &M->second.second;
5301 MethList && MethList->Method;
5302 MethList = MethList->Next) {
5303 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
5307 Result R(MethList->Method, 0);
5308 R.StartParameter = NumSelIdents;
5309 R.AllParametersAreInformative = false;
5310 Results.MaybeAddResult(R, SemaRef.CurContext);
5315 Results.ExitScope();
5318 void Sema::CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
5319 IdentifierInfo **SelIdents,
5320 unsigned NumSelIdents,
5321 bool AtArgumentExpression,
5324 QualType T = this->GetTypeFromParser(Receiver);
5326 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5327 CodeCompleter->getCodeCompletionTUInfo(),
5328 CodeCompletionContext(CodeCompletionContext::CCC_ObjCClassMessage,
5329 T, SelIdents, NumSelIdents));
5331 AddClassMessageCompletions(*this, S, Receiver, SelIdents, NumSelIdents,
5332 AtArgumentExpression, IsSuper, Results);
5334 // If we're actually at the argument expression (rather than prior to the
5335 // selector), we're actually performing code completion for an expression.
5336 // Determine whether we have a single, best method. If so, we can
5337 // code-complete the expression using the corresponding parameter type as
5338 // our preferred type, improving completion results.
5339 if (AtArgumentExpression) {
5340 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results,
5342 if (PreferredType.isNull())
5343 CodeCompleteOrdinaryName(S, PCC_Expression);
5345 CodeCompleteExpression(S, PreferredType);
5349 HandleCodeCompleteResults(this, CodeCompleter,
5350 Results.getCompletionContext(),
5351 Results.data(), Results.size());
5354 void Sema::CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
5355 IdentifierInfo **SelIdents,
5356 unsigned NumSelIdents,
5357 bool AtArgumentExpression,
5358 ObjCInterfaceDecl *Super) {
5359 typedef CodeCompletionResult Result;
5361 Expr *RecExpr = static_cast<Expr *>(Receiver);
5363 // If necessary, apply function/array conversion to the receiver.
5364 // C99 6.7.5.3p[7,8].
5366 ExprResult Conv = DefaultFunctionArrayLvalueConversion(RecExpr);
5367 if (Conv.isInvalid()) // conversion failed. bail.
5369 RecExpr = Conv.take();
5371 QualType ReceiverType = RecExpr? RecExpr->getType()
5372 : Super? Context.getObjCObjectPointerType(
5373 Context.getObjCInterfaceType(Super))
5374 : Context.getObjCIdType();
5376 // If we're messaging an expression with type "id" or "Class", check
5377 // whether we know something special about the receiver that allows
5378 // us to assume a more-specific receiver type.
5379 if (ReceiverType->isObjCIdType() || ReceiverType->isObjCClassType())
5380 if (ObjCInterfaceDecl *IFace = GetAssumedMessageSendExprType(RecExpr)) {
5381 if (ReceiverType->isObjCClassType())
5382 return CodeCompleteObjCClassMessage(S,
5383 ParsedType::make(Context.getObjCInterfaceType(IFace)),
5384 SelIdents, NumSelIdents,
5385 AtArgumentExpression, Super);
5387 ReceiverType = Context.getObjCObjectPointerType(
5388 Context.getObjCInterfaceType(IFace));
5391 // Build the set of methods we can see.
5392 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5393 CodeCompleter->getCodeCompletionTUInfo(),
5394 CodeCompletionContext(CodeCompletionContext::CCC_ObjCInstanceMessage,
5395 ReceiverType, SelIdents, NumSelIdents));
5397 Results.EnterNewScope();
5399 // If this is a send-to-super, try to add the special "super" send
5402 if (ObjCMethodDecl *SuperMethod
5403 = AddSuperSendCompletion(*this, false, SelIdents, NumSelIdents,
5405 Results.Ignore(SuperMethod);
5408 // If we're inside an Objective-C method definition, prefer its selector to
5410 if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
5411 Results.setPreferredSelector(CurMethod->getSelector());
5413 // Keep track of the selectors we've already added.
5414 VisitedSelectorSet Selectors;
5416 // Handle messages to Class. This really isn't a message to an instance
5417 // method, so we treat it the same way we would treat a message send to a
5419 if (ReceiverType->isObjCClassType() ||
5420 ReceiverType->isObjCQualifiedClassType()) {
5421 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
5422 if (ObjCInterfaceDecl *ClassDecl = CurMethod->getClassInterface())
5423 AddObjCMethods(ClassDecl, false, MK_Any, SelIdents, NumSelIdents,
5424 CurContext, Selectors, AtArgumentExpression, Results);
5427 // Handle messages to a qualified ID ("id<foo>").
5428 else if (const ObjCObjectPointerType *QualID
5429 = ReceiverType->getAsObjCQualifiedIdType()) {
5430 // Search protocols for instance methods.
5431 for (ObjCObjectPointerType::qual_iterator I = QualID->qual_begin(),
5432 E = QualID->qual_end();
5434 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
5435 Selectors, AtArgumentExpression, Results);
5437 // Handle messages to a pointer to interface type.
5438 else if (const ObjCObjectPointerType *IFacePtr
5439 = ReceiverType->getAsObjCInterfacePointerType()) {
5440 // Search the class, its superclasses, etc., for instance methods.
5441 AddObjCMethods(IFacePtr->getInterfaceDecl(), true, MK_Any, SelIdents,
5442 NumSelIdents, CurContext, Selectors, AtArgumentExpression,
5445 // Search protocols for instance methods.
5446 for (ObjCObjectPointerType::qual_iterator I = IFacePtr->qual_begin(),
5447 E = IFacePtr->qual_end();
5449 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
5450 Selectors, AtArgumentExpression, Results);
5452 // Handle messages to "id".
5453 else if (ReceiverType->isObjCIdType()) {
5454 // We're messaging "id", so provide all instance methods we know
5455 // about as code-completion results.
5457 // If we have an external source, load the entire class method
5458 // pool from the AST file.
5459 if (ExternalSource) {
5460 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
5462 Selector Sel = ExternalSource->GetExternalSelector(I);
5463 if (Sel.isNull() || MethodPool.count(Sel))
5466 ReadMethodPool(Sel);
5470 for (GlobalMethodPool::iterator M = MethodPool.begin(),
5471 MEnd = MethodPool.end();
5473 for (ObjCMethodList *MethList = &M->second.first;
5474 MethList && MethList->Method;
5475 MethList = MethList->Next) {
5476 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
5480 if (!Selectors.insert(MethList->Method->getSelector()))
5483 Result R(MethList->Method, 0);
5484 R.StartParameter = NumSelIdents;
5485 R.AllParametersAreInformative = false;
5486 Results.MaybeAddResult(R, CurContext);
5490 Results.ExitScope();
5493 // If we're actually at the argument expression (rather than prior to the
5494 // selector), we're actually performing code completion for an expression.
5495 // Determine whether we have a single, best method. If so, we can
5496 // code-complete the expression using the corresponding parameter type as
5497 // our preferred type, improving completion results.
5498 if (AtArgumentExpression) {
5499 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results,
5501 if (PreferredType.isNull())
5502 CodeCompleteOrdinaryName(S, PCC_Expression);
5504 CodeCompleteExpression(S, PreferredType);
5508 HandleCodeCompleteResults(this, CodeCompleter,
5509 Results.getCompletionContext(),
5510 Results.data(),Results.size());
5513 void Sema::CodeCompleteObjCForCollection(Scope *S,
5514 DeclGroupPtrTy IterationVar) {
5515 CodeCompleteExpressionData Data;
5516 Data.ObjCCollection = true;
5518 if (IterationVar.getAsOpaquePtr()) {
5519 DeclGroupRef DG = IterationVar.getAsVal<DeclGroupRef>();
5520 for (DeclGroupRef::iterator I = DG.begin(), End = DG.end(); I != End; ++I) {
5522 Data.IgnoreDecls.push_back(*I);
5526 CodeCompleteExpression(S, Data);
5529 void Sema::CodeCompleteObjCSelector(Scope *S, IdentifierInfo **SelIdents,
5530 unsigned NumSelIdents) {
5531 // If we have an external source, load the entire class method
5532 // pool from the AST file.
5533 if (ExternalSource) {
5534 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
5536 Selector Sel = ExternalSource->GetExternalSelector(I);
5537 if (Sel.isNull() || MethodPool.count(Sel))
5540 ReadMethodPool(Sel);
5544 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5545 CodeCompleter->getCodeCompletionTUInfo(),
5546 CodeCompletionContext::CCC_SelectorName);
5547 Results.EnterNewScope();
5548 for (GlobalMethodPool::iterator M = MethodPool.begin(),
5549 MEnd = MethodPool.end();
5552 Selector Sel = M->first;
5553 if (!isAcceptableObjCSelector(Sel, MK_Any, SelIdents, NumSelIdents))
5556 CodeCompletionBuilder Builder(Results.getAllocator(),
5557 Results.getCodeCompletionTUInfo());
5558 if (Sel.isUnarySelector()) {
5559 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
5560 Sel.getNameForSlot(0)));
5561 Results.AddResult(Builder.TakeString());
5565 std::string Accumulator;
5566 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I) {
5567 if (I == NumSelIdents) {
5568 if (!Accumulator.empty()) {
5569 Builder.AddInformativeChunk(Builder.getAllocator().CopyString(
5571 Accumulator.clear();
5575 Accumulator += Sel.getNameForSlot(I);
5578 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString( Accumulator));
5579 Results.AddResult(Builder.TakeString());
5581 Results.ExitScope();
5583 HandleCodeCompleteResults(this, CodeCompleter,
5584 CodeCompletionContext::CCC_SelectorName,
5585 Results.data(), Results.size());
5588 /// \brief Add all of the protocol declarations that we find in the given
5589 /// (translation unit) context.
5590 static void AddProtocolResults(DeclContext *Ctx, DeclContext *CurContext,
5591 bool OnlyForwardDeclarations,
5592 ResultBuilder &Results) {
5593 typedef CodeCompletionResult Result;
5595 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
5596 DEnd = Ctx->decls_end();
5598 // Record any protocols we find.
5599 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*D))
5600 if (!OnlyForwardDeclarations || !Proto->hasDefinition())
5601 Results.AddResult(Result(Proto, 0), CurContext, 0, false);
5605 void Sema::CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols,
5606 unsigned NumProtocols) {
5607 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5608 CodeCompleter->getCodeCompletionTUInfo(),
5609 CodeCompletionContext::CCC_ObjCProtocolName);
5611 if (CodeCompleter && CodeCompleter->includeGlobals()) {
5612 Results.EnterNewScope();
5614 // Tell the result set to ignore all of the protocols we have
5616 // FIXME: This doesn't work when caching code-completion results.
5617 for (unsigned I = 0; I != NumProtocols; ++I)
5618 if (ObjCProtocolDecl *Protocol = LookupProtocol(Protocols[I].first,
5619 Protocols[I].second))
5620 Results.Ignore(Protocol);
5622 // Add all protocols.
5623 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, false,
5626 Results.ExitScope();
5629 HandleCodeCompleteResults(this, CodeCompleter,
5630 CodeCompletionContext::CCC_ObjCProtocolName,
5631 Results.data(),Results.size());
5634 void Sema::CodeCompleteObjCProtocolDecl(Scope *) {
5635 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5636 CodeCompleter->getCodeCompletionTUInfo(),
5637 CodeCompletionContext::CCC_ObjCProtocolName);
5639 if (CodeCompleter && CodeCompleter->includeGlobals()) {
5640 Results.EnterNewScope();
5642 // Add all protocols.
5643 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, true,
5646 Results.ExitScope();
5649 HandleCodeCompleteResults(this, CodeCompleter,
5650 CodeCompletionContext::CCC_ObjCProtocolName,
5651 Results.data(),Results.size());
5654 /// \brief Add all of the Objective-C interface declarations that we find in
5655 /// the given (translation unit) context.
5656 static void AddInterfaceResults(DeclContext *Ctx, DeclContext *CurContext,
5657 bool OnlyForwardDeclarations,
5658 bool OnlyUnimplemented,
5659 ResultBuilder &Results) {
5660 typedef CodeCompletionResult Result;
5662 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
5663 DEnd = Ctx->decls_end();
5665 // Record any interfaces we find.
5666 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*D))
5667 if ((!OnlyForwardDeclarations || !Class->hasDefinition()) &&
5668 (!OnlyUnimplemented || !Class->getImplementation()))
5669 Results.AddResult(Result(Class, 0), CurContext, 0, false);
5673 void Sema::CodeCompleteObjCInterfaceDecl(Scope *S) {
5674 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5675 CodeCompleter->getCodeCompletionTUInfo(),
5676 CodeCompletionContext::CCC_Other);
5677 Results.EnterNewScope();
5679 if (CodeCompleter->includeGlobals()) {
5681 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
5685 Results.ExitScope();
5687 HandleCodeCompleteResults(this, CodeCompleter,
5688 CodeCompletionContext::CCC_ObjCInterfaceName,
5689 Results.data(),Results.size());
5692 void Sema::CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName,
5693 SourceLocation ClassNameLoc) {
5694 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5695 CodeCompleter->getCodeCompletionTUInfo(),
5696 CodeCompletionContext::CCC_ObjCInterfaceName);
5697 Results.EnterNewScope();
5699 // Make sure that we ignore the class we're currently defining.
5701 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
5702 if (CurClass && isa<ObjCInterfaceDecl>(CurClass))
5703 Results.Ignore(CurClass);
5705 if (CodeCompleter->includeGlobals()) {
5707 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
5711 Results.ExitScope();
5713 HandleCodeCompleteResults(this, CodeCompleter,
5714 CodeCompletionContext::CCC_ObjCInterfaceName,
5715 Results.data(),Results.size());
5718 void Sema::CodeCompleteObjCImplementationDecl(Scope *S) {
5719 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5720 CodeCompleter->getCodeCompletionTUInfo(),
5721 CodeCompletionContext::CCC_Other);
5722 Results.EnterNewScope();
5724 if (CodeCompleter->includeGlobals()) {
5725 // Add all unimplemented classes.
5726 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
5730 Results.ExitScope();
5732 HandleCodeCompleteResults(this, CodeCompleter,
5733 CodeCompletionContext::CCC_ObjCInterfaceName,
5734 Results.data(),Results.size());
5737 void Sema::CodeCompleteObjCInterfaceCategory(Scope *S,
5738 IdentifierInfo *ClassName,
5739 SourceLocation ClassNameLoc) {
5740 typedef CodeCompletionResult Result;
5742 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5743 CodeCompleter->getCodeCompletionTUInfo(),
5744 CodeCompletionContext::CCC_ObjCCategoryName);
5746 // Ignore any categories we find that have already been implemented by this
5748 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
5750 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
5751 if (ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass))
5752 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
5753 Category = Category->getNextClassCategory())
5754 CategoryNames.insert(Category->getIdentifier());
5756 // Add all of the categories we know about.
5757 Results.EnterNewScope();
5758 TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
5759 for (DeclContext::decl_iterator D = TU->decls_begin(),
5760 DEnd = TU->decls_end();
5762 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(*D))
5763 if (CategoryNames.insert(Category->getIdentifier()))
5764 Results.AddResult(Result(Category, 0), CurContext, 0, false);
5765 Results.ExitScope();
5767 HandleCodeCompleteResults(this, CodeCompleter,
5768 CodeCompletionContext::CCC_ObjCCategoryName,
5769 Results.data(),Results.size());
5772 void Sema::CodeCompleteObjCImplementationCategory(Scope *S,
5773 IdentifierInfo *ClassName,
5774 SourceLocation ClassNameLoc) {
5775 typedef CodeCompletionResult Result;
5777 // Find the corresponding interface. If we couldn't find the interface, the
5778 // program itself is ill-formed. However, we'll try to be helpful still by
5779 // providing the list of all of the categories we know about.
5781 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
5782 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass);
5784 return CodeCompleteObjCInterfaceCategory(S, ClassName, ClassNameLoc);
5786 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5787 CodeCompleter->getCodeCompletionTUInfo(),
5788 CodeCompletionContext::CCC_ObjCCategoryName);
5790 // Add all of the categories that have have corresponding interface
5791 // declarations in this class and any of its superclasses, except for
5792 // already-implemented categories in the class itself.
5793 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
5794 Results.EnterNewScope();
5795 bool IgnoreImplemented = true;
5797 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
5798 Category = Category->getNextClassCategory())
5799 if ((!IgnoreImplemented || !Category->getImplementation()) &&
5800 CategoryNames.insert(Category->getIdentifier()))
5801 Results.AddResult(Result(Category, 0), CurContext, 0, false);
5803 Class = Class->getSuperClass();
5804 IgnoreImplemented = false;
5806 Results.ExitScope();
5808 HandleCodeCompleteResults(this, CodeCompleter,
5809 CodeCompletionContext::CCC_ObjCCategoryName,
5810 Results.data(),Results.size());
5813 void Sema::CodeCompleteObjCPropertyDefinition(Scope *S) {
5814 typedef CodeCompletionResult Result;
5815 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5816 CodeCompleter->getCodeCompletionTUInfo(),
5817 CodeCompletionContext::CCC_Other);
5819 // Figure out where this @synthesize lives.
5820 ObjCContainerDecl *Container
5821 = dyn_cast_or_null<ObjCContainerDecl>(CurContext);
5823 (!isa<ObjCImplementationDecl>(Container) &&
5824 !isa<ObjCCategoryImplDecl>(Container)))
5827 // Ignore any properties that have already been implemented.
5828 for (DeclContext::decl_iterator D = Container->decls_begin(),
5829 DEnd = Container->decls_end();
5831 if (ObjCPropertyImplDecl *PropertyImpl = dyn_cast<ObjCPropertyImplDecl>(*D))
5832 Results.Ignore(PropertyImpl->getPropertyDecl());
5834 // Add any properties that we find.
5835 AddedPropertiesSet AddedProperties;
5836 Results.EnterNewScope();
5837 if (ObjCImplementationDecl *ClassImpl
5838 = dyn_cast<ObjCImplementationDecl>(Container))
5839 AddObjCProperties(ClassImpl->getClassInterface(), false,
5840 /*AllowNullaryMethods=*/false, CurContext,
5841 AddedProperties, Results);
5843 AddObjCProperties(cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl(),
5844 false, /*AllowNullaryMethods=*/false, CurContext,
5845 AddedProperties, Results);
5846 Results.ExitScope();
5848 HandleCodeCompleteResults(this, CodeCompleter,
5849 CodeCompletionContext::CCC_Other,
5850 Results.data(),Results.size());
5853 void Sema::CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
5854 IdentifierInfo *PropertyName) {
5855 typedef CodeCompletionResult Result;
5856 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5857 CodeCompleter->getCodeCompletionTUInfo(),
5858 CodeCompletionContext::CCC_Other);
5860 // Figure out where this @synthesize lives.
5861 ObjCContainerDecl *Container
5862 = dyn_cast_or_null<ObjCContainerDecl>(CurContext);
5864 (!isa<ObjCImplementationDecl>(Container) &&
5865 !isa<ObjCCategoryImplDecl>(Container)))
5868 // Figure out which interface we're looking into.
5869 ObjCInterfaceDecl *Class = 0;
5870 if (ObjCImplementationDecl *ClassImpl
5871 = dyn_cast<ObjCImplementationDecl>(Container))
5872 Class = ClassImpl->getClassInterface();
5874 Class = cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl()
5875 ->getClassInterface();
5877 // Determine the type of the property we're synthesizing.
5878 QualType PropertyType = Context.getObjCIdType();
5880 if (ObjCPropertyDecl *Property
5881 = Class->FindPropertyDeclaration(PropertyName)) {
5883 = Property->getType().getNonReferenceType().getUnqualifiedType();
5885 // Give preference to ivars
5886 Results.setPreferredType(PropertyType);
5890 // Add all of the instance variables in this class and its superclasses.
5891 Results.EnterNewScope();
5892 bool SawSimilarlyNamedIvar = false;
5893 std::string NameWithPrefix;
5894 NameWithPrefix += '_';
5895 NameWithPrefix += PropertyName->getName();
5896 std::string NameWithSuffix = PropertyName->getName().str();
5897 NameWithSuffix += '_';
5898 for(; Class; Class = Class->getSuperClass()) {
5899 for (ObjCIvarDecl *Ivar = Class->all_declared_ivar_begin(); Ivar;
5900 Ivar = Ivar->getNextIvar()) {
5901 Results.AddResult(Result(Ivar, 0), CurContext, 0, false);
5903 // Determine whether we've seen an ivar with a name similar to the
5905 if ((PropertyName == Ivar->getIdentifier() ||
5906 NameWithPrefix == Ivar->getName() ||
5907 NameWithSuffix == Ivar->getName())) {
5908 SawSimilarlyNamedIvar = true;
5910 // Reduce the priority of this result by one, to give it a slight
5911 // advantage over other results whose names don't match so closely.
5912 if (Results.size() &&
5913 Results.data()[Results.size() - 1].Kind
5914 == CodeCompletionResult::RK_Declaration &&
5915 Results.data()[Results.size() - 1].Declaration == Ivar)
5916 Results.data()[Results.size() - 1].Priority--;
5921 if (!SawSimilarlyNamedIvar) {
5922 // Create ivar result _propName, that the user can use to synthesize
5923 // an ivar of the appropriate type.
5924 unsigned Priority = CCP_MemberDeclaration + 1;
5925 typedef CodeCompletionResult Result;
5926 CodeCompletionAllocator &Allocator = Results.getAllocator();
5927 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo(),
5928 Priority,CXAvailability_Available);
5930 PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
5931 Builder.AddResultTypeChunk(GetCompletionTypeString(PropertyType, Context,
5932 Policy, Allocator));
5933 Builder.AddTypedTextChunk(Allocator.CopyString(NameWithPrefix));
5934 Results.AddResult(Result(Builder.TakeString(), Priority,
5935 CXCursor_ObjCIvarDecl));
5938 Results.ExitScope();
5940 HandleCodeCompleteResults(this, CodeCompleter,
5941 CodeCompletionContext::CCC_Other,
5942 Results.data(),Results.size());
5945 // Mapping from selectors to the methods that implement that selector, along
5946 // with the "in original class" flag.
5947 typedef llvm::DenseMap<Selector, std::pair<ObjCMethodDecl *, bool> >
5950 /// \brief Find all of the methods that reside in the given container
5951 /// (and its superclasses, protocols, etc.) that meet the given
5952 /// criteria. Insert those methods into the map of known methods,
5953 /// indexed by selector so they can be easily found.
5954 static void FindImplementableMethods(ASTContext &Context,
5955 ObjCContainerDecl *Container,
5956 bool WantInstanceMethods,
5957 QualType ReturnType,
5958 KnownMethodsMap &KnownMethods,
5959 bool InOriginalClass = true) {
5960 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)) {
5961 // Recurse into protocols.
5962 if (!IFace->hasDefinition())
5965 const ObjCList<ObjCProtocolDecl> &Protocols
5966 = IFace->getReferencedProtocols();
5967 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
5968 E = Protocols.end();
5970 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
5971 KnownMethods, InOriginalClass);
5973 // Add methods from any class extensions and categories.
5974 for (const ObjCCategoryDecl *Cat = IFace->getCategoryList(); Cat;
5975 Cat = Cat->getNextClassCategory())
5976 FindImplementableMethods(Context, const_cast<ObjCCategoryDecl*>(Cat),
5977 WantInstanceMethods, ReturnType,
5978 KnownMethods, false);
5980 // Visit the superclass.
5981 if (IFace->getSuperClass())
5982 FindImplementableMethods(Context, IFace->getSuperClass(),
5983 WantInstanceMethods, ReturnType,
5984 KnownMethods, false);
5987 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
5988 // Recurse into protocols.
5989 const ObjCList<ObjCProtocolDecl> &Protocols
5990 = Category->getReferencedProtocols();
5991 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
5992 E = Protocols.end();
5994 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
5995 KnownMethods, InOriginalClass);
5997 // If this category is the original class, jump to the interface.
5998 if (InOriginalClass && Category->getClassInterface())
5999 FindImplementableMethods(Context, Category->getClassInterface(),
6000 WantInstanceMethods, ReturnType, KnownMethods,
6004 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
6005 if (Protocol->hasDefinition()) {
6006 // Recurse into protocols.
6007 const ObjCList<ObjCProtocolDecl> &Protocols
6008 = Protocol->getReferencedProtocols();
6009 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
6010 E = Protocols.end();
6012 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
6013 KnownMethods, false);
6017 // Add methods in this container. This operation occurs last because
6018 // we want the methods from this container to override any methods
6019 // we've previously seen with the same selector.
6020 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
6021 MEnd = Container->meth_end();
6023 if ((*M)->isInstanceMethod() == WantInstanceMethods) {
6024 if (!ReturnType.isNull() &&
6025 !Context.hasSameUnqualifiedType(ReturnType, (*M)->getResultType()))
6028 KnownMethods[(*M)->getSelector()] = std::make_pair(*M, InOriginalClass);
6033 /// \brief Add the parenthesized return or parameter type chunk to a code
6034 /// completion string.
6035 static void AddObjCPassingTypeChunk(QualType Type,
6036 unsigned ObjCDeclQuals,
6037 ASTContext &Context,
6038 const PrintingPolicy &Policy,
6039 CodeCompletionBuilder &Builder) {
6040 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6041 std::string Quals = formatObjCParamQualifiers(ObjCDeclQuals);
6043 Builder.AddTextChunk(Builder.getAllocator().CopyString(Quals));
6044 Builder.AddTextChunk(GetCompletionTypeString(Type, Context, Policy,
6045 Builder.getAllocator()));
6046 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6049 /// \brief Determine whether the given class is or inherits from a class by
6051 static bool InheritsFromClassNamed(ObjCInterfaceDecl *Class,
6056 if (Class->getIdentifier() && Class->getIdentifier()->getName() == Name)
6059 return InheritsFromClassNamed(Class->getSuperClass(), Name);
6062 /// \brief Add code completions for Objective-C Key-Value Coding (KVC) and
6063 /// Key-Value Observing (KVO).
6064 static void AddObjCKeyValueCompletions(ObjCPropertyDecl *Property,
6065 bool IsInstanceMethod,
6066 QualType ReturnType,
6067 ASTContext &Context,
6068 VisitedSelectorSet &KnownSelectors,
6069 ResultBuilder &Results) {
6070 IdentifierInfo *PropName = Property->getIdentifier();
6071 if (!PropName || PropName->getLength() == 0)
6074 PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema());
6076 // Builder that will create each code completion.
6077 typedef CodeCompletionResult Result;
6078 CodeCompletionAllocator &Allocator = Results.getAllocator();
6079 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
6081 // The selector table.
6082 SelectorTable &Selectors = Context.Selectors;
6084 // The property name, copied into the code completion allocation region
6087 CodeCompletionAllocator &Allocator;
6089 const char *CopiedKey;
6091 KeyHolder(CodeCompletionAllocator &Allocator, StringRef Key)
6092 : Allocator(Allocator), Key(Key), CopiedKey(0) { }
6094 operator const char *() {
6098 return CopiedKey = Allocator.CopyString(Key);
6100 } Key(Allocator, PropName->getName());
6102 // The uppercased name of the property name.
6103 std::string UpperKey = PropName->getName();
6104 if (!UpperKey.empty())
6105 UpperKey[0] = toupper(UpperKey[0]);
6107 bool ReturnTypeMatchesProperty = ReturnType.isNull() ||
6108 Context.hasSameUnqualifiedType(ReturnType.getNonReferenceType(),
6109 Property->getType());
6110 bool ReturnTypeMatchesVoid
6111 = ReturnType.isNull() || ReturnType->isVoidType();
6113 // Add the normal accessor -(type)key.
6114 if (IsInstanceMethod &&
6115 KnownSelectors.insert(Selectors.getNullarySelector(PropName)) &&
6116 ReturnTypeMatchesProperty && !Property->getGetterMethodDecl()) {
6117 if (ReturnType.isNull())
6118 AddObjCPassingTypeChunk(Property->getType(), /*Quals=*/0,
6119 Context, Policy, Builder);
6121 Builder.AddTypedTextChunk(Key);
6122 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6123 CXCursor_ObjCInstanceMethodDecl));
6126 // If we have an integral or boolean property (or the user has provided
6127 // an integral or boolean return type), add the accessor -(type)isKey.
6128 if (IsInstanceMethod &&
6129 ((!ReturnType.isNull() &&
6130 (ReturnType->isIntegerType() || ReturnType->isBooleanType())) ||
6131 (ReturnType.isNull() &&
6132 (Property->getType()->isIntegerType() ||
6133 Property->getType()->isBooleanType())))) {
6134 std::string SelectorName = (Twine("is") + UpperKey).str();
6135 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6136 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
6137 if (ReturnType.isNull()) {
6138 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6139 Builder.AddTextChunk("BOOL");
6140 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6143 Builder.AddTypedTextChunk(
6144 Allocator.CopyString(SelectorId->getName()));
6145 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6146 CXCursor_ObjCInstanceMethodDecl));
6150 // Add the normal mutator.
6151 if (IsInstanceMethod && ReturnTypeMatchesVoid &&
6152 !Property->getSetterMethodDecl()) {
6153 std::string SelectorName = (Twine("set") + UpperKey).str();
6154 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6155 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
6156 if (ReturnType.isNull()) {
6157 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6158 Builder.AddTextChunk("void");
6159 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6162 Builder.AddTypedTextChunk(
6163 Allocator.CopyString(SelectorId->getName()));
6164 Builder.AddTypedTextChunk(":");
6165 AddObjCPassingTypeChunk(Property->getType(), /*Quals=*/0,
6166 Context, Policy, Builder);
6167 Builder.AddTextChunk(Key);
6168 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6169 CXCursor_ObjCInstanceMethodDecl));
6173 // Indexed and unordered accessors
6174 unsigned IndexedGetterPriority = CCP_CodePattern;
6175 unsigned IndexedSetterPriority = CCP_CodePattern;
6176 unsigned UnorderedGetterPriority = CCP_CodePattern;
6177 unsigned UnorderedSetterPriority = CCP_CodePattern;
6178 if (const ObjCObjectPointerType *ObjCPointer
6179 = Property->getType()->getAs<ObjCObjectPointerType>()) {
6180 if (ObjCInterfaceDecl *IFace = ObjCPointer->getInterfaceDecl()) {
6181 // If this interface type is not provably derived from a known
6182 // collection, penalize the corresponding completions.
6183 if (!InheritsFromClassNamed(IFace, "NSMutableArray")) {
6184 IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
6185 if (!InheritsFromClassNamed(IFace, "NSArray"))
6186 IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
6189 if (!InheritsFromClassNamed(IFace, "NSMutableSet")) {
6190 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
6191 if (!InheritsFromClassNamed(IFace, "NSSet"))
6192 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
6196 IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
6197 IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
6198 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
6199 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
6202 // Add -(NSUInteger)countOf<key>
6203 if (IsInstanceMethod &&
6204 (ReturnType.isNull() || ReturnType->isIntegerType())) {
6205 std::string SelectorName = (Twine("countOf") + UpperKey).str();
6206 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6207 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
6208 if (ReturnType.isNull()) {
6209 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6210 Builder.AddTextChunk("NSUInteger");
6211 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6214 Builder.AddTypedTextChunk(
6215 Allocator.CopyString(SelectorId->getName()));
6216 Results.AddResult(Result(Builder.TakeString(),
6217 std::min(IndexedGetterPriority,
6218 UnorderedGetterPriority),
6219 CXCursor_ObjCInstanceMethodDecl));
6224 // Add -(id)objectInKeyAtIndex:(NSUInteger)index
6225 if (IsInstanceMethod &&
6226 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
6227 std::string SelectorName
6228 = (Twine("objectIn") + UpperKey + "AtIndex").str();
6229 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6230 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
6231 if (ReturnType.isNull()) {
6232 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6233 Builder.AddTextChunk("id");
6234 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6237 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6238 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6239 Builder.AddTextChunk("NSUInteger");
6240 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6241 Builder.AddTextChunk("index");
6242 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
6243 CXCursor_ObjCInstanceMethodDecl));
6247 // Add -(NSArray *)keyAtIndexes:(NSIndexSet *)indexes
6248 if (IsInstanceMethod &&
6249 (ReturnType.isNull() ||
6250 (ReturnType->isObjCObjectPointerType() &&
6251 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6252 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6253 ->getName() == "NSArray"))) {
6254 std::string SelectorName
6255 = (Twine(Property->getName()) + "AtIndexes").str();
6256 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6257 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
6258 if (ReturnType.isNull()) {
6259 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6260 Builder.AddTextChunk("NSArray *");
6261 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6264 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6265 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6266 Builder.AddTextChunk("NSIndexSet *");
6267 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6268 Builder.AddTextChunk("indexes");
6269 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
6270 CXCursor_ObjCInstanceMethodDecl));
6274 // Add -(void)getKey:(type **)buffer range:(NSRange)inRange
6275 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
6276 std::string SelectorName = (Twine("get") + UpperKey).str();
6277 IdentifierInfo *SelectorIds[2] = {
6278 &Context.Idents.get(SelectorName),
6279 &Context.Idents.get("range")
6282 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
6283 if (ReturnType.isNull()) {
6284 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6285 Builder.AddTextChunk("void");
6286 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6289 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6290 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6291 Builder.AddPlaceholderChunk("object-type");
6292 Builder.AddTextChunk(" **");
6293 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6294 Builder.AddTextChunk("buffer");
6295 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6296 Builder.AddTypedTextChunk("range:");
6297 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6298 Builder.AddTextChunk("NSRange");
6299 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6300 Builder.AddTextChunk("inRange");
6301 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
6302 CXCursor_ObjCInstanceMethodDecl));
6306 // Mutable indexed accessors
6308 // - (void)insertObject:(type *)object inKeyAtIndex:(NSUInteger)index
6309 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
6310 std::string SelectorName = (Twine("in") + UpperKey + "AtIndex").str();
6311 IdentifierInfo *SelectorIds[2] = {
6312 &Context.Idents.get("insertObject"),
6313 &Context.Idents.get(SelectorName)
6316 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
6317 if (ReturnType.isNull()) {
6318 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6319 Builder.AddTextChunk("void");
6320 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6323 Builder.AddTypedTextChunk("insertObject:");
6324 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6325 Builder.AddPlaceholderChunk("object-type");
6326 Builder.AddTextChunk(" *");
6327 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6328 Builder.AddTextChunk("object");
6329 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6330 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6331 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6332 Builder.AddPlaceholderChunk("NSUInteger");
6333 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6334 Builder.AddTextChunk("index");
6335 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6336 CXCursor_ObjCInstanceMethodDecl));
6340 // - (void)insertKey:(NSArray *)array atIndexes:(NSIndexSet *)indexes
6341 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
6342 std::string SelectorName = (Twine("insert") + UpperKey).str();
6343 IdentifierInfo *SelectorIds[2] = {
6344 &Context.Idents.get(SelectorName),
6345 &Context.Idents.get("atIndexes")
6348 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
6349 if (ReturnType.isNull()) {
6350 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6351 Builder.AddTextChunk("void");
6352 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6355 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6356 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6357 Builder.AddTextChunk("NSArray *");
6358 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6359 Builder.AddTextChunk("array");
6360 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6361 Builder.AddTypedTextChunk("atIndexes:");
6362 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6363 Builder.AddPlaceholderChunk("NSIndexSet *");
6364 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6365 Builder.AddTextChunk("indexes");
6366 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6367 CXCursor_ObjCInstanceMethodDecl));
6371 // -(void)removeObjectFromKeyAtIndex:(NSUInteger)index
6372 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
6373 std::string SelectorName
6374 = (Twine("removeObjectFrom") + UpperKey + "AtIndex").str();
6375 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6376 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
6377 if (ReturnType.isNull()) {
6378 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6379 Builder.AddTextChunk("void");
6380 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6383 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6384 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6385 Builder.AddTextChunk("NSUInteger");
6386 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6387 Builder.AddTextChunk("index");
6388 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6389 CXCursor_ObjCInstanceMethodDecl));
6393 // -(void)removeKeyAtIndexes:(NSIndexSet *)indexes
6394 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
6395 std::string SelectorName
6396 = (Twine("remove") + UpperKey + "AtIndexes").str();
6397 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6398 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
6399 if (ReturnType.isNull()) {
6400 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6401 Builder.AddTextChunk("void");
6402 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6405 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6406 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6407 Builder.AddTextChunk("NSIndexSet *");
6408 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6409 Builder.AddTextChunk("indexes");
6410 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6411 CXCursor_ObjCInstanceMethodDecl));
6415 // - (void)replaceObjectInKeyAtIndex:(NSUInteger)index withObject:(id)object
6416 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
6417 std::string SelectorName
6418 = (Twine("replaceObjectIn") + UpperKey + "AtIndex").str();
6419 IdentifierInfo *SelectorIds[2] = {
6420 &Context.Idents.get(SelectorName),
6421 &Context.Idents.get("withObject")
6424 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
6425 if (ReturnType.isNull()) {
6426 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6427 Builder.AddTextChunk("void");
6428 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6431 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6432 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6433 Builder.AddPlaceholderChunk("NSUInteger");
6434 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6435 Builder.AddTextChunk("index");
6436 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6437 Builder.AddTypedTextChunk("withObject:");
6438 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6439 Builder.AddTextChunk("id");
6440 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6441 Builder.AddTextChunk("object");
6442 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6443 CXCursor_ObjCInstanceMethodDecl));
6447 // - (void)replaceKeyAtIndexes:(NSIndexSet *)indexes withKey:(NSArray *)array
6448 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
6449 std::string SelectorName1
6450 = (Twine("replace") + UpperKey + "AtIndexes").str();
6451 std::string SelectorName2 = (Twine("with") + UpperKey).str();
6452 IdentifierInfo *SelectorIds[2] = {
6453 &Context.Idents.get(SelectorName1),
6454 &Context.Idents.get(SelectorName2)
6457 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds))) {
6458 if (ReturnType.isNull()) {
6459 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6460 Builder.AddTextChunk("void");
6461 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6464 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName1 + ":"));
6465 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6466 Builder.AddPlaceholderChunk("NSIndexSet *");
6467 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6468 Builder.AddTextChunk("indexes");
6469 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6470 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName2 + ":"));
6471 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6472 Builder.AddTextChunk("NSArray *");
6473 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6474 Builder.AddTextChunk("array");
6475 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
6476 CXCursor_ObjCInstanceMethodDecl));
6480 // Unordered getters
6481 // - (NSEnumerator *)enumeratorOfKey
6482 if (IsInstanceMethod &&
6483 (ReturnType.isNull() ||
6484 (ReturnType->isObjCObjectPointerType() &&
6485 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6486 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6487 ->getName() == "NSEnumerator"))) {
6488 std::string SelectorName = (Twine("enumeratorOf") + UpperKey).str();
6489 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6490 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
6491 if (ReturnType.isNull()) {
6492 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6493 Builder.AddTextChunk("NSEnumerator *");
6494 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6497 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6498 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
6499 CXCursor_ObjCInstanceMethodDecl));
6503 // - (type *)memberOfKey:(type *)object
6504 if (IsInstanceMethod &&
6505 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
6506 std::string SelectorName = (Twine("memberOf") + UpperKey).str();
6507 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6508 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
6509 if (ReturnType.isNull()) {
6510 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6511 Builder.AddPlaceholderChunk("object-type");
6512 Builder.AddTextChunk(" *");
6513 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6516 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6517 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6518 if (ReturnType.isNull()) {
6519 Builder.AddPlaceholderChunk("object-type");
6520 Builder.AddTextChunk(" *");
6522 Builder.AddTextChunk(GetCompletionTypeString(ReturnType, Context,
6524 Builder.getAllocator()));
6526 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6527 Builder.AddTextChunk("object");
6528 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
6529 CXCursor_ObjCInstanceMethodDecl));
6533 // Mutable unordered accessors
6534 // - (void)addKeyObject:(type *)object
6535 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
6536 std::string SelectorName
6537 = (Twine("add") + UpperKey + Twine("Object")).str();
6538 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6539 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
6540 if (ReturnType.isNull()) {
6541 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6542 Builder.AddTextChunk("void");
6543 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6546 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6547 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6548 Builder.AddPlaceholderChunk("object-type");
6549 Builder.AddTextChunk(" *");
6550 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6551 Builder.AddTextChunk("object");
6552 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6553 CXCursor_ObjCInstanceMethodDecl));
6557 // - (void)addKey:(NSSet *)objects
6558 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
6559 std::string SelectorName = (Twine("add") + UpperKey).str();
6560 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6561 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
6562 if (ReturnType.isNull()) {
6563 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6564 Builder.AddTextChunk("void");
6565 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6568 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6569 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6570 Builder.AddTextChunk("NSSet *");
6571 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6572 Builder.AddTextChunk("objects");
6573 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6574 CXCursor_ObjCInstanceMethodDecl));
6578 // - (void)removeKeyObject:(type *)object
6579 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
6580 std::string SelectorName
6581 = (Twine("remove") + UpperKey + Twine("Object")).str();
6582 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6583 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
6584 if (ReturnType.isNull()) {
6585 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6586 Builder.AddTextChunk("void");
6587 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6590 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6591 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6592 Builder.AddPlaceholderChunk("object-type");
6593 Builder.AddTextChunk(" *");
6594 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6595 Builder.AddTextChunk("object");
6596 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6597 CXCursor_ObjCInstanceMethodDecl));
6601 // - (void)removeKey:(NSSet *)objects
6602 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
6603 std::string SelectorName = (Twine("remove") + UpperKey).str();
6604 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6605 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
6606 if (ReturnType.isNull()) {
6607 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6608 Builder.AddTextChunk("void");
6609 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6612 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6613 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6614 Builder.AddTextChunk("NSSet *");
6615 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6616 Builder.AddTextChunk("objects");
6617 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6618 CXCursor_ObjCInstanceMethodDecl));
6622 // - (void)intersectKey:(NSSet *)objects
6623 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
6624 std::string SelectorName = (Twine("intersect") + UpperKey).str();
6625 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6626 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId))) {
6627 if (ReturnType.isNull()) {
6628 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6629 Builder.AddTextChunk("void");
6630 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6633 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
6634 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6635 Builder.AddTextChunk("NSSet *");
6636 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6637 Builder.AddTextChunk("objects");
6638 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
6639 CXCursor_ObjCInstanceMethodDecl));
6643 // Key-Value Observing
6644 // + (NSSet *)keyPathsForValuesAffectingKey
6645 if (!IsInstanceMethod &&
6646 (ReturnType.isNull() ||
6647 (ReturnType->isObjCObjectPointerType() &&
6648 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
6649 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()
6650 ->getName() == "NSSet"))) {
6651 std::string SelectorName
6652 = (Twine("keyPathsForValuesAffecting") + UpperKey).str();
6653 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6654 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
6655 if (ReturnType.isNull()) {
6656 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6657 Builder.AddTextChunk("NSSet *");
6658 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6661 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6662 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6663 CXCursor_ObjCClassMethodDecl));
6667 // + (BOOL)automaticallyNotifiesObserversForKey
6668 if (!IsInstanceMethod &&
6669 (ReturnType.isNull() ||
6670 ReturnType->isIntegerType() ||
6671 ReturnType->isBooleanType())) {
6672 std::string SelectorName
6673 = (Twine("automaticallyNotifiesObserversOf") + UpperKey).str();
6674 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
6675 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))) {
6676 if (ReturnType.isNull()) {
6677 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6678 Builder.AddTextChunk("BOOL");
6679 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6682 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
6683 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
6684 CXCursor_ObjCClassMethodDecl));
6689 void Sema::CodeCompleteObjCMethodDecl(Scope *S,
6690 bool IsInstanceMethod,
6691 ParsedType ReturnTy) {
6692 // Determine the return type of the method we're declaring, if
6694 QualType ReturnType = GetTypeFromParser(ReturnTy);
6696 if (CurContext->isObjCContainer()) {
6697 ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext);
6698 IDecl = cast<Decl>(OCD);
6700 // Determine where we should start searching for methods.
6701 ObjCContainerDecl *SearchDecl = 0;
6702 bool IsInImplementation = false;
6703 if (Decl *D = IDecl) {
6704 if (ObjCImplementationDecl *Impl = dyn_cast<ObjCImplementationDecl>(D)) {
6705 SearchDecl = Impl->getClassInterface();
6706 IsInImplementation = true;
6707 } else if (ObjCCategoryImplDecl *CatImpl
6708 = dyn_cast<ObjCCategoryImplDecl>(D)) {
6709 SearchDecl = CatImpl->getCategoryDecl();
6710 IsInImplementation = true;
6712 SearchDecl = dyn_cast<ObjCContainerDecl>(D);
6715 if (!SearchDecl && S) {
6716 if (DeclContext *DC = static_cast<DeclContext *>(S->getEntity()))
6717 SearchDecl = dyn_cast<ObjCContainerDecl>(DC);
6721 HandleCodeCompleteResults(this, CodeCompleter,
6722 CodeCompletionContext::CCC_Other,
6727 // Find all of the methods that we could declare/implement here.
6728 KnownMethodsMap KnownMethods;
6729 FindImplementableMethods(Context, SearchDecl, IsInstanceMethod,
6730 ReturnType, KnownMethods);
6732 // Add declarations or definitions for each of the known methods.
6733 typedef CodeCompletionResult Result;
6734 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6735 CodeCompleter->getCodeCompletionTUInfo(),
6736 CodeCompletionContext::CCC_Other);
6737 Results.EnterNewScope();
6738 PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
6739 for (KnownMethodsMap::iterator M = KnownMethods.begin(),
6740 MEnd = KnownMethods.end();
6742 ObjCMethodDecl *Method = M->second.first;
6743 CodeCompletionBuilder Builder(Results.getAllocator(),
6744 Results.getCodeCompletionTUInfo());
6746 // If the result type was not already provided, add it to the
6747 // pattern as (type).
6748 if (ReturnType.isNull())
6749 AddObjCPassingTypeChunk(Method->getResultType(),
6750 Method->getObjCDeclQualifier(),
6754 Selector Sel = Method->getSelector();
6756 // Add the first part of the selector to the pattern.
6757 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
6758 Sel.getNameForSlot(0)));
6760 // Add parameters to the pattern.
6762 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
6763 PEnd = Method->param_end();
6764 P != PEnd; (void)++P, ++I) {
6765 // Add the part of the selector name.
6767 Builder.AddTypedTextChunk(":");
6768 else if (I < Sel.getNumArgs()) {
6769 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6770 Builder.AddTypedTextChunk(
6771 Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":"));
6775 // Add the parameter type.
6776 AddObjCPassingTypeChunk((*P)->getOriginalType(),
6777 (*P)->getObjCDeclQualifier(),
6781 if (IdentifierInfo *Id = (*P)->getIdentifier())
6782 Builder.AddTextChunk(Builder.getAllocator().CopyString( Id->getName()));
6785 if (Method->isVariadic()) {
6786 if (Method->param_size() > 0)
6787 Builder.AddChunk(CodeCompletionString::CK_Comma);
6788 Builder.AddTextChunk("...");
6791 if (IsInImplementation && Results.includeCodePatterns()) {
6792 // We will be defining the method here, so add a compound statement.
6793 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6794 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
6795 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
6796 if (!Method->getResultType()->isVoidType()) {
6797 // If the result type is not void, add a return clause.
6798 Builder.AddTextChunk("return");
6799 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6800 Builder.AddPlaceholderChunk("expression");
6801 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
6803 Builder.AddPlaceholderChunk("statements");
6805 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
6806 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
6809 unsigned Priority = CCP_CodePattern;
6810 if (!M->second.second)
6811 Priority += CCD_InBaseClass;
6813 Results.AddResult(Result(Builder.TakeString(), Method, Priority));
6816 // Add Key-Value-Coding and Key-Value-Observing accessor methods for all of
6817 // the properties in this class and its categories.
6818 if (Context.getLangOpts().ObjC2) {
6819 SmallVector<ObjCContainerDecl *, 4> Containers;
6820 Containers.push_back(SearchDecl);
6822 VisitedSelectorSet KnownSelectors;
6823 for (KnownMethodsMap::iterator M = KnownMethods.begin(),
6824 MEnd = KnownMethods.end();
6826 KnownSelectors.insert(M->first);
6829 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(SearchDecl);
6831 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(SearchDecl))
6832 IFace = Category->getClassInterface();
6835 for (ObjCCategoryDecl *Category = IFace->getCategoryList(); Category;
6836 Category = Category->getNextClassCategory())
6837 Containers.push_back(Category);
6840 for (unsigned I = 0, N = Containers.size(); I != N; ++I) {
6841 for (ObjCContainerDecl::prop_iterator P = Containers[I]->prop_begin(),
6842 PEnd = Containers[I]->prop_end();
6844 AddObjCKeyValueCompletions(*P, IsInstanceMethod, ReturnType, Context,
6845 KnownSelectors, Results);
6850 Results.ExitScope();
6852 HandleCodeCompleteResults(this, CodeCompleter,
6853 CodeCompletionContext::CCC_Other,
6854 Results.data(),Results.size());
6857 void Sema::CodeCompleteObjCMethodDeclSelector(Scope *S,
6858 bool IsInstanceMethod,
6859 bool AtParameterName,
6860 ParsedType ReturnTy,
6861 IdentifierInfo **SelIdents,
6862 unsigned NumSelIdents) {
6863 // If we have an external source, load the entire class method
6864 // pool from the AST file.
6865 if (ExternalSource) {
6866 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
6868 Selector Sel = ExternalSource->GetExternalSelector(I);
6869 if (Sel.isNull() || MethodPool.count(Sel))
6872 ReadMethodPool(Sel);
6876 // Build the set of methods we can see.
6877 typedef CodeCompletionResult Result;
6878 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6879 CodeCompleter->getCodeCompletionTUInfo(),
6880 CodeCompletionContext::CCC_Other);
6883 Results.setPreferredType(GetTypeFromParser(ReturnTy).getNonReferenceType());
6885 Results.EnterNewScope();
6886 for (GlobalMethodPool::iterator M = MethodPool.begin(),
6887 MEnd = MethodPool.end();
6889 for (ObjCMethodList *MethList = IsInstanceMethod ? &M->second.first :
6891 MethList && MethList->Method;
6892 MethList = MethList->Next) {
6893 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
6897 if (AtParameterName) {
6898 // Suggest parameter names we've seen before.
6899 if (NumSelIdents && NumSelIdents <= MethList->Method->param_size()) {
6900 ParmVarDecl *Param = MethList->Method->param_begin()[NumSelIdents-1];
6901 if (Param->getIdentifier()) {
6902 CodeCompletionBuilder Builder(Results.getAllocator(),
6903 Results.getCodeCompletionTUInfo());
6904 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
6905 Param->getIdentifier()->getName()));
6906 Results.AddResult(Builder.TakeString());
6913 Result R(MethList->Method, 0);
6914 R.StartParameter = NumSelIdents;
6915 R.AllParametersAreInformative = false;
6916 R.DeclaringEntity = true;
6917 Results.MaybeAddResult(R, CurContext);
6921 Results.ExitScope();
6922 HandleCodeCompleteResults(this, CodeCompleter,
6923 CodeCompletionContext::CCC_Other,
6924 Results.data(),Results.size());
6927 void Sema::CodeCompletePreprocessorDirective(bool InConditional) {
6928 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
6929 CodeCompleter->getCodeCompletionTUInfo(),
6930 CodeCompletionContext::CCC_PreprocessorDirective);
6931 Results.EnterNewScope();
6934 CodeCompletionBuilder Builder(Results.getAllocator(),
6935 Results.getCodeCompletionTUInfo());
6936 Builder.AddTypedTextChunk("if");
6937 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6938 Builder.AddPlaceholderChunk("condition");
6939 Results.AddResult(Builder.TakeString());
6942 Builder.AddTypedTextChunk("ifdef");
6943 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6944 Builder.AddPlaceholderChunk("macro");
6945 Results.AddResult(Builder.TakeString());
6948 Builder.AddTypedTextChunk("ifndef");
6949 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6950 Builder.AddPlaceholderChunk("macro");
6951 Results.AddResult(Builder.TakeString());
6953 if (InConditional) {
6954 // #elif <condition>
6955 Builder.AddTypedTextChunk("elif");
6956 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6957 Builder.AddPlaceholderChunk("condition");
6958 Results.AddResult(Builder.TakeString());
6961 Builder.AddTypedTextChunk("else");
6962 Results.AddResult(Builder.TakeString());
6965 Builder.AddTypedTextChunk("endif");
6966 Results.AddResult(Builder.TakeString());
6969 // #include "header"
6970 Builder.AddTypedTextChunk("include");
6971 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6972 Builder.AddTextChunk("\"");
6973 Builder.AddPlaceholderChunk("header");
6974 Builder.AddTextChunk("\"");
6975 Results.AddResult(Builder.TakeString());
6977 // #include <header>
6978 Builder.AddTypedTextChunk("include");
6979 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6980 Builder.AddTextChunk("<");
6981 Builder.AddPlaceholderChunk("header");
6982 Builder.AddTextChunk(">");
6983 Results.AddResult(Builder.TakeString());
6986 Builder.AddTypedTextChunk("define");
6987 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6988 Builder.AddPlaceholderChunk("macro");
6989 Results.AddResult(Builder.TakeString());
6991 // #define <macro>(<args>)
6992 Builder.AddTypedTextChunk("define");
6993 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
6994 Builder.AddPlaceholderChunk("macro");
6995 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6996 Builder.AddPlaceholderChunk("args");
6997 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6998 Results.AddResult(Builder.TakeString());
7001 Builder.AddTypedTextChunk("undef");
7002 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7003 Builder.AddPlaceholderChunk("macro");
7004 Results.AddResult(Builder.TakeString());
7007 Builder.AddTypedTextChunk("line");
7008 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7009 Builder.AddPlaceholderChunk("number");
7010 Results.AddResult(Builder.TakeString());
7012 // #line <number> "filename"
7013 Builder.AddTypedTextChunk("line");
7014 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7015 Builder.AddPlaceholderChunk("number");
7016 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7017 Builder.AddTextChunk("\"");
7018 Builder.AddPlaceholderChunk("filename");
7019 Builder.AddTextChunk("\"");
7020 Results.AddResult(Builder.TakeString());
7023 Builder.AddTypedTextChunk("error");
7024 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7025 Builder.AddPlaceholderChunk("message");
7026 Results.AddResult(Builder.TakeString());
7028 // #pragma <arguments>
7029 Builder.AddTypedTextChunk("pragma");
7030 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7031 Builder.AddPlaceholderChunk("arguments");
7032 Results.AddResult(Builder.TakeString());
7034 if (getLangOpts().ObjC1) {
7036 Builder.AddTypedTextChunk("import");
7037 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7038 Builder.AddTextChunk("\"");
7039 Builder.AddPlaceholderChunk("header");
7040 Builder.AddTextChunk("\"");
7041 Results.AddResult(Builder.TakeString());
7044 Builder.AddTypedTextChunk("import");
7045 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7046 Builder.AddTextChunk("<");
7047 Builder.AddPlaceholderChunk("header");
7048 Builder.AddTextChunk(">");
7049 Results.AddResult(Builder.TakeString());
7052 // #include_next "header"
7053 Builder.AddTypedTextChunk("include_next");
7054 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7055 Builder.AddTextChunk("\"");
7056 Builder.AddPlaceholderChunk("header");
7057 Builder.AddTextChunk("\"");
7058 Results.AddResult(Builder.TakeString());
7060 // #include_next <header>
7061 Builder.AddTypedTextChunk("include_next");
7062 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7063 Builder.AddTextChunk("<");
7064 Builder.AddPlaceholderChunk("header");
7065 Builder.AddTextChunk(">");
7066 Results.AddResult(Builder.TakeString());
7068 // #warning <message>
7069 Builder.AddTypedTextChunk("warning");
7070 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7071 Builder.AddPlaceholderChunk("message");
7072 Results.AddResult(Builder.TakeString());
7074 // Note: #ident and #sccs are such crazy anachronisms that we don't provide
7075 // completions for them. And __include_macros is a Clang-internal extension
7076 // that we don't want to encourage anyone to use.
7078 // FIXME: we don't support #assert or #unassert, so don't suggest them.
7079 Results.ExitScope();
7081 HandleCodeCompleteResults(this, CodeCompleter,
7082 CodeCompletionContext::CCC_PreprocessorDirective,
7083 Results.data(), Results.size());
7086 void Sema::CodeCompleteInPreprocessorConditionalExclusion(Scope *S) {
7087 CodeCompleteOrdinaryName(S,
7088 S->getFnParent()? Sema::PCC_RecoveryInFunction
7089 : Sema::PCC_Namespace);
7092 void Sema::CodeCompletePreprocessorMacroName(bool IsDefinition) {
7093 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
7094 CodeCompleter->getCodeCompletionTUInfo(),
7095 IsDefinition? CodeCompletionContext::CCC_MacroName
7096 : CodeCompletionContext::CCC_MacroNameUse);
7097 if (!IsDefinition && (!CodeCompleter || CodeCompleter->includeMacros())) {
7098 // Add just the names of macros, not their arguments.
7099 CodeCompletionBuilder Builder(Results.getAllocator(),
7100 Results.getCodeCompletionTUInfo());
7101 Results.EnterNewScope();
7102 for (Preprocessor::macro_iterator M = PP.macro_begin(),
7103 MEnd = PP.macro_end();
7105 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
7106 M->first->getName()));
7107 Results.AddResult(Builder.TakeString());
7109 Results.ExitScope();
7110 } else if (IsDefinition) {
7111 // FIXME: Can we detect when the user just wrote an include guard above?
7114 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
7115 Results.data(), Results.size());
7118 void Sema::CodeCompletePreprocessorExpression() {
7119 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
7120 CodeCompleter->getCodeCompletionTUInfo(),
7121 CodeCompletionContext::CCC_PreprocessorExpression);
7123 if (!CodeCompleter || CodeCompleter->includeMacros())
7124 AddMacroResults(PP, Results);
7126 // defined (<macro>)
7127 Results.EnterNewScope();
7128 CodeCompletionBuilder Builder(Results.getAllocator(),
7129 Results.getCodeCompletionTUInfo());
7130 Builder.AddTypedTextChunk("defined");
7131 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
7132 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7133 Builder.AddPlaceholderChunk("macro");
7134 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7135 Results.AddResult(Builder.TakeString());
7136 Results.ExitScope();
7138 HandleCodeCompleteResults(this, CodeCompleter,
7139 CodeCompletionContext::CCC_PreprocessorExpression,
7140 Results.data(), Results.size());
7143 void Sema::CodeCompletePreprocessorMacroArgument(Scope *S,
7144 IdentifierInfo *Macro,
7145 MacroInfo *MacroInfo,
7146 unsigned Argument) {
7147 // FIXME: In the future, we could provide "overload" results, much like we
7148 // do for function calls.
7150 // Now just ignore this. There will be another code-completion callback
7151 // for the expanded tokens.
7154 void Sema::CodeCompleteNaturalLanguage() {
7155 HandleCodeCompleteResults(this, CodeCompleter,
7156 CodeCompletionContext::CCC_NaturalLanguage,
7160 void Sema::GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
7161 CodeCompletionTUInfo &CCTUInfo,
7162 SmallVectorImpl<CodeCompletionResult> &Results) {
7163 ResultBuilder Builder(*this, Allocator, CCTUInfo,
7164 CodeCompletionContext::CCC_Recovery);
7165 if (!CodeCompleter || CodeCompleter->includeGlobals()) {
7166 CodeCompletionDeclConsumer Consumer(Builder,
7167 Context.getTranslationUnitDecl());
7168 LookupVisibleDecls(Context.getTranslationUnitDecl(), LookupAnyName,
7172 if (!CodeCompleter || CodeCompleter->includeMacros())
7173 AddMacroResults(PP, Builder);
7176 Results.insert(Results.end(),
7177 Builder.data(), Builder.data() + Builder.size());