1 //===---------------- SemaCodeComplete.cpp - Code Completion ----*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the code-completion semantic actions.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Sema/CodeCompleteConsumer.h"
15 #include "clang/AST/ExprCXX.h"
16 #include "llvm/ADT/SmallPtrSet.h"
17 #include "llvm/ADT/StringExtras.h"
22 using namespace clang;
24 /// \brief Set the code-completion consumer for semantic analysis.
25 void Sema::setCodeCompleteConsumer(CodeCompleteConsumer *CCC) {
26 assert(((CodeCompleter != 0) != (CCC != 0)) &&
27 "Already set or cleared a code-completion consumer?");
32 /// \brief A container of code-completion results.
35 /// \brief The type of a name-lookup filter, which can be provided to the
36 /// name-lookup routines to specify which declarations should be included in
37 /// the result set (when it returns true) and which declarations should be
38 /// filtered out (returns false).
39 typedef bool (ResultBuilder::*LookupFilter)(NamedDecl *) const;
41 typedef CodeCompleteConsumer::Result Result;
44 /// \brief The actual results we have found.
45 std::vector<Result> Results;
47 /// \brief A record of all of the declarations we have found and placed
48 /// into the result set, used to ensure that no declaration ever gets into
49 /// the result set twice.
50 llvm::SmallPtrSet<Decl*, 16> AllDeclsFound;
52 /// \brief A mapping from declaration names to the declarations that have
53 /// this name within a particular scope and their index within the list of
55 typedef std::multimap<DeclarationName,
56 std::pair<NamedDecl *, unsigned> > ShadowMap;
58 /// \brief The semantic analysis object for which results are being
62 /// \brief If non-NULL, a filter function used to remove any code-completion
63 /// results that are not desirable.
66 /// \brief A list of shadow maps, which is used to model name hiding at
67 /// different levels of, e.g., the inheritance hierarchy.
68 std::list<ShadowMap> ShadowMaps;
71 explicit ResultBuilder(Sema &SemaRef, LookupFilter Filter = 0)
72 : SemaRef(SemaRef), Filter(Filter) { }
74 /// \brief Set the filter used for code-completion results.
75 void setFilter(LookupFilter Filter) {
76 this->Filter = Filter;
79 typedef std::vector<Result>::iterator iterator;
80 iterator begin() { return Results.begin(); }
81 iterator end() { return Results.end(); }
83 Result *data() { return Results.empty()? 0 : &Results.front(); }
84 unsigned size() const { return Results.size(); }
85 bool empty() const { return Results.empty(); }
87 /// \brief Add a new result to this result set (if it isn't already in one
88 /// of the shadow maps), or replace an existing result (for, e.g., a
91 /// \param R the result to add (if it is unique).
93 /// \param R the context in which this result will be named.
94 void MaybeAddResult(Result R, DeclContext *CurContext = 0);
96 /// \brief Enter into a new scope.
99 /// \brief Exit from the current scope.
102 /// \name Name lookup predicates
104 /// These predicates can be passed to the name lookup functions to filter the
105 /// results of name lookup. All of the predicates have the same type, so that
108 bool IsOrdinaryName(NamedDecl *ND) const;
109 bool IsNestedNameSpecifier(NamedDecl *ND) const;
110 bool IsEnum(NamedDecl *ND) const;
111 bool IsClassOrStruct(NamedDecl *ND) const;
112 bool IsUnion(NamedDecl *ND) const;
113 bool IsNamespace(NamedDecl *ND) const;
114 bool IsNamespaceOrAlias(NamedDecl *ND) const;
115 bool IsType(NamedDecl *ND) const;
116 bool IsMember(NamedDecl *ND) const;
121 /// \brief Determines whether the given hidden result could be found with
122 /// some extra work, e.g., by qualifying the name.
124 /// \param Hidden the declaration that is hidden by the currenly \p Visible
127 /// \param Visible the declaration with the same name that is already visible.
129 /// \returns true if the hidden result can be found by some mechanism,
131 static bool canHiddenResultBeFound(const LangOptions &LangOpts,
132 NamedDecl *Hidden, NamedDecl *Visible) {
133 // In C, there is no way to refer to a hidden name.
134 if (!LangOpts.CPlusPlus)
137 DeclContext *HiddenCtx = Hidden->getDeclContext()->getLookupContext();
139 // There is no way to qualify a name declared in a function or method.
140 if (HiddenCtx->isFunctionOrMethod())
143 return HiddenCtx != Visible->getDeclContext()->getLookupContext();
146 /// \brief Compute the qualification required to get from the current context
147 /// (\p CurContext) to the target context (\p TargetContext).
149 /// \param Context the AST context in which the qualification will be used.
151 /// \param CurContext the context where an entity is being named, which is
152 /// typically based on the current scope.
154 /// \param TargetContext the context in which the named entity actually
157 /// \returns a nested name specifier that refers into the target context, or
158 /// NULL if no qualification is needed.
159 static NestedNameSpecifier *
160 getRequiredQualification(ASTContext &Context,
161 DeclContext *CurContext,
162 DeclContext *TargetContext) {
163 llvm::SmallVector<DeclContext *, 4> TargetParents;
165 for (DeclContext *CommonAncestor = TargetContext;
166 CommonAncestor && !CommonAncestor->Encloses(CurContext);
167 CommonAncestor = CommonAncestor->getLookupParent()) {
168 if (CommonAncestor->isTransparentContext() ||
169 CommonAncestor->isFunctionOrMethod())
172 TargetParents.push_back(CommonAncestor);
175 NestedNameSpecifier *Result = 0;
176 while (!TargetParents.empty()) {
177 DeclContext *Parent = TargetParents.back();
178 TargetParents.pop_back();
180 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Parent))
181 Result = NestedNameSpecifier::Create(Context, Result, Namespace);
182 else if (TagDecl *TD = dyn_cast<TagDecl>(Parent))
183 Result = NestedNameSpecifier::Create(Context, Result,
185 Context.getTypeDeclType(TD).getTypePtr());
187 assert(Parent->isTranslationUnit());
193 void ResultBuilder::MaybeAddResult(Result R, DeclContext *CurContext) {
194 assert(!ShadowMaps.empty() && "Must enter into a results scope");
196 if (R.Kind != Result::RK_Declaration) {
197 // For non-declaration results, just add the result.
198 Results.push_back(R);
202 // Skip unnamed entities.
203 if (!R.Declaration->getDeclName())
206 // Look through using declarations.
207 if (UsingDecl *Using = dyn_cast<UsingDecl>(R.Declaration))
208 MaybeAddResult(Result(Using->getTargetDecl(), R.Rank, R.Qualifier),
211 // Handle each declaration in an overload set separately.
212 if (OverloadedFunctionDecl *Ovl
213 = dyn_cast<OverloadedFunctionDecl>(R.Declaration)) {
214 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
215 FEnd = Ovl->function_end();
217 MaybeAddResult(Result(*F, R.Rank, R.Qualifier), CurContext);
222 Decl *CanonDecl = R.Declaration->getCanonicalDecl();
223 unsigned IDNS = CanonDecl->getIdentifierNamespace();
225 // Friend declarations and declarations introduced due to friends are never
227 if (isa<FriendDecl>(CanonDecl) ||
228 (IDNS & (Decl::IDNS_OrdinaryFriend | Decl::IDNS_TagFriend)))
231 if (const IdentifierInfo *Id = R.Declaration->getIdentifier()) {
232 // __va_list_tag is a freak of nature. Find it and skip it.
233 if (Id->isStr("__va_list_tag") || Id->isStr("__builtin_va_list"))
236 // Filter out names reserved for the implementation (C99 7.1.3,
237 // C++ [lib.global.names]). Users don't need to see those.
238 if (Id->getLength() >= 2) {
239 const char *Name = Id->getName();
240 if (Name[0] == '_' &&
241 (Name[1] == '_' || (Name[1] >= 'A' && Name[1] <= 'Z')))
246 // C++ constructors are never found by name lookup.
247 if (isa<CXXConstructorDecl>(CanonDecl))
250 // Filter out any unwanted results.
251 if (Filter && !(this->*Filter)(R.Declaration))
254 ShadowMap &SMap = ShadowMaps.back();
255 ShadowMap::iterator I, IEnd;
256 for (llvm::tie(I, IEnd) = SMap.equal_range(R.Declaration->getDeclName());
258 NamedDecl *ND = I->second.first;
259 unsigned Index = I->second.second;
260 if (ND->getCanonicalDecl() == CanonDecl) {
261 // This is a redeclaration. Always pick the newer declaration.
262 I->second.first = R.Declaration;
263 Results[Index].Declaration = R.Declaration;
265 // Pick the best rank of the two.
266 Results[Index].Rank = std::min(Results[Index].Rank, R.Rank);
273 // This is a new declaration in this scope. However, check whether this
274 // declaration name is hidden by a similarly-named declaration in an outer
276 std::list<ShadowMap>::iterator SM, SMEnd = ShadowMaps.end();
278 for (SM = ShadowMaps.begin(); SM != SMEnd; ++SM) {
279 for (llvm::tie(I, IEnd) = SM->equal_range(R.Declaration->getDeclName());
281 // A tag declaration does not hide a non-tag declaration.
282 if (I->second.first->getIdentifierNamespace() == Decl::IDNS_Tag &&
283 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
284 Decl::IDNS_ObjCProtocol)))
287 // Protocols are in distinct namespaces from everything else.
288 if (((I->second.first->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
289 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
290 I->second.first->getIdentifierNamespace() != IDNS)
293 // The newly-added result is hidden by an entry in the shadow map.
294 if (canHiddenResultBeFound(SemaRef.getLangOptions(), R.Declaration,
296 // Note that this result was hidden.
298 R.QualifierIsInformative = false;
301 R.Qualifier = getRequiredQualification(SemaRef.Context,
303 R.Declaration->getDeclContext());
305 // This result was hidden and cannot be found; don't bother adding
314 // Make sure that any given declaration only shows up in the result set once.
315 if (!AllDeclsFound.insert(CanonDecl))
318 // If the filter is for nested-name-specifiers, then this result starts a
319 // nested-name-specifier.
320 if ((Filter == &ResultBuilder::IsNestedNameSpecifier) ||
321 (Filter == &ResultBuilder::IsMember &&
322 isa<CXXRecordDecl>(R.Declaration) &&
323 cast<CXXRecordDecl>(R.Declaration)->isInjectedClassName()))
324 R.StartsNestedNameSpecifier = true;
326 // If this result is supposed to have an informative qualifier, add one.
327 if (R.QualifierIsInformative && !R.Qualifier &&
328 !R.StartsNestedNameSpecifier) {
329 DeclContext *Ctx = R.Declaration->getDeclContext();
330 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
331 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, Namespace);
332 else if (TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
333 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, false,
334 SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
336 R.QualifierIsInformative = false;
339 // Insert this result into the set of results and into the current shadow
341 SMap.insert(std::make_pair(R.Declaration->getDeclName(),
342 std::make_pair(R.Declaration, Results.size())));
343 Results.push_back(R);
346 /// \brief Enter into a new scope.
347 void ResultBuilder::EnterNewScope() {
348 ShadowMaps.push_back(ShadowMap());
351 /// \brief Exit from the current scope.
352 void ResultBuilder::ExitScope() {
353 ShadowMaps.pop_back();
356 /// \brief Determines whether this given declaration will be found by
357 /// ordinary name lookup.
358 bool ResultBuilder::IsOrdinaryName(NamedDecl *ND) const {
359 unsigned IDNS = Decl::IDNS_Ordinary;
360 if (SemaRef.getLangOptions().CPlusPlus)
361 IDNS |= Decl::IDNS_Tag;
363 return ND->getIdentifierNamespace() & IDNS;
366 /// \brief Determines whether the given declaration is suitable as the
367 /// start of a C++ nested-name-specifier, e.g., a class or namespace.
368 bool ResultBuilder::IsNestedNameSpecifier(NamedDecl *ND) const {
369 // Allow us to find class templates, too.
370 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
371 ND = ClassTemplate->getTemplatedDecl();
373 return SemaRef.isAcceptableNestedNameSpecifier(ND);
376 /// \brief Determines whether the given declaration is an enumeration.
377 bool ResultBuilder::IsEnum(NamedDecl *ND) const {
378 return isa<EnumDecl>(ND);
381 /// \brief Determines whether the given declaration is a class or struct.
382 bool ResultBuilder::IsClassOrStruct(NamedDecl *ND) const {
383 // Allow us to find class templates, too.
384 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
385 ND = ClassTemplate->getTemplatedDecl();
387 if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
388 return RD->getTagKind() == TagDecl::TK_class ||
389 RD->getTagKind() == TagDecl::TK_struct;
394 /// \brief Determines whether the given declaration is a union.
395 bool ResultBuilder::IsUnion(NamedDecl *ND) const {
396 // Allow us to find class templates, too.
397 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
398 ND = ClassTemplate->getTemplatedDecl();
400 if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
401 return RD->getTagKind() == TagDecl::TK_union;
406 /// \brief Determines whether the given declaration is a namespace.
407 bool ResultBuilder::IsNamespace(NamedDecl *ND) const {
408 return isa<NamespaceDecl>(ND);
411 /// \brief Determines whether the given declaration is a namespace or
413 bool ResultBuilder::IsNamespaceOrAlias(NamedDecl *ND) const {
414 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
417 /// \brief Brief determines whether the given declaration is a namespace or
419 bool ResultBuilder::IsType(NamedDecl *ND) const {
420 return isa<TypeDecl>(ND);
423 /// \brief Since every declaration found within a class is a member that we
424 /// care about, always returns true. This predicate exists mostly to
425 /// communicate to the result builder that we are performing a lookup for
427 bool ResultBuilder::IsMember(NamedDecl *ND) const {
431 // Find the next outer declaration context corresponding to this scope.
432 static DeclContext *findOuterContext(Scope *S) {
433 for (S = S->getParent(); S; S = S->getParent())
435 return static_cast<DeclContext *>(S->getEntity())->getPrimaryContext();
440 /// \brief Collect the results of searching for members within the given
441 /// declaration context.
443 /// \param Ctx the declaration context from which we will gather results.
445 /// \param Rank the rank given to results in this declaration context.
447 /// \param Visited the set of declaration contexts that have already been
448 /// visited. Declaration contexts will only be visited once.
450 /// \param Results the result set that will be extended with any results
451 /// found within this declaration context (and, for a C++ class, its bases).
453 /// \param InBaseClass whether we are in a base class.
455 /// \returns the next higher rank value, after considering all of the
456 /// names within this declaration context.
457 static unsigned CollectMemberLookupResults(DeclContext *Ctx,
459 DeclContext *CurContext,
460 llvm::SmallPtrSet<DeclContext *, 16> &Visited,
461 ResultBuilder &Results,
462 bool InBaseClass = false) {
463 // Make sure we don't visit the same context twice.
464 if (!Visited.insert(Ctx->getPrimaryContext()))
467 // Enumerate all of the results in this context.
468 typedef CodeCompleteConsumer::Result Result;
469 Results.EnterNewScope();
470 for (DeclContext *CurCtx = Ctx->getPrimaryContext(); CurCtx;
471 CurCtx = CurCtx->getNextContext()) {
472 for (DeclContext::decl_iterator D = CurCtx->decls_begin(),
473 DEnd = CurCtx->decls_end();
475 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
476 Results.MaybeAddResult(Result(ND, Rank, 0, InBaseClass), CurContext);
480 // Traverse the contexts of inherited classes.
481 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
482 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(),
483 BEnd = Record->bases_end();
485 QualType BaseType = B->getType();
487 // Don't look into dependent bases, because name lookup can't look
489 if (BaseType->isDependentType())
492 const RecordType *Record = BaseType->getAs<RecordType>();
496 // FIXME: It would be nice to be able to determine whether referencing
497 // a particular member would be ambiguous. For example, given
499 // struct A { int member; };
500 // struct B { int member; };
501 // struct C : A, B { };
503 // void f(C *c) { c->### }
504 // accessing 'member' would result in an ambiguity. However, code
505 // completion could be smart enough to qualify the member with the
514 // Collect results from this base class (and its bases).
515 CollectMemberLookupResults(Record->getDecl(), Rank, CurContext, Visited,
516 Results, /*InBaseClass=*/true);
520 // FIXME: Look into base classes in Objective-C!
526 /// \brief Collect the results of searching for members within the given
527 /// declaration context.
529 /// \param Ctx the declaration context from which we will gather results.
531 /// \param InitialRank the initial rank given to results in this declaration
532 /// context. Larger rank values will be used for, e.g., members found in
535 /// \param Results the result set that will be extended with any results
536 /// found within this declaration context (and, for a C++ class, its bases).
538 /// \returns the next higher rank value, after considering all of the
539 /// names within this declaration context.
540 static unsigned CollectMemberLookupResults(DeclContext *Ctx,
541 unsigned InitialRank,
542 DeclContext *CurContext,
543 ResultBuilder &Results) {
544 llvm::SmallPtrSet<DeclContext *, 16> Visited;
545 return CollectMemberLookupResults(Ctx, InitialRank, CurContext, Visited,
549 /// \brief Collect the results of searching for declarations within the given
550 /// scope and its parent scopes.
552 /// \param S the scope in which we will start looking for declarations.
554 /// \param InitialRank the initial rank given to results in this scope.
555 /// Larger rank values will be used for results found in parent scopes.
557 /// \param CurContext the context from which lookup results will be found.
559 /// \param Results the builder object that will receive each result.
560 static unsigned CollectLookupResults(Scope *S,
561 TranslationUnitDecl *TranslationUnit,
562 unsigned InitialRank,
563 DeclContext *CurContext,
564 ResultBuilder &Results) {
568 // FIXME: Using directives!
570 unsigned NextRank = InitialRank;
571 Results.EnterNewScope();
572 if (S->getEntity() &&
573 !((DeclContext *)S->getEntity())->isFunctionOrMethod()) {
574 // Look into this scope's declaration context, along with any of its
575 // parent lookup contexts (e.g., enclosing classes), up to the point
576 // where we hit the context stored in the next outer scope.
577 DeclContext *Ctx = (DeclContext *)S->getEntity();
578 DeclContext *OuterCtx = findOuterContext(S);
580 for (; Ctx && Ctx->getPrimaryContext() != OuterCtx;
581 Ctx = Ctx->getLookupParent()) {
582 if (Ctx->isFunctionOrMethod())
585 NextRank = CollectMemberLookupResults(Ctx, NextRank + 1, CurContext,
588 } else if (!S->getParent()) {
589 // Look into the translation unit scope. We walk through the translation
590 // unit's declaration context, because the Scope itself won't have all of
591 // the declarations if we loaded a precompiled header.
592 // FIXME: We would like the translation unit's Scope object to point to the
593 // translation unit, so we don't need this special "if" branch. However,
594 // doing so would force the normal C++ name-lookup code to look into the
595 // translation unit decl when the IdentifierInfo chains would suffice.
596 // Once we fix that problem (which is part of a more general "don't look
597 // in DeclContexts unless we have to" optimization), we can eliminate the
598 // TranslationUnit parameter entirely.
599 NextRank = CollectMemberLookupResults(TranslationUnit, NextRank + 1,
600 CurContext, Results);
602 // Walk through the declarations in this Scope.
603 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
605 if (NamedDecl *ND = dyn_cast<NamedDecl>((Decl *)((*D).get())))
606 Results.MaybeAddResult(CodeCompleteConsumer::Result(ND, NextRank),
610 NextRank = NextRank + 1;
613 // Lookup names in the parent scope.
614 NextRank = CollectLookupResults(S->getParent(), TranslationUnit, NextRank,
615 CurContext, Results);
621 /// \brief Add type specifiers for the current language as keyword results.
622 static void AddTypeSpecifierResults(const LangOptions &LangOpts, unsigned Rank,
623 ResultBuilder &Results) {
624 typedef CodeCompleteConsumer::Result Result;
625 Results.MaybeAddResult(Result("short", Rank));
626 Results.MaybeAddResult(Result("long", Rank));
627 Results.MaybeAddResult(Result("signed", Rank));
628 Results.MaybeAddResult(Result("unsigned", Rank));
629 Results.MaybeAddResult(Result("void", Rank));
630 Results.MaybeAddResult(Result("char", Rank));
631 Results.MaybeAddResult(Result("int", Rank));
632 Results.MaybeAddResult(Result("float", Rank));
633 Results.MaybeAddResult(Result("double", Rank));
634 Results.MaybeAddResult(Result("enum", Rank));
635 Results.MaybeAddResult(Result("struct", Rank));
636 Results.MaybeAddResult(Result("union", Rank));
640 Results.MaybeAddResult(Result("_Complex", Rank));
641 Results.MaybeAddResult(Result("_Imaginary", Rank));
642 Results.MaybeAddResult(Result("_Bool", Rank));
645 if (LangOpts.CPlusPlus) {
647 Results.MaybeAddResult(Result("bool", Rank));
648 Results.MaybeAddResult(Result("class", Rank));
649 Results.MaybeAddResult(Result("typename", Rank));
650 Results.MaybeAddResult(Result("wchar_t", Rank));
652 if (LangOpts.CPlusPlus0x) {
653 Results.MaybeAddResult(Result("char16_t", Rank));
654 Results.MaybeAddResult(Result("char32_t", Rank));
655 Results.MaybeAddResult(Result("decltype", Rank));
660 if (LangOpts.GNUMode) {
661 // FIXME: Enable when we actually support decimal floating point.
662 // Results.MaybeAddResult(Result("_Decimal32", Rank));
663 // Results.MaybeAddResult(Result("_Decimal64", Rank));
664 // Results.MaybeAddResult(Result("_Decimal128", Rank));
665 Results.MaybeAddResult(Result("typeof", Rank));
669 /// \brief Add function parameter chunks to the given code completion string.
670 static void AddFunctionParameterChunks(ASTContext &Context,
671 FunctionDecl *Function,
672 CodeCompletionString *Result) {
673 CodeCompletionString *CCStr = Result;
675 for (unsigned P = 0, N = Function->getNumParams(); P != N; ++P) {
676 ParmVarDecl *Param = Function->getParamDecl(P);
678 if (Param->hasDefaultArg()) {
679 // When we see an optional default argument, put that argument and
680 // the remaining default arguments into a new, optional string.
681 CodeCompletionString *Opt = new CodeCompletionString;
682 CCStr->AddOptionalChunk(std::auto_ptr<CodeCompletionString>(Opt));
687 CCStr->AddTextChunk(", ");
689 // Format the placeholder string.
690 std::string PlaceholderStr;
691 if (Param->getIdentifier())
692 PlaceholderStr = Param->getIdentifier()->getName();
694 Param->getType().getAsStringInternal(PlaceholderStr,
695 Context.PrintingPolicy);
697 // Add the placeholder string.
698 CCStr->AddPlaceholderChunk(PlaceholderStr.c_str());
701 if (const FunctionProtoType *Proto
702 = Function->getType()->getAs<FunctionProtoType>())
703 if (Proto->isVariadic())
704 CCStr->AddPlaceholderChunk(", ...");
707 /// \brief Add template parameter chunks to the given code completion string.
708 static void AddTemplateParameterChunks(ASTContext &Context,
709 TemplateDecl *Template,
710 CodeCompletionString *Result,
711 unsigned MaxParameters = 0) {
712 CodeCompletionString *CCStr = Result;
713 bool FirstParameter = true;
715 TemplateParameterList *Params = Template->getTemplateParameters();
716 TemplateParameterList::iterator PEnd = Params->end();
718 PEnd = Params->begin() + MaxParameters;
719 for (TemplateParameterList::iterator P = Params->begin(); P != PEnd; ++P) {
720 bool HasDefaultArg = false;
721 std::string PlaceholderStr;
722 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
723 if (TTP->wasDeclaredWithTypename())
724 PlaceholderStr = "typename";
726 PlaceholderStr = "class";
728 if (TTP->getIdentifier()) {
729 PlaceholderStr += ' ';
730 PlaceholderStr += TTP->getIdentifier()->getName();
733 HasDefaultArg = TTP->hasDefaultArgument();
734 } else if (NonTypeTemplateParmDecl *NTTP
735 = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
736 if (NTTP->getIdentifier())
737 PlaceholderStr = NTTP->getIdentifier()->getName();
738 NTTP->getType().getAsStringInternal(PlaceholderStr,
739 Context.PrintingPolicy);
740 HasDefaultArg = NTTP->hasDefaultArgument();
742 assert(isa<TemplateTemplateParmDecl>(*P));
743 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
745 // Since putting the template argument list into the placeholder would
746 // be very, very long, we just use an abbreviation.
747 PlaceholderStr = "template<...> class";
748 if (TTP->getIdentifier()) {
749 PlaceholderStr += ' ';
750 PlaceholderStr += TTP->getIdentifier()->getName();
753 HasDefaultArg = TTP->hasDefaultArgument();
757 // When we see an optional default argument, put that argument and
758 // the remaining default arguments into a new, optional string.
759 CodeCompletionString *Opt = new CodeCompletionString;
760 CCStr->AddOptionalChunk(std::auto_ptr<CodeCompletionString>(Opt));
765 FirstParameter = false;
767 CCStr->AddTextChunk(", ");
769 // Add the placeholder string.
770 CCStr->AddPlaceholderChunk(PlaceholderStr.c_str());
774 /// \brief Add a qualifier to the given code-completion string, if the
775 /// provided nested-name-specifier is non-NULL.
776 void AddQualifierToCompletionString(CodeCompletionString *Result,
777 NestedNameSpecifier *Qualifier,
778 bool QualifierIsInformative,
779 ASTContext &Context) {
783 std::string PrintedNNS;
785 llvm::raw_string_ostream OS(PrintedNNS);
786 Qualifier->print(OS, Context.PrintingPolicy);
788 if (QualifierIsInformative)
789 Result->AddInformativeChunk(PrintedNNS.c_str());
791 Result->AddTextChunk(PrintedNNS.c_str());
794 /// \brief If possible, create a new code completion string for the given
797 /// \returns Either a new, heap-allocated code completion string describing
798 /// how to use this result, or NULL to indicate that the string or name of the
799 /// result is all that is needed.
800 CodeCompletionString *
801 CodeCompleteConsumer::Result::CreateCodeCompletionString(Sema &S) {
802 if (Kind != RK_Declaration)
805 NamedDecl *ND = Declaration;
807 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND)) {
808 CodeCompletionString *Result = new CodeCompletionString;
809 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
811 Result->AddTextChunk(Function->getNameAsString().c_str());
812 Result->AddTextChunk("(");
813 AddFunctionParameterChunks(S.Context, Function, Result);
814 Result->AddTextChunk(")");
818 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND)) {
819 CodeCompletionString *Result = new CodeCompletionString;
820 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
822 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
823 Result->AddTextChunk(Function->getNameAsString().c_str());
825 // Figure out which template parameters are deduced (or have default
827 llvm::SmallVector<bool, 16> Deduced;
828 S.MarkDeducedTemplateParameters(FunTmpl, Deduced);
829 unsigned LastDeducibleArgument;
830 for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0;
831 --LastDeducibleArgument) {
832 if (!Deduced[LastDeducibleArgument - 1]) {
833 // C++0x: Figure out if the template argument has a default. If so,
834 // the user doesn't need to type this argument.
835 // FIXME: We need to abstract template parameters better!
836 bool HasDefaultArg = false;
837 NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam(
838 LastDeducibleArgument - 1);
839 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
840 HasDefaultArg = TTP->hasDefaultArgument();
841 else if (NonTypeTemplateParmDecl *NTTP
842 = dyn_cast<NonTypeTemplateParmDecl>(Param))
843 HasDefaultArg = NTTP->hasDefaultArgument();
845 assert(isa<TemplateTemplateParmDecl>(Param));
847 = cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument();
855 if (LastDeducibleArgument) {
856 // Some of the function template arguments cannot be deduced from a
857 // function call, so we introduce an explicit template argument list
858 // containing all of the arguments up to the first deducible argument.
859 Result->AddTextChunk("<");
860 AddTemplateParameterChunks(S.Context, FunTmpl, Result,
861 LastDeducibleArgument);
862 Result->AddTextChunk(">");
865 // Add the function parameters
866 Result->AddTextChunk("(");
867 AddFunctionParameterChunks(S.Context, Function, Result);
868 Result->AddTextChunk(")");
872 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(ND)) {
873 CodeCompletionString *Result = new CodeCompletionString;
874 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
876 Result->AddTextChunk(Template->getNameAsString().c_str());
877 Result->AddTextChunk("<");
878 AddTemplateParameterChunks(S.Context, Template, Result);
879 Result->AddTextChunk(">");
883 if (Qualifier || StartsNestedNameSpecifier) {
884 CodeCompletionString *Result = new CodeCompletionString;
885 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
887 Result->AddTextChunk(ND->getNameAsString().c_str());
888 if (StartsNestedNameSpecifier)
889 Result->AddTextChunk("::");
896 CodeCompletionString *
897 CodeCompleteConsumer::OverloadCandidate::CreateSignatureString(
900 CodeCompletionString *Result = new CodeCompletionString;
901 FunctionDecl *FDecl = getFunction();
902 const FunctionProtoType *Proto
903 = dyn_cast<FunctionProtoType>(getFunctionType());
904 if (!FDecl && !Proto) {
905 // Function without a prototype. Just give the return type and a
906 // highlighted ellipsis.
907 const FunctionType *FT = getFunctionType();
908 Result->AddTextChunk(
909 FT->getResultType().getAsString(S.Context.PrintingPolicy).c_str());
910 Result->AddTextChunk("(");
911 Result->AddPlaceholderChunk("...");
912 Result->AddTextChunk("(");
917 Result->AddTextChunk(FDecl->getNameAsString().c_str());
919 Result->AddTextChunk(
920 Proto->getResultType().getAsString(S.Context.PrintingPolicy).c_str());
922 Result->AddTextChunk("(");
923 unsigned NumParams = FDecl? FDecl->getNumParams() : Proto->getNumArgs();
924 for (unsigned I = 0; I != NumParams; ++I) {
926 Result->AddTextChunk(", ");
928 std::string ArgString;
932 ArgString = FDecl->getParamDecl(I)->getNameAsString();
933 ArgType = FDecl->getParamDecl(I)->getOriginalType();
935 ArgType = Proto->getArgType(I);
938 ArgType.getAsStringInternal(ArgString, S.Context.PrintingPolicy);
941 Result->AddPlaceholderChunk(ArgString.c_str());
943 Result->AddTextChunk(ArgString.c_str());
946 if (Proto && Proto->isVariadic()) {
947 Result->AddTextChunk(", ");
948 if (CurrentArg < NumParams)
949 Result->AddTextChunk("...");
951 Result->AddPlaceholderChunk("...");
953 Result->AddTextChunk(")");
959 struct SortCodeCompleteResult {
960 typedef CodeCompleteConsumer::Result Result;
962 bool isEarlierDeclarationName(DeclarationName X, DeclarationName Y) const {
963 if (X.getNameKind() != Y.getNameKind())
964 return X.getNameKind() < Y.getNameKind();
966 return llvm::LowercaseString(X.getAsString())
967 < llvm::LowercaseString(Y.getAsString());
970 bool operator()(const Result &X, const Result &Y) const {
971 // Sort first by rank.
974 else if (X.Rank > Y.Rank)
977 // Result kinds are ordered by decreasing importance.
980 else if (X.Kind > Y.Kind)
983 // Non-hidden names precede hidden names.
984 if (X.Hidden != Y.Hidden)
987 // Non-nested-name-specifiers precede nested-name-specifiers.
988 if (X.StartsNestedNameSpecifier != Y.StartsNestedNameSpecifier)
989 return !X.StartsNestedNameSpecifier;
991 // Ordering depends on the kind of result.
993 case Result::RK_Declaration:
994 // Order based on the declaration names.
995 return isEarlierDeclarationName(X.Declaration->getDeclName(),
996 Y.Declaration->getDeclName());
998 case Result::RK_Keyword:
999 return strcmp(X.Keyword, Y.Keyword) < 0;
1002 // Silence GCC warning.
1008 static void HandleCodeCompleteResults(CodeCompleteConsumer *CodeCompleter,
1009 CodeCompleteConsumer::Result *Results,
1010 unsigned NumResults) {
1011 // Sort the results by rank/kind/etc.
1012 std::stable_sort(Results, Results + NumResults, SortCodeCompleteResult());
1015 CodeCompleter->ProcessCodeCompleteResults(Results, NumResults);
1018 void Sema::CodeCompleteOrdinaryName(Scope *S) {
1019 ResultBuilder Results(*this, &ResultBuilder::IsOrdinaryName);
1020 CollectLookupResults(S, Context.getTranslationUnitDecl(), 0, CurContext,
1022 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
1025 void Sema::CodeCompleteMemberReferenceExpr(Scope *S, ExprTy *BaseE,
1026 SourceLocation OpLoc,
1028 if (!BaseE || !CodeCompleter)
1031 typedef CodeCompleteConsumer::Result Result;
1033 Expr *Base = static_cast<Expr *>(BaseE);
1034 QualType BaseType = Base->getType();
1037 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
1038 BaseType = Ptr->getPointeeType();
1039 else if (BaseType->isObjCObjectPointerType())
1045 ResultBuilder Results(*this, &ResultBuilder::IsMember);
1046 unsigned NextRank = 0;
1048 if (const RecordType *Record = BaseType->getAs<RecordType>()) {
1049 NextRank = CollectMemberLookupResults(Record->getDecl(), NextRank,
1050 Record->getDecl(), Results);
1052 if (getLangOptions().CPlusPlus) {
1053 if (!Results.empty()) {
1054 // The "template" keyword can follow "->" or "." in the grammar.
1055 // However, we only want to suggest the template keyword if something
1057 bool IsDependent = BaseType->isDependentType();
1059 for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent())
1060 if (DeclContext *Ctx = (DeclContext *)DepScope->getEntity()) {
1061 IsDependent = Ctx->isDependentContext();
1067 Results.MaybeAddResult(Result("template", NextRank++));
1070 // We could have the start of a nested-name-specifier. Add those
1072 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
1073 CollectLookupResults(S, Context.getTranslationUnitDecl(), NextRank,
1074 CurContext, Results);
1077 // Hand off the results found for code completion.
1078 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
1085 void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) {
1089 typedef CodeCompleteConsumer::Result Result;
1090 ResultBuilder::LookupFilter Filter = 0;
1091 switch ((DeclSpec::TST)TagSpec) {
1092 case DeclSpec::TST_enum:
1093 Filter = &ResultBuilder::IsEnum;
1096 case DeclSpec::TST_union:
1097 Filter = &ResultBuilder::IsUnion;
1100 case DeclSpec::TST_struct:
1101 case DeclSpec::TST_class:
1102 Filter = &ResultBuilder::IsClassOrStruct;
1106 assert(false && "Unknown type specifier kind in CodeCompleteTag");
1110 ResultBuilder Results(*this, Filter);
1111 unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
1112 0, CurContext, Results);
1114 if (getLangOptions().CPlusPlus) {
1115 // We could have the start of a nested-name-specifier. Add those
1117 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
1118 CollectLookupResults(S, Context.getTranslationUnitDecl(), NextRank,
1119 CurContext, Results);
1122 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
1125 void Sema::CodeCompleteCase(Scope *S) {
1126 if (getSwitchStack().empty() || !CodeCompleter)
1129 SwitchStmt *Switch = getSwitchStack().back();
1130 if (!Switch->getCond()->getType()->isEnumeralType())
1133 // Code-complete the cases of a switch statement over an enumeration type
1134 // by providing the list of
1135 EnumDecl *Enum = Switch->getCond()->getType()->getAs<EnumType>()->getDecl();
1137 // Determine which enumerators we have already seen in the switch statement.
1138 // FIXME: Ideally, we would also be able to look *past* the code-completion
1139 // token, in case we are code-completing in the middle of the switch and not
1140 // at the end. However, we aren't able to do so at the moment.
1141 llvm::SmallPtrSet<EnumConstantDecl *, 8> EnumeratorsSeen;
1142 NestedNameSpecifier *Qualifier = 0;
1143 for (SwitchCase *SC = Switch->getSwitchCaseList(); SC;
1144 SC = SC->getNextSwitchCase()) {
1145 CaseStmt *Case = dyn_cast<CaseStmt>(SC);
1149 Expr *CaseVal = Case->getLHS()->IgnoreParenCasts();
1150 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseVal))
1151 if (EnumConstantDecl *Enumerator
1152 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
1153 // We look into the AST of the case statement to determine which
1154 // enumerator was named. Alternatively, we could compute the value of
1155 // the integral constant expression, then compare it against the
1156 // values of each enumerator. However, value-based approach would not
1157 // work as well with C++ templates where enumerators declared within a
1158 // template are type- and value-dependent.
1159 EnumeratorsSeen.insert(Enumerator);
1161 // If this is a qualified-id, keep track of the nested-name-specifier
1162 // so that we can reproduce it as part of code completion, e.g.,
1164 // switch (TagD.getKind()) {
1165 // case TagDecl::TK_enum:
1169 // At the XXX, our completions are TagDecl::TK_union,
1170 // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
1171 // TK_struct, and TK_class.
1172 if (QualifiedDeclRefExpr *QDRE = dyn_cast<QualifiedDeclRefExpr>(DRE))
1173 Qualifier = QDRE->getQualifier();
1177 if (getLangOptions().CPlusPlus && !Qualifier && EnumeratorsSeen.empty()) {
1178 // If there are no prior enumerators in C++, check whether we have to
1179 // qualify the names of the enumerators that we suggest, because they
1180 // may not be visible in this scope.
1181 Qualifier = getRequiredQualification(Context, CurContext,
1182 Enum->getDeclContext());
1184 // FIXME: Scoped enums need to start with "EnumDecl" as the context!
1187 // Add any enumerators that have not yet been mentioned.
1188 ResultBuilder Results(*this);
1189 Results.EnterNewScope();
1190 for (EnumDecl::enumerator_iterator E = Enum->enumerator_begin(),
1191 EEnd = Enum->enumerator_end();
1193 if (EnumeratorsSeen.count(*E))
1196 Results.MaybeAddResult(CodeCompleteConsumer::Result(*E, 0, Qualifier));
1198 Results.ExitScope();
1200 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
1204 struct IsBetterOverloadCandidate {
1208 explicit IsBetterOverloadCandidate(Sema &S) : S(S) { }
1211 operator()(const OverloadCandidate &X, const OverloadCandidate &Y) const {
1212 return S.isBetterOverloadCandidate(X, Y);
1217 void Sema::CodeCompleteCall(Scope *S, ExprTy *FnIn,
1218 ExprTy **ArgsIn, unsigned NumArgs) {
1222 Expr *Fn = (Expr *)FnIn;
1223 Expr **Args = (Expr **)ArgsIn;
1225 // Ignore type-dependent call expressions entirely.
1226 if (Fn->isTypeDependent() ||
1227 Expr::hasAnyTypeDependentArguments(Args, NumArgs))
1230 NamedDecl *Function;
1231 DeclarationName UnqualifiedName;
1232 NestedNameSpecifier *Qualifier;
1233 SourceRange QualifierRange;
1234 bool ArgumentDependentLookup;
1235 bool HasExplicitTemplateArgs;
1236 const TemplateArgument *ExplicitTemplateArgs;
1237 unsigned NumExplicitTemplateArgs;
1239 DeconstructCallFunction(Fn,
1240 Function, UnqualifiedName, Qualifier, QualifierRange,
1241 ArgumentDependentLookup, HasExplicitTemplateArgs,
1242 ExplicitTemplateArgs, NumExplicitTemplateArgs);
1245 // FIXME: What if we're calling something that isn't a function declaration?
1246 // FIXME: What if we're calling a pseudo-destructor?
1247 // FIXME: What if we're calling a member function?
1249 // Build an overload candidate set based on the functions we find.
1250 OverloadCandidateSet CandidateSet;
1251 AddOverloadedCallCandidates(Function, UnqualifiedName,
1252 ArgumentDependentLookup, HasExplicitTemplateArgs,
1253 ExplicitTemplateArgs, NumExplicitTemplateArgs,
1256 /*PartialOverloading=*/true);
1258 // Sort the overload candidate set by placing the best overloads first.
1259 std::stable_sort(CandidateSet.begin(), CandidateSet.end(),
1260 IsBetterOverloadCandidate(*this));
1262 // Add the remaining viable overload candidates as code-completion reslults.
1263 typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate;
1264 llvm::SmallVector<ResultCandidate, 8> Results;
1266 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
1267 CandEnd = CandidateSet.end();
1268 Cand != CandEnd; ++Cand) {
1270 Results.push_back(ResultCandidate(Cand->Function));
1272 CodeCompleter->ProcessOverloadCandidates(NumArgs, Results.data(),
1276 void Sema::CodeCompleteQualifiedId(Scope *S, const CXXScopeSpec &SS,
1277 bool EnteringContext) {
1278 if (!SS.getScopeRep() || !CodeCompleter)
1281 DeclContext *Ctx = computeDeclContext(SS, EnteringContext);
1285 ResultBuilder Results(*this);
1286 unsigned NextRank = CollectMemberLookupResults(Ctx, 0, Ctx, Results);
1288 // The "template" keyword can follow "::" in the grammar, but only
1289 // put it into the grammar if the nested-name-specifier is dependent.
1290 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
1291 if (!Results.empty() && NNS->isDependent())
1292 Results.MaybeAddResult(CodeCompleteConsumer::Result("template", NextRank));
1294 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
1297 void Sema::CodeCompleteUsing(Scope *S) {
1301 ResultBuilder Results(*this, &ResultBuilder::IsNestedNameSpecifier);
1302 Results.EnterNewScope();
1304 // If we aren't in class scope, we could see the "namespace" keyword.
1305 if (!S->isClassScope())
1306 Results.MaybeAddResult(CodeCompleteConsumer::Result("namespace", 0));
1308 // After "using", we can see anything that would start a
1309 // nested-name-specifier.
1310 CollectLookupResults(S, Context.getTranslationUnitDecl(), 0,
1311 CurContext, Results);
1312 Results.ExitScope();
1314 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
1317 void Sema::CodeCompleteUsingDirective(Scope *S) {
1321 // After "using namespace", we expect to see a namespace name or namespace
1323 ResultBuilder Results(*this, &ResultBuilder::IsNamespaceOrAlias);
1324 Results.EnterNewScope();
1325 CollectLookupResults(S, Context.getTranslationUnitDecl(), 0, CurContext,
1327 Results.ExitScope();
1328 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
1331 void Sema::CodeCompleteNamespaceDecl(Scope *S) {
1335 ResultBuilder Results(*this, &ResultBuilder::IsNamespace);
1336 DeclContext *Ctx = (DeclContext *)S->getEntity();
1337 if (!S->getParent())
1338 Ctx = Context.getTranslationUnitDecl();
1340 if (Ctx && Ctx->isFileContext()) {
1341 // We only want to see those namespaces that have already been defined
1342 // within this scope, because its likely that the user is creating an
1343 // extended namespace declaration. Keep track of the most recent
1344 // definition of each namespace.
1345 std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest;
1346 for (DeclContext::specific_decl_iterator<NamespaceDecl>
1347 NS(Ctx->decls_begin()), NSEnd(Ctx->decls_end());
1349 OrigToLatest[NS->getOriginalNamespace()] = *NS;
1351 // Add the most recent definition (or extended definition) of each
1352 // namespace to the list of results.
1353 Results.EnterNewScope();
1354 for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator
1355 NS = OrigToLatest.begin(), NSEnd = OrigToLatest.end();
1357 Results.MaybeAddResult(CodeCompleteConsumer::Result(NS->second, 0),
1359 Results.ExitScope();
1362 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
1365 void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) {
1369 // After "namespace", we expect to see a namespace or alias.
1370 ResultBuilder Results(*this, &ResultBuilder::IsNamespaceOrAlias);
1371 CollectLookupResults(S, Context.getTranslationUnitDecl(), 0, CurContext,
1373 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
1376 void Sema::CodeCompleteOperatorName(Scope *S) {
1380 typedef CodeCompleteConsumer::Result Result;
1381 ResultBuilder Results(*this, &ResultBuilder::IsType);
1382 Results.EnterNewScope();
1384 // Add the names of overloadable operators.
1385 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
1386 if (std::strcmp(Spelling, "?")) \
1387 Results.MaybeAddResult(Result(Spelling, 0));
1388 #include "clang/Basic/OperatorKinds.def"
1390 // Add any type names visible from the current scope
1391 unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(),
1392 0, CurContext, Results);
1394 // Add any type specifiers
1395 AddTypeSpecifierResults(getLangOptions(), 0, Results);
1397 // Add any nested-name-specifiers
1398 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
1399 CollectLookupResults(S, Context.getTranslationUnitDecl(), NextRank + 1,
1400 CurContext, Results);
1401 Results.ExitScope();
1403 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());
1406 void Sema::CodeCompleteObjCProperty(Scope *S, ObjCDeclSpec &ODS) {
1409 unsigned Attributes = ODS.getPropertyAttributes();
1411 typedef CodeCompleteConsumer::Result Result;
1412 ResultBuilder Results(*this);
1413 Results.EnterNewScope();
1414 if (!(Attributes & ObjCDeclSpec::DQ_PR_readonly))
1415 Results.MaybeAddResult(CodeCompleteConsumer::Result("readonly", 0));
1416 if (!(Attributes & ObjCDeclSpec::DQ_PR_assign))
1417 Results.MaybeAddResult(CodeCompleteConsumer::Result("assign", 0));
1418 if (!(Attributes & ObjCDeclSpec::DQ_PR_readwrite))
1419 Results.MaybeAddResult(CodeCompleteConsumer::Result("readwrite", 0));
1420 if (!(Attributes & ObjCDeclSpec::DQ_PR_retain))
1421 Results.MaybeAddResult(CodeCompleteConsumer::Result("retain", 0));
1422 if (!(Attributes & ObjCDeclSpec::DQ_PR_copy))
1423 Results.MaybeAddResult(CodeCompleteConsumer::Result("copy", 0));
1424 if (!(Attributes & ObjCDeclSpec::DQ_PR_nonatomic))
1425 Results.MaybeAddResult(CodeCompleteConsumer::Result("nonatomic", 0));
1426 if (!(Attributes & ObjCDeclSpec::DQ_PR_setter))
1427 Results.MaybeAddResult(CodeCompleteConsumer::Result("setter", 0));
1428 if (!(Attributes & ObjCDeclSpec::DQ_PR_getter))
1429 Results.MaybeAddResult(CodeCompleteConsumer::Result("getter", 0));
1430 Results.ExitScope();
1431 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size());