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 //===----------------------------------------------------------------------===//
15 #include "clang/Sema/CodeCompleteConsumer.h"
16 #include "clang/AST/ExprCXX.h"
17 #include "clang/AST/ExprObjC.h"
18 #include "clang/Lex/MacroInfo.h"
19 #include "clang/Lex/Preprocessor.h"
20 #include "llvm/ADT/SmallPtrSet.h"
21 #include "llvm/ADT/StringExtras.h"
26 using namespace clang;
29 /// \brief A container of code-completion results.
32 /// \brief The type of a name-lookup filter, which can be provided to the
33 /// name-lookup routines to specify which declarations should be included in
34 /// the result set (when it returns true) and which declarations should be
35 /// filtered out (returns false).
36 typedef bool (ResultBuilder::*LookupFilter)(NamedDecl *) const;
38 typedef CodeCompleteConsumer::Result Result;
41 /// \brief The actual results we have found.
42 std::vector<Result> Results;
44 /// \brief A record of all of the declarations we have found and placed
45 /// into the result set, used to ensure that no declaration ever gets into
46 /// the result set twice.
47 llvm::SmallPtrSet<Decl*, 16> AllDeclsFound;
49 typedef std::pair<NamedDecl *, unsigned> DeclIndexPair;
51 /// \brief An entry in the shadow map, which is optimized to store
52 /// a single (declaration, index) mapping (the common case) but
53 /// can also store a list of (declaration, index) mappings.
54 class ShadowMapEntry {
55 typedef llvm::SmallVector<DeclIndexPair, 4> DeclIndexPairVector;
57 /// \brief Contains either the solitary NamedDecl * or a vector
58 /// of (declaration, index) pairs.
59 llvm::PointerUnion<NamedDecl *, DeclIndexPairVector*> DeclOrVector;
61 /// \brief When the entry contains a single declaration, this is
62 /// the index associated with that entry.
63 unsigned SingleDeclIndex;
66 ShadowMapEntry() : DeclOrVector(), SingleDeclIndex(0) { }
68 void Add(NamedDecl *ND, unsigned Index) {
69 if (DeclOrVector.isNull()) {
70 // 0 - > 1 elements: just set the single element information.
72 SingleDeclIndex = Index;
76 if (NamedDecl *PrevND = DeclOrVector.dyn_cast<NamedDecl *>()) {
77 // 1 -> 2 elements: create the vector of results and push in the
78 // existing declaration.
79 DeclIndexPairVector *Vec = new DeclIndexPairVector;
80 Vec->push_back(DeclIndexPair(PrevND, SingleDeclIndex));
84 // Add the new element to the end of the vector.
85 DeclOrVector.get<DeclIndexPairVector*>()->push_back(
86 DeclIndexPair(ND, Index));
90 if (DeclIndexPairVector *Vec
91 = DeclOrVector.dyn_cast<DeclIndexPairVector *>()) {
93 DeclOrVector = ((NamedDecl *)0);
99 iterator begin() const;
100 iterator end() const;
103 /// \brief A mapping from declaration names to the declarations that have
104 /// this name within a particular scope and their index within the list of
106 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
108 /// \brief The semantic analysis object for which results are being
112 /// \brief If non-NULL, a filter function used to remove any code-completion
113 /// results that are not desirable.
116 /// \brief Whether we should allow declarations as
117 /// nested-name-specifiers that would otherwise be filtered out.
118 bool AllowNestedNameSpecifiers;
120 /// \brief A list of shadow maps, which is used to model name hiding at
121 /// different levels of, e.g., the inheritance hierarchy.
122 std::list<ShadowMap> ShadowMaps;
125 explicit ResultBuilder(Sema &SemaRef, LookupFilter Filter = 0)
126 : SemaRef(SemaRef), Filter(Filter), AllowNestedNameSpecifiers(false) { }
128 /// \brief Set the filter used for code-completion results.
129 void setFilter(LookupFilter Filter) {
130 this->Filter = Filter;
133 typedef std::vector<Result>::iterator iterator;
134 iterator begin() { return Results.begin(); }
135 iterator end() { return Results.end(); }
137 Result *data() { return Results.empty()? 0 : &Results.front(); }
138 unsigned size() const { return Results.size(); }
139 bool empty() const { return Results.empty(); }
141 /// \brief Specify whether nested-name-specifiers are allowed.
142 void allowNestedNameSpecifiers(bool Allow = true) {
143 AllowNestedNameSpecifiers = Allow;
146 /// \brief Determine whether the given declaration is at all interesting
147 /// as a code-completion result.
149 /// \param ND the declaration that we are inspecting.
151 /// \param AsNestedNameSpecifier will be set true if this declaration is
152 /// only interesting when it is a nested-name-specifier.
153 bool isInterestingDecl(NamedDecl *ND, bool &AsNestedNameSpecifier) const;
155 /// \brief Check whether the result is hidden by the Hiding declaration.
157 /// \returns true if the result is hidden and cannot be found, false if
158 /// the hidden result could still be found. When false, \p R may be
159 /// modified to describe how the result can be found (e.g., via extra
161 bool CheckHiddenResult(Result &R, DeclContext *CurContext,
164 /// \brief Add a new result to this result set (if it isn't already in one
165 /// of the shadow maps), or replace an existing result (for, e.g., a
168 /// \param CurContext the result to add (if it is unique).
170 /// \param R the context in which this result will be named.
171 void MaybeAddResult(Result R, DeclContext *CurContext = 0);
173 /// \brief Add a new result to this result set, where we already know
174 /// the hiding declation (if any).
176 /// \param R the result to add (if it is unique).
178 /// \param CurContext the context in which this result will be named.
180 /// \param Hiding the declaration that hides the result.
182 /// \param InBaseClass whether the result was found in a base
183 /// class of the searched context.
184 void AddResult(Result R, DeclContext *CurContext, NamedDecl *Hiding,
187 /// \brief Add a new non-declaration result to this result set.
188 void AddResult(Result R);
190 /// \brief Enter into a new scope.
191 void EnterNewScope();
193 /// \brief Exit from the current scope.
196 /// \brief Ignore this declaration, if it is seen again.
197 void Ignore(Decl *D) { AllDeclsFound.insert(D->getCanonicalDecl()); }
199 /// \name Name lookup predicates
201 /// These predicates can be passed to the name lookup functions to filter the
202 /// results of name lookup. All of the predicates have the same type, so that
205 bool IsOrdinaryName(NamedDecl *ND) const;
206 bool IsOrdinaryNonValueName(NamedDecl *ND) const;
207 bool IsNestedNameSpecifier(NamedDecl *ND) const;
208 bool IsEnum(NamedDecl *ND) const;
209 bool IsClassOrStruct(NamedDecl *ND) const;
210 bool IsUnion(NamedDecl *ND) const;
211 bool IsNamespace(NamedDecl *ND) const;
212 bool IsNamespaceOrAlias(NamedDecl *ND) const;
213 bool IsType(NamedDecl *ND) const;
214 bool IsMember(NamedDecl *ND) const;
215 bool IsObjCIvar(NamedDecl *ND) const;
220 class ResultBuilder::ShadowMapEntry::iterator {
221 llvm::PointerUnion<NamedDecl*, const DeclIndexPair*> DeclOrIterator;
222 unsigned SingleDeclIndex;
225 typedef DeclIndexPair value_type;
226 typedef value_type reference;
227 typedef std::ptrdiff_t difference_type;
228 typedef std::input_iterator_tag iterator_category;
234 pointer(const DeclIndexPair &Value) : Value(Value) { }
236 const DeclIndexPair *operator->() const {
241 iterator() : DeclOrIterator((NamedDecl *)0), SingleDeclIndex(0) { }
243 iterator(NamedDecl *SingleDecl, unsigned Index)
244 : DeclOrIterator(SingleDecl), SingleDeclIndex(Index) { }
246 iterator(const DeclIndexPair *Iterator)
247 : DeclOrIterator(Iterator), SingleDeclIndex(0) { }
249 iterator &operator++() {
250 if (DeclOrIterator.is<NamedDecl *>()) {
251 DeclOrIterator = (NamedDecl *)0;
256 const DeclIndexPair *I = DeclOrIterator.get<const DeclIndexPair*>();
262 iterator operator++(int) {
268 reference operator*() const {
269 if (NamedDecl *ND = DeclOrIterator.dyn_cast<NamedDecl *>())
270 return reference(ND, SingleDeclIndex);
272 return *DeclOrIterator.get<const DeclIndexPair*>();
275 pointer operator->() const {
276 return pointer(**this);
279 friend bool operator==(const iterator &X, const iterator &Y) {
280 return X.DeclOrIterator.getOpaqueValue()
281 == Y.DeclOrIterator.getOpaqueValue() &&
282 X.SingleDeclIndex == Y.SingleDeclIndex;
285 friend bool operator!=(const iterator &X, const iterator &Y) {
290 ResultBuilder::ShadowMapEntry::iterator
291 ResultBuilder::ShadowMapEntry::begin() const {
292 if (DeclOrVector.isNull())
295 if (NamedDecl *ND = DeclOrVector.dyn_cast<NamedDecl *>())
296 return iterator(ND, SingleDeclIndex);
298 return iterator(DeclOrVector.get<DeclIndexPairVector *>()->begin());
301 ResultBuilder::ShadowMapEntry::iterator
302 ResultBuilder::ShadowMapEntry::end() const {
303 if (DeclOrVector.is<NamedDecl *>() || DeclOrVector.isNull())
306 return iterator(DeclOrVector.get<DeclIndexPairVector *>()->end());
309 /// \brief Compute the qualification required to get from the current context
310 /// (\p CurContext) to the target context (\p TargetContext).
312 /// \param Context the AST context in which the qualification will be used.
314 /// \param CurContext the context where an entity is being named, which is
315 /// typically based on the current scope.
317 /// \param TargetContext the context in which the named entity actually
320 /// \returns a nested name specifier that refers into the target context, or
321 /// NULL if no qualification is needed.
322 static NestedNameSpecifier *
323 getRequiredQualification(ASTContext &Context,
324 DeclContext *CurContext,
325 DeclContext *TargetContext) {
326 llvm::SmallVector<DeclContext *, 4> TargetParents;
328 for (DeclContext *CommonAncestor = TargetContext;
329 CommonAncestor && !CommonAncestor->Encloses(CurContext);
330 CommonAncestor = CommonAncestor->getLookupParent()) {
331 if (CommonAncestor->isTransparentContext() ||
332 CommonAncestor->isFunctionOrMethod())
335 TargetParents.push_back(CommonAncestor);
338 NestedNameSpecifier *Result = 0;
339 while (!TargetParents.empty()) {
340 DeclContext *Parent = TargetParents.back();
341 TargetParents.pop_back();
343 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Parent))
344 Result = NestedNameSpecifier::Create(Context, Result, Namespace);
345 else if (TagDecl *TD = dyn_cast<TagDecl>(Parent))
346 Result = NestedNameSpecifier::Create(Context, Result,
348 Context.getTypeDeclType(TD).getTypePtr());
350 assert(Parent->isTranslationUnit());
355 bool ResultBuilder::isInterestingDecl(NamedDecl *ND,
356 bool &AsNestedNameSpecifier) const {
357 AsNestedNameSpecifier = false;
359 ND = ND->getUnderlyingDecl();
360 unsigned IDNS = ND->getIdentifierNamespace();
362 // Skip unnamed entities.
363 if (!ND->getDeclName())
366 // Friend declarations and declarations introduced due to friends are never
368 if (isa<FriendDecl>(ND) ||
369 (IDNS & (Decl::IDNS_OrdinaryFriend | Decl::IDNS_TagFriend)))
372 // Class template (partial) specializations are never added as results.
373 if (isa<ClassTemplateSpecializationDecl>(ND) ||
374 isa<ClassTemplatePartialSpecializationDecl>(ND))
377 // Using declarations themselves are never added as results.
378 if (isa<UsingDecl>(ND))
381 // Some declarations have reserved names that we don't want to ever show.
382 if (const IdentifierInfo *Id = ND->getIdentifier()) {
383 // __va_list_tag is a freak of nature. Find it and skip it.
384 if (Id->isStr("__va_list_tag") || Id->isStr("__builtin_va_list"))
387 // Filter out names reserved for the implementation (C99 7.1.3,
388 // C++ [lib.global.names]). Users don't need to see those.
390 // FIXME: Add predicate for this.
391 if (Id->getLength() >= 2) {
392 const char *Name = Id->getNameStart();
393 if (Name[0] == '_' &&
394 (Name[1] == '_' || (Name[1] >= 'A' && Name[1] <= 'Z')))
399 // C++ constructors are never found by name lookup.
400 if (isa<CXXConstructorDecl>(ND))
403 // Filter out any unwanted results.
404 if (Filter && !(this->*Filter)(ND)) {
405 // Check whether it is interesting as a nested-name-specifier.
406 if (AllowNestedNameSpecifiers && SemaRef.getLangOptions().CPlusPlus &&
407 IsNestedNameSpecifier(ND) &&
408 (Filter != &ResultBuilder::IsMember ||
409 (isa<CXXRecordDecl>(ND) &&
410 cast<CXXRecordDecl>(ND)->isInjectedClassName()))) {
411 AsNestedNameSpecifier = true;
418 // ... then it must be interesting!
422 bool ResultBuilder::CheckHiddenResult(Result &R, DeclContext *CurContext,
424 // In C, there is no way to refer to a hidden name.
425 // FIXME: This isn't true; we can find a tag name hidden by an ordinary
426 // name if we introduce the tag type.
427 if (!SemaRef.getLangOptions().CPlusPlus)
430 DeclContext *HiddenCtx = R.Declaration->getDeclContext()->getLookupContext();
432 // There is no way to qualify a name declared in a function or method.
433 if (HiddenCtx->isFunctionOrMethod())
436 if (HiddenCtx == Hiding->getDeclContext()->getLookupContext())
439 // We can refer to the result with the appropriate qualification. Do it.
441 R.QualifierIsInformative = false;
444 R.Qualifier = getRequiredQualification(SemaRef.Context,
446 R.Declaration->getDeclContext());
450 void ResultBuilder::MaybeAddResult(Result R, DeclContext *CurContext) {
451 assert(!ShadowMaps.empty() && "Must enter into a results scope");
453 if (R.Kind != Result::RK_Declaration) {
454 // For non-declaration results, just add the result.
455 Results.push_back(R);
459 // Look through using declarations.
460 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
461 MaybeAddResult(Result(Using->getTargetDecl(), R.Qualifier), CurContext);
465 Decl *CanonDecl = R.Declaration->getCanonicalDecl();
466 unsigned IDNS = CanonDecl->getIdentifierNamespace();
468 bool AsNestedNameSpecifier = false;
469 if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
472 ShadowMap &SMap = ShadowMaps.back();
473 ShadowMapEntry::iterator I, IEnd;
474 ShadowMap::iterator NamePos = SMap.find(R.Declaration->getDeclName());
475 if (NamePos != SMap.end()) {
476 I = NamePos->second.begin();
477 IEnd = NamePos->second.end();
480 for (; I != IEnd; ++I) {
481 NamedDecl *ND = I->first;
482 unsigned Index = I->second;
483 if (ND->getCanonicalDecl() == CanonDecl) {
484 // This is a redeclaration. Always pick the newer declaration.
485 Results[Index].Declaration = R.Declaration;
492 // This is a new declaration in this scope. However, check whether this
493 // declaration name is hidden by a similarly-named declaration in an outer
495 std::list<ShadowMap>::iterator SM, SMEnd = ShadowMaps.end();
497 for (SM = ShadowMaps.begin(); SM != SMEnd; ++SM) {
498 ShadowMapEntry::iterator I, IEnd;
499 ShadowMap::iterator NamePos = SM->find(R.Declaration->getDeclName());
500 if (NamePos != SM->end()) {
501 I = NamePos->second.begin();
502 IEnd = NamePos->second.end();
504 for (; I != IEnd; ++I) {
505 // A tag declaration does not hide a non-tag declaration.
506 if (I->first->getIdentifierNamespace() == Decl::IDNS_Tag &&
507 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
508 Decl::IDNS_ObjCProtocol)))
511 // Protocols are in distinct namespaces from everything else.
512 if (((I->first->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
513 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
514 I->first->getIdentifierNamespace() != IDNS)
517 // The newly-added result is hidden by an entry in the shadow map.
518 if (CheckHiddenResult(R, CurContext, I->first))
525 // Make sure that any given declaration only shows up in the result set once.
526 if (!AllDeclsFound.insert(CanonDecl))
529 // If the filter is for nested-name-specifiers, then this result starts a
530 // nested-name-specifier.
531 if (AsNestedNameSpecifier)
532 R.StartsNestedNameSpecifier = true;
534 // If this result is supposed to have an informative qualifier, add one.
535 if (R.QualifierIsInformative && !R.Qualifier &&
536 !R.StartsNestedNameSpecifier) {
537 DeclContext *Ctx = R.Declaration->getDeclContext();
538 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
539 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, Namespace);
540 else if (TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
541 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, false,
542 SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
544 R.QualifierIsInformative = false;
547 // Insert this result into the set of results and into the current shadow
549 SMap[R.Declaration->getDeclName()].Add(R.Declaration, Results.size());
550 Results.push_back(R);
553 void ResultBuilder::AddResult(Result R, DeclContext *CurContext,
554 NamedDecl *Hiding, bool InBaseClass = false) {
555 if (R.Kind != Result::RK_Declaration) {
556 // For non-declaration results, just add the result.
557 Results.push_back(R);
561 // Look through using declarations.
562 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
563 AddResult(Result(Using->getTargetDecl(), R.Qualifier), CurContext, Hiding);
567 bool AsNestedNameSpecifier = false;
568 if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
571 if (Hiding && CheckHiddenResult(R, CurContext, Hiding))
574 // Make sure that any given declaration only shows up in the result set once.
575 if (!AllDeclsFound.insert(R.Declaration->getCanonicalDecl()))
578 // If the filter is for nested-name-specifiers, then this result starts a
579 // nested-name-specifier.
580 if (AsNestedNameSpecifier)
581 R.StartsNestedNameSpecifier = true;
582 else if (Filter == &ResultBuilder::IsMember && !R.Qualifier && InBaseClass &&
583 isa<CXXRecordDecl>(R.Declaration->getDeclContext()
584 ->getLookupContext()))
585 R.QualifierIsInformative = true;
587 // If this result is supposed to have an informative qualifier, add one.
588 if (R.QualifierIsInformative && !R.Qualifier &&
589 !R.StartsNestedNameSpecifier) {
590 DeclContext *Ctx = R.Declaration->getDeclContext();
591 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
592 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, Namespace);
593 else if (TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
594 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, false,
595 SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
597 R.QualifierIsInformative = false;
600 // Insert this result into the set of results.
601 Results.push_back(R);
604 void ResultBuilder::AddResult(Result R) {
605 assert(R.Kind != Result::RK_Declaration &&
606 "Declaration results need more context");
607 Results.push_back(R);
610 /// \brief Enter into a new scope.
611 void ResultBuilder::EnterNewScope() {
612 ShadowMaps.push_back(ShadowMap());
615 /// \brief Exit from the current scope.
616 void ResultBuilder::ExitScope() {
617 for (ShadowMap::iterator E = ShadowMaps.back().begin(),
618 EEnd = ShadowMaps.back().end();
623 ShadowMaps.pop_back();
626 /// \brief Determines whether this given declaration will be found by
627 /// ordinary name lookup.
628 bool ResultBuilder::IsOrdinaryName(NamedDecl *ND) const {
629 unsigned IDNS = Decl::IDNS_Ordinary;
630 if (SemaRef.getLangOptions().CPlusPlus)
631 IDNS |= Decl::IDNS_Tag;
632 else if (SemaRef.getLangOptions().ObjC1 && isa<ObjCIvarDecl>(ND))
635 return ND->getIdentifierNamespace() & IDNS;
638 /// \brief Determines whether this given declaration will be found by
639 /// ordinary name lookup.
640 bool ResultBuilder::IsOrdinaryNonValueName(NamedDecl *ND) const {
641 unsigned IDNS = Decl::IDNS_Ordinary;
642 if (SemaRef.getLangOptions().CPlusPlus)
643 IDNS |= Decl::IDNS_Tag;
645 return (ND->getIdentifierNamespace() & IDNS) &&
646 !isa<ValueDecl>(ND) && !isa<FunctionTemplateDecl>(ND);
649 /// \brief Determines whether the given declaration is suitable as the
650 /// start of a C++ nested-name-specifier, e.g., a class or namespace.
651 bool ResultBuilder::IsNestedNameSpecifier(NamedDecl *ND) const {
652 // Allow us to find class templates, too.
653 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
654 ND = ClassTemplate->getTemplatedDecl();
656 return SemaRef.isAcceptableNestedNameSpecifier(ND);
659 /// \brief Determines whether the given declaration is an enumeration.
660 bool ResultBuilder::IsEnum(NamedDecl *ND) const {
661 return isa<EnumDecl>(ND);
664 /// \brief Determines whether the given declaration is a class or struct.
665 bool ResultBuilder::IsClassOrStruct(NamedDecl *ND) const {
666 // Allow us to find class templates, too.
667 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
668 ND = ClassTemplate->getTemplatedDecl();
670 if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
671 return RD->getTagKind() == TagDecl::TK_class ||
672 RD->getTagKind() == TagDecl::TK_struct;
677 /// \brief Determines whether the given declaration is a union.
678 bool ResultBuilder::IsUnion(NamedDecl *ND) const {
679 // Allow us to find class templates, too.
680 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
681 ND = ClassTemplate->getTemplatedDecl();
683 if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
684 return RD->getTagKind() == TagDecl::TK_union;
689 /// \brief Determines whether the given declaration is a namespace.
690 bool ResultBuilder::IsNamespace(NamedDecl *ND) const {
691 return isa<NamespaceDecl>(ND);
694 /// \brief Determines whether the given declaration is a namespace or
696 bool ResultBuilder::IsNamespaceOrAlias(NamedDecl *ND) const {
697 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
700 /// \brief Determines whether the given declaration is a type.
701 bool ResultBuilder::IsType(NamedDecl *ND) const {
702 return isa<TypeDecl>(ND);
705 /// \brief Determines which members of a class should be visible via
706 /// "." or "->". Only value declarations, nested name specifiers, and
707 /// using declarations thereof should show up.
708 bool ResultBuilder::IsMember(NamedDecl *ND) const {
709 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(ND))
710 ND = Using->getTargetDecl();
712 return isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND) ||
713 isa<ObjCPropertyDecl>(ND);
716 /// \rief Determines whether the given declaration is an Objective-C
717 /// instance variable.
718 bool ResultBuilder::IsObjCIvar(NamedDecl *ND) const {
719 return isa<ObjCIvarDecl>(ND);
723 /// \brief Visible declaration consumer that adds a code-completion result
724 /// for each visible declaration.
725 class CodeCompletionDeclConsumer : public VisibleDeclConsumer {
726 ResultBuilder &Results;
727 DeclContext *CurContext;
730 CodeCompletionDeclConsumer(ResultBuilder &Results, DeclContext *CurContext)
731 : Results(Results), CurContext(CurContext) { }
733 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, bool InBaseClass) {
734 Results.AddResult(ND, CurContext, Hiding, InBaseClass);
739 /// \brief Add type specifiers for the current language as keyword results.
740 static void AddTypeSpecifierResults(const LangOptions &LangOpts,
741 ResultBuilder &Results) {
742 typedef CodeCompleteConsumer::Result Result;
743 Results.AddResult(Result("short"));
744 Results.AddResult(Result("long"));
745 Results.AddResult(Result("signed"));
746 Results.AddResult(Result("unsigned"));
747 Results.AddResult(Result("void"));
748 Results.AddResult(Result("char"));
749 Results.AddResult(Result("int"));
750 Results.AddResult(Result("float"));
751 Results.AddResult(Result("double"));
752 Results.AddResult(Result("enum"));
753 Results.AddResult(Result("struct"));
754 Results.AddResult(Result("union"));
755 Results.AddResult(Result("const"));
756 Results.AddResult(Result("volatile"));
760 Results.AddResult(Result("_Complex"));
761 Results.AddResult(Result("_Imaginary"));
762 Results.AddResult(Result("_Bool"));
763 Results.AddResult(Result("restrict"));
766 if (LangOpts.CPlusPlus) {
768 Results.AddResult(Result("bool"));
769 Results.AddResult(Result("class"));
770 Results.AddResult(Result("wchar_t"));
772 // typename qualified-id
773 CodeCompletionString *Pattern = new CodeCompletionString;
774 Pattern->AddTypedTextChunk("typename");
775 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
776 Pattern->AddPlaceholderChunk("qualified-id");
777 Results.AddResult(Result(Pattern));
779 if (LangOpts.CPlusPlus0x) {
780 Results.AddResult(Result("auto"));
781 Results.AddResult(Result("char16_t"));
782 Results.AddResult(Result("char32_t"));
783 Results.AddResult(Result("decltype"));
788 if (LangOpts.GNUMode) {
789 // FIXME: Enable when we actually support decimal floating point.
790 // Results.AddResult(Result("_Decimal32"));
791 // Results.AddResult(Result("_Decimal64"));
792 // Results.AddResult(Result("_Decimal128"));
794 CodeCompletionString *Pattern = new CodeCompletionString;
795 Pattern->AddTypedTextChunk("typeof");
796 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
797 Pattern->AddPlaceholderChunk("expression-or-type");
798 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
799 Results.AddResult(Result(Pattern));
803 static void AddStorageSpecifiers(Action::CodeCompletionContext CCC,
804 const LangOptions &LangOpts,
805 ResultBuilder &Results) {
806 typedef CodeCompleteConsumer::Result Result;
807 // Note: we don't suggest either "auto" or "register", because both
808 // are pointless as storage specifiers. Elsewhere, we suggest "auto"
809 // in C++0x as a type specifier.
810 Results.AddResult(Result("extern"));
811 Results.AddResult(Result("static"));
814 static void AddFunctionSpecifiers(Action::CodeCompletionContext CCC,
815 const LangOptions &LangOpts,
816 ResultBuilder &Results) {
817 typedef CodeCompleteConsumer::Result Result;
819 case Action::CCC_Class:
820 case Action::CCC_MemberTemplate:
821 if (LangOpts.CPlusPlus) {
822 Results.AddResult(Result("explicit"));
823 Results.AddResult(Result("friend"));
824 Results.AddResult(Result("mutable"));
825 Results.AddResult(Result("virtual"));
829 case Action::CCC_ObjCInterface:
830 case Action::CCC_ObjCImplementation:
831 case Action::CCC_Namespace:
832 case Action::CCC_Template:
833 if (LangOpts.CPlusPlus || LangOpts.C99)
834 Results.AddResult(Result("inline"));
837 case Action::CCC_ObjCInstanceVariableList:
838 case Action::CCC_Expression:
839 case Action::CCC_Statement:
840 case Action::CCC_ForInit:
841 case Action::CCC_Condition:
846 static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt);
847 static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt);
848 static void AddObjCVisibilityResults(const LangOptions &LangOpts,
849 ResultBuilder &Results,
851 static void AddObjCImplementationResults(const LangOptions &LangOpts,
852 ResultBuilder &Results,
854 static void AddObjCInterfaceResults(const LangOptions &LangOpts,
855 ResultBuilder &Results,
857 static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt);
859 /// \brief Add language constructs that show up for "ordinary" names.
860 static void AddOrdinaryNameResults(Action::CodeCompletionContext CCC,
863 ResultBuilder &Results) {
864 typedef CodeCompleteConsumer::Result Result;
866 case Action::CCC_Namespace:
867 if (SemaRef.getLangOptions().CPlusPlus) {
868 // namespace <identifier> { }
869 CodeCompletionString *Pattern = new CodeCompletionString;
870 Pattern->AddTypedTextChunk("namespace");
871 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
872 Pattern->AddPlaceholderChunk("identifier");
873 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
874 Pattern->AddPlaceholderChunk("declarations");
875 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
876 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
877 Results.AddResult(Result(Pattern));
879 // namespace identifier = identifier ;
880 Pattern = new CodeCompletionString;
881 Pattern->AddTypedTextChunk("namespace");
882 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
883 Pattern->AddPlaceholderChunk("identifier");
884 Pattern->AddChunk(CodeCompletionString::CK_Equal);
885 Pattern->AddPlaceholderChunk("identifier");
886 Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
887 Results.AddResult(Result(Pattern));
890 Pattern = new CodeCompletionString;
891 Pattern->AddTypedTextChunk("using");
892 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
893 Pattern->AddTextChunk("namespace");
894 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
895 Pattern->AddPlaceholderChunk("identifier");
896 Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
897 Results.AddResult(Result(Pattern));
899 // asm(string-literal)
900 Pattern = new CodeCompletionString;
901 Pattern->AddTypedTextChunk("asm");
902 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
903 Pattern->AddPlaceholderChunk("string-literal");
904 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
905 Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
906 Results.AddResult(Result(Pattern));
908 // Explicit template instantiation
909 Pattern = new CodeCompletionString;
910 Pattern->AddTypedTextChunk("template");
911 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
912 Pattern->AddPlaceholderChunk("declaration");
913 Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
914 Results.AddResult(Result(Pattern));
917 if (SemaRef.getLangOptions().ObjC1)
918 AddObjCTopLevelResults(Results, true);
922 case Action::CCC_Class:
923 Results.AddResult(Result("typedef"));
924 if (SemaRef.getLangOptions().CPlusPlus) {
926 CodeCompletionString *Pattern = new CodeCompletionString;
927 Pattern->AddTypedTextChunk("using");
928 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
929 Pattern->AddPlaceholderChunk("qualified-id");
930 Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
931 Results.AddResult(Result(Pattern));
933 // using typename qualified-id; (only in a dependent context)
934 if (SemaRef.CurContext->isDependentContext()) {
935 Pattern = new CodeCompletionString;
936 Pattern->AddTypedTextChunk("using");
937 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
938 Pattern->AddTextChunk("typename");
939 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
940 Pattern->AddPlaceholderChunk("qualified-id");
941 Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
942 Results.AddResult(Result(Pattern));
945 if (CCC == Action::CCC_Class) {
947 Pattern = new CodeCompletionString;
948 Pattern->AddTypedTextChunk("public");
949 Pattern->AddChunk(CodeCompletionString::CK_Colon);
950 Results.AddResult(Result(Pattern));
953 Pattern = new CodeCompletionString;
954 Pattern->AddTypedTextChunk("protected");
955 Pattern->AddChunk(CodeCompletionString::CK_Colon);
956 Results.AddResult(Result(Pattern));
959 Pattern = new CodeCompletionString;
960 Pattern->AddTypedTextChunk("private");
961 Pattern->AddChunk(CodeCompletionString::CK_Colon);
962 Results.AddResult(Result(Pattern));
967 case Action::CCC_Template:
968 case Action::CCC_MemberTemplate:
969 if (SemaRef.getLangOptions().CPlusPlus) {
970 // template < parameters >
971 CodeCompletionString *Pattern = new CodeCompletionString;
972 Pattern->AddTypedTextChunk("template");
973 Pattern->AddChunk(CodeCompletionString::CK_LeftAngle);
974 Pattern->AddPlaceholderChunk("parameters");
975 Pattern->AddChunk(CodeCompletionString::CK_RightAngle);
976 Results.AddResult(Result(Pattern));
979 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
980 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
983 case Action::CCC_ObjCInterface:
984 AddObjCInterfaceResults(SemaRef.getLangOptions(), Results, true);
985 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
986 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
989 case Action::CCC_ObjCImplementation:
990 AddObjCImplementationResults(SemaRef.getLangOptions(), Results, true);
991 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
992 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
995 case Action::CCC_ObjCInstanceVariableList:
996 AddObjCVisibilityResults(SemaRef.getLangOptions(), Results, true);
999 case Action::CCC_Statement: {
1000 Results.AddResult(Result("typedef"));
1002 CodeCompletionString *Pattern = 0;
1003 if (SemaRef.getLangOptions().CPlusPlus) {
1004 Pattern = new CodeCompletionString;
1005 Pattern->AddTypedTextChunk("try");
1006 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1007 Pattern->AddPlaceholderChunk("statements");
1008 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1009 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1010 Pattern->AddTextChunk("catch");
1011 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1012 Pattern->AddPlaceholderChunk("declaration");
1013 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1014 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1015 Pattern->AddPlaceholderChunk("statements");
1016 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1017 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1018 Results.AddResult(Result(Pattern));
1020 if (SemaRef.getLangOptions().ObjC1)
1021 AddObjCStatementResults(Results, true);
1023 // if (condition) { statements }
1024 Pattern = new CodeCompletionString;
1025 Pattern->AddTypedTextChunk("if");
1026 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1027 if (SemaRef.getLangOptions().CPlusPlus)
1028 Pattern->AddPlaceholderChunk("condition");
1030 Pattern->AddPlaceholderChunk("expression");
1031 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1032 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1033 Pattern->AddPlaceholderChunk("statements");
1034 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1035 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1036 Results.AddResult(Result(Pattern));
1038 // switch (condition) { }
1039 Pattern = new CodeCompletionString;
1040 Pattern->AddTypedTextChunk("switch");
1041 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1042 if (SemaRef.getLangOptions().CPlusPlus)
1043 Pattern->AddPlaceholderChunk("condition");
1045 Pattern->AddPlaceholderChunk("expression");
1046 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1047 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1048 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1049 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1050 Results.AddResult(Result(Pattern));
1052 // Switch-specific statements.
1053 if (!SemaRef.getSwitchStack().empty()) {
1055 Pattern = new CodeCompletionString;
1056 Pattern->AddTypedTextChunk("case");
1057 Pattern->AddPlaceholderChunk("expression");
1058 Pattern->AddChunk(CodeCompletionString::CK_Colon);
1059 Results.AddResult(Result(Pattern));
1062 Pattern = new CodeCompletionString;
1063 Pattern->AddTypedTextChunk("default");
1064 Pattern->AddChunk(CodeCompletionString::CK_Colon);
1065 Results.AddResult(Result(Pattern));
1068 /// while (condition) { statements }
1069 Pattern = new CodeCompletionString;
1070 Pattern->AddTypedTextChunk("while");
1071 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1072 if (SemaRef.getLangOptions().CPlusPlus)
1073 Pattern->AddPlaceholderChunk("condition");
1075 Pattern->AddPlaceholderChunk("expression");
1076 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1077 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1078 Pattern->AddPlaceholderChunk("statements");
1079 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1080 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1081 Results.AddResult(Result(Pattern));
1083 // do { statements } while ( expression );
1084 Pattern = new CodeCompletionString;
1085 Pattern->AddTypedTextChunk("do");
1086 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1087 Pattern->AddPlaceholderChunk("statements");
1088 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1089 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1090 Pattern->AddTextChunk("while");
1091 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1092 Pattern->AddPlaceholderChunk("expression");
1093 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1094 Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
1095 Results.AddResult(Result(Pattern));
1097 // for ( for-init-statement ; condition ; expression ) { statements }
1098 Pattern = new CodeCompletionString;
1099 Pattern->AddTypedTextChunk("for");
1100 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1101 if (SemaRef.getLangOptions().CPlusPlus || SemaRef.getLangOptions().C99)
1102 Pattern->AddPlaceholderChunk("init-statement");
1104 Pattern->AddPlaceholderChunk("init-expression");
1105 Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
1106 Pattern->AddPlaceholderChunk("condition");
1107 Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
1108 Pattern->AddPlaceholderChunk("inc-expression");
1109 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1110 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1111 Pattern->AddPlaceholderChunk("statements");
1112 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1113 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1114 Results.AddResult(Result(Pattern));
1116 if (S->getContinueParent()) {
1118 Pattern = new CodeCompletionString;
1119 Pattern->AddTypedTextChunk("continue");
1120 Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
1121 Results.AddResult(Result(Pattern));
1124 if (S->getBreakParent()) {
1126 Pattern = new CodeCompletionString;
1127 Pattern->AddTypedTextChunk("break");
1128 Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
1129 Results.AddResult(Result(Pattern));
1132 // "return expression ;" or "return ;", depending on whether we
1133 // know the function is void or not.
1134 bool isVoid = false;
1135 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(SemaRef.CurContext))
1136 isVoid = Function->getResultType()->isVoidType();
1137 else if (ObjCMethodDecl *Method
1138 = dyn_cast<ObjCMethodDecl>(SemaRef.CurContext))
1139 isVoid = Method->getResultType()->isVoidType();
1140 else if (SemaRef.getCurBlock() &&
1141 !SemaRef.getCurBlock()->ReturnType.isNull())
1142 isVoid = SemaRef.getCurBlock()->ReturnType->isVoidType();
1143 Pattern = new CodeCompletionString;
1144 Pattern->AddTypedTextChunk("return");
1146 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1147 Pattern->AddPlaceholderChunk("expression");
1149 Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
1150 Results.AddResult(Result(Pattern));
1152 // goto identifier ;
1153 Pattern = new CodeCompletionString;
1154 Pattern->AddTypedTextChunk("goto");
1155 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1156 Pattern->AddPlaceholderChunk("identifier");
1157 Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
1158 Results.AddResult(Result(Pattern));
1161 Pattern = new CodeCompletionString;
1162 Pattern->AddTypedTextChunk("using");
1163 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1164 Pattern->AddTextChunk("namespace");
1165 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1166 Pattern->AddPlaceholderChunk("identifier");
1167 Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
1168 Results.AddResult(Result(Pattern));
1171 // Fall through (for statement expressions).
1172 case Action::CCC_ForInit:
1173 case Action::CCC_Condition:
1174 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1175 // Fall through: conditions and statements can have expressions.
1177 case Action::CCC_Expression: {
1178 CodeCompletionString *Pattern = 0;
1179 if (SemaRef.getLangOptions().CPlusPlus) {
1180 // 'this', if we're in a non-static member function.
1181 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(SemaRef.CurContext))
1182 if (!Method->isStatic())
1183 Results.AddResult(Result("this"));
1186 Results.AddResult(Result("true"));
1187 Results.AddResult(Result("false"));
1189 // dynamic_cast < type-id > ( expression )
1190 Pattern = new CodeCompletionString;
1191 Pattern->AddTypedTextChunk("dynamic_cast");
1192 Pattern->AddChunk(CodeCompletionString::CK_LeftAngle);
1193 Pattern->AddPlaceholderChunk("type-id");
1194 Pattern->AddChunk(CodeCompletionString::CK_RightAngle);
1195 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1196 Pattern->AddPlaceholderChunk("expression");
1197 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1198 Results.AddResult(Result(Pattern));
1200 // static_cast < type-id > ( expression )
1201 Pattern = new CodeCompletionString;
1202 Pattern->AddTypedTextChunk("static_cast");
1203 Pattern->AddChunk(CodeCompletionString::CK_LeftAngle);
1204 Pattern->AddPlaceholderChunk("type-id");
1205 Pattern->AddChunk(CodeCompletionString::CK_RightAngle);
1206 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1207 Pattern->AddPlaceholderChunk("expression");
1208 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1209 Results.AddResult(Result(Pattern));
1211 // reinterpret_cast < type-id > ( expression )
1212 Pattern = new CodeCompletionString;
1213 Pattern->AddTypedTextChunk("reinterpret_cast");
1214 Pattern->AddChunk(CodeCompletionString::CK_LeftAngle);
1215 Pattern->AddPlaceholderChunk("type-id");
1216 Pattern->AddChunk(CodeCompletionString::CK_RightAngle);
1217 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1218 Pattern->AddPlaceholderChunk("expression");
1219 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1220 Results.AddResult(Result(Pattern));
1222 // const_cast < type-id > ( expression )
1223 Pattern = new CodeCompletionString;
1224 Pattern->AddTypedTextChunk("const_cast");
1225 Pattern->AddChunk(CodeCompletionString::CK_LeftAngle);
1226 Pattern->AddPlaceholderChunk("type-id");
1227 Pattern->AddChunk(CodeCompletionString::CK_RightAngle);
1228 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1229 Pattern->AddPlaceholderChunk("expression");
1230 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1231 Results.AddResult(Result(Pattern));
1233 // typeid ( expression-or-type )
1234 Pattern = new CodeCompletionString;
1235 Pattern->AddTypedTextChunk("typeid");
1236 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1237 Pattern->AddPlaceholderChunk("expression-or-type");
1238 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1239 Results.AddResult(Result(Pattern));
1242 Pattern = new CodeCompletionString;
1243 Pattern->AddTypedTextChunk("new");
1244 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1245 Pattern->AddPlaceholderChunk("type-id");
1246 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1247 Pattern->AddPlaceholderChunk("expressions");
1248 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1249 Results.AddResult(Result(Pattern));
1251 // new T [ ] ( ... )
1252 Pattern = new CodeCompletionString;
1253 Pattern->AddTypedTextChunk("new");
1254 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1255 Pattern->AddPlaceholderChunk("type-id");
1256 Pattern->AddChunk(CodeCompletionString::CK_LeftBracket);
1257 Pattern->AddPlaceholderChunk("size");
1258 Pattern->AddChunk(CodeCompletionString::CK_RightBracket);
1259 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1260 Pattern->AddPlaceholderChunk("expressions");
1261 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1262 Results.AddResult(Result(Pattern));
1264 // delete expression
1265 Pattern = new CodeCompletionString;
1266 Pattern->AddTypedTextChunk("delete");
1267 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1268 Pattern->AddPlaceholderChunk("expression");
1269 Results.AddResult(Result(Pattern));
1271 // delete [] expression
1272 Pattern = new CodeCompletionString;
1273 Pattern->AddTypedTextChunk("delete");
1274 Pattern->AddChunk(CodeCompletionString::CK_LeftBracket);
1275 Pattern->AddChunk(CodeCompletionString::CK_RightBracket);
1276 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1277 Pattern->AddPlaceholderChunk("expression");
1278 Results.AddResult(Result(Pattern));
1281 Pattern = new CodeCompletionString;
1282 Pattern->AddTypedTextChunk("throw");
1283 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1284 Pattern->AddPlaceholderChunk("expression");
1285 Results.AddResult(Result(Pattern));
1288 if (SemaRef.getLangOptions().ObjC1) {
1289 // Add "super", if we're in an Objective-C class with a superclass.
1290 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl())
1291 if (Method->getClassInterface()->getSuperClass())
1292 Results.AddResult(Result("super"));
1294 AddObjCExpressionResults(Results, true);
1297 // sizeof expression
1298 Pattern = new CodeCompletionString;
1299 Pattern->AddTypedTextChunk("sizeof");
1300 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1301 Pattern->AddPlaceholderChunk("expression-or-type");
1302 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1303 Results.AddResult(Result(Pattern));
1308 AddTypeSpecifierResults(SemaRef.getLangOptions(), Results);
1310 if (SemaRef.getLangOptions().CPlusPlus)
1311 Results.AddResult(Result("operator"));
1314 /// \brief If the given declaration has an associated type, add it as a result
1316 static void AddResultTypeChunk(ASTContext &Context,
1318 CodeCompletionString *Result) {
1322 // Determine the type of the declaration (if it has a type).
1324 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND))
1325 T = Function->getResultType();
1326 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND))
1327 T = Method->getResultType();
1328 else if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND))
1329 T = FunTmpl->getTemplatedDecl()->getResultType();
1330 else if (EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND))
1331 T = Context.getTypeDeclType(cast<TypeDecl>(Enumerator->getDeclContext()));
1332 else if (isa<UnresolvedUsingValueDecl>(ND)) {
1333 /* Do nothing: ignore unresolved using declarations*/
1334 } else if (ValueDecl *Value = dyn_cast<ValueDecl>(ND))
1335 T = Value->getType();
1336 else if (ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND))
1337 T = Property->getType();
1339 if (T.isNull() || Context.hasSameType(T, Context.DependentTy))
1342 std::string TypeStr;
1343 T.getAsStringInternal(TypeStr, Context.PrintingPolicy);
1344 Result->AddResultTypeChunk(TypeStr);
1347 /// \brief Add function parameter chunks to the given code completion string.
1348 static void AddFunctionParameterChunks(ASTContext &Context,
1349 FunctionDecl *Function,
1350 CodeCompletionString *Result) {
1351 typedef CodeCompletionString::Chunk Chunk;
1353 CodeCompletionString *CCStr = Result;
1355 for (unsigned P = 0, N = Function->getNumParams(); P != N; ++P) {
1356 ParmVarDecl *Param = Function->getParamDecl(P);
1358 if (Param->hasDefaultArg()) {
1359 // When we see an optional default argument, put that argument and
1360 // the remaining default arguments into a new, optional string.
1361 CodeCompletionString *Opt = new CodeCompletionString;
1362 CCStr->AddOptionalChunk(std::auto_ptr<CodeCompletionString>(Opt));
1367 CCStr->AddChunk(Chunk(CodeCompletionString::CK_Comma));
1369 // Format the placeholder string.
1370 std::string PlaceholderStr;
1371 if (Param->getIdentifier())
1372 PlaceholderStr = Param->getIdentifier()->getName();
1374 Param->getType().getAsStringInternal(PlaceholderStr,
1375 Context.PrintingPolicy);
1377 // Add the placeholder string.
1378 CCStr->AddPlaceholderChunk(PlaceholderStr);
1381 if (const FunctionProtoType *Proto
1382 = Function->getType()->getAs<FunctionProtoType>())
1383 if (Proto->isVariadic())
1384 CCStr->AddPlaceholderChunk(", ...");
1387 /// \brief Add template parameter chunks to the given code completion string.
1388 static void AddTemplateParameterChunks(ASTContext &Context,
1389 TemplateDecl *Template,
1390 CodeCompletionString *Result,
1391 unsigned MaxParameters = 0) {
1392 typedef CodeCompletionString::Chunk Chunk;
1394 CodeCompletionString *CCStr = Result;
1395 bool FirstParameter = true;
1397 TemplateParameterList *Params = Template->getTemplateParameters();
1398 TemplateParameterList::iterator PEnd = Params->end();
1400 PEnd = Params->begin() + MaxParameters;
1401 for (TemplateParameterList::iterator P = Params->begin(); P != PEnd; ++P) {
1402 bool HasDefaultArg = false;
1403 std::string PlaceholderStr;
1404 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
1405 if (TTP->wasDeclaredWithTypename())
1406 PlaceholderStr = "typename";
1408 PlaceholderStr = "class";
1410 if (TTP->getIdentifier()) {
1411 PlaceholderStr += ' ';
1412 PlaceholderStr += TTP->getIdentifier()->getName();
1415 HasDefaultArg = TTP->hasDefaultArgument();
1416 } else if (NonTypeTemplateParmDecl *NTTP
1417 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
1418 if (NTTP->getIdentifier())
1419 PlaceholderStr = NTTP->getIdentifier()->getName();
1420 NTTP->getType().getAsStringInternal(PlaceholderStr,
1421 Context.PrintingPolicy);
1422 HasDefaultArg = NTTP->hasDefaultArgument();
1424 assert(isa<TemplateTemplateParmDecl>(*P));
1425 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
1427 // Since putting the template argument list into the placeholder would
1428 // be very, very long, we just use an abbreviation.
1429 PlaceholderStr = "template<...> class";
1430 if (TTP->getIdentifier()) {
1431 PlaceholderStr += ' ';
1432 PlaceholderStr += TTP->getIdentifier()->getName();
1435 HasDefaultArg = TTP->hasDefaultArgument();
1438 if (HasDefaultArg) {
1439 // When we see an optional default argument, put that argument and
1440 // the remaining default arguments into a new, optional string.
1441 CodeCompletionString *Opt = new CodeCompletionString;
1442 CCStr->AddOptionalChunk(std::auto_ptr<CodeCompletionString>(Opt));
1447 FirstParameter = false;
1449 CCStr->AddChunk(Chunk(CodeCompletionString::CK_Comma));
1451 // Add the placeholder string.
1452 CCStr->AddPlaceholderChunk(PlaceholderStr);
1456 /// \brief Add a qualifier to the given code-completion string, if the
1457 /// provided nested-name-specifier is non-NULL.
1459 AddQualifierToCompletionString(CodeCompletionString *Result,
1460 NestedNameSpecifier *Qualifier,
1461 bool QualifierIsInformative,
1462 ASTContext &Context) {
1466 std::string PrintedNNS;
1468 llvm::raw_string_ostream OS(PrintedNNS);
1469 Qualifier->print(OS, Context.PrintingPolicy);
1471 if (QualifierIsInformative)
1472 Result->AddInformativeChunk(PrintedNNS);
1474 Result->AddTextChunk(PrintedNNS);
1477 static void AddFunctionTypeQualsToCompletionString(CodeCompletionString *Result,
1478 FunctionDecl *Function) {
1479 const FunctionProtoType *Proto
1480 = Function->getType()->getAs<FunctionProtoType>();
1481 if (!Proto || !Proto->getTypeQuals())
1484 std::string QualsStr;
1485 if (Proto->getTypeQuals() & Qualifiers::Const)
1486 QualsStr += " const";
1487 if (Proto->getTypeQuals() & Qualifiers::Volatile)
1488 QualsStr += " volatile";
1489 if (Proto->getTypeQuals() & Qualifiers::Restrict)
1490 QualsStr += " restrict";
1491 Result->AddInformativeChunk(QualsStr);
1494 /// \brief If possible, create a new code completion string for the given
1497 /// \returns Either a new, heap-allocated code completion string describing
1498 /// how to use this result, or NULL to indicate that the string or name of the
1499 /// result is all that is needed.
1500 CodeCompletionString *
1501 CodeCompleteConsumer::Result::CreateCodeCompletionString(Sema &S) {
1502 typedef CodeCompletionString::Chunk Chunk;
1504 if (Kind == RK_Pattern)
1505 return Pattern->Clone();
1507 CodeCompletionString *Result = new CodeCompletionString;
1509 if (Kind == RK_Keyword) {
1510 Result->AddTypedTextChunk(Keyword);
1514 if (Kind == RK_Macro) {
1515 MacroInfo *MI = S.PP.getMacroInfo(Macro);
1516 assert(MI && "Not a macro?");
1518 Result->AddTypedTextChunk(Macro->getName());
1520 if (!MI->isFunctionLike())
1523 // Format a function-like macro with placeholders for the arguments.
1524 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
1525 for (MacroInfo::arg_iterator A = MI->arg_begin(), AEnd = MI->arg_end();
1527 if (A != MI->arg_begin())
1528 Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
1530 if (!MI->isVariadic() || A != AEnd - 1) {
1531 // Non-variadic argument.
1532 Result->AddPlaceholderChunk((*A)->getName());
1536 // Variadic argument; cope with the different between GNU and C99
1537 // variadic macros, providing a single placeholder for the rest of the
1539 if ((*A)->isStr("__VA_ARGS__"))
1540 Result->AddPlaceholderChunk("...");
1542 std::string Arg = (*A)->getName();
1544 Result->AddPlaceholderChunk(Arg);
1547 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
1551 assert(Kind == RK_Declaration && "Missed a macro kind?");
1552 NamedDecl *ND = Declaration;
1554 if (StartsNestedNameSpecifier) {
1555 Result->AddTypedTextChunk(ND->getNameAsString());
1556 Result->AddTextChunk("::");
1560 AddResultTypeChunk(S.Context, ND, Result);
1562 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND)) {
1563 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
1565 Result->AddTypedTextChunk(Function->getNameAsString());
1566 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
1567 AddFunctionParameterChunks(S.Context, Function, Result);
1568 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
1569 AddFunctionTypeQualsToCompletionString(Result, Function);
1573 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND)) {
1574 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
1576 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
1577 Result->AddTypedTextChunk(Function->getNameAsString());
1579 // Figure out which template parameters are deduced (or have default
1581 llvm::SmallVector<bool, 16> Deduced;
1582 S.MarkDeducedTemplateParameters(FunTmpl, Deduced);
1583 unsigned LastDeducibleArgument;
1584 for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0;
1585 --LastDeducibleArgument) {
1586 if (!Deduced[LastDeducibleArgument - 1]) {
1587 // C++0x: Figure out if the template argument has a default. If so,
1588 // the user doesn't need to type this argument.
1589 // FIXME: We need to abstract template parameters better!
1590 bool HasDefaultArg = false;
1591 NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam(
1592 LastDeducibleArgument - 1);
1593 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
1594 HasDefaultArg = TTP->hasDefaultArgument();
1595 else if (NonTypeTemplateParmDecl *NTTP
1596 = dyn_cast<NonTypeTemplateParmDecl>(Param))
1597 HasDefaultArg = NTTP->hasDefaultArgument();
1599 assert(isa<TemplateTemplateParmDecl>(Param));
1601 = cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument();
1609 if (LastDeducibleArgument) {
1610 // Some of the function template arguments cannot be deduced from a
1611 // function call, so we introduce an explicit template argument list
1612 // containing all of the arguments up to the first deducible argument.
1613 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
1614 AddTemplateParameterChunks(S.Context, FunTmpl, Result,
1615 LastDeducibleArgument);
1616 Result->AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
1619 // Add the function parameters
1620 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
1621 AddFunctionParameterChunks(S.Context, Function, Result);
1622 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
1623 AddFunctionTypeQualsToCompletionString(Result, Function);
1627 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(ND)) {
1628 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
1630 Result->AddTypedTextChunk(Template->getNameAsString());
1631 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
1632 AddTemplateParameterChunks(S.Context, Template, Result);
1633 Result->AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
1637 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND)) {
1638 Selector Sel = Method->getSelector();
1639 if (Sel.isUnarySelector()) {
1640 Result->AddTypedTextChunk(Sel.getIdentifierInfoForSlot(0)->getName());
1644 std::string SelName = Sel.getIdentifierInfoForSlot(0)->getName().str();
1646 if (StartParameter == 0)
1647 Result->AddTypedTextChunk(SelName);
1649 Result->AddInformativeChunk(SelName);
1651 // If there is only one parameter, and we're past it, add an empty
1652 // typed-text chunk since there is nothing to type.
1653 if (Method->param_size() == 1)
1654 Result->AddTypedTextChunk("");
1657 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
1658 PEnd = Method->param_end();
1659 P != PEnd; (void)++P, ++Idx) {
1661 std::string Keyword;
1662 if (Idx > StartParameter)
1663 Result->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1664 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(Idx))
1665 Keyword += II->getName().str();
1667 if (Idx < StartParameter || AllParametersAreInformative) {
1668 Result->AddInformativeChunk(Keyword);
1669 } else if (Idx == StartParameter)
1670 Result->AddTypedTextChunk(Keyword);
1672 Result->AddTextChunk(Keyword);
1675 // If we're before the starting parameter, skip the placeholder.
1676 if (Idx < StartParameter)
1680 (*P)->getType().getAsStringInternal(Arg, S.Context.PrintingPolicy);
1681 Arg = "(" + Arg + ")";
1682 if (IdentifierInfo *II = (*P)->getIdentifier())
1683 Arg += II->getName().str();
1684 if (AllParametersAreInformative)
1685 Result->AddInformativeChunk(Arg);
1687 Result->AddPlaceholderChunk(Arg);
1690 if (Method->isVariadic()) {
1691 if (AllParametersAreInformative)
1692 Result->AddInformativeChunk(", ...");
1694 Result->AddPlaceholderChunk(", ...");
1701 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
1704 Result->AddTypedTextChunk(ND->getNameAsString());
1708 CodeCompletionString *
1709 CodeCompleteConsumer::OverloadCandidate::CreateSignatureString(
1710 unsigned CurrentArg,
1712 typedef CodeCompletionString::Chunk Chunk;
1714 CodeCompletionString *Result = new CodeCompletionString;
1715 FunctionDecl *FDecl = getFunction();
1716 AddResultTypeChunk(S.Context, FDecl, Result);
1717 const FunctionProtoType *Proto
1718 = dyn_cast<FunctionProtoType>(getFunctionType());
1719 if (!FDecl && !Proto) {
1720 // Function without a prototype. Just give the return type and a
1721 // highlighted ellipsis.
1722 const FunctionType *FT = getFunctionType();
1723 Result->AddTextChunk(
1724 FT->getResultType().getAsString(S.Context.PrintingPolicy));
1725 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
1726 Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
1727 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
1732 Result->AddTextChunk(FDecl->getNameAsString());
1734 Result->AddTextChunk(
1735 Proto->getResultType().getAsString(S.Context.PrintingPolicy));
1737 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
1738 unsigned NumParams = FDecl? FDecl->getNumParams() : Proto->getNumArgs();
1739 for (unsigned I = 0; I != NumParams; ++I) {
1741 Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
1743 std::string ArgString;
1747 ArgString = FDecl->getParamDecl(I)->getNameAsString();
1748 ArgType = FDecl->getParamDecl(I)->getOriginalType();
1750 ArgType = Proto->getArgType(I);
1753 ArgType.getAsStringInternal(ArgString, S.Context.PrintingPolicy);
1755 if (I == CurrentArg)
1756 Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter,
1759 Result->AddTextChunk(ArgString);
1762 if (Proto && Proto->isVariadic()) {
1763 Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
1764 if (CurrentArg < NumParams)
1765 Result->AddTextChunk("...");
1767 Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
1769 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
1775 struct SortCodeCompleteResult {
1776 typedef CodeCompleteConsumer::Result Result;
1778 bool isEarlierDeclarationName(DeclarationName X, DeclarationName Y) const {
1779 Selector XSel = X.getObjCSelector();
1780 Selector YSel = Y.getObjCSelector();
1781 if (!XSel.isNull() && !YSel.isNull()) {
1782 // We are comparing two selectors.
1783 unsigned N = std::min(XSel.getNumArgs(), YSel.getNumArgs());
1786 for (unsigned I = 0; I != N; ++I) {
1787 IdentifierInfo *XId = XSel.getIdentifierInfoForSlot(I);
1788 IdentifierInfo *YId = YSel.getIdentifierInfoForSlot(I);
1792 switch (XId->getName().compare_lower(YId->getName())) {
1793 case -1: return true;
1794 case 1: return false;
1799 return XSel.getNumArgs() < YSel.getNumArgs();
1802 // For non-selectors, order by kind.
1803 if (X.getNameKind() != Y.getNameKind())
1804 return X.getNameKind() < Y.getNameKind();
1806 // Order identifiers by comparison of their lowercased names.
1807 if (IdentifierInfo *XId = X.getAsIdentifierInfo())
1808 return XId->getName().compare_lower(
1809 Y.getAsIdentifierInfo()->getName()) < 0;
1811 // Order overloaded operators by the order in which they appear
1812 // in our list of operators.
1813 if (OverloadedOperatorKind XOp = X.getCXXOverloadedOperator())
1814 return XOp < Y.getCXXOverloadedOperator();
1816 // Order C++0x user-defined literal operators lexically by their
1817 // lowercased suffixes.
1818 if (IdentifierInfo *XLit = X.getCXXLiteralIdentifier())
1819 return XLit->getName().compare_lower(
1820 Y.getCXXLiteralIdentifier()->getName()) < 0;
1822 // The only stable ordering we have is to turn the name into a
1823 // string and then compare the lower-case strings. This is
1824 // inefficient, but thankfully does not happen too often.
1825 return llvm::StringRef(X.getAsString()).compare_lower(
1826 Y.getAsString()) < 0;
1829 /// \brief Retrieve the name that should be used to order a result.
1831 /// If the name needs to be constructed as a string, that string will be
1832 /// saved into Saved and the returned StringRef will refer to it.
1833 static llvm::StringRef getOrderedName(const Result &R,
1834 std::string &Saved) {
1836 case Result::RK_Keyword:
1839 case Result::RK_Pattern:
1840 return R.Pattern->getTypedText();
1842 case Result::RK_Macro:
1843 return R.Macro->getName();
1845 case Result::RK_Declaration:
1846 // Handle declarations below.
1850 DeclarationName Name = R.Declaration->getDeclName();
1852 // If the name is a simple identifier (by far the common case), or a
1853 // zero-argument selector, just return a reference to that identifier.
1854 if (IdentifierInfo *Id = Name.getAsIdentifierInfo())
1855 return Id->getName();
1856 if (Name.isObjCZeroArgSelector())
1857 if (IdentifierInfo *Id
1858 = Name.getObjCSelector().getIdentifierInfoForSlot(0))
1859 return Id->getName();
1861 Saved = Name.getAsString();
1865 bool operator()(const Result &X, const Result &Y) const {
1866 std::string XSaved, YSaved;
1867 llvm::StringRef XStr = getOrderedName(X, XSaved);
1868 llvm::StringRef YStr = getOrderedName(Y, YSaved);
1869 int cmp = XStr.compare_lower(YStr);
1873 // Non-hidden names precede hidden names.
1874 if (X.Hidden != Y.Hidden)
1877 // Non-nested-name-specifiers precede nested-name-specifiers.
1878 if (X.StartsNestedNameSpecifier != Y.StartsNestedNameSpecifier)
1879 return !X.StartsNestedNameSpecifier;
1886 static void AddMacroResults(Preprocessor &PP, ResultBuilder &Results) {
1887 Results.EnterNewScope();
1888 for (Preprocessor::macro_iterator M = PP.macro_begin(),
1889 MEnd = PP.macro_end();
1891 Results.AddResult(M->first);
1892 Results.ExitScope();
1895 static void HandleCodeCompleteResults(Sema *S,
1896 CodeCompleteConsumer *CodeCompleter,
1897 CodeCompleteConsumer::Result *Results,
1898 unsigned NumResults) {
1899 std::stable_sort(Results, Results + NumResults, SortCodeCompleteResult());
1902 CodeCompleter->ProcessCodeCompleteResults(*S, Results, NumResults);
1904 for (unsigned I = 0; I != NumResults; ++I)
1905 Results[I].Destroy();
1908 void Sema::CodeCompleteOrdinaryName(Scope *S,
1909 CodeCompletionContext CompletionContext) {
1910 typedef CodeCompleteConsumer::Result Result;
1911 ResultBuilder Results(*this);
1913 // Determine how to filter results, e.g., so that the names of
1914 // values (functions, enumerators, function templates, etc.) are
1915 // only allowed where we can have an expression.
1916 switch (CompletionContext) {
1919 case CCC_ObjCInterface:
1920 case CCC_ObjCImplementation:
1921 case CCC_ObjCInstanceVariableList:
1923 case CCC_MemberTemplate:
1924 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
1927 case CCC_Expression:
1931 Results.setFilter(&ResultBuilder::IsOrdinaryName);
1935 CodeCompletionDeclConsumer Consumer(Results, CurContext);
1936 LookupVisibleDecls(S, LookupOrdinaryName, Consumer);
1938 Results.EnterNewScope();
1939 AddOrdinaryNameResults(CompletionContext, S, *this, Results);
1940 Results.ExitScope();
1942 if (CodeCompleter->includeMacros())
1943 AddMacroResults(PP, Results);
1944 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
1947 static void AddObjCProperties(ObjCContainerDecl *Container,
1948 bool AllowCategories,
1949 DeclContext *CurContext,
1950 ResultBuilder &Results) {
1951 typedef CodeCompleteConsumer::Result Result;
1953 // Add properties in this container.
1954 for (ObjCContainerDecl::prop_iterator P = Container->prop_begin(),
1955 PEnd = Container->prop_end();
1958 Results.MaybeAddResult(Result(*P, 0), CurContext);
1960 // Add properties in referenced protocols.
1961 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
1962 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
1963 PEnd = Protocol->protocol_end();
1965 AddObjCProperties(*P, AllowCategories, CurContext, Results);
1966 } else if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)){
1967 if (AllowCategories) {
1968 // Look through categories.
1969 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
1970 Category; Category = Category->getNextClassCategory())
1971 AddObjCProperties(Category, AllowCategories, CurContext, Results);
1974 // Look through protocols.
1975 for (ObjCInterfaceDecl::protocol_iterator I = IFace->protocol_begin(),
1976 E = IFace->protocol_end();
1978 AddObjCProperties(*I, AllowCategories, CurContext, Results);
1980 // Look in the superclass.
1981 if (IFace->getSuperClass())
1982 AddObjCProperties(IFace->getSuperClass(), AllowCategories, CurContext,
1984 } else if (const ObjCCategoryDecl *Category
1985 = dyn_cast<ObjCCategoryDecl>(Container)) {
1986 // Look through protocols.
1987 for (ObjCInterfaceDecl::protocol_iterator P = Category->protocol_begin(),
1988 PEnd = Category->protocol_end();
1990 AddObjCProperties(*P, AllowCategories, CurContext, Results);
1994 void Sema::CodeCompleteMemberReferenceExpr(Scope *S, ExprTy *BaseE,
1995 SourceLocation OpLoc,
1997 if (!BaseE || !CodeCompleter)
2000 typedef CodeCompleteConsumer::Result Result;
2002 Expr *Base = static_cast<Expr *>(BaseE);
2003 QualType BaseType = Base->getType();
2006 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
2007 BaseType = Ptr->getPointeeType();
2008 else if (BaseType->isObjCObjectPointerType())
2014 ResultBuilder Results(*this, &ResultBuilder::IsMember);
2015 Results.EnterNewScope();
2016 if (const RecordType *Record = BaseType->getAs<RecordType>()) {
2017 // Access to a C/C++ class, struct, or union.
2018 Results.allowNestedNameSpecifiers();
2019 CodeCompletionDeclConsumer Consumer(Results, CurContext);
2020 LookupVisibleDecls(Record->getDecl(), LookupMemberName, Consumer);
2022 if (getLangOptions().CPlusPlus) {
2023 if (!Results.empty()) {
2024 // The "template" keyword can follow "->" or "." in the grammar.
2025 // However, we only want to suggest the template keyword if something
2027 bool IsDependent = BaseType->isDependentType();
2029 for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent())
2030 if (DeclContext *Ctx = (DeclContext *)DepScope->getEntity()) {
2031 IsDependent = Ctx->isDependentContext();
2037 Results.AddResult(Result("template"));
2040 } else if (!IsArrow && BaseType->getAsObjCInterfacePointerType()) {
2041 // Objective-C property reference.
2043 // Add property results based on our interface.
2044 const ObjCObjectPointerType *ObjCPtr
2045 = BaseType->getAsObjCInterfacePointerType();
2046 assert(ObjCPtr && "Non-NULL pointer guaranteed above!");
2047 AddObjCProperties(ObjCPtr->getInterfaceDecl(), true, CurContext, Results);
2049 // Add properties from the protocols in a qualified interface.
2050 for (ObjCObjectPointerType::qual_iterator I = ObjCPtr->qual_begin(),
2051 E = ObjCPtr->qual_end();
2053 AddObjCProperties(*I, true, CurContext, Results);
2054 } else if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
2055 (!IsArrow && BaseType->isObjCInterfaceType())) {
2056 // Objective-C instance variable access.
2057 ObjCInterfaceDecl *Class = 0;
2058 if (const ObjCObjectPointerType *ObjCPtr
2059 = BaseType->getAs<ObjCObjectPointerType>())
2060 Class = ObjCPtr->getInterfaceDecl();
2062 Class = BaseType->getAs<ObjCInterfaceType>()->getDecl();
2064 // Add all ivars from this class and its superclasses.
2066 CodeCompletionDeclConsumer Consumer(Results, CurContext);
2067 Results.setFilter(&ResultBuilder::IsObjCIvar);
2068 LookupVisibleDecls(Class, LookupMemberName, Consumer);
2072 // FIXME: How do we cope with isa?
2074 Results.ExitScope();
2077 if (CodeCompleter->includeMacros())
2078 AddMacroResults(PP, Results);
2080 // Hand off the results found for code completion.
2081 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2084 void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) {
2088 typedef CodeCompleteConsumer::Result Result;
2089 ResultBuilder::LookupFilter Filter = 0;
2090 switch ((DeclSpec::TST)TagSpec) {
2091 case DeclSpec::TST_enum:
2092 Filter = &ResultBuilder::IsEnum;
2095 case DeclSpec::TST_union:
2096 Filter = &ResultBuilder::IsUnion;
2099 case DeclSpec::TST_struct:
2100 case DeclSpec::TST_class:
2101 Filter = &ResultBuilder::IsClassOrStruct;
2105 assert(false && "Unknown type specifier kind in CodeCompleteTag");
2109 ResultBuilder Results(*this, Filter);
2110 Results.allowNestedNameSpecifiers();
2111 CodeCompletionDeclConsumer Consumer(Results, CurContext);
2112 LookupVisibleDecls(S, LookupTagName, Consumer);
2114 if (CodeCompleter->includeMacros())
2115 AddMacroResults(PP, Results);
2116 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2119 void Sema::CodeCompleteCase(Scope *S) {
2120 if (getSwitchStack().empty() || !CodeCompleter)
2123 SwitchStmt *Switch = getSwitchStack().back();
2124 if (!Switch->getCond()->getType()->isEnumeralType())
2127 // Code-complete the cases of a switch statement over an enumeration type
2128 // by providing the list of
2129 EnumDecl *Enum = Switch->getCond()->getType()->getAs<EnumType>()->getDecl();
2131 // Determine which enumerators we have already seen in the switch statement.
2132 // FIXME: Ideally, we would also be able to look *past* the code-completion
2133 // token, in case we are code-completing in the middle of the switch and not
2134 // at the end. However, we aren't able to do so at the moment.
2135 llvm::SmallPtrSet<EnumConstantDecl *, 8> EnumeratorsSeen;
2136 NestedNameSpecifier *Qualifier = 0;
2137 for (SwitchCase *SC = Switch->getSwitchCaseList(); SC;
2138 SC = SC->getNextSwitchCase()) {
2139 CaseStmt *Case = dyn_cast<CaseStmt>(SC);
2143 Expr *CaseVal = Case->getLHS()->IgnoreParenCasts();
2144 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseVal))
2145 if (EnumConstantDecl *Enumerator
2146 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
2147 // We look into the AST of the case statement to determine which
2148 // enumerator was named. Alternatively, we could compute the value of
2149 // the integral constant expression, then compare it against the
2150 // values of each enumerator. However, value-based approach would not
2151 // work as well with C++ templates where enumerators declared within a
2152 // template are type- and value-dependent.
2153 EnumeratorsSeen.insert(Enumerator);
2155 // If this is a qualified-id, keep track of the nested-name-specifier
2156 // so that we can reproduce it as part of code completion, e.g.,
2158 // switch (TagD.getKind()) {
2159 // case TagDecl::TK_enum:
2163 // At the XXX, our completions are TagDecl::TK_union,
2164 // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
2165 // TK_struct, and TK_class.
2166 Qualifier = DRE->getQualifier();
2170 if (getLangOptions().CPlusPlus && !Qualifier && EnumeratorsSeen.empty()) {
2171 // If there are no prior enumerators in C++, check whether we have to
2172 // qualify the names of the enumerators that we suggest, because they
2173 // may not be visible in this scope.
2174 Qualifier = getRequiredQualification(Context, CurContext,
2175 Enum->getDeclContext());
2177 // FIXME: Scoped enums need to start with "EnumDecl" as the context!
2180 // Add any enumerators that have not yet been mentioned.
2181 ResultBuilder Results(*this);
2182 Results.EnterNewScope();
2183 for (EnumDecl::enumerator_iterator E = Enum->enumerator_begin(),
2184 EEnd = Enum->enumerator_end();
2186 if (EnumeratorsSeen.count(*E))
2189 Results.AddResult(CodeCompleteConsumer::Result(*E, Qualifier),
2190 CurContext, 0, false);
2192 Results.ExitScope();
2194 if (CodeCompleter->includeMacros())
2195 AddMacroResults(PP, Results);
2196 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2200 struct IsBetterOverloadCandidate {
2205 explicit IsBetterOverloadCandidate(Sema &S, SourceLocation Loc)
2206 : S(S), Loc(Loc) { }
2209 operator()(const OverloadCandidate &X, const OverloadCandidate &Y) const {
2210 return S.isBetterOverloadCandidate(X, Y, Loc);
2215 void Sema::CodeCompleteCall(Scope *S, ExprTy *FnIn,
2216 ExprTy **ArgsIn, unsigned NumArgs) {
2220 // When we're code-completing for a call, we fall back to ordinary
2221 // name code-completion whenever we can't produce specific
2222 // results. We may want to revisit this strategy in the future,
2223 // e.g., by merging the two kinds of results.
2225 Expr *Fn = (Expr *)FnIn;
2226 Expr **Args = (Expr **)ArgsIn;
2228 // Ignore type-dependent call expressions entirely.
2229 if (Fn->isTypeDependent() ||
2230 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
2231 CodeCompleteOrdinaryName(S, CCC_Expression);
2235 // Build an overload candidate set based on the functions we find.
2236 SourceLocation Loc = Fn->getExprLoc();
2237 OverloadCandidateSet CandidateSet(Loc);
2239 // FIXME: What if we're calling something that isn't a function declaration?
2240 // FIXME: What if we're calling a pseudo-destructor?
2241 // FIXME: What if we're calling a member function?
2243 typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate;
2244 llvm::SmallVector<ResultCandidate, 8> Results;
2246 Expr *NakedFn = Fn->IgnoreParenCasts();
2247 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(NakedFn))
2248 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet,
2249 /*PartialOverloading=*/ true);
2250 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
2251 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl());
2253 if (!FDecl->getType()->getAs<FunctionProtoType>())
2254 Results.push_back(ResultCandidate(FDecl));
2257 AddOverloadCandidate(FDecl, AS_none, Args, NumArgs, CandidateSet,
2258 false, false, /*PartialOverloading*/ true);
2262 if (!CandidateSet.empty()) {
2263 // Sort the overload candidate set by placing the best overloads first.
2264 std::stable_sort(CandidateSet.begin(), CandidateSet.end(),
2265 IsBetterOverloadCandidate(*this, Loc));
2267 // Add the remaining viable overload candidates as code-completion reslults.
2268 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
2269 CandEnd = CandidateSet.end();
2270 Cand != CandEnd; ++Cand) {
2272 Results.push_back(ResultCandidate(Cand->Function));
2276 if (Results.empty())
2277 CodeCompleteOrdinaryName(S, CCC_Expression);
2279 CodeCompleter->ProcessOverloadCandidates(*this, NumArgs, Results.data(),
2283 void Sema::CodeCompleteQualifiedId(Scope *S, const CXXScopeSpec &SS,
2284 bool EnteringContext) {
2285 if (!SS.getScopeRep() || !CodeCompleter)
2288 DeclContext *Ctx = computeDeclContext(SS, EnteringContext);
2292 // Try to instantiate any non-dependent declaration contexts before
2294 if (!isDependentScopeSpecifier(SS) && RequireCompleteDeclContext(SS))
2297 ResultBuilder Results(*this);
2298 CodeCompletionDeclConsumer Consumer(Results, CurContext);
2299 LookupVisibleDecls(Ctx, LookupOrdinaryName, Consumer);
2301 // The "template" keyword can follow "::" in the grammar, but only
2302 // put it into the grammar if the nested-name-specifier is dependent.
2303 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
2304 if (!Results.empty() && NNS->isDependent())
2305 Results.AddResult("template");
2307 if (CodeCompleter->includeMacros())
2308 AddMacroResults(PP, Results);
2309 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2312 void Sema::CodeCompleteUsing(Scope *S) {
2316 ResultBuilder Results(*this, &ResultBuilder::IsNestedNameSpecifier);
2317 Results.EnterNewScope();
2319 // If we aren't in class scope, we could see the "namespace" keyword.
2320 if (!S->isClassScope())
2321 Results.AddResult(CodeCompleteConsumer::Result("namespace"));
2323 // After "using", we can see anything that would start a
2324 // nested-name-specifier.
2325 CodeCompletionDeclConsumer Consumer(Results, CurContext);
2326 LookupVisibleDecls(S, LookupOrdinaryName, Consumer);
2327 Results.ExitScope();
2329 if (CodeCompleter->includeMacros())
2330 AddMacroResults(PP, Results);
2331 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2334 void Sema::CodeCompleteUsingDirective(Scope *S) {
2338 // After "using namespace", we expect to see a namespace name or namespace
2340 ResultBuilder Results(*this, &ResultBuilder::IsNamespaceOrAlias);
2341 Results.EnterNewScope();
2342 CodeCompletionDeclConsumer Consumer(Results, CurContext);
2343 LookupVisibleDecls(S, LookupOrdinaryName, Consumer);
2344 Results.ExitScope();
2345 if (CodeCompleter->includeMacros())
2346 AddMacroResults(PP, Results);
2347 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2350 void Sema::CodeCompleteNamespaceDecl(Scope *S) {
2354 ResultBuilder Results(*this, &ResultBuilder::IsNamespace);
2355 DeclContext *Ctx = (DeclContext *)S->getEntity();
2356 if (!S->getParent())
2357 Ctx = Context.getTranslationUnitDecl();
2359 if (Ctx && Ctx->isFileContext()) {
2360 // We only want to see those namespaces that have already been defined
2361 // within this scope, because its likely that the user is creating an
2362 // extended namespace declaration. Keep track of the most recent
2363 // definition of each namespace.
2364 std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest;
2365 for (DeclContext::specific_decl_iterator<NamespaceDecl>
2366 NS(Ctx->decls_begin()), NSEnd(Ctx->decls_end());
2368 OrigToLatest[NS->getOriginalNamespace()] = *NS;
2370 // Add the most recent definition (or extended definition) of each
2371 // namespace to the list of results.
2372 Results.EnterNewScope();
2373 for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator
2374 NS = OrigToLatest.begin(), NSEnd = OrigToLatest.end();
2376 Results.AddResult(CodeCompleteConsumer::Result(NS->second, 0),
2377 CurContext, 0, false);
2378 Results.ExitScope();
2381 if (CodeCompleter->includeMacros())
2382 AddMacroResults(PP, Results);
2383 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2386 void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) {
2390 // After "namespace", we expect to see a namespace or alias.
2391 ResultBuilder Results(*this, &ResultBuilder::IsNamespaceOrAlias);
2392 CodeCompletionDeclConsumer Consumer(Results, CurContext);
2393 LookupVisibleDecls(S, LookupOrdinaryName, Consumer);
2394 if (CodeCompleter->includeMacros())
2395 AddMacroResults(PP, Results);
2396 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2399 void Sema::CodeCompleteOperatorName(Scope *S) {
2403 typedef CodeCompleteConsumer::Result Result;
2404 ResultBuilder Results(*this, &ResultBuilder::IsType);
2405 Results.EnterNewScope();
2407 // Add the names of overloadable operators.
2408 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2409 if (std::strcmp(Spelling, "?")) \
2410 Results.AddResult(Result(Spelling));
2411 #include "clang/Basic/OperatorKinds.def"
2413 // Add any type names visible from the current scope
2414 Results.allowNestedNameSpecifiers();
2415 CodeCompletionDeclConsumer Consumer(Results, CurContext);
2416 LookupVisibleDecls(S, LookupOrdinaryName, Consumer);
2418 // Add any type specifiers
2419 AddTypeSpecifierResults(getLangOptions(), Results);
2420 Results.ExitScope();
2422 if (CodeCompleter->includeMacros())
2423 AddMacroResults(PP, Results);
2424 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2427 // Macro that expands to @Keyword or Keyword, depending on whether NeedAt is
2429 #define OBJC_AT_KEYWORD_NAME(NeedAt,Keyword) NeedAt? "@" #Keyword : #Keyword
2430 static void AddObjCImplementationResults(const LangOptions &LangOpts,
2431 ResultBuilder &Results,
2433 typedef CodeCompleteConsumer::Result Result;
2434 // Since we have an implementation, we can end it.
2435 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,end)));
2437 CodeCompletionString *Pattern = 0;
2438 if (LangOpts.ObjC2) {
2440 Pattern = new CodeCompletionString;
2441 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,dynamic));
2442 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
2443 Pattern->AddPlaceholderChunk("property");
2444 Results.AddResult(Result(Pattern));
2447 Pattern = new CodeCompletionString;
2448 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,synthesize));
2449 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
2450 Pattern->AddPlaceholderChunk("property");
2451 Results.AddResult(Result(Pattern));
2455 static void AddObjCInterfaceResults(const LangOptions &LangOpts,
2456 ResultBuilder &Results,
2458 typedef CodeCompleteConsumer::Result Result;
2460 // Since we have an interface or protocol, we can end it.
2461 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,end)));
2463 if (LangOpts.ObjC2) {
2465 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,property)));
2468 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,required)));
2471 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,optional)));
2475 static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt) {
2476 typedef CodeCompleteConsumer::Result Result;
2477 CodeCompletionString *Pattern = 0;
2480 Pattern = new CodeCompletionString;
2481 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,class));
2482 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
2483 Pattern->AddPlaceholderChunk("identifier");
2484 Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
2485 Results.AddResult(Result(Pattern));
2488 // FIXME: Could introduce the whole pattern, including superclasses and
2490 Pattern = new CodeCompletionString;
2491 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,interface));
2492 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
2493 Pattern->AddPlaceholderChunk("class");
2494 Results.AddResult(Result(Pattern));
2497 Pattern = new CodeCompletionString;
2498 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,protocol));
2499 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
2500 Pattern->AddPlaceholderChunk("protocol");
2501 Results.AddResult(Result(Pattern));
2503 // @implementation name
2504 Pattern = new CodeCompletionString;
2505 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,implementation));
2506 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
2507 Pattern->AddPlaceholderChunk("class");
2508 Results.AddResult(Result(Pattern));
2510 // @compatibility_alias name
2511 Pattern = new CodeCompletionString;
2512 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,compatibility_alias));
2513 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
2514 Pattern->AddPlaceholderChunk("alias");
2515 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
2516 Pattern->AddPlaceholderChunk("class");
2517 Results.AddResult(Result(Pattern));
2520 void Sema::CodeCompleteObjCAtDirective(Scope *S, DeclPtrTy ObjCImpDecl,
2522 typedef CodeCompleteConsumer::Result Result;
2523 ResultBuilder Results(*this);
2524 Results.EnterNewScope();
2526 AddObjCImplementationResults(getLangOptions(), Results, false);
2527 else if (InInterface)
2528 AddObjCInterfaceResults(getLangOptions(), Results, false);
2530 AddObjCTopLevelResults(Results, false);
2531 Results.ExitScope();
2532 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2535 static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt) {
2536 typedef CodeCompleteConsumer::Result Result;
2537 CodeCompletionString *Pattern = 0;
2539 // @encode ( type-name )
2540 Pattern = new CodeCompletionString;
2541 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,encode));
2542 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
2543 Pattern->AddPlaceholderChunk("type-name");
2544 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
2545 Results.AddResult(Result(Pattern));
2547 // @protocol ( protocol-name )
2548 Pattern = new CodeCompletionString;
2549 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,protocol));
2550 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
2551 Pattern->AddPlaceholderChunk("protocol-name");
2552 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
2553 Results.AddResult(Result(Pattern));
2555 // @selector ( selector )
2556 Pattern = new CodeCompletionString;
2557 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,selector));
2558 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
2559 Pattern->AddPlaceholderChunk("selector");
2560 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
2561 Results.AddResult(Result(Pattern));
2564 static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt) {
2565 typedef CodeCompleteConsumer::Result Result;
2566 CodeCompletionString *Pattern = 0;
2568 // @try { statements } @catch ( declaration ) { statements } @finally
2570 Pattern = new CodeCompletionString;
2571 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,try));
2572 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
2573 Pattern->AddPlaceholderChunk("statements");
2574 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
2575 Pattern->AddTextChunk("@catch");
2576 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
2577 Pattern->AddPlaceholderChunk("parameter");
2578 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
2579 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
2580 Pattern->AddPlaceholderChunk("statements");
2581 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
2582 Pattern->AddTextChunk("@finally");
2583 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
2584 Pattern->AddPlaceholderChunk("statements");
2585 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
2586 Results.AddResult(Result(Pattern));
2589 Pattern = new CodeCompletionString;
2590 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,throw));
2591 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
2592 Pattern->AddPlaceholderChunk("expression");
2593 Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
2594 Results.AddResult(Result(Pattern));
2596 // @synchronized ( expression ) { statements }
2597 Pattern = new CodeCompletionString;
2598 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,synchronized));
2599 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
2600 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
2601 Pattern->AddPlaceholderChunk("expression");
2602 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
2603 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
2604 Pattern->AddPlaceholderChunk("statements");
2605 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
2606 Results.AddResult(Result(Pattern));
2609 static void AddObjCVisibilityResults(const LangOptions &LangOpts,
2610 ResultBuilder &Results,
2612 typedef CodeCompleteConsumer::Result Result;
2613 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,private)));
2614 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,protected)));
2615 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,public)));
2617 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,package)));
2620 void Sema::CodeCompleteObjCAtVisibility(Scope *S) {
2621 ResultBuilder Results(*this);
2622 Results.EnterNewScope();
2623 AddObjCVisibilityResults(getLangOptions(), Results, false);
2624 Results.ExitScope();
2625 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2628 void Sema::CodeCompleteObjCAtStatement(Scope *S) {
2629 ResultBuilder Results(*this);
2630 Results.EnterNewScope();
2631 AddObjCStatementResults(Results, false);
2632 AddObjCExpressionResults(Results, false);
2633 Results.ExitScope();
2634 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2637 void Sema::CodeCompleteObjCAtExpression(Scope *S) {
2638 ResultBuilder Results(*this);
2639 Results.EnterNewScope();
2640 AddObjCExpressionResults(Results, false);
2641 Results.ExitScope();
2642 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2645 /// \brief Determine whether the addition of the given flag to an Objective-C
2646 /// property's attributes will cause a conflict.
2647 static bool ObjCPropertyFlagConflicts(unsigned Attributes, unsigned NewFlag) {
2648 // Check if we've already added this flag.
2649 if (Attributes & NewFlag)
2652 Attributes |= NewFlag;
2654 // Check for collisions with "readonly".
2655 if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
2656 (Attributes & (ObjCDeclSpec::DQ_PR_readwrite |
2657 ObjCDeclSpec::DQ_PR_assign |
2658 ObjCDeclSpec::DQ_PR_copy |
2659 ObjCDeclSpec::DQ_PR_retain)))
2662 // Check for more than one of { assign, copy, retain }.
2663 unsigned AssignCopyRetMask = Attributes & (ObjCDeclSpec::DQ_PR_assign |
2664 ObjCDeclSpec::DQ_PR_copy |
2665 ObjCDeclSpec::DQ_PR_retain);
2666 if (AssignCopyRetMask &&
2667 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_assign &&
2668 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_copy &&
2669 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_retain)
2675 void Sema::CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS) {
2679 unsigned Attributes = ODS.getPropertyAttributes();
2681 typedef CodeCompleteConsumer::Result Result;
2682 ResultBuilder Results(*this);
2683 Results.EnterNewScope();
2684 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readonly))
2685 Results.AddResult(CodeCompleteConsumer::Result("readonly"));
2686 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_assign))
2687 Results.AddResult(CodeCompleteConsumer::Result("assign"));
2688 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readwrite))
2689 Results.AddResult(CodeCompleteConsumer::Result("readwrite"));
2690 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_retain))
2691 Results.AddResult(CodeCompleteConsumer::Result("retain"));
2692 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_copy))
2693 Results.AddResult(CodeCompleteConsumer::Result("copy"));
2694 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nonatomic))
2695 Results.AddResult(CodeCompleteConsumer::Result("nonatomic"));
2696 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_setter)) {
2697 CodeCompletionString *Setter = new CodeCompletionString;
2698 Setter->AddTypedTextChunk("setter");
2699 Setter->AddTextChunk(" = ");
2700 Setter->AddPlaceholderChunk("method");
2701 Results.AddResult(CodeCompleteConsumer::Result(Setter));
2703 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_getter)) {
2704 CodeCompletionString *Getter = new CodeCompletionString;
2705 Getter->AddTypedTextChunk("getter");
2706 Getter->AddTextChunk(" = ");
2707 Getter->AddPlaceholderChunk("method");
2708 Results.AddResult(CodeCompleteConsumer::Result(Getter));
2710 Results.ExitScope();
2711 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2714 /// \brief Descripts the kind of Objective-C method that we want to find
2715 /// via code completion.
2716 enum ObjCMethodKind {
2717 MK_Any, //< Any kind of method, provided it means other specified criteria.
2718 MK_ZeroArgSelector, //< Zero-argument (unary) selector.
2719 MK_OneArgSelector //< One-argument selector.
2722 static bool isAcceptableObjCMethod(ObjCMethodDecl *Method,
2723 ObjCMethodKind WantKind,
2724 IdentifierInfo **SelIdents,
2725 unsigned NumSelIdents) {
2726 Selector Sel = Method->getSelector();
2727 if (NumSelIdents > Sel.getNumArgs())
2732 case MK_ZeroArgSelector: return Sel.isUnarySelector();
2733 case MK_OneArgSelector: return Sel.getNumArgs() == 1;
2736 for (unsigned I = 0; I != NumSelIdents; ++I)
2737 if (SelIdents[I] != Sel.getIdentifierInfoForSlot(I))
2743 /// \brief Add all of the Objective-C methods in the given Objective-C
2744 /// container to the set of results.
2746 /// The container will be a class, protocol, category, or implementation of
2747 /// any of the above. This mether will recurse to include methods from
2748 /// the superclasses of classes along with their categories, protocols, and
2749 /// implementations.
2751 /// \param Container the container in which we'll look to find methods.
2753 /// \param WantInstance whether to add instance methods (only); if false, this
2754 /// routine will add factory methods (only).
2756 /// \param CurContext the context in which we're performing the lookup that
2759 /// \param Results the structure into which we'll add results.
2760 static void AddObjCMethods(ObjCContainerDecl *Container,
2761 bool WantInstanceMethods,
2762 ObjCMethodKind WantKind,
2763 IdentifierInfo **SelIdents,
2764 unsigned NumSelIdents,
2765 DeclContext *CurContext,
2766 ResultBuilder &Results) {
2767 typedef CodeCompleteConsumer::Result Result;
2768 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
2769 MEnd = Container->meth_end();
2771 if ((*M)->isInstanceMethod() == WantInstanceMethods) {
2772 // Check whether the selector identifiers we've been given are a
2773 // subset of the identifiers for this particular method.
2774 if (!isAcceptableObjCMethod(*M, WantKind, SelIdents, NumSelIdents))
2777 Result R = Result(*M, 0);
2778 R.StartParameter = NumSelIdents;
2779 R.AllParametersAreInformative = (WantKind != MK_Any);
2780 Results.MaybeAddResult(R, CurContext);
2784 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container);
2788 // Add methods in protocols.
2789 const ObjCList<ObjCProtocolDecl> &Protocols= IFace->getReferencedProtocols();
2790 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
2791 E = Protocols.end();
2793 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, NumSelIdents,
2794 CurContext, Results);
2796 // Add methods in categories.
2797 for (ObjCCategoryDecl *CatDecl = IFace->getCategoryList(); CatDecl;
2798 CatDecl = CatDecl->getNextClassCategory()) {
2799 AddObjCMethods(CatDecl, WantInstanceMethods, WantKind, SelIdents,
2800 NumSelIdents, CurContext, Results);
2802 // Add a categories protocol methods.
2803 const ObjCList<ObjCProtocolDecl> &Protocols
2804 = CatDecl->getReferencedProtocols();
2805 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
2806 E = Protocols.end();
2808 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents,
2809 NumSelIdents, CurContext, Results);
2811 // Add methods in category implementations.
2812 if (ObjCCategoryImplDecl *Impl = CatDecl->getImplementation())
2813 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
2814 NumSelIdents, CurContext, Results);
2817 // Add methods in superclass.
2818 if (IFace->getSuperClass())
2819 AddObjCMethods(IFace->getSuperClass(), WantInstanceMethods, WantKind,
2820 SelIdents, NumSelIdents, CurContext, Results);
2822 // Add methods in our implementation, if any.
2823 if (ObjCImplementationDecl *Impl = IFace->getImplementation())
2824 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
2825 NumSelIdents, CurContext, Results);
2829 void Sema::CodeCompleteObjCPropertyGetter(Scope *S, DeclPtrTy ClassDecl,
2831 unsigned NumMethods) {
2832 typedef CodeCompleteConsumer::Result Result;
2834 // Try to find the interface where getters might live.
2835 ObjCInterfaceDecl *Class
2836 = dyn_cast_or_null<ObjCInterfaceDecl>(ClassDecl.getAs<Decl>());
2838 if (ObjCCategoryDecl *Category
2839 = dyn_cast_or_null<ObjCCategoryDecl>(ClassDecl.getAs<Decl>()))
2840 Class = Category->getClassInterface();
2846 // Find all of the potential getters.
2847 ResultBuilder Results(*this);
2848 Results.EnterNewScope();
2850 // FIXME: We need to do this because Objective-C methods don't get
2851 // pushed into DeclContexts early enough. Argh!
2852 for (unsigned I = 0; I != NumMethods; ++I) {
2853 if (ObjCMethodDecl *Method
2854 = dyn_cast_or_null<ObjCMethodDecl>(Methods[I].getAs<Decl>()))
2855 if (Method->isInstanceMethod() &&
2856 isAcceptableObjCMethod(Method, MK_ZeroArgSelector, 0, 0)) {
2857 Result R = Result(Method, 0);
2858 R.AllParametersAreInformative = true;
2859 Results.MaybeAddResult(R, CurContext);
2863 AddObjCMethods(Class, true, MK_ZeroArgSelector, 0, 0, CurContext, Results);
2864 Results.ExitScope();
2865 HandleCodeCompleteResults(this, CodeCompleter,Results.data(),Results.size());
2868 void Sema::CodeCompleteObjCPropertySetter(Scope *S, DeclPtrTy ObjCImplDecl,
2870 unsigned NumMethods) {
2871 typedef CodeCompleteConsumer::Result Result;
2873 // Try to find the interface where setters might live.
2874 ObjCInterfaceDecl *Class
2875 = dyn_cast_or_null<ObjCInterfaceDecl>(ObjCImplDecl.getAs<Decl>());
2877 if (ObjCCategoryDecl *Category
2878 = dyn_cast_or_null<ObjCCategoryDecl>(ObjCImplDecl.getAs<Decl>()))
2879 Class = Category->getClassInterface();
2885 // Find all of the potential getters.
2886 ResultBuilder Results(*this);
2887 Results.EnterNewScope();
2889 // FIXME: We need to do this because Objective-C methods don't get
2890 // pushed into DeclContexts early enough. Argh!
2891 for (unsigned I = 0; I != NumMethods; ++I) {
2892 if (ObjCMethodDecl *Method
2893 = dyn_cast_or_null<ObjCMethodDecl>(Methods[I].getAs<Decl>()))
2894 if (Method->isInstanceMethod() &&
2895 isAcceptableObjCMethod(Method, MK_OneArgSelector, 0, 0)) {
2896 Result R = Result(Method, 0);
2897 R.AllParametersAreInformative = true;
2898 Results.MaybeAddResult(R, CurContext);
2902 AddObjCMethods(Class, true, MK_OneArgSelector, 0, 0, CurContext, Results);
2904 Results.ExitScope();
2905 HandleCodeCompleteResults(this, CodeCompleter,Results.data(),Results.size());
2908 void Sema::CodeCompleteObjCClassMessage(Scope *S, IdentifierInfo *FName,
2909 SourceLocation FNameLoc,
2910 IdentifierInfo **SelIdents,
2911 unsigned NumSelIdents) {
2912 typedef CodeCompleteConsumer::Result Result;
2913 ObjCInterfaceDecl *CDecl = 0;
2915 if (FName->isStr("super")) {
2916 // We're sending a message to "super".
2917 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
2918 // Figure out which interface we're in.
2919 CDecl = CurMethod->getClassInterface();
2923 // Find the superclass of this class.
2924 CDecl = CDecl->getSuperClass();
2928 if (CurMethod->isInstanceMethod()) {
2929 // We are inside an instance method, which means that the message
2930 // send [super ...] is actually calling an instance method on the
2931 // current object. Build the super expression and handle this like
2932 // an instance method.
2933 QualType SuperTy = Context.getObjCInterfaceType(CDecl);
2934 SuperTy = Context.getObjCObjectPointerType(SuperTy);
2935 OwningExprResult Super
2936 = Owned(new (Context) ObjCSuperExpr(FNameLoc, SuperTy));
2937 return CodeCompleteObjCInstanceMessage(S, (Expr *)Super.get(),
2938 SelIdents, NumSelIdents);
2941 // Okay, we're calling a factory method in our superclass.
2945 // If the given name refers to an interface type, retrieve the
2946 // corresponding declaration.
2948 if (TypeTy *Ty = getTypeName(*FName, FNameLoc, S, 0, false)) {
2949 QualType T = GetTypeFromParser(Ty, 0);
2951 if (const ObjCInterfaceType *Interface = T->getAs<ObjCInterfaceType>())
2952 CDecl = Interface->getDecl();
2955 if (!CDecl && FName->isStr("super")) {
2956 // "super" may be the name of a variable, in which case we are
2957 // probably calling an instance method.
2960 id.setIdentifier(FName, FNameLoc);
2961 OwningExprResult Super = ActOnIdExpression(S, SS, id, false, false);
2962 return CodeCompleteObjCInstanceMessage(S, (Expr *)Super.get(),
2963 SelIdents, NumSelIdents);
2966 // Add all of the factory methods in this Objective-C class, its protocols,
2967 // superclasses, categories, implementation, etc.
2968 ResultBuilder Results(*this);
2969 Results.EnterNewScope();
2970 AddObjCMethods(CDecl, false, MK_Any, SelIdents, NumSelIdents, CurContext,
2972 Results.ExitScope();
2974 // This also suppresses remaining diagnostics.
2975 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
2978 void Sema::CodeCompleteObjCInstanceMessage(Scope *S, ExprTy *Receiver,
2979 IdentifierInfo **SelIdents,
2980 unsigned NumSelIdents) {
2981 typedef CodeCompleteConsumer::Result Result;
2983 Expr *RecExpr = static_cast<Expr *>(Receiver);
2985 // If necessary, apply function/array conversion to the receiver.
2986 // C99 6.7.5.3p[7,8].
2987 DefaultFunctionArrayLvalueConversion(RecExpr);
2988 QualType ReceiverType = RecExpr->getType();
2990 if (ReceiverType->isObjCIdType() || ReceiverType->isBlockPointerType()) {
2991 // FIXME: We're messaging 'id'. Do we actually want to look up every method
2996 // Build the set of methods we can see.
2997 ResultBuilder Results(*this);
2998 Results.EnterNewScope();
3000 // Handle messages to Class. This really isn't a message to an instance
3001 // method, so we treat it the same way we would treat a message send to a
3003 if (ReceiverType->isObjCClassType() ||
3004 ReceiverType->isObjCQualifiedClassType()) {
3005 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
3006 if (ObjCInterfaceDecl *ClassDecl = CurMethod->getClassInterface())
3007 AddObjCMethods(ClassDecl, false, MK_Any, SelIdents, NumSelIdents,
3008 CurContext, Results);
3011 // Handle messages to a qualified ID ("id<foo>").
3012 else if (const ObjCObjectPointerType *QualID
3013 = ReceiverType->getAsObjCQualifiedIdType()) {
3014 // Search protocols for instance methods.
3015 for (ObjCObjectPointerType::qual_iterator I = QualID->qual_begin(),
3016 E = QualID->qual_end();
3018 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
3021 // Handle messages to a pointer to interface type.
3022 else if (const ObjCObjectPointerType *IFacePtr
3023 = ReceiverType->getAsObjCInterfacePointerType()) {
3024 // Search the class, its superclasses, etc., for instance methods.
3025 AddObjCMethods(IFacePtr->getInterfaceDecl(), true, MK_Any, SelIdents,
3026 NumSelIdents, CurContext, Results);
3028 // Search protocols for instance methods.
3029 for (ObjCObjectPointerType::qual_iterator I = IFacePtr->qual_begin(),
3030 E = IFacePtr->qual_end();
3032 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
3036 Results.ExitScope();
3037 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3040 /// \brief Add all of the protocol declarations that we find in the given
3041 /// (translation unit) context.
3042 static void AddProtocolResults(DeclContext *Ctx, DeclContext *CurContext,
3043 bool OnlyForwardDeclarations,
3044 ResultBuilder &Results) {
3045 typedef CodeCompleteConsumer::Result Result;
3047 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
3048 DEnd = Ctx->decls_end();
3050 // Record any protocols we find.
3051 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*D))
3052 if (!OnlyForwardDeclarations || Proto->isForwardDecl())
3053 Results.AddResult(Result(Proto, 0), CurContext, 0, false);
3055 // Record any forward-declared protocols we find.
3056 if (ObjCForwardProtocolDecl *Forward
3057 = dyn_cast<ObjCForwardProtocolDecl>(*D)) {
3058 for (ObjCForwardProtocolDecl::protocol_iterator
3059 P = Forward->protocol_begin(),
3060 PEnd = Forward->protocol_end();
3062 if (!OnlyForwardDeclarations || (*P)->isForwardDecl())
3063 Results.AddResult(Result(*P, 0), CurContext, 0, false);
3068 void Sema::CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols,
3069 unsigned NumProtocols) {
3070 ResultBuilder Results(*this);
3071 Results.EnterNewScope();
3073 // Tell the result set to ignore all of the protocols we have
3075 for (unsigned I = 0; I != NumProtocols; ++I)
3076 if (ObjCProtocolDecl *Protocol = LookupProtocol(Protocols[I].first))
3077 Results.Ignore(Protocol);
3079 // Add all protocols.
3080 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, false,
3083 Results.ExitScope();
3084 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3087 void Sema::CodeCompleteObjCProtocolDecl(Scope *) {
3088 ResultBuilder Results(*this);
3089 Results.EnterNewScope();
3091 // Add all protocols.
3092 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, true,
3095 Results.ExitScope();
3096 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3099 /// \brief Add all of the Objective-C interface declarations that we find in
3100 /// the given (translation unit) context.
3101 static void AddInterfaceResults(DeclContext *Ctx, DeclContext *CurContext,
3102 bool OnlyForwardDeclarations,
3103 bool OnlyUnimplemented,
3104 ResultBuilder &Results) {
3105 typedef CodeCompleteConsumer::Result Result;
3107 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
3108 DEnd = Ctx->decls_end();
3110 // Record any interfaces we find.
3111 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*D))
3112 if ((!OnlyForwardDeclarations || Class->isForwardDecl()) &&
3113 (!OnlyUnimplemented || !Class->getImplementation()))
3114 Results.AddResult(Result(Class, 0), CurContext, 0, false);
3116 // Record any forward-declared interfaces we find.
3117 if (ObjCClassDecl *Forward = dyn_cast<ObjCClassDecl>(*D)) {
3118 for (ObjCClassDecl::iterator C = Forward->begin(), CEnd = Forward->end();
3120 if ((!OnlyForwardDeclarations || C->getInterface()->isForwardDecl()) &&
3121 (!OnlyUnimplemented || !C->getInterface()->getImplementation()))
3122 Results.AddResult(Result(C->getInterface(), 0), CurContext,
3128 void Sema::CodeCompleteObjCInterfaceDecl(Scope *S) {
3129 ResultBuilder Results(*this);
3130 Results.EnterNewScope();
3133 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, true,
3136 Results.ExitScope();
3137 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3140 void Sema::CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName) {
3141 ResultBuilder Results(*this);
3142 Results.EnterNewScope();
3144 // Make sure that we ignore the class we're currently defining.
3146 = LookupSingleName(TUScope, ClassName, LookupOrdinaryName);
3147 if (CurClass && isa<ObjCInterfaceDecl>(CurClass))
3148 Results.Ignore(CurClass);
3151 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
3154 Results.ExitScope();
3155 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3158 void Sema::CodeCompleteObjCImplementationDecl(Scope *S) {
3159 ResultBuilder Results(*this);
3160 Results.EnterNewScope();
3162 // Add all unimplemented classes.
3163 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
3166 Results.ExitScope();
3167 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3170 void Sema::CodeCompleteObjCInterfaceCategory(Scope *S,
3171 IdentifierInfo *ClassName) {
3172 typedef CodeCompleteConsumer::Result Result;
3174 ResultBuilder Results(*this);
3176 // Ignore any categories we find that have already been implemented by this
3178 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
3180 = LookupSingleName(TUScope, ClassName, LookupOrdinaryName);
3181 if (ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass))
3182 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
3183 Category = Category->getNextClassCategory())
3184 CategoryNames.insert(Category->getIdentifier());
3186 // Add all of the categories we know about.
3187 Results.EnterNewScope();
3188 TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
3189 for (DeclContext::decl_iterator D = TU->decls_begin(),
3190 DEnd = TU->decls_end();
3192 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(*D))
3193 if (CategoryNames.insert(Category->getIdentifier()))
3194 Results.AddResult(Result(Category, 0), CurContext, 0, false);
3195 Results.ExitScope();
3197 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3200 void Sema::CodeCompleteObjCImplementationCategory(Scope *S,
3201 IdentifierInfo *ClassName) {
3202 typedef CodeCompleteConsumer::Result Result;
3204 // Find the corresponding interface. If we couldn't find the interface, the
3205 // program itself is ill-formed. However, we'll try to be helpful still by
3206 // providing the list of all of the categories we know about.
3208 = LookupSingleName(TUScope, ClassName, LookupOrdinaryName);
3209 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass);
3211 return CodeCompleteObjCInterfaceCategory(S, ClassName);
3213 ResultBuilder Results(*this);
3215 // Add all of the categories that have have corresponding interface
3216 // declarations in this class and any of its superclasses, except for
3217 // already-implemented categories in the class itself.
3218 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
3219 Results.EnterNewScope();
3220 bool IgnoreImplemented = true;
3222 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
3223 Category = Category->getNextClassCategory())
3224 if ((!IgnoreImplemented || !Category->getImplementation()) &&
3225 CategoryNames.insert(Category->getIdentifier()))
3226 Results.AddResult(Result(Category, 0), CurContext, 0, false);
3228 Class = Class->getSuperClass();
3229 IgnoreImplemented = false;
3231 Results.ExitScope();
3233 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3236 void Sema::CodeCompleteObjCPropertyDefinition(Scope *S, DeclPtrTy ObjCImpDecl) {
3237 typedef CodeCompleteConsumer::Result Result;
3238 ResultBuilder Results(*this);
3240 // Figure out where this @synthesize lives.
3241 ObjCContainerDecl *Container
3242 = dyn_cast_or_null<ObjCContainerDecl>(ObjCImpDecl.getAs<Decl>());
3244 (!isa<ObjCImplementationDecl>(Container) &&
3245 !isa<ObjCCategoryImplDecl>(Container)))
3248 // Ignore any properties that have already been implemented.
3249 for (DeclContext::decl_iterator D = Container->decls_begin(),
3250 DEnd = Container->decls_end();
3252 if (ObjCPropertyImplDecl *PropertyImpl = dyn_cast<ObjCPropertyImplDecl>(*D))
3253 Results.Ignore(PropertyImpl->getPropertyDecl());
3255 // Add any properties that we find.
3256 Results.EnterNewScope();
3257 if (ObjCImplementationDecl *ClassImpl
3258 = dyn_cast<ObjCImplementationDecl>(Container))
3259 AddObjCProperties(ClassImpl->getClassInterface(), false, CurContext,
3262 AddObjCProperties(cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl(),
3263 false, CurContext, Results);
3264 Results.ExitScope();
3266 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
3269 void Sema::CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
3270 IdentifierInfo *PropertyName,
3271 DeclPtrTy ObjCImpDecl) {
3272 typedef CodeCompleteConsumer::Result Result;
3273 ResultBuilder Results(*this);
3275 // Figure out where this @synthesize lives.
3276 ObjCContainerDecl *Container
3277 = dyn_cast_or_null<ObjCContainerDecl>(ObjCImpDecl.getAs<Decl>());
3279 (!isa<ObjCImplementationDecl>(Container) &&
3280 !isa<ObjCCategoryImplDecl>(Container)))
3283 // Figure out which interface we're looking into.
3284 ObjCInterfaceDecl *Class = 0;
3285 if (ObjCImplementationDecl *ClassImpl
3286 = dyn_cast<ObjCImplementationDecl>(Container))
3287 Class = ClassImpl->getClassInterface();
3289 Class = cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl()
3290 ->getClassInterface();
3292 // Add all of the instance variables in this class and its superclasses.
3293 Results.EnterNewScope();
3294 for(; Class; Class = Class->getSuperClass()) {
3295 // FIXME: We could screen the type of each ivar for compatibility with
3296 // the property, but is that being too paternal?
3297 for (ObjCInterfaceDecl::ivar_iterator IVar = Class->ivar_begin(),
3298 IVarEnd = Class->ivar_end();
3299 IVar != IVarEnd; ++IVar)
3300 Results.AddResult(Result(*IVar, 0), CurContext, 0, false);
3302 Results.ExitScope();
3304 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());