Keep the source location of the selector in ObjCMessageExpr.
[clang.git] / lib / Sema / SemaCodeComplete.cpp
blob2394629be59b66afecab9e2c7dccaacaeef05729
1 //===---------------- SemaCodeComplete.cpp - Code Completion ----*- C++ -*-===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the code-completion semantic actions.
12 //===----------------------------------------------------------------------===//
13 #include "clang/Sema/SemaInternal.h"
14 #include "clang/Sema/Lookup.h"
15 #include "clang/Sema/Overload.h"
16 #include "clang/Sema/CodeCompleteConsumer.h"
17 #include "clang/Sema/ExternalSemaSource.h"
18 #include "clang/Sema/Scope.h"
19 #include "clang/Sema/ScopeInfo.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/ExprCXX.h"
22 #include "clang/AST/ExprObjC.h"
23 #include "clang/Lex/MacroInfo.h"
24 #include "clang/Lex/Preprocessor.h"
25 #include "llvm/ADT/DenseSet.h"
26 #include "llvm/ADT/SmallPtrSet.h"
27 #include "llvm/ADT/StringExtras.h"
28 #include "llvm/ADT/StringSwitch.h"
29 #include "llvm/ADT/Twine.h"
30 #include <list>
31 #include <map>
32 #include <vector>
34 using namespace clang;
35 using namespace sema;
37 namespace {
38 /// \brief A container of code-completion results.
39 class ResultBuilder {
40 public:
41 /// \brief The type of a name-lookup filter, which can be provided to the
42 /// name-lookup routines to specify which declarations should be included in
43 /// the result set (when it returns true) and which declarations should be
44 /// filtered out (returns false).
45 typedef bool (ResultBuilder::*LookupFilter)(NamedDecl *) const;
47 typedef CodeCompletionResult Result;
49 private:
50 /// \brief The actual results we have found.
51 std::vector<Result> Results;
53 /// \brief A record of all of the declarations we have found and placed
54 /// into the result set, used to ensure that no declaration ever gets into
55 /// the result set twice.
56 llvm::SmallPtrSet<Decl*, 16> AllDeclsFound;
58 typedef std::pair<NamedDecl *, unsigned> DeclIndexPair;
60 /// \brief An entry in the shadow map, which is optimized to store
61 /// a single (declaration, index) mapping (the common case) but
62 /// can also store a list of (declaration, index) mappings.
63 class ShadowMapEntry {
64 typedef llvm::SmallVector<DeclIndexPair, 4> DeclIndexPairVector;
66 /// \brief Contains either the solitary NamedDecl * or a vector
67 /// of (declaration, index) pairs.
68 llvm::PointerUnion<NamedDecl *, DeclIndexPairVector*> DeclOrVector;
70 /// \brief When the entry contains a single declaration, this is
71 /// the index associated with that entry.
72 unsigned SingleDeclIndex;
74 public:
75 ShadowMapEntry() : DeclOrVector(), SingleDeclIndex(0) { }
77 void Add(NamedDecl *ND, unsigned Index) {
78 if (DeclOrVector.isNull()) {
79 // 0 - > 1 elements: just set the single element information.
80 DeclOrVector = ND;
81 SingleDeclIndex = Index;
82 return;
85 if (NamedDecl *PrevND = DeclOrVector.dyn_cast<NamedDecl *>()) {
86 // 1 -> 2 elements: create the vector of results and push in the
87 // existing declaration.
88 DeclIndexPairVector *Vec = new DeclIndexPairVector;
89 Vec->push_back(DeclIndexPair(PrevND, SingleDeclIndex));
90 DeclOrVector = Vec;
93 // Add the new element to the end of the vector.
94 DeclOrVector.get<DeclIndexPairVector*>()->push_back(
95 DeclIndexPair(ND, Index));
98 void Destroy() {
99 if (DeclIndexPairVector *Vec
100 = DeclOrVector.dyn_cast<DeclIndexPairVector *>()) {
101 delete Vec;
102 DeclOrVector = ((NamedDecl *)0);
106 // Iteration.
107 class iterator;
108 iterator begin() const;
109 iterator end() const;
112 /// \brief A mapping from declaration names to the declarations that have
113 /// this name within a particular scope and their index within the list of
114 /// results.
115 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
117 /// \brief The semantic analysis object for which results are being
118 /// produced.
119 Sema &SemaRef;
121 /// \brief If non-NULL, a filter function used to remove any code-completion
122 /// results that are not desirable.
123 LookupFilter Filter;
125 /// \brief Whether we should allow declarations as
126 /// nested-name-specifiers that would otherwise be filtered out.
127 bool AllowNestedNameSpecifiers;
129 /// \brief If set, the type that we would prefer our resulting value
130 /// declarations to have.
132 /// Closely matching the preferred type gives a boost to a result's
133 /// priority.
134 CanQualType PreferredType;
136 /// \brief A list of shadow maps, which is used to model name hiding at
137 /// different levels of, e.g., the inheritance hierarchy.
138 std::list<ShadowMap> ShadowMaps;
140 /// \brief If we're potentially referring to a C++ member function, the set
141 /// of qualifiers applied to the object type.
142 Qualifiers ObjectTypeQualifiers;
144 /// \brief Whether the \p ObjectTypeQualifiers field is active.
145 bool HasObjectTypeQualifiers;
147 /// \brief The selector that we prefer.
148 Selector PreferredSelector;
150 /// \brief The completion context in which we are gathering results.
151 CodeCompletionContext CompletionContext;
153 /// \brief If we are in an instance method definition, the @implementation
154 /// object.
155 ObjCImplementationDecl *ObjCImplementation;
157 void AdjustResultPriorityForDecl(Result &R);
159 void MaybeAddConstructorResults(Result R);
161 public:
162 explicit ResultBuilder(Sema &SemaRef,
163 const CodeCompletionContext &CompletionContext,
164 LookupFilter Filter = 0)
165 : SemaRef(SemaRef), Filter(Filter), AllowNestedNameSpecifiers(false),
166 HasObjectTypeQualifiers(false),
167 CompletionContext(CompletionContext),
168 ObjCImplementation(0)
170 // If this is an Objective-C instance method definition, dig out the
171 // corresponding implementation.
172 switch (CompletionContext.getKind()) {
173 case CodeCompletionContext::CCC_Expression:
174 case CodeCompletionContext::CCC_ObjCMessageReceiver:
175 case CodeCompletionContext::CCC_ParenthesizedExpression:
176 case CodeCompletionContext::CCC_Statement:
177 case CodeCompletionContext::CCC_Recovery:
178 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl())
179 if (Method->isInstanceMethod())
180 if (ObjCInterfaceDecl *Interface = Method->getClassInterface())
181 ObjCImplementation = Interface->getImplementation();
182 break;
184 default:
185 break;
189 /// \brief Whether we should include code patterns in the completion
190 /// results.
191 bool includeCodePatterns() const {
192 return SemaRef.CodeCompleter &&
193 SemaRef.CodeCompleter->includeCodePatterns();
196 /// \brief Set the filter used for code-completion results.
197 void setFilter(LookupFilter Filter) {
198 this->Filter = Filter;
201 Result *data() { return Results.empty()? 0 : &Results.front(); }
202 unsigned size() const { return Results.size(); }
203 bool empty() const { return Results.empty(); }
205 /// \brief Specify the preferred type.
206 void setPreferredType(QualType T) {
207 PreferredType = SemaRef.Context.getCanonicalType(T);
210 /// \brief Set the cv-qualifiers on the object type, for us in filtering
211 /// calls to member functions.
213 /// When there are qualifiers in this set, they will be used to filter
214 /// out member functions that aren't available (because there will be a
215 /// cv-qualifier mismatch) or prefer functions with an exact qualifier
216 /// match.
217 void setObjectTypeQualifiers(Qualifiers Quals) {
218 ObjectTypeQualifiers = Quals;
219 HasObjectTypeQualifiers = true;
222 /// \brief Set the preferred selector.
224 /// When an Objective-C method declaration result is added, and that
225 /// method's selector matches this preferred selector, we give that method
226 /// a slight priority boost.
227 void setPreferredSelector(Selector Sel) {
228 PreferredSelector = Sel;
231 /// \brief Retrieve the code-completion context for which results are
232 /// being collected.
233 const CodeCompletionContext &getCompletionContext() const {
234 return CompletionContext;
237 /// \brief Specify whether nested-name-specifiers are allowed.
238 void allowNestedNameSpecifiers(bool Allow = true) {
239 AllowNestedNameSpecifiers = Allow;
242 /// \brief Return the semantic analysis object for which we are collecting
243 /// code completion results.
244 Sema &getSema() const { return SemaRef; }
246 /// \brief Determine whether the given declaration is at all interesting
247 /// as a code-completion result.
249 /// \param ND the declaration that we are inspecting.
251 /// \param AsNestedNameSpecifier will be set true if this declaration is
252 /// only interesting when it is a nested-name-specifier.
253 bool isInterestingDecl(NamedDecl *ND, bool &AsNestedNameSpecifier) const;
255 /// \brief Check whether the result is hidden by the Hiding declaration.
257 /// \returns true if the result is hidden and cannot be found, false if
258 /// the hidden result could still be found. When false, \p R may be
259 /// modified to describe how the result can be found (e.g., via extra
260 /// qualification).
261 bool CheckHiddenResult(Result &R, DeclContext *CurContext,
262 NamedDecl *Hiding);
264 /// \brief Add a new result to this result set (if it isn't already in one
265 /// of the shadow maps), or replace an existing result (for, e.g., a
266 /// redeclaration).
268 /// \param CurContext the result to add (if it is unique).
270 /// \param R the context in which this result will be named.
271 void MaybeAddResult(Result R, DeclContext *CurContext = 0);
273 /// \brief Add a new result to this result set, where we already know
274 /// the hiding declation (if any).
276 /// \param R the result to add (if it is unique).
278 /// \param CurContext the context in which this result will be named.
280 /// \param Hiding the declaration that hides the result.
282 /// \param InBaseClass whether the result was found in a base
283 /// class of the searched context.
284 void AddResult(Result R, DeclContext *CurContext, NamedDecl *Hiding,
285 bool InBaseClass);
287 /// \brief Add a new non-declaration result to this result set.
288 void AddResult(Result R);
290 /// \brief Enter into a new scope.
291 void EnterNewScope();
293 /// \brief Exit from the current scope.
294 void ExitScope();
296 /// \brief Ignore this declaration, if it is seen again.
297 void Ignore(Decl *D) { AllDeclsFound.insert(D->getCanonicalDecl()); }
299 /// \name Name lookup predicates
301 /// These predicates can be passed to the name lookup functions to filter the
302 /// results of name lookup. All of the predicates have the same type, so that
303 ///
304 //@{
305 bool IsOrdinaryName(NamedDecl *ND) const;
306 bool IsOrdinaryNonTypeName(NamedDecl *ND) const;
307 bool IsIntegralConstantValue(NamedDecl *ND) const;
308 bool IsOrdinaryNonValueName(NamedDecl *ND) const;
309 bool IsNestedNameSpecifier(NamedDecl *ND) const;
310 bool IsEnum(NamedDecl *ND) const;
311 bool IsClassOrStruct(NamedDecl *ND) const;
312 bool IsUnion(NamedDecl *ND) const;
313 bool IsNamespace(NamedDecl *ND) const;
314 bool IsNamespaceOrAlias(NamedDecl *ND) const;
315 bool IsType(NamedDecl *ND) const;
316 bool IsMember(NamedDecl *ND) const;
317 bool IsObjCIvar(NamedDecl *ND) const;
318 bool IsObjCMessageReceiver(NamedDecl *ND) const;
319 bool IsObjCCollection(NamedDecl *ND) const;
320 bool IsImpossibleToSatisfy(NamedDecl *ND) const;
321 //@}
325 class ResultBuilder::ShadowMapEntry::iterator {
326 llvm::PointerUnion<NamedDecl*, const DeclIndexPair*> DeclOrIterator;
327 unsigned SingleDeclIndex;
329 public:
330 typedef DeclIndexPair value_type;
331 typedef value_type reference;
332 typedef std::ptrdiff_t difference_type;
333 typedef std::input_iterator_tag iterator_category;
335 class pointer {
336 DeclIndexPair Value;
338 public:
339 pointer(const DeclIndexPair &Value) : Value(Value) { }
341 const DeclIndexPair *operator->() const {
342 return &Value;
346 iterator() : DeclOrIterator((NamedDecl *)0), SingleDeclIndex(0) { }
348 iterator(NamedDecl *SingleDecl, unsigned Index)
349 : DeclOrIterator(SingleDecl), SingleDeclIndex(Index) { }
351 iterator(const DeclIndexPair *Iterator)
352 : DeclOrIterator(Iterator), SingleDeclIndex(0) { }
354 iterator &operator++() {
355 if (DeclOrIterator.is<NamedDecl *>()) {
356 DeclOrIterator = (NamedDecl *)0;
357 SingleDeclIndex = 0;
358 return *this;
361 const DeclIndexPair *I = DeclOrIterator.get<const DeclIndexPair*>();
362 ++I;
363 DeclOrIterator = I;
364 return *this;
367 /*iterator operator++(int) {
368 iterator tmp(*this);
369 ++(*this);
370 return tmp;
373 reference operator*() const {
374 if (NamedDecl *ND = DeclOrIterator.dyn_cast<NamedDecl *>())
375 return reference(ND, SingleDeclIndex);
377 return *DeclOrIterator.get<const DeclIndexPair*>();
380 pointer operator->() const {
381 return pointer(**this);
384 friend bool operator==(const iterator &X, const iterator &Y) {
385 return X.DeclOrIterator.getOpaqueValue()
386 == Y.DeclOrIterator.getOpaqueValue() &&
387 X.SingleDeclIndex == Y.SingleDeclIndex;
390 friend bool operator!=(const iterator &X, const iterator &Y) {
391 return !(X == Y);
395 ResultBuilder::ShadowMapEntry::iterator
396 ResultBuilder::ShadowMapEntry::begin() const {
397 if (DeclOrVector.isNull())
398 return iterator();
400 if (NamedDecl *ND = DeclOrVector.dyn_cast<NamedDecl *>())
401 return iterator(ND, SingleDeclIndex);
403 return iterator(DeclOrVector.get<DeclIndexPairVector *>()->begin());
406 ResultBuilder::ShadowMapEntry::iterator
407 ResultBuilder::ShadowMapEntry::end() const {
408 if (DeclOrVector.is<NamedDecl *>() || DeclOrVector.isNull())
409 return iterator();
411 return iterator(DeclOrVector.get<DeclIndexPairVector *>()->end());
414 /// \brief Compute the qualification required to get from the current context
415 /// (\p CurContext) to the target context (\p TargetContext).
417 /// \param Context the AST context in which the qualification will be used.
419 /// \param CurContext the context where an entity is being named, which is
420 /// typically based on the current scope.
422 /// \param TargetContext the context in which the named entity actually
423 /// resides.
425 /// \returns a nested name specifier that refers into the target context, or
426 /// NULL if no qualification is needed.
427 static NestedNameSpecifier *
428 getRequiredQualification(ASTContext &Context,
429 DeclContext *CurContext,
430 DeclContext *TargetContext) {
431 llvm::SmallVector<DeclContext *, 4> TargetParents;
433 for (DeclContext *CommonAncestor = TargetContext;
434 CommonAncestor && !CommonAncestor->Encloses(CurContext);
435 CommonAncestor = CommonAncestor->getLookupParent()) {
436 if (CommonAncestor->isTransparentContext() ||
437 CommonAncestor->isFunctionOrMethod())
438 continue;
440 TargetParents.push_back(CommonAncestor);
443 NestedNameSpecifier *Result = 0;
444 while (!TargetParents.empty()) {
445 DeclContext *Parent = TargetParents.back();
446 TargetParents.pop_back();
448 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Parent)) {
449 if (!Namespace->getIdentifier())
450 continue;
452 Result = NestedNameSpecifier::Create(Context, Result, Namespace);
454 else if (TagDecl *TD = dyn_cast<TagDecl>(Parent))
455 Result = NestedNameSpecifier::Create(Context, Result,
456 false,
457 Context.getTypeDeclType(TD).getTypePtr());
459 return Result;
462 bool ResultBuilder::isInterestingDecl(NamedDecl *ND,
463 bool &AsNestedNameSpecifier) const {
464 AsNestedNameSpecifier = false;
466 ND = ND->getUnderlyingDecl();
467 unsigned IDNS = ND->getIdentifierNamespace();
469 // Skip unnamed entities.
470 if (!ND->getDeclName())
471 return false;
473 // Friend declarations and declarations introduced due to friends are never
474 // added as results.
475 if (IDNS & (Decl::IDNS_OrdinaryFriend | Decl::IDNS_TagFriend))
476 return false;
478 // Class template (partial) specializations are never added as results.
479 if (isa<ClassTemplateSpecializationDecl>(ND) ||
480 isa<ClassTemplatePartialSpecializationDecl>(ND))
481 return false;
483 // Using declarations themselves are never added as results.
484 if (isa<UsingDecl>(ND))
485 return false;
487 // Some declarations have reserved names that we don't want to ever show.
488 if (const IdentifierInfo *Id = ND->getIdentifier()) {
489 // __va_list_tag is a freak of nature. Find it and skip it.
490 if (Id->isStr("__va_list_tag") || Id->isStr("__builtin_va_list"))
491 return false;
493 // Filter out names reserved for the implementation (C99 7.1.3,
494 // C++ [lib.global.names]) if they come from a system header.
496 // FIXME: Add predicate for this.
497 if (Id->getLength() >= 2) {
498 const char *Name = Id->getNameStart();
499 if (Name[0] == '_' &&
500 (Name[1] == '_' || (Name[1] >= 'A' && Name[1] <= 'Z')) &&
501 (ND->getLocation().isInvalid() ||
502 SemaRef.SourceMgr.isInSystemHeader(
503 SemaRef.SourceMgr.getSpellingLoc(ND->getLocation()))))
504 return false;
508 // Skip out-of-line declarations and definitions.
509 // NOTE: Unless it's an Objective-C property, method, or ivar, where
510 // the contexts can be messy.
511 if (!ND->getDeclContext()->Equals(ND->getLexicalDeclContext()) &&
512 !(isa<ObjCPropertyDecl>(ND) || isa<ObjCIvarDecl>(ND) ||
513 isa<ObjCMethodDecl>(ND)))
514 return false;
516 if (Filter == &ResultBuilder::IsNestedNameSpecifier ||
517 ((isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) &&
518 Filter != &ResultBuilder::IsNamespace &&
519 Filter != &ResultBuilder::IsNamespaceOrAlias &&
520 Filter != 0))
521 AsNestedNameSpecifier = true;
523 // Filter out any unwanted results.
524 if (Filter && !(this->*Filter)(ND)) {
525 // Check whether it is interesting as a nested-name-specifier.
526 if (AllowNestedNameSpecifiers && SemaRef.getLangOptions().CPlusPlus &&
527 IsNestedNameSpecifier(ND) &&
528 (Filter != &ResultBuilder::IsMember ||
529 (isa<CXXRecordDecl>(ND) &&
530 cast<CXXRecordDecl>(ND)->isInjectedClassName()))) {
531 AsNestedNameSpecifier = true;
532 return true;
535 return false;
537 // ... then it must be interesting!
538 return true;
541 bool ResultBuilder::CheckHiddenResult(Result &R, DeclContext *CurContext,
542 NamedDecl *Hiding) {
543 // In C, there is no way to refer to a hidden name.
544 // FIXME: This isn't true; we can find a tag name hidden by an ordinary
545 // name if we introduce the tag type.
546 if (!SemaRef.getLangOptions().CPlusPlus)
547 return true;
549 DeclContext *HiddenCtx = R.Declaration->getDeclContext()->getRedeclContext();
551 // There is no way to qualify a name declared in a function or method.
552 if (HiddenCtx->isFunctionOrMethod())
553 return true;
555 if (HiddenCtx == Hiding->getDeclContext()->getRedeclContext())
556 return true;
558 // We can refer to the result with the appropriate qualification. Do it.
559 R.Hidden = true;
560 R.QualifierIsInformative = false;
562 if (!R.Qualifier)
563 R.Qualifier = getRequiredQualification(SemaRef.Context,
564 CurContext,
565 R.Declaration->getDeclContext());
566 return false;
569 /// \brief A simplified classification of types used to determine whether two
570 /// types are "similar enough" when adjusting priorities.
571 SimplifiedTypeClass clang::getSimplifiedTypeClass(CanQualType T) {
572 switch (T->getTypeClass()) {
573 case Type::Builtin:
574 switch (cast<BuiltinType>(T)->getKind()) {
575 case BuiltinType::Void:
576 return STC_Void;
578 case BuiltinType::NullPtr:
579 return STC_Pointer;
581 case BuiltinType::Overload:
582 case BuiltinType::Dependent:
583 case BuiltinType::UndeducedAuto:
584 return STC_Other;
586 case BuiltinType::ObjCId:
587 case BuiltinType::ObjCClass:
588 case BuiltinType::ObjCSel:
589 return STC_ObjectiveC;
591 default:
592 return STC_Arithmetic;
594 return STC_Other;
596 case Type::Complex:
597 return STC_Arithmetic;
599 case Type::Pointer:
600 return STC_Pointer;
602 case Type::BlockPointer:
603 return STC_Block;
605 case Type::LValueReference:
606 case Type::RValueReference:
607 return getSimplifiedTypeClass(T->getAs<ReferenceType>()->getPointeeType());
609 case Type::ConstantArray:
610 case Type::IncompleteArray:
611 case Type::VariableArray:
612 case Type::DependentSizedArray:
613 return STC_Array;
615 case Type::DependentSizedExtVector:
616 case Type::Vector:
617 case Type::ExtVector:
618 return STC_Arithmetic;
620 case Type::FunctionProto:
621 case Type::FunctionNoProto:
622 return STC_Function;
624 case Type::Record:
625 return STC_Record;
627 case Type::Enum:
628 return STC_Arithmetic;
630 case Type::ObjCObject:
631 case Type::ObjCInterface:
632 case Type::ObjCObjectPointer:
633 return STC_ObjectiveC;
635 default:
636 return STC_Other;
640 /// \brief Get the type that a given expression will have if this declaration
641 /// is used as an expression in its "typical" code-completion form.
642 QualType clang::getDeclUsageType(ASTContext &C, NamedDecl *ND) {
643 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
645 if (TypeDecl *Type = dyn_cast<TypeDecl>(ND))
646 return C.getTypeDeclType(Type);
647 if (ObjCInterfaceDecl *Iface = dyn_cast<ObjCInterfaceDecl>(ND))
648 return C.getObjCInterfaceType(Iface);
650 QualType T;
651 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND))
652 T = Function->getCallResultType();
653 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND))
654 T = Method->getSendResultType();
655 else if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND))
656 T = FunTmpl->getTemplatedDecl()->getCallResultType();
657 else if (EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND))
658 T = C.getTypeDeclType(cast<EnumDecl>(Enumerator->getDeclContext()));
659 else if (ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND))
660 T = Property->getType();
661 else if (ValueDecl *Value = dyn_cast<ValueDecl>(ND))
662 T = Value->getType();
663 else
664 return QualType();
666 return T.getNonReferenceType();
669 void ResultBuilder::AdjustResultPriorityForDecl(Result &R) {
670 // If this is an Objective-C method declaration whose selector matches our
671 // preferred selector, give it a priority boost.
672 if (!PreferredSelector.isNull())
673 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(R.Declaration))
674 if (PreferredSelector == Method->getSelector())
675 R.Priority += CCD_SelectorMatch;
677 // If we have a preferred type, adjust the priority for results with exactly-
678 // matching or nearly-matching types.
679 if (!PreferredType.isNull()) {
680 QualType T = getDeclUsageType(SemaRef.Context, R.Declaration);
681 if (!T.isNull()) {
682 CanQualType TC = SemaRef.Context.getCanonicalType(T);
683 // Check for exactly-matching types (modulo qualifiers).
684 if (SemaRef.Context.hasSameUnqualifiedType(PreferredType, TC))
685 R.Priority /= CCF_ExactTypeMatch;
686 // Check for nearly-matching types, based on classification of each.
687 else if ((getSimplifiedTypeClass(PreferredType)
688 == getSimplifiedTypeClass(TC)) &&
689 !(PreferredType->isEnumeralType() && TC->isEnumeralType()))
690 R.Priority /= CCF_SimilarTypeMatch;
695 void ResultBuilder::MaybeAddConstructorResults(Result R) {
696 if (!SemaRef.getLangOptions().CPlusPlus || !R.Declaration ||
697 !CompletionContext.wantConstructorResults())
698 return;
700 ASTContext &Context = SemaRef.Context;
701 NamedDecl *D = R.Declaration;
702 CXXRecordDecl *Record = 0;
703 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D))
704 Record = ClassTemplate->getTemplatedDecl();
705 else if ((Record = dyn_cast<CXXRecordDecl>(D))) {
706 // Skip specializations and partial specializations.
707 if (isa<ClassTemplateSpecializationDecl>(Record))
708 return;
709 } else {
710 // There are no constructors here.
711 return;
714 Record = Record->getDefinition();
715 if (!Record)
716 return;
719 QualType RecordTy = Context.getTypeDeclType(Record);
720 DeclarationName ConstructorName
721 = Context.DeclarationNames.getCXXConstructorName(
722 Context.getCanonicalType(RecordTy));
723 for (DeclContext::lookup_result Ctors = Record->lookup(ConstructorName);
724 Ctors.first != Ctors.second; ++Ctors.first) {
725 R.Declaration = *Ctors.first;
726 R.CursorKind = getCursorKindForDecl(R.Declaration);
727 Results.push_back(R);
731 void ResultBuilder::MaybeAddResult(Result R, DeclContext *CurContext) {
732 assert(!ShadowMaps.empty() && "Must enter into a results scope");
734 if (R.Kind != Result::RK_Declaration) {
735 // For non-declaration results, just add the result.
736 Results.push_back(R);
737 return;
740 // Look through using declarations.
741 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
742 MaybeAddResult(Result(Using->getTargetDecl(), R.Qualifier), CurContext);
743 return;
746 Decl *CanonDecl = R.Declaration->getCanonicalDecl();
747 unsigned IDNS = CanonDecl->getIdentifierNamespace();
749 bool AsNestedNameSpecifier = false;
750 if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
751 return;
753 // C++ constructors are never found by name lookup.
754 if (isa<CXXConstructorDecl>(R.Declaration))
755 return;
757 ShadowMap &SMap = ShadowMaps.back();
758 ShadowMapEntry::iterator I, IEnd;
759 ShadowMap::iterator NamePos = SMap.find(R.Declaration->getDeclName());
760 if (NamePos != SMap.end()) {
761 I = NamePos->second.begin();
762 IEnd = NamePos->second.end();
765 for (; I != IEnd; ++I) {
766 NamedDecl *ND = I->first;
767 unsigned Index = I->second;
768 if (ND->getCanonicalDecl() == CanonDecl) {
769 // This is a redeclaration. Always pick the newer declaration.
770 Results[Index].Declaration = R.Declaration;
772 // We're done.
773 return;
777 // This is a new declaration in this scope. However, check whether this
778 // declaration name is hidden by a similarly-named declaration in an outer
779 // scope.
780 std::list<ShadowMap>::iterator SM, SMEnd = ShadowMaps.end();
781 --SMEnd;
782 for (SM = ShadowMaps.begin(); SM != SMEnd; ++SM) {
783 ShadowMapEntry::iterator I, IEnd;
784 ShadowMap::iterator NamePos = SM->find(R.Declaration->getDeclName());
785 if (NamePos != SM->end()) {
786 I = NamePos->second.begin();
787 IEnd = NamePos->second.end();
789 for (; I != IEnd; ++I) {
790 // A tag declaration does not hide a non-tag declaration.
791 if (I->first->hasTagIdentifierNamespace() &&
792 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
793 Decl::IDNS_ObjCProtocol)))
794 continue;
796 // Protocols are in distinct namespaces from everything else.
797 if (((I->first->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
798 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
799 I->first->getIdentifierNamespace() != IDNS)
800 continue;
802 // The newly-added result is hidden by an entry in the shadow map.
803 if (CheckHiddenResult(R, CurContext, I->first))
804 return;
806 break;
810 // Make sure that any given declaration only shows up in the result set once.
811 if (!AllDeclsFound.insert(CanonDecl))
812 return;
814 // If the filter is for nested-name-specifiers, then this result starts a
815 // nested-name-specifier.
816 if (AsNestedNameSpecifier) {
817 R.StartsNestedNameSpecifier = true;
818 R.Priority = CCP_NestedNameSpecifier;
819 } else
820 AdjustResultPriorityForDecl(R);
822 // If this result is supposed to have an informative qualifier, add one.
823 if (R.QualifierIsInformative && !R.Qualifier &&
824 !R.StartsNestedNameSpecifier) {
825 DeclContext *Ctx = R.Declaration->getDeclContext();
826 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
827 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, Namespace);
828 else if (TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
829 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, false,
830 SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
831 else
832 R.QualifierIsInformative = false;
835 // Insert this result into the set of results and into the current shadow
836 // map.
837 SMap[R.Declaration->getDeclName()].Add(R.Declaration, Results.size());
838 Results.push_back(R);
840 if (!AsNestedNameSpecifier)
841 MaybeAddConstructorResults(R);
844 void ResultBuilder::AddResult(Result R, DeclContext *CurContext,
845 NamedDecl *Hiding, bool InBaseClass = false) {
846 if (R.Kind != Result::RK_Declaration) {
847 // For non-declaration results, just add the result.
848 Results.push_back(R);
849 return;
852 // Look through using declarations.
853 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
854 AddResult(Result(Using->getTargetDecl(), R.Qualifier), CurContext, Hiding);
855 return;
858 bool AsNestedNameSpecifier = false;
859 if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
860 return;
862 // C++ constructors are never found by name lookup.
863 if (isa<CXXConstructorDecl>(R.Declaration))
864 return;
866 if (Hiding && CheckHiddenResult(R, CurContext, Hiding))
867 return;
869 // Make sure that any given declaration only shows up in the result set once.
870 if (!AllDeclsFound.insert(R.Declaration->getCanonicalDecl()))
871 return;
873 // If the filter is for nested-name-specifiers, then this result starts a
874 // nested-name-specifier.
875 if (AsNestedNameSpecifier) {
876 R.StartsNestedNameSpecifier = true;
877 R.Priority = CCP_NestedNameSpecifier;
879 else if (Filter == &ResultBuilder::IsMember && !R.Qualifier && InBaseClass &&
880 isa<CXXRecordDecl>(R.Declaration->getDeclContext()
881 ->getRedeclContext()))
882 R.QualifierIsInformative = true;
884 // If this result is supposed to have an informative qualifier, add one.
885 if (R.QualifierIsInformative && !R.Qualifier &&
886 !R.StartsNestedNameSpecifier) {
887 DeclContext *Ctx = R.Declaration->getDeclContext();
888 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
889 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, Namespace);
890 else if (TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
891 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, false,
892 SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
893 else
894 R.QualifierIsInformative = false;
897 // Adjust the priority if this result comes from a base class.
898 if (InBaseClass)
899 R.Priority += CCD_InBaseClass;
901 AdjustResultPriorityForDecl(R);
903 if (HasObjectTypeQualifiers)
904 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(R.Declaration))
905 if (Method->isInstance()) {
906 Qualifiers MethodQuals
907 = Qualifiers::fromCVRMask(Method->getTypeQualifiers());
908 if (ObjectTypeQualifiers == MethodQuals)
909 R.Priority += CCD_ObjectQualifierMatch;
910 else if (ObjectTypeQualifiers - MethodQuals) {
911 // The method cannot be invoked, because doing so would drop
912 // qualifiers.
913 return;
917 // Insert this result into the set of results.
918 Results.push_back(R);
920 if (!AsNestedNameSpecifier)
921 MaybeAddConstructorResults(R);
924 void ResultBuilder::AddResult(Result R) {
925 assert(R.Kind != Result::RK_Declaration &&
926 "Declaration results need more context");
927 Results.push_back(R);
930 /// \brief Enter into a new scope.
931 void ResultBuilder::EnterNewScope() {
932 ShadowMaps.push_back(ShadowMap());
935 /// \brief Exit from the current scope.
936 void ResultBuilder::ExitScope() {
937 for (ShadowMap::iterator E = ShadowMaps.back().begin(),
938 EEnd = ShadowMaps.back().end();
939 E != EEnd;
940 ++E)
941 E->second.Destroy();
943 ShadowMaps.pop_back();
946 /// \brief Determines whether this given declaration will be found by
947 /// ordinary name lookup.
948 bool ResultBuilder::IsOrdinaryName(NamedDecl *ND) const {
949 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
951 unsigned IDNS = Decl::IDNS_Ordinary;
952 if (SemaRef.getLangOptions().CPlusPlus)
953 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
954 else if (SemaRef.getLangOptions().ObjC1) {
955 if (isa<ObjCIvarDecl>(ND))
956 return true;
957 if (isa<ObjCPropertyDecl>(ND) &&
958 SemaRef.canSynthesizeProvisionalIvar(cast<ObjCPropertyDecl>(ND)))
959 return true;
962 return ND->getIdentifierNamespace() & IDNS;
965 /// \brief Determines whether this given declaration will be found by
966 /// ordinary name lookup but is not a type name.
967 bool ResultBuilder::IsOrdinaryNonTypeName(NamedDecl *ND) const {
968 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
969 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND))
970 return false;
972 unsigned IDNS = Decl::IDNS_Ordinary;
973 if (SemaRef.getLangOptions().CPlusPlus)
974 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
975 else if (SemaRef.getLangOptions().ObjC1) {
976 if (isa<ObjCIvarDecl>(ND))
977 return true;
978 if (isa<ObjCPropertyDecl>(ND) &&
979 SemaRef.canSynthesizeProvisionalIvar(cast<ObjCPropertyDecl>(ND)))
980 return true;
983 return ND->getIdentifierNamespace() & IDNS;
986 bool ResultBuilder::IsIntegralConstantValue(NamedDecl *ND) const {
987 if (!IsOrdinaryNonTypeName(ND))
988 return 0;
990 if (ValueDecl *VD = dyn_cast<ValueDecl>(ND->getUnderlyingDecl()))
991 if (VD->getType()->isIntegralOrEnumerationType())
992 return true;
994 return false;
997 /// \brief Determines whether this given declaration will be found by
998 /// ordinary name lookup.
999 bool ResultBuilder::IsOrdinaryNonValueName(NamedDecl *ND) const {
1000 ND = cast<NamedDecl>(ND->getUnderlyingDecl());
1002 unsigned IDNS = Decl::IDNS_Ordinary;
1003 if (SemaRef.getLangOptions().CPlusPlus)
1004 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace;
1006 return (ND->getIdentifierNamespace() & IDNS) &&
1007 !isa<ValueDecl>(ND) && !isa<FunctionTemplateDecl>(ND) &&
1008 !isa<ObjCPropertyDecl>(ND);
1011 /// \brief Determines whether the given declaration is suitable as the
1012 /// start of a C++ nested-name-specifier, e.g., a class or namespace.
1013 bool ResultBuilder::IsNestedNameSpecifier(NamedDecl *ND) const {
1014 // Allow us to find class templates, too.
1015 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
1016 ND = ClassTemplate->getTemplatedDecl();
1018 return SemaRef.isAcceptableNestedNameSpecifier(ND);
1021 /// \brief Determines whether the given declaration is an enumeration.
1022 bool ResultBuilder::IsEnum(NamedDecl *ND) const {
1023 return isa<EnumDecl>(ND);
1026 /// \brief Determines whether the given declaration is a class or struct.
1027 bool ResultBuilder::IsClassOrStruct(NamedDecl *ND) const {
1028 // Allow us to find class templates, too.
1029 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
1030 ND = ClassTemplate->getTemplatedDecl();
1032 if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
1033 return RD->getTagKind() == TTK_Class ||
1034 RD->getTagKind() == TTK_Struct;
1036 return false;
1039 /// \brief Determines whether the given declaration is a union.
1040 bool ResultBuilder::IsUnion(NamedDecl *ND) const {
1041 // Allow us to find class templates, too.
1042 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
1043 ND = ClassTemplate->getTemplatedDecl();
1045 if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
1046 return RD->getTagKind() == TTK_Union;
1048 return false;
1051 /// \brief Determines whether the given declaration is a namespace.
1052 bool ResultBuilder::IsNamespace(NamedDecl *ND) const {
1053 return isa<NamespaceDecl>(ND);
1056 /// \brief Determines whether the given declaration is a namespace or
1057 /// namespace alias.
1058 bool ResultBuilder::IsNamespaceOrAlias(NamedDecl *ND) const {
1059 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
1062 /// \brief Determines whether the given declaration is a type.
1063 bool ResultBuilder::IsType(NamedDecl *ND) const {
1064 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(ND))
1065 ND = Using->getTargetDecl();
1067 return isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
1070 /// \brief Determines which members of a class should be visible via
1071 /// "." or "->". Only value declarations, nested name specifiers, and
1072 /// using declarations thereof should show up.
1073 bool ResultBuilder::IsMember(NamedDecl *ND) const {
1074 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(ND))
1075 ND = Using->getTargetDecl();
1077 return isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND) ||
1078 isa<ObjCPropertyDecl>(ND);
1081 static bool isObjCReceiverType(ASTContext &C, QualType T) {
1082 T = C.getCanonicalType(T);
1083 switch (T->getTypeClass()) {
1084 case Type::ObjCObject:
1085 case Type::ObjCInterface:
1086 case Type::ObjCObjectPointer:
1087 return true;
1089 case Type::Builtin:
1090 switch (cast<BuiltinType>(T)->getKind()) {
1091 case BuiltinType::ObjCId:
1092 case BuiltinType::ObjCClass:
1093 case BuiltinType::ObjCSel:
1094 return true;
1096 default:
1097 break;
1099 return false;
1101 default:
1102 break;
1105 if (!C.getLangOptions().CPlusPlus)
1106 return false;
1108 // FIXME: We could perform more analysis here to determine whether a
1109 // particular class type has any conversions to Objective-C types. For now,
1110 // just accept all class types.
1111 return T->isDependentType() || T->isRecordType();
1114 bool ResultBuilder::IsObjCMessageReceiver(NamedDecl *ND) const {
1115 QualType T = getDeclUsageType(SemaRef.Context, ND);
1116 if (T.isNull())
1117 return false;
1119 T = SemaRef.Context.getBaseElementType(T);
1120 return isObjCReceiverType(SemaRef.Context, T);
1123 bool ResultBuilder::IsObjCCollection(NamedDecl *ND) const {
1124 if ((SemaRef.getLangOptions().CPlusPlus && !IsOrdinaryName(ND)) ||
1125 (!SemaRef.getLangOptions().CPlusPlus && !IsOrdinaryNonTypeName(ND)))
1126 return false;
1128 QualType T = getDeclUsageType(SemaRef.Context, ND);
1129 if (T.isNull())
1130 return false;
1132 T = SemaRef.Context.getBaseElementType(T);
1133 return T->isObjCObjectType() || T->isObjCObjectPointerType() ||
1134 T->isObjCIdType() ||
1135 (SemaRef.getLangOptions().CPlusPlus && T->isRecordType());
1138 bool ResultBuilder::IsImpossibleToSatisfy(NamedDecl *ND) const {
1139 return false;
1142 /// \rief Determines whether the given declaration is an Objective-C
1143 /// instance variable.
1144 bool ResultBuilder::IsObjCIvar(NamedDecl *ND) const {
1145 return isa<ObjCIvarDecl>(ND);
1148 namespace {
1149 /// \brief Visible declaration consumer that adds a code-completion result
1150 /// for each visible declaration.
1151 class CodeCompletionDeclConsumer : public VisibleDeclConsumer {
1152 ResultBuilder &Results;
1153 DeclContext *CurContext;
1155 public:
1156 CodeCompletionDeclConsumer(ResultBuilder &Results, DeclContext *CurContext)
1157 : Results(Results), CurContext(CurContext) { }
1159 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, bool InBaseClass) {
1160 Results.AddResult(ND, CurContext, Hiding, InBaseClass);
1165 /// \brief Add type specifiers for the current language as keyword results.
1166 static void AddTypeSpecifierResults(const LangOptions &LangOpts,
1167 ResultBuilder &Results) {
1168 typedef CodeCompletionResult Result;
1169 Results.AddResult(Result("short", CCP_Type));
1170 Results.AddResult(Result("long", CCP_Type));
1171 Results.AddResult(Result("signed", CCP_Type));
1172 Results.AddResult(Result("unsigned", CCP_Type));
1173 Results.AddResult(Result("void", CCP_Type));
1174 Results.AddResult(Result("char", CCP_Type));
1175 Results.AddResult(Result("int", CCP_Type));
1176 Results.AddResult(Result("float", CCP_Type));
1177 Results.AddResult(Result("double", CCP_Type));
1178 Results.AddResult(Result("enum", CCP_Type));
1179 Results.AddResult(Result("struct", CCP_Type));
1180 Results.AddResult(Result("union", CCP_Type));
1181 Results.AddResult(Result("const", CCP_Type));
1182 Results.AddResult(Result("volatile", CCP_Type));
1184 if (LangOpts.C99) {
1185 // C99-specific
1186 Results.AddResult(Result("_Complex", CCP_Type));
1187 Results.AddResult(Result("_Imaginary", CCP_Type));
1188 Results.AddResult(Result("_Bool", CCP_Type));
1189 Results.AddResult(Result("restrict", CCP_Type));
1192 if (LangOpts.CPlusPlus) {
1193 // C++-specific
1194 Results.AddResult(Result("bool", CCP_Type +
1195 (LangOpts.ObjC1? CCD_bool_in_ObjC : 0)));
1196 Results.AddResult(Result("class", CCP_Type));
1197 Results.AddResult(Result("wchar_t", CCP_Type));
1199 // typename qualified-id
1200 CodeCompletionString *Pattern = new CodeCompletionString;
1201 Pattern->AddTypedTextChunk("typename");
1202 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1203 Pattern->AddPlaceholderChunk("qualifier");
1204 Pattern->AddTextChunk("::");
1205 Pattern->AddPlaceholderChunk("name");
1206 Results.AddResult(Result(Pattern));
1208 if (LangOpts.CPlusPlus0x) {
1209 Results.AddResult(Result("auto", CCP_Type));
1210 Results.AddResult(Result("char16_t", CCP_Type));
1211 Results.AddResult(Result("char32_t", CCP_Type));
1213 CodeCompletionString *Pattern = new CodeCompletionString;
1214 Pattern->AddTypedTextChunk("decltype");
1215 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1216 Pattern->AddPlaceholderChunk("expression");
1217 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1218 Results.AddResult(Result(Pattern));
1222 // GNU extensions
1223 if (LangOpts.GNUMode) {
1224 // FIXME: Enable when we actually support decimal floating point.
1225 // Results.AddResult(Result("_Decimal32"));
1226 // Results.AddResult(Result("_Decimal64"));
1227 // Results.AddResult(Result("_Decimal128"));
1229 CodeCompletionString *Pattern = new CodeCompletionString;
1230 Pattern->AddTypedTextChunk("typeof");
1231 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1232 Pattern->AddPlaceholderChunk("expression");
1233 Results.AddResult(Result(Pattern));
1235 Pattern = new CodeCompletionString;
1236 Pattern->AddTypedTextChunk("typeof");
1237 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1238 Pattern->AddPlaceholderChunk("type");
1239 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1240 Results.AddResult(Result(Pattern));
1244 static void AddStorageSpecifiers(Sema::ParserCompletionContext CCC,
1245 const LangOptions &LangOpts,
1246 ResultBuilder &Results) {
1247 typedef CodeCompletionResult Result;
1248 // Note: we don't suggest either "auto" or "register", because both
1249 // are pointless as storage specifiers. Elsewhere, we suggest "auto"
1250 // in C++0x as a type specifier.
1251 Results.AddResult(Result("extern"));
1252 Results.AddResult(Result("static"));
1255 static void AddFunctionSpecifiers(Sema::ParserCompletionContext CCC,
1256 const LangOptions &LangOpts,
1257 ResultBuilder &Results) {
1258 typedef CodeCompletionResult Result;
1259 switch (CCC) {
1260 case Sema::PCC_Class:
1261 case Sema::PCC_MemberTemplate:
1262 if (LangOpts.CPlusPlus) {
1263 Results.AddResult(Result("explicit"));
1264 Results.AddResult(Result("friend"));
1265 Results.AddResult(Result("mutable"));
1266 Results.AddResult(Result("virtual"));
1268 // Fall through
1270 case Sema::PCC_ObjCInterface:
1271 case Sema::PCC_ObjCImplementation:
1272 case Sema::PCC_Namespace:
1273 case Sema::PCC_Template:
1274 if (LangOpts.CPlusPlus || LangOpts.C99)
1275 Results.AddResult(Result("inline"));
1276 break;
1278 case Sema::PCC_ObjCInstanceVariableList:
1279 case Sema::PCC_Expression:
1280 case Sema::PCC_Statement:
1281 case Sema::PCC_ForInit:
1282 case Sema::PCC_Condition:
1283 case Sema::PCC_RecoveryInFunction:
1284 case Sema::PCC_Type:
1285 case Sema::PCC_ParenthesizedExpression:
1286 break;
1290 static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt);
1291 static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt);
1292 static void AddObjCVisibilityResults(const LangOptions &LangOpts,
1293 ResultBuilder &Results,
1294 bool NeedAt);
1295 static void AddObjCImplementationResults(const LangOptions &LangOpts,
1296 ResultBuilder &Results,
1297 bool NeedAt);
1298 static void AddObjCInterfaceResults(const LangOptions &LangOpts,
1299 ResultBuilder &Results,
1300 bool NeedAt);
1301 static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt);
1303 static void AddTypedefResult(ResultBuilder &Results) {
1304 CodeCompletionString *Pattern = new CodeCompletionString;
1305 Pattern->AddTypedTextChunk("typedef");
1306 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1307 Pattern->AddPlaceholderChunk("type");
1308 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1309 Pattern->AddPlaceholderChunk("name");
1310 Results.AddResult(CodeCompletionResult(Pattern));
1313 static bool WantTypesInContext(Sema::ParserCompletionContext CCC,
1314 const LangOptions &LangOpts) {
1315 switch (CCC) {
1316 case Sema::PCC_Namespace:
1317 case Sema::PCC_Class:
1318 case Sema::PCC_ObjCInstanceVariableList:
1319 case Sema::PCC_Template:
1320 case Sema::PCC_MemberTemplate:
1321 case Sema::PCC_Statement:
1322 case Sema::PCC_RecoveryInFunction:
1323 case Sema::PCC_Type:
1324 case Sema::PCC_ParenthesizedExpression:
1325 return true;
1327 case Sema::PCC_Expression:
1328 case Sema::PCC_Condition:
1329 return LangOpts.CPlusPlus;
1331 case Sema::PCC_ObjCInterface:
1332 case Sema::PCC_ObjCImplementation:
1333 return false;
1335 case Sema::PCC_ForInit:
1336 return LangOpts.CPlusPlus || LangOpts.ObjC1 || LangOpts.C99;
1339 return false;
1342 /// \brief Add language constructs that show up for "ordinary" names.
1343 static void AddOrdinaryNameResults(Sema::ParserCompletionContext CCC,
1344 Scope *S,
1345 Sema &SemaRef,
1346 ResultBuilder &Results) {
1347 typedef CodeCompletionResult Result;
1348 switch (CCC) {
1349 case Sema::PCC_Namespace:
1350 if (SemaRef.getLangOptions().CPlusPlus) {
1351 CodeCompletionString *Pattern = 0;
1353 if (Results.includeCodePatterns()) {
1354 // namespace <identifier> { declarations }
1355 CodeCompletionString *Pattern = new CodeCompletionString;
1356 Pattern->AddTypedTextChunk("namespace");
1357 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1358 Pattern->AddPlaceholderChunk("identifier");
1359 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1360 Pattern->AddPlaceholderChunk("declarations");
1361 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1362 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1363 Results.AddResult(Result(Pattern));
1366 // namespace identifier = identifier ;
1367 Pattern = new CodeCompletionString;
1368 Pattern->AddTypedTextChunk("namespace");
1369 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1370 Pattern->AddPlaceholderChunk("name");
1371 Pattern->AddChunk(CodeCompletionString::CK_Equal);
1372 Pattern->AddPlaceholderChunk("namespace");
1373 Results.AddResult(Result(Pattern));
1375 // Using directives
1376 Pattern = new CodeCompletionString;
1377 Pattern->AddTypedTextChunk("using");
1378 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1379 Pattern->AddTextChunk("namespace");
1380 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1381 Pattern->AddPlaceholderChunk("identifier");
1382 Results.AddResult(Result(Pattern));
1384 // asm(string-literal)
1385 Pattern = new CodeCompletionString;
1386 Pattern->AddTypedTextChunk("asm");
1387 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1388 Pattern->AddPlaceholderChunk("string-literal");
1389 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1390 Results.AddResult(Result(Pattern));
1392 if (Results.includeCodePatterns()) {
1393 // Explicit template instantiation
1394 Pattern = new CodeCompletionString;
1395 Pattern->AddTypedTextChunk("template");
1396 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1397 Pattern->AddPlaceholderChunk("declaration");
1398 Results.AddResult(Result(Pattern));
1402 if (SemaRef.getLangOptions().ObjC1)
1403 AddObjCTopLevelResults(Results, true);
1405 AddTypedefResult(Results);
1406 // Fall through
1408 case Sema::PCC_Class:
1409 if (SemaRef.getLangOptions().CPlusPlus) {
1410 // Using declaration
1411 CodeCompletionString *Pattern = new CodeCompletionString;
1412 Pattern->AddTypedTextChunk("using");
1413 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1414 Pattern->AddPlaceholderChunk("qualifier");
1415 Pattern->AddTextChunk("::");
1416 Pattern->AddPlaceholderChunk("name");
1417 Results.AddResult(Result(Pattern));
1419 // using typename qualifier::name (only in a dependent context)
1420 if (SemaRef.CurContext->isDependentContext()) {
1421 Pattern = new CodeCompletionString;
1422 Pattern->AddTypedTextChunk("using");
1423 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1424 Pattern->AddTextChunk("typename");
1425 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1426 Pattern->AddPlaceholderChunk("qualifier");
1427 Pattern->AddTextChunk("::");
1428 Pattern->AddPlaceholderChunk("name");
1429 Results.AddResult(Result(Pattern));
1432 if (CCC == Sema::PCC_Class) {
1433 AddTypedefResult(Results);
1435 // public:
1436 Pattern = new CodeCompletionString;
1437 Pattern->AddTypedTextChunk("public");
1438 Pattern->AddChunk(CodeCompletionString::CK_Colon);
1439 Results.AddResult(Result(Pattern));
1441 // protected:
1442 Pattern = new CodeCompletionString;
1443 Pattern->AddTypedTextChunk("protected");
1444 Pattern->AddChunk(CodeCompletionString::CK_Colon);
1445 Results.AddResult(Result(Pattern));
1447 // private:
1448 Pattern = new CodeCompletionString;
1449 Pattern->AddTypedTextChunk("private");
1450 Pattern->AddChunk(CodeCompletionString::CK_Colon);
1451 Results.AddResult(Result(Pattern));
1454 // Fall through
1456 case Sema::PCC_Template:
1457 case Sema::PCC_MemberTemplate:
1458 if (SemaRef.getLangOptions().CPlusPlus && Results.includeCodePatterns()) {
1459 // template < parameters >
1460 CodeCompletionString *Pattern = new CodeCompletionString;
1461 Pattern->AddTypedTextChunk("template");
1462 Pattern->AddChunk(CodeCompletionString::CK_LeftAngle);
1463 Pattern->AddPlaceholderChunk("parameters");
1464 Pattern->AddChunk(CodeCompletionString::CK_RightAngle);
1465 Results.AddResult(Result(Pattern));
1468 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1469 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1470 break;
1472 case Sema::PCC_ObjCInterface:
1473 AddObjCInterfaceResults(SemaRef.getLangOptions(), Results, true);
1474 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1475 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1476 break;
1478 case Sema::PCC_ObjCImplementation:
1479 AddObjCImplementationResults(SemaRef.getLangOptions(), Results, true);
1480 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1481 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1482 break;
1484 case Sema::PCC_ObjCInstanceVariableList:
1485 AddObjCVisibilityResults(SemaRef.getLangOptions(), Results, true);
1486 break;
1488 case Sema::PCC_RecoveryInFunction:
1489 case Sema::PCC_Statement: {
1490 AddTypedefResult(Results);
1492 CodeCompletionString *Pattern = 0;
1493 if (SemaRef.getLangOptions().CPlusPlus && Results.includeCodePatterns()) {
1494 Pattern = new CodeCompletionString;
1495 Pattern->AddTypedTextChunk("try");
1496 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1497 Pattern->AddPlaceholderChunk("statements");
1498 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1499 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1500 Pattern->AddTextChunk("catch");
1501 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1502 Pattern->AddPlaceholderChunk("declaration");
1503 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1504 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1505 Pattern->AddPlaceholderChunk("statements");
1506 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1507 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1508 Results.AddResult(Result(Pattern));
1510 if (SemaRef.getLangOptions().ObjC1)
1511 AddObjCStatementResults(Results, true);
1513 if (Results.includeCodePatterns()) {
1514 // if (condition) { statements }
1515 Pattern = new CodeCompletionString;
1516 Pattern->AddTypedTextChunk("if");
1517 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1518 if (SemaRef.getLangOptions().CPlusPlus)
1519 Pattern->AddPlaceholderChunk("condition");
1520 else
1521 Pattern->AddPlaceholderChunk("expression");
1522 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1523 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1524 Pattern->AddPlaceholderChunk("statements");
1525 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1526 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1527 Results.AddResult(Result(Pattern));
1529 // switch (condition) { }
1530 Pattern = new CodeCompletionString;
1531 Pattern->AddTypedTextChunk("switch");
1532 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1533 if (SemaRef.getLangOptions().CPlusPlus)
1534 Pattern->AddPlaceholderChunk("condition");
1535 else
1536 Pattern->AddPlaceholderChunk("expression");
1537 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1538 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1539 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1540 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1541 Results.AddResult(Result(Pattern));
1544 // Switch-specific statements.
1545 if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
1546 // case expression:
1547 Pattern = new CodeCompletionString;
1548 Pattern->AddTypedTextChunk("case");
1549 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1550 Pattern->AddPlaceholderChunk("expression");
1551 Pattern->AddChunk(CodeCompletionString::CK_Colon);
1552 Results.AddResult(Result(Pattern));
1554 // default:
1555 Pattern = new CodeCompletionString;
1556 Pattern->AddTypedTextChunk("default");
1557 Pattern->AddChunk(CodeCompletionString::CK_Colon);
1558 Results.AddResult(Result(Pattern));
1561 if (Results.includeCodePatterns()) {
1562 /// while (condition) { statements }
1563 Pattern = new CodeCompletionString;
1564 Pattern->AddTypedTextChunk("while");
1565 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1566 if (SemaRef.getLangOptions().CPlusPlus)
1567 Pattern->AddPlaceholderChunk("condition");
1568 else
1569 Pattern->AddPlaceholderChunk("expression");
1570 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1571 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1572 Pattern->AddPlaceholderChunk("statements");
1573 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1574 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1575 Results.AddResult(Result(Pattern));
1577 // do { statements } while ( expression );
1578 Pattern = new CodeCompletionString;
1579 Pattern->AddTypedTextChunk("do");
1580 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1581 Pattern->AddPlaceholderChunk("statements");
1582 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1583 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1584 Pattern->AddTextChunk("while");
1585 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1586 Pattern->AddPlaceholderChunk("expression");
1587 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1588 Results.AddResult(Result(Pattern));
1590 // for ( for-init-statement ; condition ; expression ) { statements }
1591 Pattern = new CodeCompletionString;
1592 Pattern->AddTypedTextChunk("for");
1593 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1594 if (SemaRef.getLangOptions().CPlusPlus || SemaRef.getLangOptions().C99)
1595 Pattern->AddPlaceholderChunk("init-statement");
1596 else
1597 Pattern->AddPlaceholderChunk("init-expression");
1598 Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
1599 Pattern->AddPlaceholderChunk("condition");
1600 Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
1601 Pattern->AddPlaceholderChunk("inc-expression");
1602 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1603 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
1604 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1605 Pattern->AddPlaceholderChunk("statements");
1606 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
1607 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
1608 Results.AddResult(Result(Pattern));
1611 if (S->getContinueParent()) {
1612 // continue ;
1613 Pattern = new CodeCompletionString;
1614 Pattern->AddTypedTextChunk("continue");
1615 Results.AddResult(Result(Pattern));
1618 if (S->getBreakParent()) {
1619 // break ;
1620 Pattern = new CodeCompletionString;
1621 Pattern->AddTypedTextChunk("break");
1622 Results.AddResult(Result(Pattern));
1625 // "return expression ;" or "return ;", depending on whether we
1626 // know the function is void or not.
1627 bool isVoid = false;
1628 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(SemaRef.CurContext))
1629 isVoid = Function->getResultType()->isVoidType();
1630 else if (ObjCMethodDecl *Method
1631 = dyn_cast<ObjCMethodDecl>(SemaRef.CurContext))
1632 isVoid = Method->getResultType()->isVoidType();
1633 else if (SemaRef.getCurBlock() &&
1634 !SemaRef.getCurBlock()->ReturnType.isNull())
1635 isVoid = SemaRef.getCurBlock()->ReturnType->isVoidType();
1636 Pattern = new CodeCompletionString;
1637 Pattern->AddTypedTextChunk("return");
1638 if (!isVoid) {
1639 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1640 Pattern->AddPlaceholderChunk("expression");
1642 Results.AddResult(Result(Pattern));
1644 // goto identifier ;
1645 Pattern = new CodeCompletionString;
1646 Pattern->AddTypedTextChunk("goto");
1647 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1648 Pattern->AddPlaceholderChunk("label");
1649 Results.AddResult(Result(Pattern));
1651 // Using directives
1652 Pattern = new CodeCompletionString;
1653 Pattern->AddTypedTextChunk("using");
1654 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1655 Pattern->AddTextChunk("namespace");
1656 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1657 Pattern->AddPlaceholderChunk("identifier");
1658 Results.AddResult(Result(Pattern));
1661 // Fall through (for statement expressions).
1662 case Sema::PCC_ForInit:
1663 case Sema::PCC_Condition:
1664 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
1665 // Fall through: conditions and statements can have expressions.
1667 case Sema::PCC_ParenthesizedExpression:
1668 case Sema::PCC_Expression: {
1669 CodeCompletionString *Pattern = 0;
1670 if (SemaRef.getLangOptions().CPlusPlus) {
1671 // 'this', if we're in a non-static member function.
1672 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(SemaRef.CurContext))
1673 if (!Method->isStatic())
1674 Results.AddResult(Result("this"));
1676 // true, false
1677 Results.AddResult(Result("true"));
1678 Results.AddResult(Result("false"));
1680 // dynamic_cast < type-id > ( expression )
1681 Pattern = new CodeCompletionString;
1682 Pattern->AddTypedTextChunk("dynamic_cast");
1683 Pattern->AddChunk(CodeCompletionString::CK_LeftAngle);
1684 Pattern->AddPlaceholderChunk("type");
1685 Pattern->AddChunk(CodeCompletionString::CK_RightAngle);
1686 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1687 Pattern->AddPlaceholderChunk("expression");
1688 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1689 Results.AddResult(Result(Pattern));
1691 // static_cast < type-id > ( expression )
1692 Pattern = new CodeCompletionString;
1693 Pattern->AddTypedTextChunk("static_cast");
1694 Pattern->AddChunk(CodeCompletionString::CK_LeftAngle);
1695 Pattern->AddPlaceholderChunk("type");
1696 Pattern->AddChunk(CodeCompletionString::CK_RightAngle);
1697 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1698 Pattern->AddPlaceholderChunk("expression");
1699 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1700 Results.AddResult(Result(Pattern));
1702 // reinterpret_cast < type-id > ( expression )
1703 Pattern = new CodeCompletionString;
1704 Pattern->AddTypedTextChunk("reinterpret_cast");
1705 Pattern->AddChunk(CodeCompletionString::CK_LeftAngle);
1706 Pattern->AddPlaceholderChunk("type");
1707 Pattern->AddChunk(CodeCompletionString::CK_RightAngle);
1708 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1709 Pattern->AddPlaceholderChunk("expression");
1710 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1711 Results.AddResult(Result(Pattern));
1713 // const_cast < type-id > ( expression )
1714 Pattern = new CodeCompletionString;
1715 Pattern->AddTypedTextChunk("const_cast");
1716 Pattern->AddChunk(CodeCompletionString::CK_LeftAngle);
1717 Pattern->AddPlaceholderChunk("type");
1718 Pattern->AddChunk(CodeCompletionString::CK_RightAngle);
1719 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1720 Pattern->AddPlaceholderChunk("expression");
1721 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1722 Results.AddResult(Result(Pattern));
1724 // typeid ( expression-or-type )
1725 Pattern = new CodeCompletionString;
1726 Pattern->AddTypedTextChunk("typeid");
1727 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1728 Pattern->AddPlaceholderChunk("expression-or-type");
1729 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1730 Results.AddResult(Result(Pattern));
1732 // new T ( ... )
1733 Pattern = new CodeCompletionString;
1734 Pattern->AddTypedTextChunk("new");
1735 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1736 Pattern->AddPlaceholderChunk("type");
1737 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1738 Pattern->AddPlaceholderChunk("expressions");
1739 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1740 Results.AddResult(Result(Pattern));
1742 // new T [ ] ( ... )
1743 Pattern = new CodeCompletionString;
1744 Pattern->AddTypedTextChunk("new");
1745 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1746 Pattern->AddPlaceholderChunk("type");
1747 Pattern->AddChunk(CodeCompletionString::CK_LeftBracket);
1748 Pattern->AddPlaceholderChunk("size");
1749 Pattern->AddChunk(CodeCompletionString::CK_RightBracket);
1750 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1751 Pattern->AddPlaceholderChunk("expressions");
1752 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1753 Results.AddResult(Result(Pattern));
1755 // delete expression
1756 Pattern = new CodeCompletionString;
1757 Pattern->AddTypedTextChunk("delete");
1758 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1759 Pattern->AddPlaceholderChunk("expression");
1760 Results.AddResult(Result(Pattern));
1762 // delete [] expression
1763 Pattern = new CodeCompletionString;
1764 Pattern->AddTypedTextChunk("delete");
1765 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1766 Pattern->AddChunk(CodeCompletionString::CK_LeftBracket);
1767 Pattern->AddChunk(CodeCompletionString::CK_RightBracket);
1768 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1769 Pattern->AddPlaceholderChunk("expression");
1770 Results.AddResult(Result(Pattern));
1772 // throw expression
1773 Pattern = new CodeCompletionString;
1774 Pattern->AddTypedTextChunk("throw");
1775 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
1776 Pattern->AddPlaceholderChunk("expression");
1777 Results.AddResult(Result(Pattern));
1779 // FIXME: Rethrow?
1782 if (SemaRef.getLangOptions().ObjC1) {
1783 // Add "super", if we're in an Objective-C class with a superclass.
1784 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
1785 // The interface can be NULL.
1786 if (ObjCInterfaceDecl *ID = Method->getClassInterface())
1787 if (ID->getSuperClass())
1788 Results.AddResult(Result("super"));
1791 AddObjCExpressionResults(Results, true);
1794 // sizeof expression
1795 Pattern = new CodeCompletionString;
1796 Pattern->AddTypedTextChunk("sizeof");
1797 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
1798 Pattern->AddPlaceholderChunk("expression-or-type");
1799 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
1800 Results.AddResult(Result(Pattern));
1801 break;
1804 case Sema::PCC_Type:
1805 break;
1808 if (WantTypesInContext(CCC, SemaRef.getLangOptions()))
1809 AddTypeSpecifierResults(SemaRef.getLangOptions(), Results);
1811 if (SemaRef.getLangOptions().CPlusPlus && CCC != Sema::PCC_Type)
1812 Results.AddResult(Result("operator"));
1815 /// \brief If the given declaration has an associated type, add it as a result
1816 /// type chunk.
1817 static void AddResultTypeChunk(ASTContext &Context,
1818 NamedDecl *ND,
1819 CodeCompletionString *Result) {
1820 if (!ND)
1821 return;
1823 // Skip constructors and conversion functions, which have their return types
1824 // built into their names.
1825 if (isa<CXXConstructorDecl>(ND) || isa<CXXConversionDecl>(ND))
1826 return;
1828 // Determine the type of the declaration (if it has a type).
1829 QualType T;
1830 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND))
1831 T = Function->getResultType();
1832 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND))
1833 T = Method->getResultType();
1834 else if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND))
1835 T = FunTmpl->getTemplatedDecl()->getResultType();
1836 else if (EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND))
1837 T = Context.getTypeDeclType(cast<TypeDecl>(Enumerator->getDeclContext()));
1838 else if (isa<UnresolvedUsingValueDecl>(ND)) {
1839 /* Do nothing: ignore unresolved using declarations*/
1840 } else if (ValueDecl *Value = dyn_cast<ValueDecl>(ND))
1841 T = Value->getType();
1842 else if (ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND))
1843 T = Property->getType();
1845 if (T.isNull() || Context.hasSameType(T, Context.DependentTy))
1846 return;
1848 PrintingPolicy Policy(Context.PrintingPolicy);
1849 Policy.AnonymousTagLocations = false;
1851 std::string TypeStr;
1852 T.getAsStringInternal(TypeStr, Policy);
1853 Result->AddResultTypeChunk(TypeStr);
1856 static void MaybeAddSentinel(ASTContext &Context, NamedDecl *FunctionOrMethod,
1857 CodeCompletionString *Result) {
1858 if (SentinelAttr *Sentinel = FunctionOrMethod->getAttr<SentinelAttr>())
1859 if (Sentinel->getSentinel() == 0) {
1860 if (Context.getLangOptions().ObjC1 &&
1861 Context.Idents.get("nil").hasMacroDefinition())
1862 Result->AddTextChunk(", nil");
1863 else if (Context.Idents.get("NULL").hasMacroDefinition())
1864 Result->AddTextChunk(", NULL");
1865 else
1866 Result->AddTextChunk(", (void*)0");
1870 static std::string FormatFunctionParameter(ASTContext &Context,
1871 ParmVarDecl *Param,
1872 bool SuppressName = false) {
1873 bool ObjCMethodParam = isa<ObjCMethodDecl>(Param->getDeclContext());
1874 if (Param->getType()->isDependentType() ||
1875 !Param->getType()->isBlockPointerType()) {
1876 // The argument for a dependent or non-block parameter is a placeholder
1877 // containing that parameter's type.
1878 std::string Result;
1880 if (Param->getIdentifier() && !ObjCMethodParam && !SuppressName)
1881 Result = Param->getIdentifier()->getName();
1883 Param->getType().getAsStringInternal(Result,
1884 Context.PrintingPolicy);
1886 if (ObjCMethodParam) {
1887 Result = "(" + Result;
1888 Result += ")";
1889 if (Param->getIdentifier() && !SuppressName)
1890 Result += Param->getIdentifier()->getName();
1892 return Result;
1895 // The argument for a block pointer parameter is a block literal with
1896 // the appropriate type.
1897 FunctionProtoTypeLoc *Block = 0;
1898 TypeLoc TL;
1899 if (TypeSourceInfo *TSInfo = Param->getTypeSourceInfo()) {
1900 TL = TSInfo->getTypeLoc().getUnqualifiedLoc();
1901 while (true) {
1902 // Look through typedefs.
1903 if (TypedefTypeLoc *TypedefTL = dyn_cast<TypedefTypeLoc>(&TL)) {
1904 if (TypeSourceInfo *InnerTSInfo
1905 = TypedefTL->getTypedefDecl()->getTypeSourceInfo()) {
1906 TL = InnerTSInfo->getTypeLoc().getUnqualifiedLoc();
1907 continue;
1911 // Look through qualified types
1912 if (QualifiedTypeLoc *QualifiedTL = dyn_cast<QualifiedTypeLoc>(&TL)) {
1913 TL = QualifiedTL->getUnqualifiedLoc();
1914 continue;
1917 // Try to get the function prototype behind the block pointer type,
1918 // then we're done.
1919 if (BlockPointerTypeLoc *BlockPtr
1920 = dyn_cast<BlockPointerTypeLoc>(&TL)) {
1921 TL = BlockPtr->getPointeeLoc();
1922 // Skip any paren typeloc.
1923 while (ParenTypeLoc *ParenPtr = dyn_cast<ParenTypeLoc>(&TL))
1924 TL = ParenPtr->getInnerLoc();
1925 Block = dyn_cast<FunctionProtoTypeLoc>(&TL);
1927 break;
1931 if (!Block) {
1932 // We were unable to find a FunctionProtoTypeLoc with parameter names
1933 // for the block; just use the parameter type as a placeholder.
1934 std::string Result;
1935 Param->getType().getUnqualifiedType().
1936 getAsStringInternal(Result, Context.PrintingPolicy);
1938 if (ObjCMethodParam) {
1939 Result = "(" + Result;
1940 Result += ")";
1941 if (Param->getIdentifier())
1942 Result += Param->getIdentifier()->getName();
1945 return Result;
1948 // We have the function prototype behind the block pointer type, as it was
1949 // written in the source.
1950 std::string Result;
1951 QualType ResultType = Block->getTypePtr()->getResultType();
1952 if (!ResultType->isVoidType())
1953 ResultType.getAsStringInternal(Result, Context.PrintingPolicy);
1955 Result = '^' + Result;
1956 if (Block->getNumArgs() == 0) {
1957 if (Block->getTypePtr()->isVariadic())
1958 Result += "(...)";
1959 else
1960 Result += "(void)";
1961 } else {
1962 Result += "(";
1963 for (unsigned I = 0, N = Block->getNumArgs(); I != N; ++I) {
1964 if (I)
1965 Result += ", ";
1966 Result += FormatFunctionParameter(Context, Block->getArg(I));
1968 if (I == N - 1 && Block->getTypePtr()->isVariadic())
1969 Result += ", ...";
1971 Result += ")";
1974 if (Param->getIdentifier())
1975 Result += Param->getIdentifier()->getName();
1977 return Result;
1980 /// \brief Add function parameter chunks to the given code completion string.
1981 static void AddFunctionParameterChunks(ASTContext &Context,
1982 FunctionDecl *Function,
1983 CodeCompletionString *Result) {
1984 typedef CodeCompletionString::Chunk Chunk;
1986 CodeCompletionString *CCStr = Result;
1988 for (unsigned P = 0, N = Function->getNumParams(); P != N; ++P) {
1989 ParmVarDecl *Param = Function->getParamDecl(P);
1991 if (Param->hasDefaultArg()) {
1992 // When we see an optional default argument, put that argument and
1993 // the remaining default arguments into a new, optional string.
1994 CodeCompletionString *Opt = new CodeCompletionString;
1995 CCStr->AddOptionalChunk(std::auto_ptr<CodeCompletionString>(Opt));
1996 CCStr = Opt;
1999 if (P != 0)
2000 CCStr->AddChunk(Chunk(CodeCompletionString::CK_Comma));
2002 // Format the placeholder string.
2003 std::string PlaceholderStr = FormatFunctionParameter(Context, Param);
2005 if (Function->isVariadic() && P == N - 1)
2006 PlaceholderStr += ", ...";
2008 // Add the placeholder string.
2009 CCStr->AddPlaceholderChunk(PlaceholderStr);
2012 if (const FunctionProtoType *Proto
2013 = Function->getType()->getAs<FunctionProtoType>())
2014 if (Proto->isVariadic()) {
2015 if (Proto->getNumArgs() == 0)
2016 CCStr->AddPlaceholderChunk("...");
2018 MaybeAddSentinel(Context, Function, CCStr);
2022 /// \brief Add template parameter chunks to the given code completion string.
2023 static void AddTemplateParameterChunks(ASTContext &Context,
2024 TemplateDecl *Template,
2025 CodeCompletionString *Result,
2026 unsigned MaxParameters = 0) {
2027 typedef CodeCompletionString::Chunk Chunk;
2029 CodeCompletionString *CCStr = Result;
2030 bool FirstParameter = true;
2032 TemplateParameterList *Params = Template->getTemplateParameters();
2033 TemplateParameterList::iterator PEnd = Params->end();
2034 if (MaxParameters)
2035 PEnd = Params->begin() + MaxParameters;
2036 for (TemplateParameterList::iterator P = Params->begin(); P != PEnd; ++P) {
2037 bool HasDefaultArg = false;
2038 std::string PlaceholderStr;
2039 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
2040 if (TTP->wasDeclaredWithTypename())
2041 PlaceholderStr = "typename";
2042 else
2043 PlaceholderStr = "class";
2045 if (TTP->getIdentifier()) {
2046 PlaceholderStr += ' ';
2047 PlaceholderStr += TTP->getIdentifier()->getName();
2050 HasDefaultArg = TTP->hasDefaultArgument();
2051 } else if (NonTypeTemplateParmDecl *NTTP
2052 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
2053 if (NTTP->getIdentifier())
2054 PlaceholderStr = NTTP->getIdentifier()->getName();
2055 NTTP->getType().getAsStringInternal(PlaceholderStr,
2056 Context.PrintingPolicy);
2057 HasDefaultArg = NTTP->hasDefaultArgument();
2058 } else {
2059 assert(isa<TemplateTemplateParmDecl>(*P));
2060 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
2062 // Since putting the template argument list into the placeholder would
2063 // be very, very long, we just use an abbreviation.
2064 PlaceholderStr = "template<...> class";
2065 if (TTP->getIdentifier()) {
2066 PlaceholderStr += ' ';
2067 PlaceholderStr += TTP->getIdentifier()->getName();
2070 HasDefaultArg = TTP->hasDefaultArgument();
2073 if (HasDefaultArg) {
2074 // When we see an optional default argument, put that argument and
2075 // the remaining default arguments into a new, optional string.
2076 CodeCompletionString *Opt = new CodeCompletionString;
2077 CCStr->AddOptionalChunk(std::auto_ptr<CodeCompletionString>(Opt));
2078 CCStr = Opt;
2081 if (FirstParameter)
2082 FirstParameter = false;
2083 else
2084 CCStr->AddChunk(Chunk(CodeCompletionString::CK_Comma));
2086 // Add the placeholder string.
2087 CCStr->AddPlaceholderChunk(PlaceholderStr);
2091 /// \brief Add a qualifier to the given code-completion string, if the
2092 /// provided nested-name-specifier is non-NULL.
2093 static void
2094 AddQualifierToCompletionString(CodeCompletionString *Result,
2095 NestedNameSpecifier *Qualifier,
2096 bool QualifierIsInformative,
2097 ASTContext &Context) {
2098 if (!Qualifier)
2099 return;
2101 std::string PrintedNNS;
2103 llvm::raw_string_ostream OS(PrintedNNS);
2104 Qualifier->print(OS, Context.PrintingPolicy);
2106 if (QualifierIsInformative)
2107 Result->AddInformativeChunk(PrintedNNS);
2108 else
2109 Result->AddTextChunk(PrintedNNS);
2112 static void AddFunctionTypeQualsToCompletionString(CodeCompletionString *Result,
2113 FunctionDecl *Function) {
2114 const FunctionProtoType *Proto
2115 = Function->getType()->getAs<FunctionProtoType>();
2116 if (!Proto || !Proto->getTypeQuals())
2117 return;
2119 std::string QualsStr;
2120 if (Proto->getTypeQuals() & Qualifiers::Const)
2121 QualsStr += " const";
2122 if (Proto->getTypeQuals() & Qualifiers::Volatile)
2123 QualsStr += " volatile";
2124 if (Proto->getTypeQuals() & Qualifiers::Restrict)
2125 QualsStr += " restrict";
2126 Result->AddInformativeChunk(QualsStr);
2129 /// \brief Add the name of the given declaration
2130 static void AddTypedNameChunk(ASTContext &Context, NamedDecl *ND,
2131 CodeCompletionString *Result) {
2132 typedef CodeCompletionString::Chunk Chunk;
2134 DeclarationName Name = ND->getDeclName();
2135 if (!Name)
2136 return;
2138 switch (Name.getNameKind()) {
2139 case DeclarationName::Identifier:
2140 case DeclarationName::CXXConversionFunctionName:
2141 case DeclarationName::CXXOperatorName:
2142 case DeclarationName::CXXDestructorName:
2143 case DeclarationName::CXXLiteralOperatorName:
2144 Result->AddTypedTextChunk(ND->getNameAsString());
2145 break;
2147 case DeclarationName::CXXUsingDirective:
2148 case DeclarationName::ObjCZeroArgSelector:
2149 case DeclarationName::ObjCOneArgSelector:
2150 case DeclarationName::ObjCMultiArgSelector:
2151 break;
2153 case DeclarationName::CXXConstructorName: {
2154 CXXRecordDecl *Record = 0;
2155 QualType Ty = Name.getCXXNameType();
2156 if (const RecordType *RecordTy = Ty->getAs<RecordType>())
2157 Record = cast<CXXRecordDecl>(RecordTy->getDecl());
2158 else if (const InjectedClassNameType *InjectedTy
2159 = Ty->getAs<InjectedClassNameType>())
2160 Record = InjectedTy->getDecl();
2161 else {
2162 Result->AddTypedTextChunk(ND->getNameAsString());
2163 break;
2166 Result->AddTypedTextChunk(Record->getNameAsString());
2167 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) {
2168 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
2169 AddTemplateParameterChunks(Context, Template, Result);
2170 Result->AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
2172 break;
2177 /// \brief If possible, create a new code completion string for the given
2178 /// result.
2180 /// \returns Either a new, heap-allocated code completion string describing
2181 /// how to use this result, or NULL to indicate that the string or name of the
2182 /// result is all that is needed.
2183 CodeCompletionString *
2184 CodeCompletionResult::CreateCodeCompletionString(Sema &S,
2185 CodeCompletionString *Result) {
2186 typedef CodeCompletionString::Chunk Chunk;
2188 if (Kind == RK_Pattern)
2189 return Pattern->Clone(Result);
2191 if (!Result)
2192 Result = new CodeCompletionString;
2194 if (Kind == RK_Keyword) {
2195 Result->AddTypedTextChunk(Keyword);
2196 return Result;
2199 if (Kind == RK_Macro) {
2200 MacroInfo *MI = S.PP.getMacroInfo(Macro);
2201 assert(MI && "Not a macro?");
2203 Result->AddTypedTextChunk(Macro->getName());
2205 if (!MI->isFunctionLike())
2206 return Result;
2208 // Format a function-like macro with placeholders for the arguments.
2209 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
2210 for (MacroInfo::arg_iterator A = MI->arg_begin(), AEnd = MI->arg_end();
2211 A != AEnd; ++A) {
2212 if (A != MI->arg_begin())
2213 Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
2215 if (!MI->isVariadic() || A != AEnd - 1) {
2216 // Non-variadic argument.
2217 Result->AddPlaceholderChunk((*A)->getName());
2218 continue;
2221 // Variadic argument; cope with the different between GNU and C99
2222 // variadic macros, providing a single placeholder for the rest of the
2223 // arguments.
2224 if ((*A)->isStr("__VA_ARGS__"))
2225 Result->AddPlaceholderChunk("...");
2226 else {
2227 std::string Arg = (*A)->getName();
2228 Arg += "...";
2229 Result->AddPlaceholderChunk(Arg);
2232 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
2233 return Result;
2236 assert(Kind == RK_Declaration && "Missed a result kind?");
2237 NamedDecl *ND = Declaration;
2239 if (StartsNestedNameSpecifier) {
2240 Result->AddTypedTextChunk(ND->getNameAsString());
2241 Result->AddTextChunk("::");
2242 return Result;
2245 AddResultTypeChunk(S.Context, ND, Result);
2247 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND)) {
2248 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2249 S.Context);
2250 AddTypedNameChunk(S.Context, ND, Result);
2251 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
2252 AddFunctionParameterChunks(S.Context, Function, Result);
2253 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
2254 AddFunctionTypeQualsToCompletionString(Result, Function);
2255 return Result;
2258 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND)) {
2259 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2260 S.Context);
2261 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
2262 AddTypedNameChunk(S.Context, Function, Result);
2264 // Figure out which template parameters are deduced (or have default
2265 // arguments).
2266 llvm::SmallVector<bool, 16> Deduced;
2267 S.MarkDeducedTemplateParameters(FunTmpl, Deduced);
2268 unsigned LastDeducibleArgument;
2269 for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0;
2270 --LastDeducibleArgument) {
2271 if (!Deduced[LastDeducibleArgument - 1]) {
2272 // C++0x: Figure out if the template argument has a default. If so,
2273 // the user doesn't need to type this argument.
2274 // FIXME: We need to abstract template parameters better!
2275 bool HasDefaultArg = false;
2276 NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam(
2277 LastDeducibleArgument - 1);
2278 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2279 HasDefaultArg = TTP->hasDefaultArgument();
2280 else if (NonTypeTemplateParmDecl *NTTP
2281 = dyn_cast<NonTypeTemplateParmDecl>(Param))
2282 HasDefaultArg = NTTP->hasDefaultArgument();
2283 else {
2284 assert(isa<TemplateTemplateParmDecl>(Param));
2285 HasDefaultArg
2286 = cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument();
2289 if (!HasDefaultArg)
2290 break;
2294 if (LastDeducibleArgument) {
2295 // Some of the function template arguments cannot be deduced from a
2296 // function call, so we introduce an explicit template argument list
2297 // containing all of the arguments up to the first deducible argument.
2298 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
2299 AddTemplateParameterChunks(S.Context, FunTmpl, Result,
2300 LastDeducibleArgument);
2301 Result->AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
2304 // Add the function parameters
2305 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
2306 AddFunctionParameterChunks(S.Context, Function, Result);
2307 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
2308 AddFunctionTypeQualsToCompletionString(Result, Function);
2309 return Result;
2312 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(ND)) {
2313 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2314 S.Context);
2315 Result->AddTypedTextChunk(Template->getNameAsString());
2316 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
2317 AddTemplateParameterChunks(S.Context, Template, Result);
2318 Result->AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
2319 return Result;
2322 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND)) {
2323 Selector Sel = Method->getSelector();
2324 if (Sel.isUnarySelector()) {
2325 Result->AddTypedTextChunk(Sel.getIdentifierInfoForSlot(0)->getName());
2326 return Result;
2329 std::string SelName = Sel.getIdentifierInfoForSlot(0)->getName().str();
2330 SelName += ':';
2331 if (StartParameter == 0)
2332 Result->AddTypedTextChunk(SelName);
2333 else {
2334 Result->AddInformativeChunk(SelName);
2336 // If there is only one parameter, and we're past it, add an empty
2337 // typed-text chunk since there is nothing to type.
2338 if (Method->param_size() == 1)
2339 Result->AddTypedTextChunk("");
2341 unsigned Idx = 0;
2342 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
2343 PEnd = Method->param_end();
2344 P != PEnd; (void)++P, ++Idx) {
2345 if (Idx > 0) {
2346 std::string Keyword;
2347 if (Idx > StartParameter)
2348 Result->AddChunk(CodeCompletionString::CK_HorizontalSpace);
2349 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(Idx))
2350 Keyword += II->getName().str();
2351 Keyword += ":";
2352 if (Idx < StartParameter || AllParametersAreInformative)
2353 Result->AddInformativeChunk(Keyword);
2354 else
2355 Result->AddTypedTextChunk(Keyword);
2358 // If we're before the starting parameter, skip the placeholder.
2359 if (Idx < StartParameter)
2360 continue;
2362 std::string Arg;
2364 if ((*P)->getType()->isBlockPointerType() && !DeclaringEntity)
2365 Arg = FormatFunctionParameter(S.Context, *P, true);
2366 else {
2367 (*P)->getType().getAsStringInternal(Arg, S.Context.PrintingPolicy);
2368 Arg = "(" + Arg + ")";
2369 if (IdentifierInfo *II = (*P)->getIdentifier())
2370 if (DeclaringEntity || AllParametersAreInformative)
2371 Arg += II->getName().str();
2374 if (Method->isVariadic() && (P + 1) == PEnd)
2375 Arg += ", ...";
2377 if (DeclaringEntity)
2378 Result->AddTextChunk(Arg);
2379 else if (AllParametersAreInformative)
2380 Result->AddInformativeChunk(Arg);
2381 else
2382 Result->AddPlaceholderChunk(Arg);
2385 if (Method->isVariadic()) {
2386 if (Method->param_size() == 0) {
2387 if (DeclaringEntity)
2388 Result->AddTextChunk(", ...");
2389 else if (AllParametersAreInformative)
2390 Result->AddInformativeChunk(", ...");
2391 else
2392 Result->AddPlaceholderChunk(", ...");
2395 MaybeAddSentinel(S.Context, Method, Result);
2398 return Result;
2401 if (Qualifier)
2402 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
2403 S.Context);
2405 Result->AddTypedTextChunk(ND->getNameAsString());
2406 return Result;
2409 CodeCompletionString *
2410 CodeCompleteConsumer::OverloadCandidate::CreateSignatureString(
2411 unsigned CurrentArg,
2412 Sema &S,
2413 CodeCompletionString *Result) const {
2414 typedef CodeCompletionString::Chunk Chunk;
2416 if (!Result)
2417 Result = new CodeCompletionString;
2418 FunctionDecl *FDecl = getFunction();
2419 AddResultTypeChunk(S.Context, FDecl, Result);
2420 const FunctionProtoType *Proto
2421 = dyn_cast<FunctionProtoType>(getFunctionType());
2422 if (!FDecl && !Proto) {
2423 // Function without a prototype. Just give the return type and a
2424 // highlighted ellipsis.
2425 const FunctionType *FT = getFunctionType();
2426 Result->AddTextChunk(
2427 FT->getResultType().getAsString(S.Context.PrintingPolicy));
2428 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
2429 Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
2430 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
2431 return Result;
2434 if (FDecl)
2435 Result->AddTextChunk(FDecl->getNameAsString());
2436 else
2437 Result->AddTextChunk(
2438 Proto->getResultType().getAsString(S.Context.PrintingPolicy));
2440 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
2441 unsigned NumParams = FDecl? FDecl->getNumParams() : Proto->getNumArgs();
2442 for (unsigned I = 0; I != NumParams; ++I) {
2443 if (I)
2444 Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
2446 std::string ArgString;
2447 QualType ArgType;
2449 if (FDecl) {
2450 ArgString = FDecl->getParamDecl(I)->getNameAsString();
2451 ArgType = FDecl->getParamDecl(I)->getOriginalType();
2452 } else {
2453 ArgType = Proto->getArgType(I);
2456 ArgType.getAsStringInternal(ArgString, S.Context.PrintingPolicy);
2458 if (I == CurrentArg)
2459 Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter,
2460 ArgString));
2461 else
2462 Result->AddTextChunk(ArgString);
2465 if (Proto && Proto->isVariadic()) {
2466 Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
2467 if (CurrentArg < NumParams)
2468 Result->AddTextChunk("...");
2469 else
2470 Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
2472 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
2474 return Result;
2477 unsigned clang::getMacroUsagePriority(llvm::StringRef MacroName,
2478 const LangOptions &LangOpts,
2479 bool PreferredTypeIsPointer) {
2480 unsigned Priority = CCP_Macro;
2482 // Treat the "nil", "Nil" and "NULL" macros as null pointer constants.
2483 if (MacroName.equals("nil") || MacroName.equals("NULL") ||
2484 MacroName.equals("Nil")) {
2485 Priority = CCP_Constant;
2486 if (PreferredTypeIsPointer)
2487 Priority = Priority / CCF_SimilarTypeMatch;
2489 // Treat "YES", "NO", "true", and "false" as constants.
2490 else if (MacroName.equals("YES") || MacroName.equals("NO") ||
2491 MacroName.equals("true") || MacroName.equals("false"))
2492 Priority = CCP_Constant;
2493 // Treat "bool" as a type.
2494 else if (MacroName.equals("bool"))
2495 Priority = CCP_Type + (LangOpts.ObjC1? CCD_bool_in_ObjC : 0);
2498 return Priority;
2501 CXCursorKind clang::getCursorKindForDecl(Decl *D) {
2502 if (!D)
2503 return CXCursor_UnexposedDecl;
2505 switch (D->getKind()) {
2506 case Decl::Enum: return CXCursor_EnumDecl;
2507 case Decl::EnumConstant: return CXCursor_EnumConstantDecl;
2508 case Decl::Field: return CXCursor_FieldDecl;
2509 case Decl::Function:
2510 return CXCursor_FunctionDecl;
2511 case Decl::ObjCCategory: return CXCursor_ObjCCategoryDecl;
2512 case Decl::ObjCCategoryImpl: return CXCursor_ObjCCategoryImplDecl;
2513 case Decl::ObjCClass:
2514 // FIXME
2515 return CXCursor_UnexposedDecl;
2516 case Decl::ObjCForwardProtocol:
2517 // FIXME
2518 return CXCursor_UnexposedDecl;
2519 case Decl::ObjCImplementation: return CXCursor_ObjCImplementationDecl;
2520 case Decl::ObjCInterface: return CXCursor_ObjCInterfaceDecl;
2521 case Decl::ObjCIvar: return CXCursor_ObjCIvarDecl;
2522 case Decl::ObjCMethod:
2523 return cast<ObjCMethodDecl>(D)->isInstanceMethod()
2524 ? CXCursor_ObjCInstanceMethodDecl : CXCursor_ObjCClassMethodDecl;
2525 case Decl::CXXMethod: return CXCursor_CXXMethod;
2526 case Decl::CXXConstructor: return CXCursor_Constructor;
2527 case Decl::CXXDestructor: return CXCursor_Destructor;
2528 case Decl::CXXConversion: return CXCursor_ConversionFunction;
2529 case Decl::ObjCProperty: return CXCursor_ObjCPropertyDecl;
2530 case Decl::ObjCProtocol: return CXCursor_ObjCProtocolDecl;
2531 case Decl::ParmVar: return CXCursor_ParmDecl;
2532 case Decl::Typedef: return CXCursor_TypedefDecl;
2533 case Decl::Var: return CXCursor_VarDecl;
2534 case Decl::Namespace: return CXCursor_Namespace;
2535 case Decl::NamespaceAlias: return CXCursor_NamespaceAlias;
2536 case Decl::TemplateTypeParm: return CXCursor_TemplateTypeParameter;
2537 case Decl::NonTypeTemplateParm:return CXCursor_NonTypeTemplateParameter;
2538 case Decl::TemplateTemplateParm:return CXCursor_TemplateTemplateParameter;
2539 case Decl::FunctionTemplate: return CXCursor_FunctionTemplate;
2540 case Decl::ClassTemplate: return CXCursor_ClassTemplate;
2541 case Decl::ClassTemplatePartialSpecialization:
2542 return CXCursor_ClassTemplatePartialSpecialization;
2543 case Decl::UsingDirective: return CXCursor_UsingDirective;
2545 case Decl::Using:
2546 case Decl::UnresolvedUsingValue:
2547 case Decl::UnresolvedUsingTypename:
2548 return CXCursor_UsingDeclaration;
2550 default:
2551 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
2552 switch (TD->getTagKind()) {
2553 case TTK_Struct: return CXCursor_StructDecl;
2554 case TTK_Class: return CXCursor_ClassDecl;
2555 case TTK_Union: return CXCursor_UnionDecl;
2556 case TTK_Enum: return CXCursor_EnumDecl;
2561 return CXCursor_UnexposedDecl;
2564 static void AddMacroResults(Preprocessor &PP, ResultBuilder &Results,
2565 bool TargetTypeIsPointer = false) {
2566 typedef CodeCompletionResult Result;
2568 Results.EnterNewScope();
2570 for (Preprocessor::macro_iterator M = PP.macro_begin(),
2571 MEnd = PP.macro_end();
2572 M != MEnd; ++M) {
2573 Results.AddResult(Result(M->first,
2574 getMacroUsagePriority(M->first->getName(),
2575 PP.getLangOptions(),
2576 TargetTypeIsPointer)));
2579 Results.ExitScope();
2583 static void AddPrettyFunctionResults(const LangOptions &LangOpts,
2584 ResultBuilder &Results) {
2585 typedef CodeCompletionResult Result;
2587 Results.EnterNewScope();
2589 Results.AddResult(Result("__PRETTY_FUNCTION__", CCP_Constant));
2590 Results.AddResult(Result("__FUNCTION__", CCP_Constant));
2591 if (LangOpts.C99 || LangOpts.CPlusPlus0x)
2592 Results.AddResult(Result("__func__", CCP_Constant));
2593 Results.ExitScope();
2596 static void HandleCodeCompleteResults(Sema *S,
2597 CodeCompleteConsumer *CodeCompleter,
2598 CodeCompletionContext Context,
2599 CodeCompletionResult *Results,
2600 unsigned NumResults) {
2601 if (CodeCompleter)
2602 CodeCompleter->ProcessCodeCompleteResults(*S, Context, Results, NumResults);
2604 for (unsigned I = 0; I != NumResults; ++I)
2605 Results[I].Destroy();
2608 static enum CodeCompletionContext::Kind mapCodeCompletionContext(Sema &S,
2609 Sema::ParserCompletionContext PCC) {
2610 switch (PCC) {
2611 case Sema::PCC_Namespace:
2612 return CodeCompletionContext::CCC_TopLevel;
2614 case Sema::PCC_Class:
2615 return CodeCompletionContext::CCC_ClassStructUnion;
2617 case Sema::PCC_ObjCInterface:
2618 return CodeCompletionContext::CCC_ObjCInterface;
2620 case Sema::PCC_ObjCImplementation:
2621 return CodeCompletionContext::CCC_ObjCImplementation;
2623 case Sema::PCC_ObjCInstanceVariableList:
2624 return CodeCompletionContext::CCC_ObjCIvarList;
2626 case Sema::PCC_Template:
2627 case Sema::PCC_MemberTemplate:
2628 if (S.CurContext->isFileContext())
2629 return CodeCompletionContext::CCC_TopLevel;
2630 else if (S.CurContext->isRecord())
2631 return CodeCompletionContext::CCC_ClassStructUnion;
2632 else
2633 return CodeCompletionContext::CCC_Other;
2635 case Sema::PCC_RecoveryInFunction:
2636 return CodeCompletionContext::CCC_Recovery;
2638 case Sema::PCC_ForInit:
2639 if (S.getLangOptions().CPlusPlus || S.getLangOptions().C99 ||
2640 S.getLangOptions().ObjC1)
2641 return CodeCompletionContext::CCC_ParenthesizedExpression;
2642 else
2643 return CodeCompletionContext::CCC_Expression;
2645 case Sema::PCC_Expression:
2646 case Sema::PCC_Condition:
2647 return CodeCompletionContext::CCC_Expression;
2649 case Sema::PCC_Statement:
2650 return CodeCompletionContext::CCC_Statement;
2652 case Sema::PCC_Type:
2653 return CodeCompletionContext::CCC_Type;
2655 case Sema::PCC_ParenthesizedExpression:
2656 return CodeCompletionContext::CCC_ParenthesizedExpression;
2659 return CodeCompletionContext::CCC_Other;
2662 /// \brief If we're in a C++ virtual member function, add completion results
2663 /// that invoke the functions we override, since it's common to invoke the
2664 /// overridden function as well as adding new functionality.
2666 /// \param S The semantic analysis object for which we are generating results.
2668 /// \param InContext This context in which the nested-name-specifier preceding
2669 /// the code-completion point
2670 static void MaybeAddOverrideCalls(Sema &S, DeclContext *InContext,
2671 ResultBuilder &Results) {
2672 // Look through blocks.
2673 DeclContext *CurContext = S.CurContext;
2674 while (isa<BlockDecl>(CurContext))
2675 CurContext = CurContext->getParent();
2678 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(CurContext);
2679 if (!Method || !Method->isVirtual())
2680 return;
2682 // We need to have names for all of the parameters, if we're going to
2683 // generate a forwarding call.
2684 for (CXXMethodDecl::param_iterator P = Method->param_begin(),
2685 PEnd = Method->param_end();
2686 P != PEnd;
2687 ++P) {
2688 if (!(*P)->getDeclName())
2689 return;
2692 for (CXXMethodDecl::method_iterator M = Method->begin_overridden_methods(),
2693 MEnd = Method->end_overridden_methods();
2694 M != MEnd; ++M) {
2695 CodeCompletionString *Pattern = new CodeCompletionString;
2696 CXXMethodDecl *Overridden = const_cast<CXXMethodDecl *>(*M);
2697 if (Overridden->getCanonicalDecl() == Method->getCanonicalDecl())
2698 continue;
2700 // If we need a nested-name-specifier, add one now.
2701 if (!InContext) {
2702 NestedNameSpecifier *NNS
2703 = getRequiredQualification(S.Context, CurContext,
2704 Overridden->getDeclContext());
2705 if (NNS) {
2706 std::string Str;
2707 llvm::raw_string_ostream OS(Str);
2708 NNS->print(OS, S.Context.PrintingPolicy);
2709 Pattern->AddTextChunk(OS.str());
2711 } else if (!InContext->Equals(Overridden->getDeclContext()))
2712 continue;
2714 Pattern->AddTypedTextChunk(Overridden->getNameAsString());
2715 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
2716 bool FirstParam = true;
2717 for (CXXMethodDecl::param_iterator P = Method->param_begin(),
2718 PEnd = Method->param_end();
2719 P != PEnd; ++P) {
2720 if (FirstParam)
2721 FirstParam = false;
2722 else
2723 Pattern->AddChunk(CodeCompletionString::CK_Comma);
2725 Pattern->AddPlaceholderChunk((*P)->getIdentifier()->getName());
2727 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
2728 Results.AddResult(CodeCompletionResult(Pattern,
2729 CCP_SuperCompletion,
2730 CXCursor_CXXMethod));
2731 Results.Ignore(Overridden);
2735 void Sema::CodeCompleteOrdinaryName(Scope *S,
2736 ParserCompletionContext CompletionContext) {
2737 typedef CodeCompletionResult Result;
2738 ResultBuilder Results(*this,
2739 mapCodeCompletionContext(*this, CompletionContext));
2740 Results.EnterNewScope();
2742 // Determine how to filter results, e.g., so that the names of
2743 // values (functions, enumerators, function templates, etc.) are
2744 // only allowed where we can have an expression.
2745 switch (CompletionContext) {
2746 case PCC_Namespace:
2747 case PCC_Class:
2748 case PCC_ObjCInterface:
2749 case PCC_ObjCImplementation:
2750 case PCC_ObjCInstanceVariableList:
2751 case PCC_Template:
2752 case PCC_MemberTemplate:
2753 case PCC_Type:
2754 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
2755 break;
2757 case PCC_Statement:
2758 case PCC_ParenthesizedExpression:
2759 case PCC_Expression:
2760 case PCC_ForInit:
2761 case PCC_Condition:
2762 if (WantTypesInContext(CompletionContext, getLangOptions()))
2763 Results.setFilter(&ResultBuilder::IsOrdinaryName);
2764 else
2765 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
2767 if (getLangOptions().CPlusPlus)
2768 MaybeAddOverrideCalls(*this, /*InContext=*/0, Results);
2769 break;
2771 case PCC_RecoveryInFunction:
2772 // Unfiltered
2773 break;
2776 // If we are in a C++ non-static member function, check the qualifiers on
2777 // the member function to filter/prioritize the results list.
2778 if (CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext))
2779 if (CurMethod->isInstance())
2780 Results.setObjectTypeQualifiers(
2781 Qualifiers::fromCVRMask(CurMethod->getTypeQualifiers()));
2783 CodeCompletionDeclConsumer Consumer(Results, CurContext);
2784 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
2785 CodeCompleter->includeGlobals());
2787 AddOrdinaryNameResults(CompletionContext, S, *this, Results);
2788 Results.ExitScope();
2790 switch (CompletionContext) {
2791 case PCC_ParenthesizedExpression:
2792 case PCC_Expression:
2793 case PCC_Statement:
2794 case PCC_RecoveryInFunction:
2795 if (S->getFnParent())
2796 AddPrettyFunctionResults(PP.getLangOptions(), Results);
2797 break;
2799 case PCC_Namespace:
2800 case PCC_Class:
2801 case PCC_ObjCInterface:
2802 case PCC_ObjCImplementation:
2803 case PCC_ObjCInstanceVariableList:
2804 case PCC_Template:
2805 case PCC_MemberTemplate:
2806 case PCC_ForInit:
2807 case PCC_Condition:
2808 case PCC_Type:
2809 break;
2812 if (CodeCompleter->includeMacros())
2813 AddMacroResults(PP, Results);
2815 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
2816 Results.data(),Results.size());
2819 static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
2820 ParsedType Receiver,
2821 IdentifierInfo **SelIdents,
2822 unsigned NumSelIdents,
2823 bool AtArgumentExpression,
2824 bool IsSuper,
2825 ResultBuilder &Results);
2827 void Sema::CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
2828 bool AllowNonIdentifiers,
2829 bool AllowNestedNameSpecifiers) {
2830 typedef CodeCompletionResult Result;
2831 ResultBuilder Results(*this,
2832 AllowNestedNameSpecifiers
2833 ? CodeCompletionContext::CCC_PotentiallyQualifiedName
2834 : CodeCompletionContext::CCC_Name);
2835 Results.EnterNewScope();
2837 // Type qualifiers can come after names.
2838 Results.AddResult(Result("const"));
2839 Results.AddResult(Result("volatile"));
2840 if (getLangOptions().C99)
2841 Results.AddResult(Result("restrict"));
2843 if (getLangOptions().CPlusPlus) {
2844 if (AllowNonIdentifiers) {
2845 Results.AddResult(Result("operator"));
2848 // Add nested-name-specifiers.
2849 if (AllowNestedNameSpecifiers) {
2850 Results.allowNestedNameSpecifiers();
2851 Results.setFilter(&ResultBuilder::IsImpossibleToSatisfy);
2852 CodeCompletionDeclConsumer Consumer(Results, CurContext);
2853 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer,
2854 CodeCompleter->includeGlobals());
2855 Results.setFilter(0);
2858 Results.ExitScope();
2860 // If we're in a context where we might have an expression (rather than a
2861 // declaration), and what we've seen so far is an Objective-C type that could
2862 // be a receiver of a class message, this may be a class message send with
2863 // the initial opening bracket '[' missing. Add appropriate completions.
2864 if (AllowNonIdentifiers && !AllowNestedNameSpecifiers &&
2865 DS.getTypeSpecType() == DeclSpec::TST_typename &&
2866 DS.getStorageClassSpecAsWritten() == DeclSpec::SCS_unspecified &&
2867 !DS.isThreadSpecified() && !DS.isExternInLinkageSpec() &&
2868 DS.getTypeSpecComplex() == DeclSpec::TSC_unspecified &&
2869 DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
2870 DS.getTypeQualifiers() == 0 &&
2871 S &&
2872 (S->getFlags() & Scope::DeclScope) != 0 &&
2873 (S->getFlags() & (Scope::ClassScope | Scope::TemplateParamScope |
2874 Scope::FunctionPrototypeScope |
2875 Scope::AtCatchScope)) == 0) {
2876 ParsedType T = DS.getRepAsType();
2877 if (!T.get().isNull() && T.get()->isObjCObjectOrInterfaceType())
2878 AddClassMessageCompletions(*this, S, T, 0, 0, false, false, Results);
2881 // Note that we intentionally suppress macro results here, since we do not
2882 // encourage using macros to produce the names of entities.
2884 HandleCodeCompleteResults(this, CodeCompleter,
2885 Results.getCompletionContext(),
2886 Results.data(), Results.size());
2889 struct Sema::CodeCompleteExpressionData {
2890 CodeCompleteExpressionData(QualType PreferredType = QualType())
2891 : PreferredType(PreferredType), IntegralConstantExpression(false),
2892 ObjCCollection(false) { }
2894 QualType PreferredType;
2895 bool IntegralConstantExpression;
2896 bool ObjCCollection;
2897 llvm::SmallVector<Decl *, 4> IgnoreDecls;
2900 /// \brief Perform code-completion in an expression context when we know what
2901 /// type we're looking for.
2903 /// \param IntegralConstantExpression Only permit integral constant
2904 /// expressions.
2905 void Sema::CodeCompleteExpression(Scope *S,
2906 const CodeCompleteExpressionData &Data) {
2907 typedef CodeCompletionResult Result;
2908 ResultBuilder Results(*this, CodeCompletionContext::CCC_Expression);
2909 if (Data.ObjCCollection)
2910 Results.setFilter(&ResultBuilder::IsObjCCollection);
2911 else if (Data.IntegralConstantExpression)
2912 Results.setFilter(&ResultBuilder::IsIntegralConstantValue);
2913 else if (WantTypesInContext(PCC_Expression, getLangOptions()))
2914 Results.setFilter(&ResultBuilder::IsOrdinaryName);
2915 else
2916 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
2918 if (!Data.PreferredType.isNull())
2919 Results.setPreferredType(Data.PreferredType.getNonReferenceType());
2921 // Ignore any declarations that we were told that we don't care about.
2922 for (unsigned I = 0, N = Data.IgnoreDecls.size(); I != N; ++I)
2923 Results.Ignore(Data.IgnoreDecls[I]);
2925 CodeCompletionDeclConsumer Consumer(Results, CurContext);
2926 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
2927 CodeCompleter->includeGlobals());
2929 Results.EnterNewScope();
2930 AddOrdinaryNameResults(PCC_Expression, S, *this, Results);
2931 Results.ExitScope();
2933 bool PreferredTypeIsPointer = false;
2934 if (!Data.PreferredType.isNull())
2935 PreferredTypeIsPointer = Data.PreferredType->isAnyPointerType()
2936 || Data.PreferredType->isMemberPointerType()
2937 || Data.PreferredType->isBlockPointerType();
2939 if (S->getFnParent() &&
2940 !Data.ObjCCollection &&
2941 !Data.IntegralConstantExpression)
2942 AddPrettyFunctionResults(PP.getLangOptions(), Results);
2944 if (CodeCompleter->includeMacros())
2945 AddMacroResults(PP, Results, PreferredTypeIsPointer);
2946 HandleCodeCompleteResults(this, CodeCompleter,
2947 CodeCompletionContext(CodeCompletionContext::CCC_Expression,
2948 Data.PreferredType),
2949 Results.data(),Results.size());
2952 void Sema::CodeCompletePostfixExpression(Scope *S, ExprResult E) {
2953 if (E.isInvalid())
2954 CodeCompleteOrdinaryName(S, PCC_RecoveryInFunction);
2955 else if (getLangOptions().ObjC1)
2956 CodeCompleteObjCInstanceMessage(S, E.take(), 0, 0, false);
2959 /// \brief The set of properties that have already been added, referenced by
2960 /// property name.
2961 typedef llvm::SmallPtrSet<IdentifierInfo*, 16> AddedPropertiesSet;
2963 static void AddObjCProperties(ObjCContainerDecl *Container,
2964 bool AllowCategories,
2965 DeclContext *CurContext,
2966 AddedPropertiesSet &AddedProperties,
2967 ResultBuilder &Results) {
2968 typedef CodeCompletionResult Result;
2970 // Add properties in this container.
2971 for (ObjCContainerDecl::prop_iterator P = Container->prop_begin(),
2972 PEnd = Container->prop_end();
2973 P != PEnd;
2974 ++P) {
2975 if (AddedProperties.insert(P->getIdentifier()))
2976 Results.MaybeAddResult(Result(*P, 0), CurContext);
2979 // Add properties in referenced protocols.
2980 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
2981 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
2982 PEnd = Protocol->protocol_end();
2983 P != PEnd; ++P)
2984 AddObjCProperties(*P, AllowCategories, CurContext, AddedProperties,
2985 Results);
2986 } else if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)){
2987 if (AllowCategories) {
2988 // Look through categories.
2989 for (ObjCCategoryDecl *Category = IFace->getCategoryList();
2990 Category; Category = Category->getNextClassCategory())
2991 AddObjCProperties(Category, AllowCategories, CurContext,
2992 AddedProperties, Results);
2995 // Look through protocols.
2996 for (ObjCInterfaceDecl::all_protocol_iterator
2997 I = IFace->all_referenced_protocol_begin(),
2998 E = IFace->all_referenced_protocol_end(); I != E; ++I)
2999 AddObjCProperties(*I, AllowCategories, CurContext, AddedProperties,
3000 Results);
3002 // Look in the superclass.
3003 if (IFace->getSuperClass())
3004 AddObjCProperties(IFace->getSuperClass(), AllowCategories, CurContext,
3005 AddedProperties, Results);
3006 } else if (const ObjCCategoryDecl *Category
3007 = dyn_cast<ObjCCategoryDecl>(Container)) {
3008 // Look through protocols.
3009 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
3010 PEnd = Category->protocol_end();
3011 P != PEnd; ++P)
3012 AddObjCProperties(*P, AllowCategories, CurContext, AddedProperties,
3013 Results);
3017 void Sema::CodeCompleteMemberReferenceExpr(Scope *S, ExprTy *BaseE,
3018 SourceLocation OpLoc,
3019 bool IsArrow) {
3020 if (!BaseE || !CodeCompleter)
3021 return;
3023 typedef CodeCompletionResult Result;
3025 Expr *Base = static_cast<Expr *>(BaseE);
3026 QualType BaseType = Base->getType();
3028 if (IsArrow) {
3029 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
3030 BaseType = Ptr->getPointeeType();
3031 else if (BaseType->isObjCObjectPointerType())
3032 /*Do nothing*/ ;
3033 else
3034 return;
3037 ResultBuilder Results(*this,
3038 CodeCompletionContext(CodeCompletionContext::CCC_MemberAccess,
3039 BaseType),
3040 &ResultBuilder::IsMember);
3041 Results.EnterNewScope();
3042 if (const RecordType *Record = BaseType->getAs<RecordType>()) {
3043 // Indicate that we are performing a member access, and the cv-qualifiers
3044 // for the base object type.
3045 Results.setObjectTypeQualifiers(BaseType.getQualifiers());
3047 // Access to a C/C++ class, struct, or union.
3048 Results.allowNestedNameSpecifiers();
3049 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3050 LookupVisibleDecls(Record->getDecl(), LookupMemberName, Consumer,
3051 CodeCompleter->includeGlobals());
3053 if (getLangOptions().CPlusPlus) {
3054 if (!Results.empty()) {
3055 // The "template" keyword can follow "->" or "." in the grammar.
3056 // However, we only want to suggest the template keyword if something
3057 // is dependent.
3058 bool IsDependent = BaseType->isDependentType();
3059 if (!IsDependent) {
3060 for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent())
3061 if (DeclContext *Ctx = (DeclContext *)DepScope->getEntity()) {
3062 IsDependent = Ctx->isDependentContext();
3063 break;
3067 if (IsDependent)
3068 Results.AddResult(Result("template"));
3071 } else if (!IsArrow && BaseType->getAsObjCInterfacePointerType()) {
3072 // Objective-C property reference.
3073 AddedPropertiesSet AddedProperties;
3075 // Add property results based on our interface.
3076 const ObjCObjectPointerType *ObjCPtr
3077 = BaseType->getAsObjCInterfacePointerType();
3078 assert(ObjCPtr && "Non-NULL pointer guaranteed above!");
3079 AddObjCProperties(ObjCPtr->getInterfaceDecl(), true, CurContext,
3080 AddedProperties, Results);
3082 // Add properties from the protocols in a qualified interface.
3083 for (ObjCObjectPointerType::qual_iterator I = ObjCPtr->qual_begin(),
3084 E = ObjCPtr->qual_end();
3085 I != E; ++I)
3086 AddObjCProperties(*I, true, CurContext, AddedProperties, Results);
3087 } else if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
3088 (!IsArrow && BaseType->isObjCObjectType())) {
3089 // Objective-C instance variable access.
3090 ObjCInterfaceDecl *Class = 0;
3091 if (const ObjCObjectPointerType *ObjCPtr
3092 = BaseType->getAs<ObjCObjectPointerType>())
3093 Class = ObjCPtr->getInterfaceDecl();
3094 else
3095 Class = BaseType->getAs<ObjCObjectType>()->getInterface();
3097 // Add all ivars from this class and its superclasses.
3098 if (Class) {
3099 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3100 Results.setFilter(&ResultBuilder::IsObjCIvar);
3101 LookupVisibleDecls(Class, LookupMemberName, Consumer,
3102 CodeCompleter->includeGlobals());
3106 // FIXME: How do we cope with isa?
3108 Results.ExitScope();
3110 // Hand off the results found for code completion.
3111 HandleCodeCompleteResults(this, CodeCompleter,
3112 Results.getCompletionContext(),
3113 Results.data(),Results.size());
3116 void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) {
3117 if (!CodeCompleter)
3118 return;
3120 typedef CodeCompletionResult Result;
3121 ResultBuilder::LookupFilter Filter = 0;
3122 enum CodeCompletionContext::Kind ContextKind
3123 = CodeCompletionContext::CCC_Other;
3124 switch ((DeclSpec::TST)TagSpec) {
3125 case DeclSpec::TST_enum:
3126 Filter = &ResultBuilder::IsEnum;
3127 ContextKind = CodeCompletionContext::CCC_EnumTag;
3128 break;
3130 case DeclSpec::TST_union:
3131 Filter = &ResultBuilder::IsUnion;
3132 ContextKind = CodeCompletionContext::CCC_UnionTag;
3133 break;
3135 case DeclSpec::TST_struct:
3136 case DeclSpec::TST_class:
3137 Filter = &ResultBuilder::IsClassOrStruct;
3138 ContextKind = CodeCompletionContext::CCC_ClassOrStructTag;
3139 break;
3141 default:
3142 assert(false && "Unknown type specifier kind in CodeCompleteTag");
3143 return;
3146 ResultBuilder Results(*this, ContextKind);
3147 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3149 // First pass: look for tags.
3150 Results.setFilter(Filter);
3151 LookupVisibleDecls(S, LookupTagName, Consumer,
3152 CodeCompleter->includeGlobals());
3154 if (CodeCompleter->includeGlobals()) {
3155 // Second pass: look for nested name specifiers.
3156 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
3157 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer);
3160 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
3161 Results.data(),Results.size());
3164 void Sema::CodeCompleteTypeQualifiers(DeclSpec &DS) {
3165 ResultBuilder Results(*this, CodeCompletionContext::CCC_TypeQualifiers);
3166 Results.EnterNewScope();
3167 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_const))
3168 Results.AddResult("const");
3169 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_volatile))
3170 Results.AddResult("volatile");
3171 if (getLangOptions().C99 &&
3172 !(DS.getTypeQualifiers() & DeclSpec::TQ_restrict))
3173 Results.AddResult("restrict");
3174 Results.ExitScope();
3175 HandleCodeCompleteResults(this, CodeCompleter,
3176 Results.getCompletionContext(),
3177 Results.data(), Results.size());
3180 void Sema::CodeCompleteCase(Scope *S) {
3181 if (getCurFunction()->SwitchStack.empty() || !CodeCompleter)
3182 return;
3184 SwitchStmt *Switch = getCurFunction()->SwitchStack.back();
3185 if (!Switch->getCond()->getType()->isEnumeralType()) {
3186 CodeCompleteExpressionData Data(Switch->getCond()->getType());
3187 Data.IntegralConstantExpression = true;
3188 CodeCompleteExpression(S, Data);
3189 return;
3192 // Code-complete the cases of a switch statement over an enumeration type
3193 // by providing the list of
3194 EnumDecl *Enum = Switch->getCond()->getType()->getAs<EnumType>()->getDecl();
3196 // Determine which enumerators we have already seen in the switch statement.
3197 // FIXME: Ideally, we would also be able to look *past* the code-completion
3198 // token, in case we are code-completing in the middle of the switch and not
3199 // at the end. However, we aren't able to do so at the moment.
3200 llvm::SmallPtrSet<EnumConstantDecl *, 8> EnumeratorsSeen;
3201 NestedNameSpecifier *Qualifier = 0;
3202 for (SwitchCase *SC = Switch->getSwitchCaseList(); SC;
3203 SC = SC->getNextSwitchCase()) {
3204 CaseStmt *Case = dyn_cast<CaseStmt>(SC);
3205 if (!Case)
3206 continue;
3208 Expr *CaseVal = Case->getLHS()->IgnoreParenCasts();
3209 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseVal))
3210 if (EnumConstantDecl *Enumerator
3211 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
3212 // We look into the AST of the case statement to determine which
3213 // enumerator was named. Alternatively, we could compute the value of
3214 // the integral constant expression, then compare it against the
3215 // values of each enumerator. However, value-based approach would not
3216 // work as well with C++ templates where enumerators declared within a
3217 // template are type- and value-dependent.
3218 EnumeratorsSeen.insert(Enumerator);
3220 // If this is a qualified-id, keep track of the nested-name-specifier
3221 // so that we can reproduce it as part of code completion, e.g.,
3223 // switch (TagD.getKind()) {
3224 // case TagDecl::TK_enum:
3225 // break;
3226 // case XXX
3228 // At the XXX, our completions are TagDecl::TK_union,
3229 // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
3230 // TK_struct, and TK_class.
3231 Qualifier = DRE->getQualifier();
3235 if (getLangOptions().CPlusPlus && !Qualifier && EnumeratorsSeen.empty()) {
3236 // If there are no prior enumerators in C++, check whether we have to
3237 // qualify the names of the enumerators that we suggest, because they
3238 // may not be visible in this scope.
3239 Qualifier = getRequiredQualification(Context, CurContext,
3240 Enum->getDeclContext());
3242 // FIXME: Scoped enums need to start with "EnumDecl" as the context!
3245 // Add any enumerators that have not yet been mentioned.
3246 ResultBuilder Results(*this, CodeCompletionContext::CCC_Expression);
3247 Results.EnterNewScope();
3248 for (EnumDecl::enumerator_iterator E = Enum->enumerator_begin(),
3249 EEnd = Enum->enumerator_end();
3250 E != EEnd; ++E) {
3251 if (EnumeratorsSeen.count(*E))
3252 continue;
3254 Results.AddResult(CodeCompletionResult(*E, Qualifier),
3255 CurContext, 0, false);
3257 Results.ExitScope();
3259 if (CodeCompleter->includeMacros())
3260 AddMacroResults(PP, Results);
3261 HandleCodeCompleteResults(this, CodeCompleter,
3262 CodeCompletionContext::CCC_Expression,
3263 Results.data(),Results.size());
3266 namespace {
3267 struct IsBetterOverloadCandidate {
3268 Sema &S;
3269 SourceLocation Loc;
3271 public:
3272 explicit IsBetterOverloadCandidate(Sema &S, SourceLocation Loc)
3273 : S(S), Loc(Loc) { }
3275 bool
3276 operator()(const OverloadCandidate &X, const OverloadCandidate &Y) const {
3277 return isBetterOverloadCandidate(S, X, Y, Loc);
3282 static bool anyNullArguments(Expr **Args, unsigned NumArgs) {
3283 if (NumArgs && !Args)
3284 return true;
3286 for (unsigned I = 0; I != NumArgs; ++I)
3287 if (!Args[I])
3288 return true;
3290 return false;
3293 void Sema::CodeCompleteCall(Scope *S, ExprTy *FnIn,
3294 ExprTy **ArgsIn, unsigned NumArgs) {
3295 if (!CodeCompleter)
3296 return;
3298 // When we're code-completing for a call, we fall back to ordinary
3299 // name code-completion whenever we can't produce specific
3300 // results. We may want to revisit this strategy in the future,
3301 // e.g., by merging the two kinds of results.
3303 Expr *Fn = (Expr *)FnIn;
3304 Expr **Args = (Expr **)ArgsIn;
3306 // Ignore type-dependent call expressions entirely.
3307 if (!Fn || Fn->isTypeDependent() || anyNullArguments(Args, NumArgs) ||
3308 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
3309 CodeCompleteOrdinaryName(S, PCC_Expression);
3310 return;
3313 // Build an overload candidate set based on the functions we find.
3314 SourceLocation Loc = Fn->getExprLoc();
3315 OverloadCandidateSet CandidateSet(Loc);
3317 // FIXME: What if we're calling something that isn't a function declaration?
3318 // FIXME: What if we're calling a pseudo-destructor?
3319 // FIXME: What if we're calling a member function?
3321 typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate;
3322 llvm::SmallVector<ResultCandidate, 8> Results;
3324 Expr *NakedFn = Fn->IgnoreParenCasts();
3325 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(NakedFn))
3326 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet,
3327 /*PartialOverloading=*/ true);
3328 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
3329 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl());
3330 if (FDecl) {
3331 if (!getLangOptions().CPlusPlus ||
3332 !FDecl->getType()->getAs<FunctionProtoType>())
3333 Results.push_back(ResultCandidate(FDecl));
3334 else
3335 // FIXME: access?
3336 AddOverloadCandidate(FDecl, DeclAccessPair::make(FDecl, AS_none),
3337 Args, NumArgs, CandidateSet,
3338 false, /*PartialOverloading*/true);
3342 QualType ParamType;
3344 if (!CandidateSet.empty()) {
3345 // Sort the overload candidate set by placing the best overloads first.
3346 std::stable_sort(CandidateSet.begin(), CandidateSet.end(),
3347 IsBetterOverloadCandidate(*this, Loc));
3349 // Add the remaining viable overload candidates as code-completion reslults.
3350 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3351 CandEnd = CandidateSet.end();
3352 Cand != CandEnd; ++Cand) {
3353 if (Cand->Viable)
3354 Results.push_back(ResultCandidate(Cand->Function));
3357 // From the viable candidates, try to determine the type of this parameter.
3358 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
3359 if (const FunctionType *FType = Results[I].getFunctionType())
3360 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FType))
3361 if (NumArgs < Proto->getNumArgs()) {
3362 if (ParamType.isNull())
3363 ParamType = Proto->getArgType(NumArgs);
3364 else if (!Context.hasSameUnqualifiedType(
3365 ParamType.getNonReferenceType(),
3366 Proto->getArgType(NumArgs).getNonReferenceType())) {
3367 ParamType = QualType();
3368 break;
3372 } else {
3373 // Try to determine the parameter type from the type of the expression
3374 // being called.
3375 QualType FunctionType = Fn->getType();
3376 if (const PointerType *Ptr = FunctionType->getAs<PointerType>())
3377 FunctionType = Ptr->getPointeeType();
3378 else if (const BlockPointerType *BlockPtr
3379 = FunctionType->getAs<BlockPointerType>())
3380 FunctionType = BlockPtr->getPointeeType();
3381 else if (const MemberPointerType *MemPtr
3382 = FunctionType->getAs<MemberPointerType>())
3383 FunctionType = MemPtr->getPointeeType();
3385 if (const FunctionProtoType *Proto
3386 = FunctionType->getAs<FunctionProtoType>()) {
3387 if (NumArgs < Proto->getNumArgs())
3388 ParamType = Proto->getArgType(NumArgs);
3392 if (ParamType.isNull())
3393 CodeCompleteOrdinaryName(S, PCC_Expression);
3394 else
3395 CodeCompleteExpression(S, ParamType);
3397 if (!Results.empty())
3398 CodeCompleter->ProcessOverloadCandidates(*this, NumArgs, Results.data(),
3399 Results.size());
3402 void Sema::CodeCompleteInitializer(Scope *S, Decl *D) {
3403 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
3404 if (!VD) {
3405 CodeCompleteOrdinaryName(S, PCC_Expression);
3406 return;
3409 CodeCompleteExpression(S, VD->getType());
3412 void Sema::CodeCompleteReturn(Scope *S) {
3413 QualType ResultType;
3414 if (isa<BlockDecl>(CurContext)) {
3415 if (BlockScopeInfo *BSI = getCurBlock())
3416 ResultType = BSI->ReturnType;
3417 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(CurContext))
3418 ResultType = Function->getResultType();
3419 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(CurContext))
3420 ResultType = Method->getResultType();
3422 if (ResultType.isNull())
3423 CodeCompleteOrdinaryName(S, PCC_Expression);
3424 else
3425 CodeCompleteExpression(S, ResultType);
3428 void Sema::CodeCompleteAssignmentRHS(Scope *S, ExprTy *LHS) {
3429 if (LHS)
3430 CodeCompleteExpression(S, static_cast<Expr *>(LHS)->getType());
3431 else
3432 CodeCompleteOrdinaryName(S, PCC_Expression);
3435 void Sema::CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
3436 bool EnteringContext) {
3437 if (!SS.getScopeRep() || !CodeCompleter)
3438 return;
3440 DeclContext *Ctx = computeDeclContext(SS, EnteringContext);
3441 if (!Ctx)
3442 return;
3444 // Try to instantiate any non-dependent declaration contexts before
3445 // we look in them.
3446 if (!isDependentScopeSpecifier(SS) && RequireCompleteDeclContext(SS, Ctx))
3447 return;
3449 ResultBuilder Results(*this, CodeCompletionContext::CCC_Name);
3450 Results.EnterNewScope();
3452 // The "template" keyword can follow "::" in the grammar, but only
3453 // put it into the grammar if the nested-name-specifier is dependent.
3454 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
3455 if (!Results.empty() && NNS->isDependent())
3456 Results.AddResult("template");
3458 // Add calls to overridden virtual functions, if there are any.
3460 // FIXME: This isn't wonderful, because we don't know whether we're actually
3461 // in a context that permits expressions. This is a general issue with
3462 // qualified-id completions.
3463 if (!EnteringContext)
3464 MaybeAddOverrideCalls(*this, Ctx, Results);
3465 Results.ExitScope();
3467 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3468 LookupVisibleDecls(Ctx, LookupOrdinaryName, Consumer);
3470 HandleCodeCompleteResults(this, CodeCompleter,
3471 CodeCompletionContext::CCC_Name,
3472 Results.data(),Results.size());
3475 void Sema::CodeCompleteUsing(Scope *S) {
3476 if (!CodeCompleter)
3477 return;
3479 ResultBuilder Results(*this,
3480 CodeCompletionContext::CCC_PotentiallyQualifiedName,
3481 &ResultBuilder::IsNestedNameSpecifier);
3482 Results.EnterNewScope();
3484 // If we aren't in class scope, we could see the "namespace" keyword.
3485 if (!S->isClassScope())
3486 Results.AddResult(CodeCompletionResult("namespace"));
3488 // After "using", we can see anything that would start a
3489 // nested-name-specifier.
3490 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3491 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3492 CodeCompleter->includeGlobals());
3493 Results.ExitScope();
3495 HandleCodeCompleteResults(this, CodeCompleter,
3496 CodeCompletionContext::CCC_PotentiallyQualifiedName,
3497 Results.data(),Results.size());
3500 void Sema::CodeCompleteUsingDirective(Scope *S) {
3501 if (!CodeCompleter)
3502 return;
3504 // After "using namespace", we expect to see a namespace name or namespace
3505 // alias.
3506 ResultBuilder Results(*this, CodeCompletionContext::CCC_Namespace,
3507 &ResultBuilder::IsNamespaceOrAlias);
3508 Results.EnterNewScope();
3509 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3510 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3511 CodeCompleter->includeGlobals());
3512 Results.ExitScope();
3513 HandleCodeCompleteResults(this, CodeCompleter,
3514 CodeCompletionContext::CCC_Namespace,
3515 Results.data(),Results.size());
3518 void Sema::CodeCompleteNamespaceDecl(Scope *S) {
3519 if (!CodeCompleter)
3520 return;
3522 DeclContext *Ctx = (DeclContext *)S->getEntity();
3523 if (!S->getParent())
3524 Ctx = Context.getTranslationUnitDecl();
3526 bool SuppressedGlobalResults
3527 = Ctx && !CodeCompleter->includeGlobals() && isa<TranslationUnitDecl>(Ctx);
3529 ResultBuilder Results(*this,
3530 SuppressedGlobalResults
3531 ? CodeCompletionContext::CCC_Namespace
3532 : CodeCompletionContext::CCC_Other,
3533 &ResultBuilder::IsNamespace);
3535 if (Ctx && Ctx->isFileContext() && !SuppressedGlobalResults) {
3536 // We only want to see those namespaces that have already been defined
3537 // within this scope, because its likely that the user is creating an
3538 // extended namespace declaration. Keep track of the most recent
3539 // definition of each namespace.
3540 std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest;
3541 for (DeclContext::specific_decl_iterator<NamespaceDecl>
3542 NS(Ctx->decls_begin()), NSEnd(Ctx->decls_end());
3543 NS != NSEnd; ++NS)
3544 OrigToLatest[NS->getOriginalNamespace()] = *NS;
3546 // Add the most recent definition (or extended definition) of each
3547 // namespace to the list of results.
3548 Results.EnterNewScope();
3549 for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator
3550 NS = OrigToLatest.begin(), NSEnd = OrigToLatest.end();
3551 NS != NSEnd; ++NS)
3552 Results.AddResult(CodeCompletionResult(NS->second, 0),
3553 CurContext, 0, false);
3554 Results.ExitScope();
3557 HandleCodeCompleteResults(this, CodeCompleter,
3558 Results.getCompletionContext(),
3559 Results.data(),Results.size());
3562 void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) {
3563 if (!CodeCompleter)
3564 return;
3566 // After "namespace", we expect to see a namespace or alias.
3567 ResultBuilder Results(*this, CodeCompletionContext::CCC_Namespace,
3568 &ResultBuilder::IsNamespaceOrAlias);
3569 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3570 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3571 CodeCompleter->includeGlobals());
3572 HandleCodeCompleteResults(this, CodeCompleter,
3573 Results.getCompletionContext(),
3574 Results.data(),Results.size());
3577 void Sema::CodeCompleteOperatorName(Scope *S) {
3578 if (!CodeCompleter)
3579 return;
3581 typedef CodeCompletionResult Result;
3582 ResultBuilder Results(*this, CodeCompletionContext::CCC_Type,
3583 &ResultBuilder::IsType);
3584 Results.EnterNewScope();
3586 // Add the names of overloadable operators.
3587 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
3588 if (std::strcmp(Spelling, "?")) \
3589 Results.AddResult(Result(Spelling));
3590 #include "clang/Basic/OperatorKinds.def"
3592 // Add any type names visible from the current scope
3593 Results.allowNestedNameSpecifiers();
3594 CodeCompletionDeclConsumer Consumer(Results, CurContext);
3595 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
3596 CodeCompleter->includeGlobals());
3598 // Add any type specifiers
3599 AddTypeSpecifierResults(getLangOptions(), Results);
3600 Results.ExitScope();
3602 HandleCodeCompleteResults(this, CodeCompleter,
3603 CodeCompletionContext::CCC_Type,
3604 Results.data(),Results.size());
3607 void Sema::CodeCompleteConstructorInitializer(Decl *ConstructorD,
3608 CXXBaseOrMemberInitializer** Initializers,
3609 unsigned NumInitializers) {
3610 CXXConstructorDecl *Constructor
3611 = static_cast<CXXConstructorDecl *>(ConstructorD);
3612 if (!Constructor)
3613 return;
3615 ResultBuilder Results(*this,
3616 CodeCompletionContext::CCC_PotentiallyQualifiedName);
3617 Results.EnterNewScope();
3619 // Fill in any already-initialized fields or base classes.
3620 llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields;
3621 llvm::SmallPtrSet<CanQualType, 4> InitializedBases;
3622 for (unsigned I = 0; I != NumInitializers; ++I) {
3623 if (Initializers[I]->isBaseInitializer())
3624 InitializedBases.insert(
3625 Context.getCanonicalType(QualType(Initializers[I]->getBaseClass(), 0)));
3626 else
3627 InitializedFields.insert(cast<FieldDecl>(
3628 Initializers[I]->getAnyMember()));
3631 // Add completions for base classes.
3632 bool SawLastInitializer = (NumInitializers == 0);
3633 CXXRecordDecl *ClassDecl = Constructor->getParent();
3634 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3635 BaseEnd = ClassDecl->bases_end();
3636 Base != BaseEnd; ++Base) {
3637 if (!InitializedBases.insert(Context.getCanonicalType(Base->getType()))) {
3638 SawLastInitializer
3639 = NumInitializers > 0 &&
3640 Initializers[NumInitializers - 1]->isBaseInitializer() &&
3641 Context.hasSameUnqualifiedType(Base->getType(),
3642 QualType(Initializers[NumInitializers - 1]->getBaseClass(), 0));
3643 continue;
3646 CodeCompletionString *Pattern = new CodeCompletionString;
3647 Pattern->AddTypedTextChunk(
3648 Base->getType().getAsString(Context.PrintingPolicy));
3649 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
3650 Pattern->AddPlaceholderChunk("args");
3651 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
3652 Results.AddResult(CodeCompletionResult(Pattern,
3653 SawLastInitializer? CCP_NextInitializer
3654 : CCP_MemberDeclaration));
3655 SawLastInitializer = false;
3658 // Add completions for virtual base classes.
3659 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
3660 BaseEnd = ClassDecl->vbases_end();
3661 Base != BaseEnd; ++Base) {
3662 if (!InitializedBases.insert(Context.getCanonicalType(Base->getType()))) {
3663 SawLastInitializer
3664 = NumInitializers > 0 &&
3665 Initializers[NumInitializers - 1]->isBaseInitializer() &&
3666 Context.hasSameUnqualifiedType(Base->getType(),
3667 QualType(Initializers[NumInitializers - 1]->getBaseClass(), 0));
3668 continue;
3671 CodeCompletionString *Pattern = new CodeCompletionString;
3672 Pattern->AddTypedTextChunk(
3673 Base->getType().getAsString(Context.PrintingPolicy));
3674 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
3675 Pattern->AddPlaceholderChunk("args");
3676 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
3677 Results.AddResult(CodeCompletionResult(Pattern,
3678 SawLastInitializer? CCP_NextInitializer
3679 : CCP_MemberDeclaration));
3680 SawLastInitializer = false;
3683 // Add completions for members.
3684 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
3685 FieldEnd = ClassDecl->field_end();
3686 Field != FieldEnd; ++Field) {
3687 if (!InitializedFields.insert(cast<FieldDecl>(Field->getCanonicalDecl()))) {
3688 SawLastInitializer
3689 = NumInitializers > 0 &&
3690 Initializers[NumInitializers - 1]->isAnyMemberInitializer() &&
3691 Initializers[NumInitializers - 1]->getAnyMember() == *Field;
3692 continue;
3695 if (!Field->getDeclName())
3696 continue;
3698 CodeCompletionString *Pattern = new CodeCompletionString;
3699 Pattern->AddTypedTextChunk(Field->getIdentifier()->getName());
3700 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
3701 Pattern->AddPlaceholderChunk("args");
3702 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
3703 Results.AddResult(CodeCompletionResult(Pattern,
3704 SawLastInitializer? CCP_NextInitializer
3705 : CCP_MemberDeclaration,
3706 CXCursor_MemberRef));
3707 SawLastInitializer = false;
3709 Results.ExitScope();
3711 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
3712 Results.data(), Results.size());
3715 // Macro that expands to @Keyword or Keyword, depending on whether NeedAt is
3716 // true or false.
3717 #define OBJC_AT_KEYWORD_NAME(NeedAt,Keyword) NeedAt? "@" #Keyword : #Keyword
3718 static void AddObjCImplementationResults(const LangOptions &LangOpts,
3719 ResultBuilder &Results,
3720 bool NeedAt) {
3721 typedef CodeCompletionResult Result;
3722 // Since we have an implementation, we can end it.
3723 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,end)));
3725 CodeCompletionString *Pattern = 0;
3726 if (LangOpts.ObjC2) {
3727 // @dynamic
3728 Pattern = new CodeCompletionString;
3729 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,dynamic));
3730 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
3731 Pattern->AddPlaceholderChunk("property");
3732 Results.AddResult(Result(Pattern));
3734 // @synthesize
3735 Pattern = new CodeCompletionString;
3736 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,synthesize));
3737 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
3738 Pattern->AddPlaceholderChunk("property");
3739 Results.AddResult(Result(Pattern));
3743 static void AddObjCInterfaceResults(const LangOptions &LangOpts,
3744 ResultBuilder &Results,
3745 bool NeedAt) {
3746 typedef CodeCompletionResult Result;
3748 // Since we have an interface or protocol, we can end it.
3749 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,end)));
3751 if (LangOpts.ObjC2) {
3752 // @property
3753 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,property)));
3755 // @required
3756 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,required)));
3758 // @optional
3759 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,optional)));
3763 static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt) {
3764 typedef CodeCompletionResult Result;
3765 CodeCompletionString *Pattern = 0;
3767 // @class name ;
3768 Pattern = new CodeCompletionString;
3769 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,class));
3770 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
3771 Pattern->AddPlaceholderChunk("name");
3772 Results.AddResult(Result(Pattern));
3774 if (Results.includeCodePatterns()) {
3775 // @interface name
3776 // FIXME: Could introduce the whole pattern, including superclasses and
3777 // such.
3778 Pattern = new CodeCompletionString;
3779 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,interface));
3780 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
3781 Pattern->AddPlaceholderChunk("class");
3782 Results.AddResult(Result(Pattern));
3784 // @protocol name
3785 Pattern = new CodeCompletionString;
3786 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,protocol));
3787 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
3788 Pattern->AddPlaceholderChunk("protocol");
3789 Results.AddResult(Result(Pattern));
3791 // @implementation name
3792 Pattern = new CodeCompletionString;
3793 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,implementation));
3794 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
3795 Pattern->AddPlaceholderChunk("class");
3796 Results.AddResult(Result(Pattern));
3799 // @compatibility_alias name
3800 Pattern = new CodeCompletionString;
3801 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,compatibility_alias));
3802 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
3803 Pattern->AddPlaceholderChunk("alias");
3804 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
3805 Pattern->AddPlaceholderChunk("class");
3806 Results.AddResult(Result(Pattern));
3809 void Sema::CodeCompleteObjCAtDirective(Scope *S, Decl *ObjCImpDecl,
3810 bool InInterface) {
3811 typedef CodeCompletionResult Result;
3812 ResultBuilder Results(*this, CodeCompletionContext::CCC_Other);
3813 Results.EnterNewScope();
3814 if (ObjCImpDecl)
3815 AddObjCImplementationResults(getLangOptions(), Results, false);
3816 else if (InInterface)
3817 AddObjCInterfaceResults(getLangOptions(), Results, false);
3818 else
3819 AddObjCTopLevelResults(Results, false);
3820 Results.ExitScope();
3821 HandleCodeCompleteResults(this, CodeCompleter,
3822 CodeCompletionContext::CCC_Other,
3823 Results.data(),Results.size());
3826 static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt) {
3827 typedef CodeCompletionResult Result;
3828 CodeCompletionString *Pattern = 0;
3830 // @encode ( type-name )
3831 Pattern = new CodeCompletionString;
3832 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,encode));
3833 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
3834 Pattern->AddPlaceholderChunk("type-name");
3835 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
3836 Results.AddResult(Result(Pattern));
3838 // @protocol ( protocol-name )
3839 Pattern = new CodeCompletionString;
3840 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,protocol));
3841 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
3842 Pattern->AddPlaceholderChunk("protocol-name");
3843 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
3844 Results.AddResult(Result(Pattern));
3846 // @selector ( selector )
3847 Pattern = new CodeCompletionString;
3848 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,selector));
3849 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
3850 Pattern->AddPlaceholderChunk("selector");
3851 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
3852 Results.AddResult(Result(Pattern));
3855 static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt) {
3856 typedef CodeCompletionResult Result;
3857 CodeCompletionString *Pattern = 0;
3859 if (Results.includeCodePatterns()) {
3860 // @try { statements } @catch ( declaration ) { statements } @finally
3861 // { statements }
3862 Pattern = new CodeCompletionString;
3863 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,try));
3864 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
3865 Pattern->AddPlaceholderChunk("statements");
3866 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
3867 Pattern->AddTextChunk("@catch");
3868 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
3869 Pattern->AddPlaceholderChunk("parameter");
3870 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
3871 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
3872 Pattern->AddPlaceholderChunk("statements");
3873 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
3874 Pattern->AddTextChunk("@finally");
3875 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
3876 Pattern->AddPlaceholderChunk("statements");
3877 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
3878 Results.AddResult(Result(Pattern));
3881 // @throw
3882 Pattern = new CodeCompletionString;
3883 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,throw));
3884 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
3885 Pattern->AddPlaceholderChunk("expression");
3886 Results.AddResult(Result(Pattern));
3888 if (Results.includeCodePatterns()) {
3889 // @synchronized ( expression ) { statements }
3890 Pattern = new CodeCompletionString;
3891 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,synchronized));
3892 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
3893 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
3894 Pattern->AddPlaceholderChunk("expression");
3895 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
3896 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
3897 Pattern->AddPlaceholderChunk("statements");
3898 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
3899 Results.AddResult(Result(Pattern));
3903 static void AddObjCVisibilityResults(const LangOptions &LangOpts,
3904 ResultBuilder &Results,
3905 bool NeedAt) {
3906 typedef CodeCompletionResult Result;
3907 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,private)));
3908 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,protected)));
3909 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,public)));
3910 if (LangOpts.ObjC2)
3911 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,package)));
3914 void Sema::CodeCompleteObjCAtVisibility(Scope *S) {
3915 ResultBuilder Results(*this, CodeCompletionContext::CCC_Other);
3916 Results.EnterNewScope();
3917 AddObjCVisibilityResults(getLangOptions(), Results, false);
3918 Results.ExitScope();
3919 HandleCodeCompleteResults(this, CodeCompleter,
3920 CodeCompletionContext::CCC_Other,
3921 Results.data(),Results.size());
3924 void Sema::CodeCompleteObjCAtStatement(Scope *S) {
3925 ResultBuilder Results(*this, CodeCompletionContext::CCC_Other);
3926 Results.EnterNewScope();
3927 AddObjCStatementResults(Results, false);
3928 AddObjCExpressionResults(Results, false);
3929 Results.ExitScope();
3930 HandleCodeCompleteResults(this, CodeCompleter,
3931 CodeCompletionContext::CCC_Other,
3932 Results.data(),Results.size());
3935 void Sema::CodeCompleteObjCAtExpression(Scope *S) {
3936 ResultBuilder Results(*this, CodeCompletionContext::CCC_Other);
3937 Results.EnterNewScope();
3938 AddObjCExpressionResults(Results, false);
3939 Results.ExitScope();
3940 HandleCodeCompleteResults(this, CodeCompleter,
3941 CodeCompletionContext::CCC_Other,
3942 Results.data(),Results.size());
3945 /// \brief Determine whether the addition of the given flag to an Objective-C
3946 /// property's attributes will cause a conflict.
3947 static bool ObjCPropertyFlagConflicts(unsigned Attributes, unsigned NewFlag) {
3948 // Check if we've already added this flag.
3949 if (Attributes & NewFlag)
3950 return true;
3952 Attributes |= NewFlag;
3954 // Check for collisions with "readonly".
3955 if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
3956 (Attributes & (ObjCDeclSpec::DQ_PR_readwrite |
3957 ObjCDeclSpec::DQ_PR_assign |
3958 ObjCDeclSpec::DQ_PR_copy |
3959 ObjCDeclSpec::DQ_PR_retain)))
3960 return true;
3962 // Check for more than one of { assign, copy, retain }.
3963 unsigned AssignCopyRetMask = Attributes & (ObjCDeclSpec::DQ_PR_assign |
3964 ObjCDeclSpec::DQ_PR_copy |
3965 ObjCDeclSpec::DQ_PR_retain);
3966 if (AssignCopyRetMask &&
3967 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_assign &&
3968 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_copy &&
3969 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_retain)
3970 return true;
3972 return false;
3975 void Sema::CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS) {
3976 if (!CodeCompleter)
3977 return;
3979 unsigned Attributes = ODS.getPropertyAttributes();
3981 typedef CodeCompletionResult Result;
3982 ResultBuilder Results(*this, CodeCompletionContext::CCC_Other);
3983 Results.EnterNewScope();
3984 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readonly))
3985 Results.AddResult(CodeCompletionResult("readonly"));
3986 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_assign))
3987 Results.AddResult(CodeCompletionResult("assign"));
3988 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readwrite))
3989 Results.AddResult(CodeCompletionResult("readwrite"));
3990 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_retain))
3991 Results.AddResult(CodeCompletionResult("retain"));
3992 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_copy))
3993 Results.AddResult(CodeCompletionResult("copy"));
3994 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nonatomic))
3995 Results.AddResult(CodeCompletionResult("nonatomic"));
3996 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_setter)) {
3997 CodeCompletionString *Setter = new CodeCompletionString;
3998 Setter->AddTypedTextChunk("setter");
3999 Setter->AddTextChunk(" = ");
4000 Setter->AddPlaceholderChunk("method");
4001 Results.AddResult(CodeCompletionResult(Setter));
4003 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_getter)) {
4004 CodeCompletionString *Getter = new CodeCompletionString;
4005 Getter->AddTypedTextChunk("getter");
4006 Getter->AddTextChunk(" = ");
4007 Getter->AddPlaceholderChunk("method");
4008 Results.AddResult(CodeCompletionResult(Getter));
4010 Results.ExitScope();
4011 HandleCodeCompleteResults(this, CodeCompleter,
4012 CodeCompletionContext::CCC_Other,
4013 Results.data(),Results.size());
4016 /// \brief Descripts the kind of Objective-C method that we want to find
4017 /// via code completion.
4018 enum ObjCMethodKind {
4019 MK_Any, //< Any kind of method, provided it means other specified criteria.
4020 MK_ZeroArgSelector, //< Zero-argument (unary) selector.
4021 MK_OneArgSelector //< One-argument selector.
4024 static bool isAcceptableObjCSelector(Selector Sel,
4025 ObjCMethodKind WantKind,
4026 IdentifierInfo **SelIdents,
4027 unsigned NumSelIdents,
4028 bool AllowSameLength = true) {
4029 if (NumSelIdents > Sel.getNumArgs())
4030 return false;
4032 switch (WantKind) {
4033 case MK_Any: break;
4034 case MK_ZeroArgSelector: return Sel.isUnarySelector();
4035 case MK_OneArgSelector: return Sel.getNumArgs() == 1;
4038 if (!AllowSameLength && NumSelIdents && NumSelIdents == Sel.getNumArgs())
4039 return false;
4041 for (unsigned I = 0; I != NumSelIdents; ++I)
4042 if (SelIdents[I] != Sel.getIdentifierInfoForSlot(I))
4043 return false;
4045 return true;
4048 static bool isAcceptableObjCMethod(ObjCMethodDecl *Method,
4049 ObjCMethodKind WantKind,
4050 IdentifierInfo **SelIdents,
4051 unsigned NumSelIdents,
4052 bool AllowSameLength = true) {
4053 return isAcceptableObjCSelector(Method->getSelector(), WantKind, SelIdents,
4054 NumSelIdents, AllowSameLength);
4057 namespace {
4058 /// \brief A set of selectors, which is used to avoid introducing multiple
4059 /// completions with the same selector into the result set.
4060 typedef llvm::SmallPtrSet<Selector, 16> VisitedSelectorSet;
4063 /// \brief Add all of the Objective-C methods in the given Objective-C
4064 /// container to the set of results.
4066 /// The container will be a class, protocol, category, or implementation of
4067 /// any of the above. This mether will recurse to include methods from
4068 /// the superclasses of classes along with their categories, protocols, and
4069 /// implementations.
4071 /// \param Container the container in which we'll look to find methods.
4073 /// \param WantInstance whether to add instance methods (only); if false, this
4074 /// routine will add factory methods (only).
4076 /// \param CurContext the context in which we're performing the lookup that
4077 /// finds methods.
4079 /// \param AllowSameLength Whether we allow a method to be added to the list
4080 /// when it has the same number of parameters as we have selector identifiers.
4082 /// \param Results the structure into which we'll add results.
4083 static void AddObjCMethods(ObjCContainerDecl *Container,
4084 bool WantInstanceMethods,
4085 ObjCMethodKind WantKind,
4086 IdentifierInfo **SelIdents,
4087 unsigned NumSelIdents,
4088 DeclContext *CurContext,
4089 VisitedSelectorSet &Selectors,
4090 bool AllowSameLength,
4091 ResultBuilder &Results,
4092 bool InOriginalClass = true) {
4093 typedef CodeCompletionResult Result;
4094 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
4095 MEnd = Container->meth_end();
4096 M != MEnd; ++M) {
4097 if ((*M)->isInstanceMethod() == WantInstanceMethods) {
4098 // Check whether the selector identifiers we've been given are a
4099 // subset of the identifiers for this particular method.
4100 if (!isAcceptableObjCMethod(*M, WantKind, SelIdents, NumSelIdents,
4101 AllowSameLength))
4102 continue;
4104 if (!Selectors.insert((*M)->getSelector()))
4105 continue;
4107 Result R = Result(*M, 0);
4108 R.StartParameter = NumSelIdents;
4109 R.AllParametersAreInformative = (WantKind != MK_Any);
4110 if (!InOriginalClass)
4111 R.Priority += CCD_InBaseClass;
4112 Results.MaybeAddResult(R, CurContext);
4116 // Visit the protocols of protocols.
4117 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4118 const ObjCList<ObjCProtocolDecl> &Protocols
4119 = Protocol->getReferencedProtocols();
4120 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4121 E = Protocols.end();
4122 I != E; ++I)
4123 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, NumSelIdents,
4124 CurContext, Selectors, AllowSameLength, Results, false);
4127 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container);
4128 if (!IFace)
4129 return;
4131 // Add methods in protocols.
4132 const ObjCList<ObjCProtocolDecl> &Protocols= IFace->getReferencedProtocols();
4133 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4134 E = Protocols.end();
4135 I != E; ++I)
4136 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, NumSelIdents,
4137 CurContext, Selectors, AllowSameLength, Results, false);
4139 // Add methods in categories.
4140 for (ObjCCategoryDecl *CatDecl = IFace->getCategoryList(); CatDecl;
4141 CatDecl = CatDecl->getNextClassCategory()) {
4142 AddObjCMethods(CatDecl, WantInstanceMethods, WantKind, SelIdents,
4143 NumSelIdents, CurContext, Selectors, AllowSameLength,
4144 Results, InOriginalClass);
4146 // Add a categories protocol methods.
4147 const ObjCList<ObjCProtocolDecl> &Protocols
4148 = CatDecl->getReferencedProtocols();
4149 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
4150 E = Protocols.end();
4151 I != E; ++I)
4152 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents,
4153 NumSelIdents, CurContext, Selectors, AllowSameLength,
4154 Results, false);
4156 // Add methods in category implementations.
4157 if (ObjCCategoryImplDecl *Impl = CatDecl->getImplementation())
4158 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
4159 NumSelIdents, CurContext, Selectors, AllowSameLength,
4160 Results, InOriginalClass);
4163 // Add methods in superclass.
4164 if (IFace->getSuperClass())
4165 AddObjCMethods(IFace->getSuperClass(), WantInstanceMethods, WantKind,
4166 SelIdents, NumSelIdents, CurContext, Selectors,
4167 AllowSameLength, Results, false);
4169 // Add methods in our implementation, if any.
4170 if (ObjCImplementationDecl *Impl = IFace->getImplementation())
4171 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
4172 NumSelIdents, CurContext, Selectors, AllowSameLength,
4173 Results, InOriginalClass);
4177 void Sema::CodeCompleteObjCPropertyGetter(Scope *S, Decl *ClassDecl,
4178 Decl **Methods,
4179 unsigned NumMethods) {
4180 typedef CodeCompletionResult Result;
4182 // Try to find the interface where getters might live.
4183 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(ClassDecl);
4184 if (!Class) {
4185 if (ObjCCategoryDecl *Category
4186 = dyn_cast_or_null<ObjCCategoryDecl>(ClassDecl))
4187 Class = Category->getClassInterface();
4189 if (!Class)
4190 return;
4193 // Find all of the potential getters.
4194 ResultBuilder Results(*this, CodeCompletionContext::CCC_Other);
4195 Results.EnterNewScope();
4197 // FIXME: We need to do this because Objective-C methods don't get
4198 // pushed into DeclContexts early enough. Argh!
4199 for (unsigned I = 0; I != NumMethods; ++I) {
4200 if (ObjCMethodDecl *Method
4201 = dyn_cast_or_null<ObjCMethodDecl>(Methods[I]))
4202 if (Method->isInstanceMethod() &&
4203 isAcceptableObjCMethod(Method, MK_ZeroArgSelector, 0, 0)) {
4204 Result R = Result(Method, 0);
4205 R.AllParametersAreInformative = true;
4206 Results.MaybeAddResult(R, CurContext);
4210 VisitedSelectorSet Selectors;
4211 AddObjCMethods(Class, true, MK_ZeroArgSelector, 0, 0, CurContext, Selectors,
4212 /*AllowSameLength=*/true, Results);
4213 Results.ExitScope();
4214 HandleCodeCompleteResults(this, CodeCompleter,
4215 CodeCompletionContext::CCC_Other,
4216 Results.data(),Results.size());
4219 void Sema::CodeCompleteObjCPropertySetter(Scope *S, Decl *ObjCImplDecl,
4220 Decl **Methods,
4221 unsigned NumMethods) {
4222 typedef CodeCompletionResult Result;
4224 // Try to find the interface where setters might live.
4225 ObjCInterfaceDecl *Class
4226 = dyn_cast_or_null<ObjCInterfaceDecl>(ObjCImplDecl);
4227 if (!Class) {
4228 if (ObjCCategoryDecl *Category
4229 = dyn_cast_or_null<ObjCCategoryDecl>(ObjCImplDecl))
4230 Class = Category->getClassInterface();
4232 if (!Class)
4233 return;
4236 // Find all of the potential getters.
4237 ResultBuilder Results(*this, CodeCompletionContext::CCC_Other);
4238 Results.EnterNewScope();
4240 // FIXME: We need to do this because Objective-C methods don't get
4241 // pushed into DeclContexts early enough. Argh!
4242 for (unsigned I = 0; I != NumMethods; ++I) {
4243 if (ObjCMethodDecl *Method
4244 = dyn_cast_or_null<ObjCMethodDecl>(Methods[I]))
4245 if (Method->isInstanceMethod() &&
4246 isAcceptableObjCMethod(Method, MK_OneArgSelector, 0, 0)) {
4247 Result R = Result(Method, 0);
4248 R.AllParametersAreInformative = true;
4249 Results.MaybeAddResult(R, CurContext);
4253 VisitedSelectorSet Selectors;
4254 AddObjCMethods(Class, true, MK_OneArgSelector, 0, 0, CurContext,
4255 Selectors, /*AllowSameLength=*/true, Results);
4257 Results.ExitScope();
4258 HandleCodeCompleteResults(this, CodeCompleter,
4259 CodeCompletionContext::CCC_Other,
4260 Results.data(),Results.size());
4263 void Sema::CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS) {
4264 typedef CodeCompletionResult Result;
4265 ResultBuilder Results(*this, CodeCompletionContext::CCC_Type);
4266 Results.EnterNewScope();
4268 // Add context-sensitive, Objective-C parameter-passing keywords.
4269 bool AddedInOut = false;
4270 if ((DS.getObjCDeclQualifier() &
4271 (ObjCDeclSpec::DQ_In | ObjCDeclSpec::DQ_Inout)) == 0) {
4272 Results.AddResult("in");
4273 Results.AddResult("inout");
4274 AddedInOut = true;
4276 if ((DS.getObjCDeclQualifier() &
4277 (ObjCDeclSpec::DQ_Out | ObjCDeclSpec::DQ_Inout)) == 0) {
4278 Results.AddResult("out");
4279 if (!AddedInOut)
4280 Results.AddResult("inout");
4282 if ((DS.getObjCDeclQualifier() &
4283 (ObjCDeclSpec::DQ_Bycopy | ObjCDeclSpec::DQ_Byref |
4284 ObjCDeclSpec::DQ_Oneway)) == 0) {
4285 Results.AddResult("bycopy");
4286 Results.AddResult("byref");
4287 Results.AddResult("oneway");
4290 // Add various builtin type names and specifiers.
4291 AddOrdinaryNameResults(PCC_Type, S, *this, Results);
4292 Results.ExitScope();
4294 // Add the various type names
4295 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
4296 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4297 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4298 CodeCompleter->includeGlobals());
4300 if (CodeCompleter->includeMacros())
4301 AddMacroResults(PP, Results);
4303 HandleCodeCompleteResults(this, CodeCompleter,
4304 CodeCompletionContext::CCC_Type,
4305 Results.data(), Results.size());
4308 /// \brief When we have an expression with type "id", we may assume
4309 /// that it has some more-specific class type based on knowledge of
4310 /// common uses of Objective-C. This routine returns that class type,
4311 /// or NULL if no better result could be determined.
4312 static ObjCInterfaceDecl *GetAssumedMessageSendExprType(Expr *E) {
4313 ObjCMessageExpr *Msg = dyn_cast_or_null<ObjCMessageExpr>(E);
4314 if (!Msg)
4315 return 0;
4317 Selector Sel = Msg->getSelector();
4318 if (Sel.isNull())
4319 return 0;
4321 IdentifierInfo *Id = Sel.getIdentifierInfoForSlot(0);
4322 if (!Id)
4323 return 0;
4325 ObjCMethodDecl *Method = Msg->getMethodDecl();
4326 if (!Method)
4327 return 0;
4329 // Determine the class that we're sending the message to.
4330 ObjCInterfaceDecl *IFace = 0;
4331 switch (Msg->getReceiverKind()) {
4332 case ObjCMessageExpr::Class:
4333 if (const ObjCObjectType *ObjType
4334 = Msg->getClassReceiver()->getAs<ObjCObjectType>())
4335 IFace = ObjType->getInterface();
4336 break;
4338 case ObjCMessageExpr::Instance: {
4339 QualType T = Msg->getInstanceReceiver()->getType();
4340 if (const ObjCObjectPointerType *Ptr = T->getAs<ObjCObjectPointerType>())
4341 IFace = Ptr->getInterfaceDecl();
4342 break;
4345 case ObjCMessageExpr::SuperInstance:
4346 case ObjCMessageExpr::SuperClass:
4347 break;
4350 if (!IFace)
4351 return 0;
4353 ObjCInterfaceDecl *Super = IFace->getSuperClass();
4354 if (Method->isInstanceMethod())
4355 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
4356 .Case("retain", IFace)
4357 .Case("autorelease", IFace)
4358 .Case("copy", IFace)
4359 .Case("copyWithZone", IFace)
4360 .Case("mutableCopy", IFace)
4361 .Case("mutableCopyWithZone", IFace)
4362 .Case("awakeFromCoder", IFace)
4363 .Case("replacementObjectFromCoder", IFace)
4364 .Case("class", IFace)
4365 .Case("classForCoder", IFace)
4366 .Case("superclass", Super)
4367 .Default(0);
4369 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
4370 .Case("new", IFace)
4371 .Case("alloc", IFace)
4372 .Case("allocWithZone", IFace)
4373 .Case("class", IFace)
4374 .Case("superclass", Super)
4375 .Default(0);
4378 // Add a special completion for a message send to "super", which fills in the
4379 // most likely case of forwarding all of our arguments to the superclass
4380 // function.
4382 /// \param S The semantic analysis object.
4384 /// \param S NeedSuperKeyword Whether we need to prefix this completion with
4385 /// the "super" keyword. Otherwise, we just need to provide the arguments.
4387 /// \param SelIdents The identifiers in the selector that have already been
4388 /// provided as arguments for a send to "super".
4390 /// \param NumSelIdents The number of identifiers in \p SelIdents.
4392 /// \param Results The set of results to augment.
4394 /// \returns the Objective-C method declaration that would be invoked by
4395 /// this "super" completion. If NULL, no completion was added.
4396 static ObjCMethodDecl *AddSuperSendCompletion(Sema &S, bool NeedSuperKeyword,
4397 IdentifierInfo **SelIdents,
4398 unsigned NumSelIdents,
4399 ResultBuilder &Results) {
4400 ObjCMethodDecl *CurMethod = S.getCurMethodDecl();
4401 if (!CurMethod)
4402 return 0;
4404 ObjCInterfaceDecl *Class = CurMethod->getClassInterface();
4405 if (!Class)
4406 return 0;
4408 // Try to find a superclass method with the same selector.
4409 ObjCMethodDecl *SuperMethod = 0;
4410 while ((Class = Class->getSuperClass()) && !SuperMethod)
4411 SuperMethod = Class->getMethod(CurMethod->getSelector(),
4412 CurMethod->isInstanceMethod());
4414 if (!SuperMethod)
4415 return 0;
4417 // Check whether the superclass method has the same signature.
4418 if (CurMethod->param_size() != SuperMethod->param_size() ||
4419 CurMethod->isVariadic() != SuperMethod->isVariadic())
4420 return 0;
4422 for (ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin(),
4423 CurPEnd = CurMethod->param_end(),
4424 SuperP = SuperMethod->param_begin();
4425 CurP != CurPEnd; ++CurP, ++SuperP) {
4426 // Make sure the parameter types are compatible.
4427 if (!S.Context.hasSameUnqualifiedType((*CurP)->getType(),
4428 (*SuperP)->getType()))
4429 return 0;
4431 // Make sure we have a parameter name to forward!
4432 if (!(*CurP)->getIdentifier())
4433 return 0;
4436 // We have a superclass method. Now, form the send-to-super completion.
4437 CodeCompletionString *Pattern = new CodeCompletionString;
4439 // Give this completion a return type.
4440 AddResultTypeChunk(S.Context, SuperMethod, Pattern);
4442 // If we need the "super" keyword, add it (plus some spacing).
4443 if (NeedSuperKeyword) {
4444 Pattern->AddTypedTextChunk("super");
4445 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
4448 Selector Sel = CurMethod->getSelector();
4449 if (Sel.isUnarySelector()) {
4450 if (NeedSuperKeyword)
4451 Pattern->AddTextChunk(Sel.getIdentifierInfoForSlot(0)->getName());
4452 else
4453 Pattern->AddTypedTextChunk(Sel.getIdentifierInfoForSlot(0)->getName());
4454 } else {
4455 ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin();
4456 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I, ++CurP) {
4457 if (I > NumSelIdents)
4458 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
4460 if (I < NumSelIdents)
4461 Pattern->AddInformativeChunk(
4462 Sel.getIdentifierInfoForSlot(I)->getName().str() + ":");
4463 else if (NeedSuperKeyword || I > NumSelIdents) {
4464 Pattern->AddTextChunk(
4465 Sel.getIdentifierInfoForSlot(I)->getName().str() + ":");
4466 Pattern->AddPlaceholderChunk((*CurP)->getIdentifier()->getName());
4467 } else {
4468 Pattern->AddTypedTextChunk(
4469 Sel.getIdentifierInfoForSlot(I)->getName().str() + ":");
4470 Pattern->AddPlaceholderChunk((*CurP)->getIdentifier()->getName());
4475 Results.AddResult(CodeCompletionResult(Pattern, CCP_SuperCompletion,
4476 SuperMethod->isInstanceMethod()
4477 ? CXCursor_ObjCInstanceMethodDecl
4478 : CXCursor_ObjCClassMethodDecl));
4479 return SuperMethod;
4482 void Sema::CodeCompleteObjCMessageReceiver(Scope *S) {
4483 typedef CodeCompletionResult Result;
4484 ResultBuilder Results(*this, CodeCompletionContext::CCC_ObjCMessageReceiver,
4485 &ResultBuilder::IsObjCMessageReceiver);
4487 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4488 Results.EnterNewScope();
4489 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4490 CodeCompleter->includeGlobals());
4492 // If we are in an Objective-C method inside a class that has a superclass,
4493 // add "super" as an option.
4494 if (ObjCMethodDecl *Method = getCurMethodDecl())
4495 if (ObjCInterfaceDecl *Iface = Method->getClassInterface())
4496 if (Iface->getSuperClass()) {
4497 Results.AddResult(Result("super"));
4499 AddSuperSendCompletion(*this, /*NeedSuperKeyword=*/true, 0, 0, Results);
4502 Results.ExitScope();
4504 if (CodeCompleter->includeMacros())
4505 AddMacroResults(PP, Results);
4506 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4507 Results.data(), Results.size());
4511 void Sema::CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
4512 IdentifierInfo **SelIdents,
4513 unsigned NumSelIdents,
4514 bool AtArgumentExpression) {
4515 ObjCInterfaceDecl *CDecl = 0;
4516 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
4517 // Figure out which interface we're in.
4518 CDecl = CurMethod->getClassInterface();
4519 if (!CDecl)
4520 return;
4522 // Find the superclass of this class.
4523 CDecl = CDecl->getSuperClass();
4524 if (!CDecl)
4525 return;
4527 if (CurMethod->isInstanceMethod()) {
4528 // We are inside an instance method, which means that the message
4529 // send [super ...] is actually calling an instance method on the
4530 // current object.
4531 return CodeCompleteObjCInstanceMessage(S, 0,
4532 SelIdents, NumSelIdents,
4533 AtArgumentExpression,
4534 CDecl);
4537 // Fall through to send to the superclass in CDecl.
4538 } else {
4539 // "super" may be the name of a type or variable. Figure out which
4540 // it is.
4541 IdentifierInfo *Super = &Context.Idents.get("super");
4542 NamedDecl *ND = LookupSingleName(S, Super, SuperLoc,
4543 LookupOrdinaryName);
4544 if ((CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(ND))) {
4545 // "super" names an interface. Use it.
4546 } else if (TypeDecl *TD = dyn_cast_or_null<TypeDecl>(ND)) {
4547 if (const ObjCObjectType *Iface
4548 = Context.getTypeDeclType(TD)->getAs<ObjCObjectType>())
4549 CDecl = Iface->getInterface();
4550 } else if (ND && isa<UnresolvedUsingTypenameDecl>(ND)) {
4551 // "super" names an unresolved type; we can't be more specific.
4552 } else {
4553 // Assume that "super" names some kind of value and parse that way.
4554 CXXScopeSpec SS;
4555 UnqualifiedId id;
4556 id.setIdentifier(Super, SuperLoc);
4557 ExprResult SuperExpr = ActOnIdExpression(S, SS, id, false, false);
4558 return CodeCompleteObjCInstanceMessage(S, (Expr *)SuperExpr.get(),
4559 SelIdents, NumSelIdents,
4560 AtArgumentExpression);
4563 // Fall through
4566 ParsedType Receiver;
4567 if (CDecl)
4568 Receiver = ParsedType::make(Context.getObjCInterfaceType(CDecl));
4569 return CodeCompleteObjCClassMessage(S, Receiver, SelIdents,
4570 NumSelIdents, AtArgumentExpression,
4571 /*IsSuper=*/true);
4574 /// \brief Given a set of code-completion results for the argument of a message
4575 /// send, determine the preferred type (if any) for that argument expression.
4576 static QualType getPreferredArgumentTypeForMessageSend(ResultBuilder &Results,
4577 unsigned NumSelIdents) {
4578 typedef CodeCompletionResult Result;
4579 ASTContext &Context = Results.getSema().Context;
4581 QualType PreferredType;
4582 unsigned BestPriority = CCP_Unlikely * 2;
4583 Result *ResultsData = Results.data();
4584 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
4585 Result &R = ResultsData[I];
4586 if (R.Kind == Result::RK_Declaration &&
4587 isa<ObjCMethodDecl>(R.Declaration)) {
4588 if (R.Priority <= BestPriority) {
4589 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(R.Declaration);
4590 if (NumSelIdents <= Method->param_size()) {
4591 QualType MyPreferredType = Method->param_begin()[NumSelIdents - 1]
4592 ->getType();
4593 if (R.Priority < BestPriority || PreferredType.isNull()) {
4594 BestPriority = R.Priority;
4595 PreferredType = MyPreferredType;
4596 } else if (!Context.hasSameUnqualifiedType(PreferredType,
4597 MyPreferredType)) {
4598 PreferredType = QualType();
4605 return PreferredType;
4608 static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
4609 ParsedType Receiver,
4610 IdentifierInfo **SelIdents,
4611 unsigned NumSelIdents,
4612 bool AtArgumentExpression,
4613 bool IsSuper,
4614 ResultBuilder &Results) {
4615 typedef CodeCompletionResult Result;
4616 ObjCInterfaceDecl *CDecl = 0;
4618 // If the given name refers to an interface type, retrieve the
4619 // corresponding declaration.
4620 if (Receiver) {
4621 QualType T = SemaRef.GetTypeFromParser(Receiver, 0);
4622 if (!T.isNull())
4623 if (const ObjCObjectType *Interface = T->getAs<ObjCObjectType>())
4624 CDecl = Interface->getInterface();
4627 // Add all of the factory methods in this Objective-C class, its protocols,
4628 // superclasses, categories, implementation, etc.
4629 Results.EnterNewScope();
4631 // If this is a send-to-super, try to add the special "super" send
4632 // completion.
4633 if (IsSuper) {
4634 if (ObjCMethodDecl *SuperMethod
4635 = AddSuperSendCompletion(SemaRef, false, SelIdents, NumSelIdents,
4636 Results))
4637 Results.Ignore(SuperMethod);
4640 // If we're inside an Objective-C method definition, prefer its selector to
4641 // others.
4642 if (ObjCMethodDecl *CurMethod = SemaRef.getCurMethodDecl())
4643 Results.setPreferredSelector(CurMethod->getSelector());
4645 VisitedSelectorSet Selectors;
4646 if (CDecl)
4647 AddObjCMethods(CDecl, false, MK_Any, SelIdents, NumSelIdents,
4648 SemaRef.CurContext, Selectors, AtArgumentExpression,
4649 Results);
4650 else {
4651 // We're messaging "id" as a type; provide all class/factory methods.
4653 // If we have an external source, load the entire class method
4654 // pool from the AST file.
4655 if (SemaRef.ExternalSource) {
4656 for (uint32_t I = 0,
4657 N = SemaRef.ExternalSource->GetNumExternalSelectors();
4658 I != N; ++I) {
4659 Selector Sel = SemaRef.ExternalSource->GetExternalSelector(I);
4660 if (Sel.isNull() || SemaRef.MethodPool.count(Sel))
4661 continue;
4663 SemaRef.ReadMethodPool(Sel);
4667 for (Sema::GlobalMethodPool::iterator M = SemaRef.MethodPool.begin(),
4668 MEnd = SemaRef.MethodPool.end();
4669 M != MEnd; ++M) {
4670 for (ObjCMethodList *MethList = &M->second.second;
4671 MethList && MethList->Method;
4672 MethList = MethList->Next) {
4673 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
4674 NumSelIdents))
4675 continue;
4677 Result R(MethList->Method, 0);
4678 R.StartParameter = NumSelIdents;
4679 R.AllParametersAreInformative = false;
4680 Results.MaybeAddResult(R, SemaRef.CurContext);
4685 Results.ExitScope();
4688 void Sema::CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
4689 IdentifierInfo **SelIdents,
4690 unsigned NumSelIdents,
4691 bool AtArgumentExpression,
4692 bool IsSuper) {
4693 ResultBuilder Results(*this, CodeCompletionContext::CCC_Other);
4694 AddClassMessageCompletions(*this, S, Receiver, SelIdents, NumSelIdents,
4695 AtArgumentExpression, IsSuper, Results);
4697 // If we're actually at the argument expression (rather than prior to the
4698 // selector), we're actually performing code completion for an expression.
4699 // Determine whether we have a single, best method. If so, we can
4700 // code-complete the expression using the corresponding parameter type as
4701 // our preferred type, improving completion results.
4702 if (AtArgumentExpression) {
4703 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results,
4704 NumSelIdents);
4705 if (PreferredType.isNull())
4706 CodeCompleteOrdinaryName(S, PCC_Expression);
4707 else
4708 CodeCompleteExpression(S, PreferredType);
4709 return;
4712 HandleCodeCompleteResults(this, CodeCompleter,
4713 CodeCompletionContext::CCC_Other,
4714 Results.data(), Results.size());
4717 void Sema::CodeCompleteObjCInstanceMessage(Scope *S, ExprTy *Receiver,
4718 IdentifierInfo **SelIdents,
4719 unsigned NumSelIdents,
4720 bool AtArgumentExpression,
4721 ObjCInterfaceDecl *Super) {
4722 typedef CodeCompletionResult Result;
4724 Expr *RecExpr = static_cast<Expr *>(Receiver);
4726 // If necessary, apply function/array conversion to the receiver.
4727 // C99 6.7.5.3p[7,8].
4728 if (RecExpr)
4729 DefaultFunctionArrayLvalueConversion(RecExpr);
4730 QualType ReceiverType = RecExpr? RecExpr->getType()
4731 : Super? Context.getObjCObjectPointerType(
4732 Context.getObjCInterfaceType(Super))
4733 : Context.getObjCIdType();
4735 // If we're messaging an expression with type "id" or "Class", check
4736 // whether we know something special about the receiver that allows
4737 // us to assume a more-specific receiver type.
4738 if (ReceiverType->isObjCIdType() || ReceiverType->isObjCClassType())
4739 if (ObjCInterfaceDecl *IFace = GetAssumedMessageSendExprType(RecExpr)) {
4740 if (ReceiverType->isObjCClassType())
4741 return CodeCompleteObjCClassMessage(S,
4742 ParsedType::make(Context.getObjCInterfaceType(IFace)),
4743 SelIdents, NumSelIdents,
4744 AtArgumentExpression, Super);
4746 ReceiverType = Context.getObjCObjectPointerType(
4747 Context.getObjCInterfaceType(IFace));
4750 // Build the set of methods we can see.
4751 ResultBuilder Results(*this, CodeCompletionContext::CCC_Other);
4752 Results.EnterNewScope();
4754 // If this is a send-to-super, try to add the special "super" send
4755 // completion.
4756 if (Super) {
4757 if (ObjCMethodDecl *SuperMethod
4758 = AddSuperSendCompletion(*this, false, SelIdents, NumSelIdents,
4759 Results))
4760 Results.Ignore(SuperMethod);
4763 // If we're inside an Objective-C method definition, prefer its selector to
4764 // others.
4765 if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
4766 Results.setPreferredSelector(CurMethod->getSelector());
4768 // Keep track of the selectors we've already added.
4769 VisitedSelectorSet Selectors;
4771 // Handle messages to Class. This really isn't a message to an instance
4772 // method, so we treat it the same way we would treat a message send to a
4773 // class method.
4774 if (ReceiverType->isObjCClassType() ||
4775 ReceiverType->isObjCQualifiedClassType()) {
4776 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
4777 if (ObjCInterfaceDecl *ClassDecl = CurMethod->getClassInterface())
4778 AddObjCMethods(ClassDecl, false, MK_Any, SelIdents, NumSelIdents,
4779 CurContext, Selectors, AtArgumentExpression, Results);
4782 // Handle messages to a qualified ID ("id<foo>").
4783 else if (const ObjCObjectPointerType *QualID
4784 = ReceiverType->getAsObjCQualifiedIdType()) {
4785 // Search protocols for instance methods.
4786 for (ObjCObjectPointerType::qual_iterator I = QualID->qual_begin(),
4787 E = QualID->qual_end();
4788 I != E; ++I)
4789 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
4790 Selectors, AtArgumentExpression, Results);
4792 // Handle messages to a pointer to interface type.
4793 else if (const ObjCObjectPointerType *IFacePtr
4794 = ReceiverType->getAsObjCInterfacePointerType()) {
4795 // Search the class, its superclasses, etc., for instance methods.
4796 AddObjCMethods(IFacePtr->getInterfaceDecl(), true, MK_Any, SelIdents,
4797 NumSelIdents, CurContext, Selectors, AtArgumentExpression,
4798 Results);
4800 // Search protocols for instance methods.
4801 for (ObjCObjectPointerType::qual_iterator I = IFacePtr->qual_begin(),
4802 E = IFacePtr->qual_end();
4803 I != E; ++I)
4804 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
4805 Selectors, AtArgumentExpression, Results);
4807 // Handle messages to "id".
4808 else if (ReceiverType->isObjCIdType()) {
4809 // We're messaging "id", so provide all instance methods we know
4810 // about as code-completion results.
4812 // If we have an external source, load the entire class method
4813 // pool from the AST file.
4814 if (ExternalSource) {
4815 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
4816 I != N; ++I) {
4817 Selector Sel = ExternalSource->GetExternalSelector(I);
4818 if (Sel.isNull() || MethodPool.count(Sel))
4819 continue;
4821 ReadMethodPool(Sel);
4825 for (GlobalMethodPool::iterator M = MethodPool.begin(),
4826 MEnd = MethodPool.end();
4827 M != MEnd; ++M) {
4828 for (ObjCMethodList *MethList = &M->second.first;
4829 MethList && MethList->Method;
4830 MethList = MethList->Next) {
4831 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
4832 NumSelIdents))
4833 continue;
4835 if (!Selectors.insert(MethList->Method->getSelector()))
4836 continue;
4838 Result R(MethList->Method, 0);
4839 R.StartParameter = NumSelIdents;
4840 R.AllParametersAreInformative = false;
4841 Results.MaybeAddResult(R, CurContext);
4845 Results.ExitScope();
4848 // If we're actually at the argument expression (rather than prior to the
4849 // selector), we're actually performing code completion for an expression.
4850 // Determine whether we have a single, best method. If so, we can
4851 // code-complete the expression using the corresponding parameter type as
4852 // our preferred type, improving completion results.
4853 if (AtArgumentExpression) {
4854 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results,
4855 NumSelIdents);
4856 if (PreferredType.isNull())
4857 CodeCompleteOrdinaryName(S, PCC_Expression);
4858 else
4859 CodeCompleteExpression(S, PreferredType);
4860 return;
4863 HandleCodeCompleteResults(this, CodeCompleter,
4864 CodeCompletionContext::CCC_Other,
4865 Results.data(),Results.size());
4868 void Sema::CodeCompleteObjCForCollection(Scope *S,
4869 DeclGroupPtrTy IterationVar) {
4870 CodeCompleteExpressionData Data;
4871 Data.ObjCCollection = true;
4873 if (IterationVar.getAsOpaquePtr()) {
4874 DeclGroupRef DG = IterationVar.getAsVal<DeclGroupRef>();
4875 for (DeclGroupRef::iterator I = DG.begin(), End = DG.end(); I != End; ++I) {
4876 if (*I)
4877 Data.IgnoreDecls.push_back(*I);
4881 CodeCompleteExpression(S, Data);
4884 void Sema::CodeCompleteObjCSelector(Scope *S, IdentifierInfo **SelIdents,
4885 unsigned NumSelIdents) {
4886 // If we have an external source, load the entire class method
4887 // pool from the AST file.
4888 if (ExternalSource) {
4889 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
4890 I != N; ++I) {
4891 Selector Sel = ExternalSource->GetExternalSelector(I);
4892 if (Sel.isNull() || MethodPool.count(Sel))
4893 continue;
4895 ReadMethodPool(Sel);
4899 ResultBuilder Results(*this, CodeCompletionContext::CCC_SelectorName);
4900 Results.EnterNewScope();
4901 for (GlobalMethodPool::iterator M = MethodPool.begin(),
4902 MEnd = MethodPool.end();
4903 M != MEnd; ++M) {
4905 Selector Sel = M->first;
4906 if (!isAcceptableObjCSelector(Sel, MK_Any, SelIdents, NumSelIdents))
4907 continue;
4909 CodeCompletionString *Pattern = new CodeCompletionString;
4910 if (Sel.isUnarySelector()) {
4911 Pattern->AddTypedTextChunk(Sel.getIdentifierInfoForSlot(0)->getName());
4912 Results.AddResult(Pattern);
4913 continue;
4916 std::string Accumulator;
4917 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I) {
4918 if (I == NumSelIdents) {
4919 if (!Accumulator.empty()) {
4920 Pattern->AddInformativeChunk(Accumulator);
4921 Accumulator.clear();
4925 Accumulator += Sel.getIdentifierInfoForSlot(I)->getName().str();
4926 Accumulator += ':';
4928 Pattern->AddTypedTextChunk(Accumulator);
4929 Results.AddResult(Pattern);
4931 Results.ExitScope();
4933 HandleCodeCompleteResults(this, CodeCompleter,
4934 CodeCompletionContext::CCC_SelectorName,
4935 Results.data(), Results.size());
4938 /// \brief Add all of the protocol declarations that we find in the given
4939 /// (translation unit) context.
4940 static void AddProtocolResults(DeclContext *Ctx, DeclContext *CurContext,
4941 bool OnlyForwardDeclarations,
4942 ResultBuilder &Results) {
4943 typedef CodeCompletionResult Result;
4945 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
4946 DEnd = Ctx->decls_end();
4947 D != DEnd; ++D) {
4948 // Record any protocols we find.
4949 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*D))
4950 if (!OnlyForwardDeclarations || Proto->isForwardDecl())
4951 Results.AddResult(Result(Proto, 0), CurContext, 0, false);
4953 // Record any forward-declared protocols we find.
4954 if (ObjCForwardProtocolDecl *Forward
4955 = dyn_cast<ObjCForwardProtocolDecl>(*D)) {
4956 for (ObjCForwardProtocolDecl::protocol_iterator
4957 P = Forward->protocol_begin(),
4958 PEnd = Forward->protocol_end();
4959 P != PEnd; ++P)
4960 if (!OnlyForwardDeclarations || (*P)->isForwardDecl())
4961 Results.AddResult(Result(*P, 0), CurContext, 0, false);
4966 void Sema::CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols,
4967 unsigned NumProtocols) {
4968 ResultBuilder Results(*this, CodeCompletionContext::CCC_ObjCProtocolName);
4970 if (CodeCompleter && CodeCompleter->includeGlobals()) {
4971 Results.EnterNewScope();
4973 // Tell the result set to ignore all of the protocols we have
4974 // already seen.
4975 // FIXME: This doesn't work when caching code-completion results.
4976 for (unsigned I = 0; I != NumProtocols; ++I)
4977 if (ObjCProtocolDecl *Protocol = LookupProtocol(Protocols[I].first,
4978 Protocols[I].second))
4979 Results.Ignore(Protocol);
4981 // Add all protocols.
4982 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, false,
4983 Results);
4985 Results.ExitScope();
4988 HandleCodeCompleteResults(this, CodeCompleter,
4989 CodeCompletionContext::CCC_ObjCProtocolName,
4990 Results.data(),Results.size());
4993 void Sema::CodeCompleteObjCProtocolDecl(Scope *) {
4994 ResultBuilder Results(*this, CodeCompletionContext::CCC_ObjCProtocolName);
4996 if (CodeCompleter && CodeCompleter->includeGlobals()) {
4997 Results.EnterNewScope();
4999 // Add all protocols.
5000 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, true,
5001 Results);
5003 Results.ExitScope();
5006 HandleCodeCompleteResults(this, CodeCompleter,
5007 CodeCompletionContext::CCC_ObjCProtocolName,
5008 Results.data(),Results.size());
5011 /// \brief Add all of the Objective-C interface declarations that we find in
5012 /// the given (translation unit) context.
5013 static void AddInterfaceResults(DeclContext *Ctx, DeclContext *CurContext,
5014 bool OnlyForwardDeclarations,
5015 bool OnlyUnimplemented,
5016 ResultBuilder &Results) {
5017 typedef CodeCompletionResult Result;
5019 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
5020 DEnd = Ctx->decls_end();
5021 D != DEnd; ++D) {
5022 // Record any interfaces we find.
5023 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*D))
5024 if ((!OnlyForwardDeclarations || Class->isForwardDecl()) &&
5025 (!OnlyUnimplemented || !Class->getImplementation()))
5026 Results.AddResult(Result(Class, 0), CurContext, 0, false);
5028 // Record any forward-declared interfaces we find.
5029 if (ObjCClassDecl *Forward = dyn_cast<ObjCClassDecl>(*D)) {
5030 for (ObjCClassDecl::iterator C = Forward->begin(), CEnd = Forward->end();
5031 C != CEnd; ++C)
5032 if ((!OnlyForwardDeclarations || C->getInterface()->isForwardDecl()) &&
5033 (!OnlyUnimplemented || !C->getInterface()->getImplementation()))
5034 Results.AddResult(Result(C->getInterface(), 0), CurContext,
5035 0, false);
5040 void Sema::CodeCompleteObjCInterfaceDecl(Scope *S) {
5041 ResultBuilder Results(*this, CodeCompletionContext::CCC_Other);
5042 Results.EnterNewScope();
5044 // Add all classes.
5045 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, true,
5046 false, Results);
5048 Results.ExitScope();
5049 // FIXME: Add a special context for this, use cached global completion
5050 // results.
5051 HandleCodeCompleteResults(this, CodeCompleter,
5052 CodeCompletionContext::CCC_Other,
5053 Results.data(),Results.size());
5056 void Sema::CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName,
5057 SourceLocation ClassNameLoc) {
5058 ResultBuilder Results(*this, CodeCompletionContext::CCC_Other);
5059 Results.EnterNewScope();
5061 // Make sure that we ignore the class we're currently defining.
5062 NamedDecl *CurClass
5063 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
5064 if (CurClass && isa<ObjCInterfaceDecl>(CurClass))
5065 Results.Ignore(CurClass);
5067 // Add all classes.
5068 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
5069 false, Results);
5071 Results.ExitScope();
5072 // FIXME: Add a special context for this, use cached global completion
5073 // results.
5074 HandleCodeCompleteResults(this, CodeCompleter,
5075 CodeCompletionContext::CCC_Other,
5076 Results.data(),Results.size());
5079 void Sema::CodeCompleteObjCImplementationDecl(Scope *S) {
5080 ResultBuilder Results(*this, CodeCompletionContext::CCC_Other);
5081 Results.EnterNewScope();
5083 // Add all unimplemented classes.
5084 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
5085 true, Results);
5087 Results.ExitScope();
5088 // FIXME: Add a special context for this, use cached global completion
5089 // results.
5090 HandleCodeCompleteResults(this, CodeCompleter,
5091 CodeCompletionContext::CCC_Other,
5092 Results.data(),Results.size());
5095 void Sema::CodeCompleteObjCInterfaceCategory(Scope *S,
5096 IdentifierInfo *ClassName,
5097 SourceLocation ClassNameLoc) {
5098 typedef CodeCompletionResult Result;
5100 ResultBuilder Results(*this, CodeCompletionContext::CCC_Other);
5102 // Ignore any categories we find that have already been implemented by this
5103 // interface.
5104 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
5105 NamedDecl *CurClass
5106 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
5107 if (ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass))
5108 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
5109 Category = Category->getNextClassCategory())
5110 CategoryNames.insert(Category->getIdentifier());
5112 // Add all of the categories we know about.
5113 Results.EnterNewScope();
5114 TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
5115 for (DeclContext::decl_iterator D = TU->decls_begin(),
5116 DEnd = TU->decls_end();
5117 D != DEnd; ++D)
5118 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(*D))
5119 if (CategoryNames.insert(Category->getIdentifier()))
5120 Results.AddResult(Result(Category, 0), CurContext, 0, false);
5121 Results.ExitScope();
5123 HandleCodeCompleteResults(this, CodeCompleter,
5124 CodeCompletionContext::CCC_Other,
5125 Results.data(),Results.size());
5128 void Sema::CodeCompleteObjCImplementationCategory(Scope *S,
5129 IdentifierInfo *ClassName,
5130 SourceLocation ClassNameLoc) {
5131 typedef CodeCompletionResult Result;
5133 // Find the corresponding interface. If we couldn't find the interface, the
5134 // program itself is ill-formed. However, we'll try to be helpful still by
5135 // providing the list of all of the categories we know about.
5136 NamedDecl *CurClass
5137 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
5138 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass);
5139 if (!Class)
5140 return CodeCompleteObjCInterfaceCategory(S, ClassName, ClassNameLoc);
5142 ResultBuilder Results(*this, CodeCompletionContext::CCC_Other);
5144 // Add all of the categories that have have corresponding interface
5145 // declarations in this class and any of its superclasses, except for
5146 // already-implemented categories in the class itself.
5147 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
5148 Results.EnterNewScope();
5149 bool IgnoreImplemented = true;
5150 while (Class) {
5151 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
5152 Category = Category->getNextClassCategory())
5153 if ((!IgnoreImplemented || !Category->getImplementation()) &&
5154 CategoryNames.insert(Category->getIdentifier()))
5155 Results.AddResult(Result(Category, 0), CurContext, 0, false);
5157 Class = Class->getSuperClass();
5158 IgnoreImplemented = false;
5160 Results.ExitScope();
5162 HandleCodeCompleteResults(this, CodeCompleter,
5163 CodeCompletionContext::CCC_Other,
5164 Results.data(),Results.size());
5167 void Sema::CodeCompleteObjCPropertyDefinition(Scope *S, Decl *ObjCImpDecl) {
5168 typedef CodeCompletionResult Result;
5169 ResultBuilder Results(*this, CodeCompletionContext::CCC_Other);
5171 // Figure out where this @synthesize lives.
5172 ObjCContainerDecl *Container
5173 = dyn_cast_or_null<ObjCContainerDecl>(ObjCImpDecl);
5174 if (!Container ||
5175 (!isa<ObjCImplementationDecl>(Container) &&
5176 !isa<ObjCCategoryImplDecl>(Container)))
5177 return;
5179 // Ignore any properties that have already been implemented.
5180 for (DeclContext::decl_iterator D = Container->decls_begin(),
5181 DEnd = Container->decls_end();
5182 D != DEnd; ++D)
5183 if (ObjCPropertyImplDecl *PropertyImpl = dyn_cast<ObjCPropertyImplDecl>(*D))
5184 Results.Ignore(PropertyImpl->getPropertyDecl());
5186 // Add any properties that we find.
5187 AddedPropertiesSet AddedProperties;
5188 Results.EnterNewScope();
5189 if (ObjCImplementationDecl *ClassImpl
5190 = dyn_cast<ObjCImplementationDecl>(Container))
5191 AddObjCProperties(ClassImpl->getClassInterface(), false, CurContext,
5192 AddedProperties, Results);
5193 else
5194 AddObjCProperties(cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl(),
5195 false, CurContext, AddedProperties, Results);
5196 Results.ExitScope();
5198 HandleCodeCompleteResults(this, CodeCompleter,
5199 CodeCompletionContext::CCC_Other,
5200 Results.data(),Results.size());
5203 void Sema::CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
5204 IdentifierInfo *PropertyName,
5205 Decl *ObjCImpDecl) {
5206 typedef CodeCompletionResult Result;
5207 ResultBuilder Results(*this, CodeCompletionContext::CCC_Other);
5209 // Figure out where this @synthesize lives.
5210 ObjCContainerDecl *Container
5211 = dyn_cast_or_null<ObjCContainerDecl>(ObjCImpDecl);
5212 if (!Container ||
5213 (!isa<ObjCImplementationDecl>(Container) &&
5214 !isa<ObjCCategoryImplDecl>(Container)))
5215 return;
5217 // Figure out which interface we're looking into.
5218 ObjCInterfaceDecl *Class = 0;
5219 if (ObjCImplementationDecl *ClassImpl
5220 = dyn_cast<ObjCImplementationDecl>(Container))
5221 Class = ClassImpl->getClassInterface();
5222 else
5223 Class = cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl()
5224 ->getClassInterface();
5226 // Add all of the instance variables in this class and its superclasses.
5227 Results.EnterNewScope();
5228 for(; Class; Class = Class->getSuperClass()) {
5229 // FIXME: We could screen the type of each ivar for compatibility with
5230 // the property, but is that being too paternal?
5231 for (ObjCInterfaceDecl::ivar_iterator IVar = Class->ivar_begin(),
5232 IVarEnd = Class->ivar_end();
5233 IVar != IVarEnd; ++IVar)
5234 Results.AddResult(Result(*IVar, 0), CurContext, 0, false);
5236 Results.ExitScope();
5238 HandleCodeCompleteResults(this, CodeCompleter,
5239 CodeCompletionContext::CCC_Other,
5240 Results.data(),Results.size());
5243 // Mapping from selectors to the methods that implement that selector, along
5244 // with the "in original class" flag.
5245 typedef llvm::DenseMap<Selector, std::pair<ObjCMethodDecl *, bool> >
5246 KnownMethodsMap;
5248 /// \brief Find all of the methods that reside in the given container
5249 /// (and its superclasses, protocols, etc.) that meet the given
5250 /// criteria. Insert those methods into the map of known methods,
5251 /// indexed by selector so they can be easily found.
5252 static void FindImplementableMethods(ASTContext &Context,
5253 ObjCContainerDecl *Container,
5254 bool WantInstanceMethods,
5255 QualType ReturnType,
5256 KnownMethodsMap &KnownMethods,
5257 bool InOriginalClass = true) {
5258 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)) {
5259 // Recurse into protocols.
5260 const ObjCList<ObjCProtocolDecl> &Protocols
5261 = IFace->getReferencedProtocols();
5262 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
5263 E = Protocols.end();
5264 I != E; ++I)
5265 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
5266 KnownMethods, InOriginalClass);
5268 // Add methods from any class extensions and categories.
5269 for (const ObjCCategoryDecl *Cat = IFace->getCategoryList(); Cat;
5270 Cat = Cat->getNextClassCategory())
5271 FindImplementableMethods(Context, const_cast<ObjCCategoryDecl*>(Cat),
5272 WantInstanceMethods, ReturnType,
5273 KnownMethods, false);
5275 // Visit the superclass.
5276 if (IFace->getSuperClass())
5277 FindImplementableMethods(Context, IFace->getSuperClass(),
5278 WantInstanceMethods, ReturnType,
5279 KnownMethods, false);
5282 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
5283 // Recurse into protocols.
5284 const ObjCList<ObjCProtocolDecl> &Protocols
5285 = Category->getReferencedProtocols();
5286 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
5287 E = Protocols.end();
5288 I != E; ++I)
5289 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
5290 KnownMethods, InOriginalClass);
5292 // If this category is the original class, jump to the interface.
5293 if (InOriginalClass && Category->getClassInterface())
5294 FindImplementableMethods(Context, Category->getClassInterface(),
5295 WantInstanceMethods, ReturnType, KnownMethods,
5296 false);
5299 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
5300 // Recurse into protocols.
5301 const ObjCList<ObjCProtocolDecl> &Protocols
5302 = Protocol->getReferencedProtocols();
5303 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
5304 E = Protocols.end();
5305 I != E; ++I)
5306 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
5307 KnownMethods, false);
5310 // Add methods in this container. This operation occurs last because
5311 // we want the methods from this container to override any methods
5312 // we've previously seen with the same selector.
5313 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
5314 MEnd = Container->meth_end();
5315 M != MEnd; ++M) {
5316 if ((*M)->isInstanceMethod() == WantInstanceMethods) {
5317 if (!ReturnType.isNull() &&
5318 !Context.hasSameUnqualifiedType(ReturnType, (*M)->getResultType()))
5319 continue;
5321 KnownMethods[(*M)->getSelector()] = std::make_pair(*M, InOriginalClass);
5326 void Sema::CodeCompleteObjCMethodDecl(Scope *S,
5327 bool IsInstanceMethod,
5328 ParsedType ReturnTy,
5329 Decl *IDecl) {
5330 // Determine the return type of the method we're declaring, if
5331 // provided.
5332 QualType ReturnType = GetTypeFromParser(ReturnTy);
5334 // Determine where we should start searching for methods.
5335 ObjCContainerDecl *SearchDecl = 0;
5336 bool IsInImplementation = false;
5337 if (Decl *D = IDecl) {
5338 if (ObjCImplementationDecl *Impl = dyn_cast<ObjCImplementationDecl>(D)) {
5339 SearchDecl = Impl->getClassInterface();
5340 IsInImplementation = true;
5341 } else if (ObjCCategoryImplDecl *CatImpl
5342 = dyn_cast<ObjCCategoryImplDecl>(D)) {
5343 SearchDecl = CatImpl->getCategoryDecl();
5344 IsInImplementation = true;
5345 } else
5346 SearchDecl = dyn_cast<ObjCContainerDecl>(D);
5349 if (!SearchDecl && S) {
5350 if (DeclContext *DC = static_cast<DeclContext *>(S->getEntity()))
5351 SearchDecl = dyn_cast<ObjCContainerDecl>(DC);
5354 if (!SearchDecl) {
5355 HandleCodeCompleteResults(this, CodeCompleter,
5356 CodeCompletionContext::CCC_Other,
5357 0, 0);
5358 return;
5361 // Find all of the methods that we could declare/implement here.
5362 KnownMethodsMap KnownMethods;
5363 FindImplementableMethods(Context, SearchDecl, IsInstanceMethod,
5364 ReturnType, KnownMethods);
5366 // Add declarations or definitions for each of the known methods.
5367 typedef CodeCompletionResult Result;
5368 ResultBuilder Results(*this, CodeCompletionContext::CCC_Other);
5369 Results.EnterNewScope();
5370 PrintingPolicy Policy(Context.PrintingPolicy);
5371 Policy.AnonymousTagLocations = false;
5372 for (KnownMethodsMap::iterator M = KnownMethods.begin(),
5373 MEnd = KnownMethods.end();
5374 M != MEnd; ++M) {
5375 ObjCMethodDecl *Method = M->second.first;
5376 CodeCompletionString *Pattern = new CodeCompletionString;
5378 // If the result type was not already provided, add it to the
5379 // pattern as (type).
5380 if (ReturnType.isNull()) {
5381 std::string TypeStr;
5382 Method->getResultType().getAsStringInternal(TypeStr, Policy);
5383 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
5384 Pattern->AddTextChunk(TypeStr);
5385 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
5388 Selector Sel = Method->getSelector();
5390 // Add the first part of the selector to the pattern.
5391 Pattern->AddTypedTextChunk(Sel.getIdentifierInfoForSlot(0)->getName());
5393 // Add parameters to the pattern.
5394 unsigned I = 0;
5395 for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
5396 PEnd = Method->param_end();
5397 P != PEnd; (void)++P, ++I) {
5398 // Add the part of the selector name.
5399 if (I == 0)
5400 Pattern->AddTypedTextChunk(":");
5401 else if (I < Sel.getNumArgs()) {
5402 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5403 Pattern->AddTypedTextChunk((Sel.getIdentifierInfoForSlot(I)->getName()
5404 + ":").str());
5405 } else
5406 break;
5408 // Add the parameter type.
5409 std::string TypeStr;
5410 (*P)->getOriginalType().getAsStringInternal(TypeStr, Policy);
5411 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
5412 Pattern->AddTextChunk(TypeStr);
5413 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
5415 if (IdentifierInfo *Id = (*P)->getIdentifier())
5416 Pattern->AddTextChunk(Id->getName());
5419 if (Method->isVariadic()) {
5420 if (Method->param_size() > 0)
5421 Pattern->AddChunk(CodeCompletionString::CK_Comma);
5422 Pattern->AddTextChunk("...");
5425 if (IsInImplementation && Results.includeCodePatterns()) {
5426 // We will be defining the method here, so add a compound statement.
5427 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5428 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
5429 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
5430 if (!Method->getResultType()->isVoidType()) {
5431 // If the result type is not void, add a return clause.
5432 Pattern->AddTextChunk("return");
5433 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5434 Pattern->AddPlaceholderChunk("expression");
5435 Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
5436 } else
5437 Pattern->AddPlaceholderChunk("statements");
5439 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
5440 Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
5443 unsigned Priority = CCP_CodePattern;
5444 if (!M->second.second)
5445 Priority += CCD_InBaseClass;
5447 Results.AddResult(Result(Pattern, Priority,
5448 Method->isInstanceMethod()
5449 ? CXCursor_ObjCInstanceMethodDecl
5450 : CXCursor_ObjCClassMethodDecl));
5453 Results.ExitScope();
5455 HandleCodeCompleteResults(this, CodeCompleter,
5456 CodeCompletionContext::CCC_Other,
5457 Results.data(),Results.size());
5460 void Sema::CodeCompleteObjCMethodDeclSelector(Scope *S,
5461 bool IsInstanceMethod,
5462 bool AtParameterName,
5463 ParsedType ReturnTy,
5464 IdentifierInfo **SelIdents,
5465 unsigned NumSelIdents) {
5466 // If we have an external source, load the entire class method
5467 // pool from the AST file.
5468 if (ExternalSource) {
5469 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
5470 I != N; ++I) {
5471 Selector Sel = ExternalSource->GetExternalSelector(I);
5472 if (Sel.isNull() || MethodPool.count(Sel))
5473 continue;
5475 ReadMethodPool(Sel);
5479 // Build the set of methods we can see.
5480 typedef CodeCompletionResult Result;
5481 ResultBuilder Results(*this, CodeCompletionContext::CCC_Other);
5483 if (ReturnTy)
5484 Results.setPreferredType(GetTypeFromParser(ReturnTy).getNonReferenceType());
5486 Results.EnterNewScope();
5487 for (GlobalMethodPool::iterator M = MethodPool.begin(),
5488 MEnd = MethodPool.end();
5489 M != MEnd; ++M) {
5490 for (ObjCMethodList *MethList = IsInstanceMethod ? &M->second.first :
5491 &M->second.second;
5492 MethList && MethList->Method;
5493 MethList = MethList->Next) {
5494 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
5495 NumSelIdents))
5496 continue;
5498 if (AtParameterName) {
5499 // Suggest parameter names we've seen before.
5500 if (NumSelIdents && NumSelIdents <= MethList->Method->param_size()) {
5501 ParmVarDecl *Param = MethList->Method->param_begin()[NumSelIdents-1];
5502 if (Param->getIdentifier()) {
5503 CodeCompletionString *Pattern = new CodeCompletionString;
5504 Pattern->AddTypedTextChunk(Param->getIdentifier()->getName());
5505 Results.AddResult(Pattern);
5509 continue;
5512 Result R(MethList->Method, 0);
5513 R.StartParameter = NumSelIdents;
5514 R.AllParametersAreInformative = false;
5515 R.DeclaringEntity = true;
5516 Results.MaybeAddResult(R, CurContext);
5520 Results.ExitScope();
5521 HandleCodeCompleteResults(this, CodeCompleter,
5522 CodeCompletionContext::CCC_Other,
5523 Results.data(),Results.size());
5526 void Sema::CodeCompletePreprocessorDirective(bool InConditional) {
5527 ResultBuilder Results(*this,
5528 CodeCompletionContext::CCC_PreprocessorDirective);
5529 Results.EnterNewScope();
5531 // #if <condition>
5532 CodeCompletionString *Pattern = new CodeCompletionString;
5533 Pattern->AddTypedTextChunk("if");
5534 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5535 Pattern->AddPlaceholderChunk("condition");
5536 Results.AddResult(Pattern);
5538 // #ifdef <macro>
5539 Pattern = new CodeCompletionString;
5540 Pattern->AddTypedTextChunk("ifdef");
5541 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5542 Pattern->AddPlaceholderChunk("macro");
5543 Results.AddResult(Pattern);
5545 // #ifndef <macro>
5546 Pattern = new CodeCompletionString;
5547 Pattern->AddTypedTextChunk("ifndef");
5548 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5549 Pattern->AddPlaceholderChunk("macro");
5550 Results.AddResult(Pattern);
5552 if (InConditional) {
5553 // #elif <condition>
5554 Pattern = new CodeCompletionString;
5555 Pattern->AddTypedTextChunk("elif");
5556 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5557 Pattern->AddPlaceholderChunk("condition");
5558 Results.AddResult(Pattern);
5560 // #else
5561 Pattern = new CodeCompletionString;
5562 Pattern->AddTypedTextChunk("else");
5563 Results.AddResult(Pattern);
5565 // #endif
5566 Pattern = new CodeCompletionString;
5567 Pattern->AddTypedTextChunk("endif");
5568 Results.AddResult(Pattern);
5571 // #include "header"
5572 Pattern = new CodeCompletionString;
5573 Pattern->AddTypedTextChunk("include");
5574 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5575 Pattern->AddTextChunk("\"");
5576 Pattern->AddPlaceholderChunk("header");
5577 Pattern->AddTextChunk("\"");
5578 Results.AddResult(Pattern);
5580 // #include <header>
5581 Pattern = new CodeCompletionString;
5582 Pattern->AddTypedTextChunk("include");
5583 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5584 Pattern->AddTextChunk("<");
5585 Pattern->AddPlaceholderChunk("header");
5586 Pattern->AddTextChunk(">");
5587 Results.AddResult(Pattern);
5589 // #define <macro>
5590 Pattern = new CodeCompletionString;
5591 Pattern->AddTypedTextChunk("define");
5592 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5593 Pattern->AddPlaceholderChunk("macro");
5594 Results.AddResult(Pattern);
5596 // #define <macro>(<args>)
5597 Pattern = new CodeCompletionString;
5598 Pattern->AddTypedTextChunk("define");
5599 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5600 Pattern->AddPlaceholderChunk("macro");
5601 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
5602 Pattern->AddPlaceholderChunk("args");
5603 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
5604 Results.AddResult(Pattern);
5606 // #undef <macro>
5607 Pattern = new CodeCompletionString;
5608 Pattern->AddTypedTextChunk("undef");
5609 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5610 Pattern->AddPlaceholderChunk("macro");
5611 Results.AddResult(Pattern);
5613 // #line <number>
5614 Pattern = new CodeCompletionString;
5615 Pattern->AddTypedTextChunk("line");
5616 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5617 Pattern->AddPlaceholderChunk("number");
5618 Results.AddResult(Pattern);
5620 // #line <number> "filename"
5621 Pattern = new CodeCompletionString;
5622 Pattern->AddTypedTextChunk("line");
5623 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5624 Pattern->AddPlaceholderChunk("number");
5625 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5626 Pattern->AddTextChunk("\"");
5627 Pattern->AddPlaceholderChunk("filename");
5628 Pattern->AddTextChunk("\"");
5629 Results.AddResult(Pattern);
5631 // #error <message>
5632 Pattern = new CodeCompletionString;
5633 Pattern->AddTypedTextChunk("error");
5634 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5635 Pattern->AddPlaceholderChunk("message");
5636 Results.AddResult(Pattern);
5638 // #pragma <arguments>
5639 Pattern = new CodeCompletionString;
5640 Pattern->AddTypedTextChunk("pragma");
5641 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5642 Pattern->AddPlaceholderChunk("arguments");
5643 Results.AddResult(Pattern);
5645 if (getLangOptions().ObjC1) {
5646 // #import "header"
5647 Pattern = new CodeCompletionString;
5648 Pattern->AddTypedTextChunk("import");
5649 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5650 Pattern->AddTextChunk("\"");
5651 Pattern->AddPlaceholderChunk("header");
5652 Pattern->AddTextChunk("\"");
5653 Results.AddResult(Pattern);
5655 // #import <header>
5656 Pattern = new CodeCompletionString;
5657 Pattern->AddTypedTextChunk("import");
5658 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5659 Pattern->AddTextChunk("<");
5660 Pattern->AddPlaceholderChunk("header");
5661 Pattern->AddTextChunk(">");
5662 Results.AddResult(Pattern);
5665 // #include_next "header"
5666 Pattern = new CodeCompletionString;
5667 Pattern->AddTypedTextChunk("include_next");
5668 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5669 Pattern->AddTextChunk("\"");
5670 Pattern->AddPlaceholderChunk("header");
5671 Pattern->AddTextChunk("\"");
5672 Results.AddResult(Pattern);
5674 // #include_next <header>
5675 Pattern = new CodeCompletionString;
5676 Pattern->AddTypedTextChunk("include_next");
5677 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5678 Pattern->AddTextChunk("<");
5679 Pattern->AddPlaceholderChunk("header");
5680 Pattern->AddTextChunk(">");
5681 Results.AddResult(Pattern);
5683 // #warning <message>
5684 Pattern = new CodeCompletionString;
5685 Pattern->AddTypedTextChunk("warning");
5686 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5687 Pattern->AddPlaceholderChunk("message");
5688 Results.AddResult(Pattern);
5690 // Note: #ident and #sccs are such crazy anachronisms that we don't provide
5691 // completions for them. And __include_macros is a Clang-internal extension
5692 // that we don't want to encourage anyone to use.
5694 // FIXME: we don't support #assert or #unassert, so don't suggest them.
5695 Results.ExitScope();
5697 HandleCodeCompleteResults(this, CodeCompleter,
5698 CodeCompletionContext::CCC_PreprocessorDirective,
5699 Results.data(), Results.size());
5702 void Sema::CodeCompleteInPreprocessorConditionalExclusion(Scope *S) {
5703 CodeCompleteOrdinaryName(S,
5704 S->getFnParent()? Sema::PCC_RecoveryInFunction
5705 : Sema::PCC_Namespace);
5708 void Sema::CodeCompletePreprocessorMacroName(bool IsDefinition) {
5709 ResultBuilder Results(*this,
5710 IsDefinition? CodeCompletionContext::CCC_MacroName
5711 : CodeCompletionContext::CCC_MacroNameUse);
5712 if (!IsDefinition && (!CodeCompleter || CodeCompleter->includeMacros())) {
5713 // Add just the names of macros, not their arguments.
5714 Results.EnterNewScope();
5715 for (Preprocessor::macro_iterator M = PP.macro_begin(),
5716 MEnd = PP.macro_end();
5717 M != MEnd; ++M) {
5718 CodeCompletionString *Pattern = new CodeCompletionString;
5719 Pattern->AddTypedTextChunk(M->first->getName());
5720 Results.AddResult(Pattern);
5722 Results.ExitScope();
5723 } else if (IsDefinition) {
5724 // FIXME: Can we detect when the user just wrote an include guard above?
5727 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
5728 Results.data(), Results.size());
5731 void Sema::CodeCompletePreprocessorExpression() {
5732 ResultBuilder Results(*this,
5733 CodeCompletionContext::CCC_PreprocessorExpression);
5735 if (!CodeCompleter || CodeCompleter->includeMacros())
5736 AddMacroResults(PP, Results);
5738 // defined (<macro>)
5739 Results.EnterNewScope();
5740 CodeCompletionString *Pattern = new CodeCompletionString;
5741 Pattern->AddTypedTextChunk("defined");
5742 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
5743 Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
5744 Pattern->AddPlaceholderChunk("macro");
5745 Pattern->AddChunk(CodeCompletionString::CK_RightParen);
5746 Results.AddResult(Pattern);
5747 Results.ExitScope();
5749 HandleCodeCompleteResults(this, CodeCompleter,
5750 CodeCompletionContext::CCC_PreprocessorExpression,
5751 Results.data(), Results.size());
5754 void Sema::CodeCompletePreprocessorMacroArgument(Scope *S,
5755 IdentifierInfo *Macro,
5756 MacroInfo *MacroInfo,
5757 unsigned Argument) {
5758 // FIXME: In the future, we could provide "overload" results, much like we
5759 // do for function calls.
5761 CodeCompleteOrdinaryName(S,
5762 S->getFnParent()? Sema::PCC_RecoveryInFunction
5763 : Sema::PCC_Namespace);
5766 void Sema::CodeCompleteNaturalLanguage() {
5767 HandleCodeCompleteResults(this, CodeCompleter,
5768 CodeCompletionContext::CCC_NaturalLanguage,
5769 0, 0);
5772 void Sema::GatherGlobalCodeCompletions(
5773 llvm::SmallVectorImpl<CodeCompletionResult> &Results) {
5774 ResultBuilder Builder(*this, CodeCompletionContext::CCC_Recovery);
5775 if (!CodeCompleter || CodeCompleter->includeGlobals()) {
5776 CodeCompletionDeclConsumer Consumer(Builder,
5777 Context.getTranslationUnitDecl());
5778 LookupVisibleDecls(Context.getTranslationUnitDecl(), LookupAnyName,
5779 Consumer);
5782 if (!CodeCompleter || CodeCompleter->includeMacros())
5783 AddMacroResults(PP, Builder);
5785 Results.clear();
5786 Results.insert(Results.end(),
5787 Builder.data(), Builder.data() + Builder.size());