SemaCodeComplete.cpp revision 3d2491e8c664a3ffe39921fa442a28d524dcc631
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. 11// 12//===----------------------------------------------------------------------===// 13#include "Sema.h" 14#include "clang/Sema/CodeCompleteConsumer.h" 15#include "clang/AST/ExprCXX.h" 16#include "llvm/ADT/SmallPtrSet.h" 17#include <list> 18#include <map> 19#include <vector> 20 21using namespace clang; 22 23/// \brief Set the code-completion consumer for semantic analysis. 24void Sema::setCodeCompleteConsumer(CodeCompleteConsumer *CCC) { 25 assert(((CodeCompleter != 0) != (CCC != 0)) && 26 "Already set or cleared a code-completion consumer?"); 27 CodeCompleter = CCC; 28} 29 30namespace { 31 /// \brief A container of code-completion results. 32 class ResultBuilder { 33 public: 34 /// \brief The type of a name-lookup filter, which can be provided to the 35 /// name-lookup routines to specify which declarations should be included in 36 /// the result set (when it returns true) and which declarations should be 37 /// filtered out (returns false). 38 typedef bool (ResultBuilder::*LookupFilter)(NamedDecl *) const; 39 40 typedef CodeCompleteConsumer::Result Result; 41 42 private: 43 /// \brief The actual results we have found. 44 std::vector<Result> Results; 45 46 /// \brief A record of all of the declarations we have found and placed 47 /// into the result set, used to ensure that no declaration ever gets into 48 /// the result set twice. 49 llvm::SmallPtrSet<Decl*, 16> AllDeclsFound; 50 51 /// \brief A mapping from declaration names to the declarations that have 52 /// this name within a particular scope and their index within the list of 53 /// results. 54 typedef std::multimap<DeclarationName, 55 std::pair<NamedDecl *, unsigned> > ShadowMap; 56 57 /// \brief The semantic analysis object for which results are being 58 /// produced. 59 Sema &SemaRef; 60 61 /// \brief If non-NULL, a filter function used to remove any code-completion 62 /// results that are not desirable. 63 LookupFilter Filter; 64 65 /// \brief A list of shadow maps, which is used to model name hiding at 66 /// different levels of, e.g., the inheritance hierarchy. 67 std::list<ShadowMap> ShadowMaps; 68 69 public: 70 explicit ResultBuilder(Sema &SemaRef, LookupFilter Filter = 0) 71 : SemaRef(SemaRef), Filter(Filter) { } 72 73 /// \brief Set the filter used for code-completion results. 74 void setFilter(LookupFilter Filter) { 75 this->Filter = Filter; 76 } 77 78 typedef std::vector<Result>::iterator iterator; 79 iterator begin() { return Results.begin(); } 80 iterator end() { return Results.end(); } 81 82 Result *data() { return Results.empty()? 0 : &Results.front(); } 83 unsigned size() const { return Results.size(); } 84 bool empty() const { return Results.empty(); } 85 86 /// \brief Add a new result to this result set (if it isn't already in one 87 /// of the shadow maps), or replace an existing result (for, e.g., a 88 /// redeclaration). 89 /// 90 /// \param R the result to add (if it is unique). 91 /// 92 /// \param R the context in which this result will be named. 93 void MaybeAddResult(Result R, DeclContext *CurContext = 0); 94 95 /// \brief Enter into a new scope. 96 void EnterNewScope(); 97 98 /// \brief Exit from the current scope. 99 void ExitScope(); 100 101 /// \name Name lookup predicates 102 /// 103 /// These predicates can be passed to the name lookup functions to filter the 104 /// results of name lookup. All of the predicates have the same type, so that 105 /// 106 //@{ 107 bool IsOrdinaryName(NamedDecl *ND) const; 108 bool IsNestedNameSpecifier(NamedDecl *ND) const; 109 bool IsEnum(NamedDecl *ND) const; 110 bool IsClassOrStruct(NamedDecl *ND) const; 111 bool IsUnion(NamedDecl *ND) const; 112 bool IsNamespace(NamedDecl *ND) const; 113 bool IsNamespaceOrAlias(NamedDecl *ND) const; 114 bool IsType(NamedDecl *ND) const; 115 //@} 116 }; 117} 118 119/// \brief Determines whether the given hidden result could be found with 120/// some extra work, e.g., by qualifying the name. 121/// 122/// \param Hidden the declaration that is hidden by the currenly \p Visible 123/// declaration. 124/// 125/// \param Visible the declaration with the same name that is already visible. 126/// 127/// \returns true if the hidden result can be found by some mechanism, 128/// false otherwise. 129static bool canHiddenResultBeFound(const LangOptions &LangOpts, 130 NamedDecl *Hidden, NamedDecl *Visible) { 131 // In C, there is no way to refer to a hidden name. 132 if (!LangOpts.CPlusPlus) 133 return false; 134 135 DeclContext *HiddenCtx = Hidden->getDeclContext()->getLookupContext(); 136 137 // There is no way to qualify a name declared in a function or method. 138 if (HiddenCtx->isFunctionOrMethod()) 139 return false; 140 141 return HiddenCtx != Visible->getDeclContext()->getLookupContext(); 142} 143 144/// \brief Compute the qualification required to get from the current context 145/// (\p CurContext) to the target context (\p TargetContext). 146/// 147/// \param Context the AST context in which the qualification will be used. 148/// 149/// \param CurContext the context where an entity is being named, which is 150/// typically based on the current scope. 151/// 152/// \param TargetContext the context in which the named entity actually 153/// resides. 154/// 155/// \returns a nested name specifier that refers into the target context, or 156/// NULL if no qualification is needed. 157static NestedNameSpecifier * 158getRequiredQualification(ASTContext &Context, 159 DeclContext *CurContext, 160 DeclContext *TargetContext) { 161 llvm::SmallVector<DeclContext *, 4> TargetParents; 162 163 for (DeclContext *CommonAncestor = TargetContext; 164 CommonAncestor && !CommonAncestor->Encloses(CurContext); 165 CommonAncestor = CommonAncestor->getLookupParent()) { 166 if (CommonAncestor->isTransparentContext() || 167 CommonAncestor->isFunctionOrMethod()) 168 continue; 169 170 TargetParents.push_back(CommonAncestor); 171 } 172 173 NestedNameSpecifier *Result = 0; 174 while (!TargetParents.empty()) { 175 DeclContext *Parent = TargetParents.back(); 176 TargetParents.pop_back(); 177 178 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Parent)) 179 Result = NestedNameSpecifier::Create(Context, Result, Namespace); 180 else if (TagDecl *TD = dyn_cast<TagDecl>(Parent)) 181 Result = NestedNameSpecifier::Create(Context, Result, 182 false, 183 Context.getTypeDeclType(TD).getTypePtr()); 184 else 185 assert(Parent->isTranslationUnit()); 186 } 187 188 return Result; 189} 190 191void ResultBuilder::MaybeAddResult(Result R, DeclContext *CurContext) { 192 if (R.Kind != Result::RK_Declaration) { 193 // For non-declaration results, just add the result. 194 Results.push_back(R); 195 return; 196 } 197 198 // Look through using declarations. 199 if (UsingDecl *Using = dyn_cast<UsingDecl>(R.Declaration)) 200 MaybeAddResult(Result(Using->getTargetDecl(), R.Rank, R.Qualifier), 201 CurContext); 202 203 // Handle each declaration in an overload set separately. 204 if (OverloadedFunctionDecl *Ovl 205 = dyn_cast<OverloadedFunctionDecl>(R.Declaration)) { 206 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(), 207 FEnd = Ovl->function_end(); 208 F != FEnd; ++F) 209 MaybeAddResult(Result(*F, R.Rank, R.Qualifier), CurContext); 210 211 return; 212 } 213 214 Decl *CanonDecl = R.Declaration->getCanonicalDecl(); 215 unsigned IDNS = CanonDecl->getIdentifierNamespace(); 216 217 // Friend declarations and declarations introduced due to friends are never 218 // added as results. 219 if (isa<FriendDecl>(CanonDecl) || 220 (IDNS & (Decl::IDNS_OrdinaryFriend | Decl::IDNS_TagFriend))) 221 return; 222 223 if (const IdentifierInfo *Id = R.Declaration->getIdentifier()) { 224 // __va_list_tag is a freak of nature. Find it and skip it. 225 if (Id->isStr("__va_list_tag") || Id->isStr("__builtin_va_list")) 226 return; 227 228 // FIXME: Should we filter out other names in the implementation's 229 // namespace, e.g., those containing a __ or that start with _[A-Z]? 230 } 231 232 // C++ constructors are never found by name lookup. 233 if (isa<CXXConstructorDecl>(CanonDecl)) 234 return; 235 236 // Filter out any unwanted results. 237 if (Filter && !(this->*Filter)(R.Declaration)) 238 return; 239 240 ShadowMap &SMap = ShadowMaps.back(); 241 ShadowMap::iterator I, IEnd; 242 for (llvm::tie(I, IEnd) = SMap.equal_range(R.Declaration->getDeclName()); 243 I != IEnd; ++I) { 244 NamedDecl *ND = I->second.first; 245 unsigned Index = I->second.second; 246 if (ND->getCanonicalDecl() == CanonDecl) { 247 // This is a redeclaration. Always pick the newer declaration. 248 I->second.first = R.Declaration; 249 Results[Index].Declaration = R.Declaration; 250 251 // Pick the best rank of the two. 252 Results[Index].Rank = std::min(Results[Index].Rank, R.Rank); 253 254 // We're done. 255 return; 256 } 257 } 258 259 // This is a new declaration in this scope. However, check whether this 260 // declaration name is hidden by a similarly-named declaration in an outer 261 // scope. 262 std::list<ShadowMap>::iterator SM, SMEnd = ShadowMaps.end(); 263 --SMEnd; 264 for (SM = ShadowMaps.begin(); SM != SMEnd; ++SM) { 265 for (llvm::tie(I, IEnd) = SM->equal_range(R.Declaration->getDeclName()); 266 I != IEnd; ++I) { 267 // A tag declaration does not hide a non-tag declaration. 268 if (I->second.first->getIdentifierNamespace() == Decl::IDNS_Tag && 269 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary | 270 Decl::IDNS_ObjCProtocol))) 271 continue; 272 273 // Protocols are in distinct namespaces from everything else. 274 if (((I->second.first->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol) 275 || (IDNS & Decl::IDNS_ObjCProtocol)) && 276 I->second.first->getIdentifierNamespace() != IDNS) 277 continue; 278 279 // The newly-added result is hidden by an entry in the shadow map. 280 if (canHiddenResultBeFound(SemaRef.getLangOptions(), R.Declaration, 281 I->second.first)) { 282 // Note that this result was hidden. 283 R.Hidden = true; 284 R.QualifierIsInformative = false; 285 286 if (!R.Qualifier) 287 R.Qualifier = getRequiredQualification(SemaRef.Context, 288 CurContext, 289 R.Declaration->getDeclContext()); 290 } else { 291 // This result was hidden and cannot be found; don't bother adding 292 // it. 293 return; 294 } 295 296 break; 297 } 298 } 299 300 // Make sure that any given declaration only shows up in the result set once. 301 if (!AllDeclsFound.insert(CanonDecl)) 302 return; 303 304 // If this result is supposed to have an informative qualifier, add one. 305 if (R.QualifierIsInformative && !R.Qualifier) { 306 DeclContext *Ctx = R.Declaration->getDeclContext(); 307 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx)) 308 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, Namespace); 309 else if (TagDecl *Tag = dyn_cast<TagDecl>(Ctx)) 310 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, false, 311 SemaRef.Context.getTypeDeclType(Tag).getTypePtr()); 312 else 313 R.QualifierIsInformative = false; 314 } 315 316 // If the filter is for nested-name-specifiers, then this result starts a 317 // nested-name-specifier. 318 if (Filter == &ResultBuilder::IsNestedNameSpecifier) 319 R.StartsNestedNameSpecifier = true; 320 321 // Insert this result into the set of results and into the current shadow 322 // map. 323 SMap.insert(std::make_pair(R.Declaration->getDeclName(), 324 std::make_pair(R.Declaration, Results.size()))); 325 Results.push_back(R); 326} 327 328/// \brief Enter into a new scope. 329void ResultBuilder::EnterNewScope() { 330 ShadowMaps.push_back(ShadowMap()); 331} 332 333/// \brief Exit from the current scope. 334void ResultBuilder::ExitScope() { 335 ShadowMaps.pop_back(); 336} 337 338/// \brief Determines whether this given declaration will be found by 339/// ordinary name lookup. 340bool ResultBuilder::IsOrdinaryName(NamedDecl *ND) const { 341 unsigned IDNS = Decl::IDNS_Ordinary; 342 if (SemaRef.getLangOptions().CPlusPlus) 343 IDNS |= Decl::IDNS_Tag; 344 345 return ND->getIdentifierNamespace() & IDNS; 346} 347 348/// \brief Determines whether the given declaration is suitable as the 349/// start of a C++ nested-name-specifier, e.g., a class or namespace. 350bool ResultBuilder::IsNestedNameSpecifier(NamedDecl *ND) const { 351 // Allow us to find class templates, too. 352 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND)) 353 ND = ClassTemplate->getTemplatedDecl(); 354 355 return SemaRef.isAcceptableNestedNameSpecifier(ND); 356} 357 358/// \brief Determines whether the given declaration is an enumeration. 359bool ResultBuilder::IsEnum(NamedDecl *ND) const { 360 return isa<EnumDecl>(ND); 361} 362 363/// \brief Determines whether the given declaration is a class or struct. 364bool ResultBuilder::IsClassOrStruct(NamedDecl *ND) const { 365 // Allow us to find class templates, too. 366 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND)) 367 ND = ClassTemplate->getTemplatedDecl(); 368 369 if (RecordDecl *RD = dyn_cast<RecordDecl>(ND)) 370 return RD->getTagKind() == TagDecl::TK_class || 371 RD->getTagKind() == TagDecl::TK_struct; 372 373 return false; 374} 375 376/// \brief Determines whether the given declaration is a union. 377bool ResultBuilder::IsUnion(NamedDecl *ND) const { 378 // Allow us to find class templates, too. 379 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND)) 380 ND = ClassTemplate->getTemplatedDecl(); 381 382 if (RecordDecl *RD = dyn_cast<RecordDecl>(ND)) 383 return RD->getTagKind() == TagDecl::TK_union; 384 385 return false; 386} 387 388/// \brief Determines whether the given declaration is a namespace. 389bool ResultBuilder::IsNamespace(NamedDecl *ND) const { 390 return isa<NamespaceDecl>(ND); 391} 392 393/// \brief Determines whether the given declaration is a namespace or 394/// namespace alias. 395bool ResultBuilder::IsNamespaceOrAlias(NamedDecl *ND) const { 396 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND); 397} 398 399/// \brief Brief determines whether the given declaration is a namespace or 400/// namespace alias. 401bool ResultBuilder::IsType(NamedDecl *ND) const { 402 return isa<TypeDecl>(ND); 403} 404 405// Find the next outer declaration context corresponding to this scope. 406static DeclContext *findOuterContext(Scope *S) { 407 for (S = S->getParent(); S; S = S->getParent()) 408 if (S->getEntity()) 409 return static_cast<DeclContext *>(S->getEntity())->getPrimaryContext(); 410 411 return 0; 412} 413 414/// \brief Collect the results of searching for members within the given 415/// declaration context. 416/// 417/// \param Ctx the declaration context from which we will gather results. 418/// 419/// \param Rank the rank given to results in this declaration context. 420/// 421/// \param Visited the set of declaration contexts that have already been 422/// visited. Declaration contexts will only be visited once. 423/// 424/// \param Results the result set that will be extended with any results 425/// found within this declaration context (and, for a C++ class, its bases). 426/// 427/// \param InBaseClass whether we are in a base class. 428/// 429/// \returns the next higher rank value, after considering all of the 430/// names within this declaration context. 431static unsigned CollectMemberLookupResults(DeclContext *Ctx, 432 unsigned Rank, 433 DeclContext *CurContext, 434 llvm::SmallPtrSet<DeclContext *, 16> &Visited, 435 ResultBuilder &Results, 436 bool InBaseClass = false) { 437 // Make sure we don't visit the same context twice. 438 if (!Visited.insert(Ctx->getPrimaryContext())) 439 return Rank; 440 441 // Enumerate all of the results in this context. 442 typedef CodeCompleteConsumer::Result Result; 443 Results.EnterNewScope(); 444 for (DeclContext *CurCtx = Ctx->getPrimaryContext(); CurCtx; 445 CurCtx = CurCtx->getNextContext()) { 446 for (DeclContext::decl_iterator D = CurCtx->decls_begin(), 447 DEnd = CurCtx->decls_end(); 448 D != DEnd; ++D) { 449 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D)) 450 Results.MaybeAddResult(Result(ND, Rank, 0, InBaseClass), CurContext); 451 } 452 } 453 454 // Traverse the contexts of inherited classes. 455 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) { 456 for (CXXRecordDecl::base_class_iterator B = Record->bases_begin(), 457 BEnd = Record->bases_end(); 458 B != BEnd; ++B) { 459 QualType BaseType = B->getType(); 460 461 // Don't look into dependent bases, because name lookup can't look 462 // there anyway. 463 if (BaseType->isDependentType()) 464 continue; 465 466 const RecordType *Record = BaseType->getAs<RecordType>(); 467 if (!Record) 468 continue; 469 470 // FIXME: It would be nice to be able to determine whether referencing 471 // a particular member would be ambiguous. For example, given 472 // 473 // struct A { int member; }; 474 // struct B { int member; }; 475 // struct C : A, B { }; 476 // 477 // void f(C *c) { c->### } 478 // accessing 'member' would result in an ambiguity. However, code 479 // completion could be smart enough to qualify the member with the 480 // base class, e.g., 481 // 482 // c->B::member 483 // 484 // or 485 // 486 // c->A::member 487 488 // Collect results from this base class (and its bases). 489 CollectMemberLookupResults(Record->getDecl(), Rank, CurContext, Visited, 490 Results, /*InBaseClass=*/true); 491 } 492 } 493 494 // FIXME: Look into base classes in Objective-C! 495 496 Results.ExitScope(); 497 return Rank + 1; 498} 499 500/// \brief Collect the results of searching for members within the given 501/// declaration context. 502/// 503/// \param Ctx the declaration context from which we will gather results. 504/// 505/// \param InitialRank the initial rank given to results in this declaration 506/// context. Larger rank values will be used for, e.g., members found in 507/// base classes. 508/// 509/// \param Results the result set that will be extended with any results 510/// found within this declaration context (and, for a C++ class, its bases). 511/// 512/// \returns the next higher rank value, after considering all of the 513/// names within this declaration context. 514static unsigned CollectMemberLookupResults(DeclContext *Ctx, 515 unsigned InitialRank, 516 DeclContext *CurContext, 517 ResultBuilder &Results) { 518 llvm::SmallPtrSet<DeclContext *, 16> Visited; 519 return CollectMemberLookupResults(Ctx, InitialRank, CurContext, Visited, 520 Results); 521} 522 523/// \brief Collect the results of searching for declarations within the given 524/// scope and its parent scopes. 525/// 526/// \param S the scope in which we will start looking for declarations. 527/// 528/// \param InitialRank the initial rank given to results in this scope. 529/// Larger rank values will be used for results found in parent scopes. 530/// 531/// \param CurContext the context from which lookup results will be found. 532/// 533/// \param Results the builder object that will receive each result. 534static unsigned CollectLookupResults(Scope *S, 535 TranslationUnitDecl *TranslationUnit, 536 unsigned InitialRank, 537 DeclContext *CurContext, 538 ResultBuilder &Results) { 539 if (!S) 540 return InitialRank; 541 542 // FIXME: Using directives! 543 544 unsigned NextRank = InitialRank; 545 Results.EnterNewScope(); 546 if (S->getEntity() && 547 !((DeclContext *)S->getEntity())->isFunctionOrMethod()) { 548 // Look into this scope's declaration context, along with any of its 549 // parent lookup contexts (e.g., enclosing classes), up to the point 550 // where we hit the context stored in the next outer scope. 551 DeclContext *Ctx = (DeclContext *)S->getEntity(); 552 DeclContext *OuterCtx = findOuterContext(S); 553 554 for (; Ctx && Ctx->getPrimaryContext() != OuterCtx; 555 Ctx = Ctx->getLookupParent()) { 556 if (Ctx->isFunctionOrMethod()) 557 continue; 558 559 NextRank = CollectMemberLookupResults(Ctx, NextRank + 1, CurContext, 560 Results); 561 } 562 } else if (!S->getParent()) { 563 // Look into the translation unit scope. We walk through the translation 564 // unit's declaration context, because the Scope itself won't have all of 565 // the declarations if we loaded a precompiled header. 566 // FIXME: We would like the translation unit's Scope object to point to the 567 // translation unit, so we don't need this special "if" branch. However, 568 // doing so would force the normal C++ name-lookup code to look into the 569 // translation unit decl when the IdentifierInfo chains would suffice. 570 // Once we fix that problem (which is part of a more general "don't look 571 // in DeclContexts unless we have to" optimization), we can eliminate the 572 // TranslationUnit parameter entirely. 573 NextRank = CollectMemberLookupResults(TranslationUnit, NextRank + 1, 574 CurContext, Results); 575 } else { 576 // Walk through the declarations in this Scope. 577 for (Scope::decl_iterator D = S->decl_begin(), DEnd = S->decl_end(); 578 D != DEnd; ++D) { 579 if (NamedDecl *ND = dyn_cast<NamedDecl>((Decl *)((*D).get()))) 580 Results.MaybeAddResult(CodeCompleteConsumer::Result(ND, NextRank), 581 CurContext); 582 } 583 584 NextRank = NextRank + 1; 585 } 586 587 // Lookup names in the parent scope. 588 NextRank = CollectLookupResults(S->getParent(), TranslationUnit, NextRank, 589 CurContext, Results); 590 Results.ExitScope(); 591 592 return NextRank; 593} 594 595/// \brief Add type specifiers for the current language as keyword results. 596static void AddTypeSpecifierResults(const LangOptions &LangOpts, unsigned Rank, 597 ResultBuilder &Results) { 598 typedef CodeCompleteConsumer::Result Result; 599 Results.MaybeAddResult(Result("short", Rank)); 600 Results.MaybeAddResult(Result("long", Rank)); 601 Results.MaybeAddResult(Result("signed", Rank)); 602 Results.MaybeAddResult(Result("unsigned", Rank)); 603 Results.MaybeAddResult(Result("void", Rank)); 604 Results.MaybeAddResult(Result("char", Rank)); 605 Results.MaybeAddResult(Result("int", Rank)); 606 Results.MaybeAddResult(Result("float", Rank)); 607 Results.MaybeAddResult(Result("double", Rank)); 608 Results.MaybeAddResult(Result("enum", Rank)); 609 Results.MaybeAddResult(Result("struct", Rank)); 610 Results.MaybeAddResult(Result("union", Rank)); 611 612 if (LangOpts.C99) { 613 // C99-specific 614 Results.MaybeAddResult(Result("_Complex", Rank)); 615 Results.MaybeAddResult(Result("_Imaginary", Rank)); 616 Results.MaybeAddResult(Result("_Bool", Rank)); 617 } 618 619 if (LangOpts.CPlusPlus) { 620 // C++-specific 621 Results.MaybeAddResult(Result("bool", Rank)); 622 Results.MaybeAddResult(Result("class", Rank)); 623 Results.MaybeAddResult(Result("typename", Rank)); 624 Results.MaybeAddResult(Result("wchar_t", Rank)); 625 626 if (LangOpts.CPlusPlus0x) { 627 Results.MaybeAddResult(Result("char16_t", Rank)); 628 Results.MaybeAddResult(Result("char32_t", Rank)); 629 Results.MaybeAddResult(Result("decltype", Rank)); 630 } 631 } 632 633 // GNU extensions 634 if (LangOpts.GNUMode) { 635 // FIXME: Enable when we actually support decimal floating point. 636 // Results.MaybeAddResult(Result("_Decimal32", Rank)); 637 // Results.MaybeAddResult(Result("_Decimal64", Rank)); 638 // Results.MaybeAddResult(Result("_Decimal128", Rank)); 639 Results.MaybeAddResult(Result("typeof", Rank)); 640 } 641} 642 643/// \brief Add function parameter chunks to the given code completion string. 644static void AddFunctionParameterChunks(ASTContext &Context, 645 FunctionDecl *Function, 646 CodeCompletionString *Result) { 647 CodeCompletionString *CCStr = Result; 648 649 for (unsigned P = 0, N = Function->getNumParams(); P != N; ++P) { 650 ParmVarDecl *Param = Function->getParamDecl(P); 651 652 if (Param->hasDefaultArg()) { 653 // When we see an optional default argument, put that argument and 654 // the remaining default arguments into a new, optional string. 655 CodeCompletionString *Opt = new CodeCompletionString; 656 CCStr->AddOptionalChunk(std::auto_ptr<CodeCompletionString>(Opt)); 657 CCStr = Opt; 658 } 659 660 if (P != 0) 661 CCStr->AddTextChunk(", "); 662 663 // Format the placeholder string. 664 std::string PlaceholderStr; 665 if (Param->getIdentifier()) 666 PlaceholderStr = Param->getIdentifier()->getName(); 667 668 Param->getType().getAsStringInternal(PlaceholderStr, 669 Context.PrintingPolicy); 670 671 // Add the placeholder string. 672 CCStr->AddPlaceholderChunk(PlaceholderStr.c_str()); 673 } 674 675 if (const FunctionProtoType *Proto 676 = Function->getType()->getAs<FunctionProtoType>()) 677 if (Proto->isVariadic()) 678 CCStr->AddPlaceholderChunk(", ..."); 679} 680 681/// \brief Add template parameter chunks to the given code completion string. 682static void AddTemplateParameterChunks(ASTContext &Context, 683 TemplateDecl *Template, 684 CodeCompletionString *Result, 685 unsigned MaxParameters = 0) { 686 CodeCompletionString *CCStr = Result; 687 bool FirstParameter = true; 688 689 TemplateParameterList *Params = Template->getTemplateParameters(); 690 TemplateParameterList::iterator PEnd = Params->end(); 691 if (MaxParameters) 692 PEnd = Params->begin() + MaxParameters; 693 for (TemplateParameterList::iterator P = Params->begin(); P != PEnd; ++P) { 694 bool HasDefaultArg = false; 695 std::string PlaceholderStr; 696 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) { 697 if (TTP->wasDeclaredWithTypename()) 698 PlaceholderStr = "typename"; 699 else 700 PlaceholderStr = "class"; 701 702 if (TTP->getIdentifier()) { 703 PlaceholderStr += ' '; 704 PlaceholderStr += TTP->getIdentifier()->getName(); 705 } 706 707 HasDefaultArg = TTP->hasDefaultArgument(); 708 } else if (NonTypeTemplateParmDecl *NTTP 709 = dyn_cast<NonTypeTemplateParmDecl>(*P)) { 710 if (NTTP->getIdentifier()) 711 PlaceholderStr = NTTP->getIdentifier()->getName(); 712 NTTP->getType().getAsStringInternal(PlaceholderStr, 713 Context.PrintingPolicy); 714 HasDefaultArg = NTTP->hasDefaultArgument(); 715 } else { 716 assert(isa<TemplateTemplateParmDecl>(*P)); 717 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P); 718 719 // Since putting the template argument list into the placeholder would 720 // be very, very long, we just use an abbreviation. 721 PlaceholderStr = "template<...> class"; 722 if (TTP->getIdentifier()) { 723 PlaceholderStr += ' '; 724 PlaceholderStr += TTP->getIdentifier()->getName(); 725 } 726 727 HasDefaultArg = TTP->hasDefaultArgument(); 728 } 729 730 if (HasDefaultArg) { 731 // When we see an optional default argument, put that argument and 732 // the remaining default arguments into a new, optional string. 733 CodeCompletionString *Opt = new CodeCompletionString; 734 CCStr->AddOptionalChunk(std::auto_ptr<CodeCompletionString>(Opt)); 735 CCStr = Opt; 736 } 737 738 if (FirstParameter) 739 FirstParameter = false; 740 else 741 CCStr->AddTextChunk(", "); 742 743 // Add the placeholder string. 744 CCStr->AddPlaceholderChunk(PlaceholderStr.c_str()); 745 } 746} 747 748/// \brief Add a qualifier to the given code-completion string, if the 749/// provided nested-name-specifier is non-NULL. 750void AddQualifierToCompletionString(CodeCompletionString *Result, 751 NestedNameSpecifier *Qualifier, 752 bool QualifierIsInformative, 753 ASTContext &Context) { 754 if (!Qualifier) 755 return; 756 757 std::string PrintedNNS; 758 { 759 llvm::raw_string_ostream OS(PrintedNNS); 760 Qualifier->print(OS, Context.PrintingPolicy); 761 } 762 if (QualifierIsInformative) 763 Result->AddInformativeChunk(PrintedNNS.c_str()); 764 else 765 Result->AddTextChunk(PrintedNNS.c_str()); 766} 767 768/// \brief If possible, create a new code completion string for the given 769/// result. 770/// 771/// \returns Either a new, heap-allocated code completion string describing 772/// how to use this result, or NULL to indicate that the string or name of the 773/// result is all that is needed. 774CodeCompletionString * 775CodeCompleteConsumer::Result::CreateCodeCompletionString(Sema &S) { 776 if (Kind != RK_Declaration) 777 return 0; 778 779 NamedDecl *ND = Declaration; 780 781 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND)) { 782 CodeCompletionString *Result = new CodeCompletionString; 783 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative, 784 S.Context); 785 Result->AddTextChunk(Function->getNameAsString().c_str()); 786 Result->AddTextChunk("("); 787 AddFunctionParameterChunks(S.Context, Function, Result); 788 Result->AddTextChunk(")"); 789 return Result; 790 } 791 792 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND)) { 793 CodeCompletionString *Result = new CodeCompletionString; 794 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative, 795 S.Context); 796 FunctionDecl *Function = FunTmpl->getTemplatedDecl(); 797 Result->AddTextChunk(Function->getNameAsString().c_str()); 798 799 // Figure out which template parameters are deduced (or have default 800 // arguments). 801 llvm::SmallVector<bool, 16> Deduced; 802 S.MarkDeducedTemplateParameters(FunTmpl, Deduced); 803 unsigned LastDeducibleArgument; 804 for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0; 805 --LastDeducibleArgument) { 806 if (!Deduced[LastDeducibleArgument - 1]) { 807 // C++0x: Figure out if the template argument has a default. If so, 808 // the user doesn't need to type this argument. 809 // FIXME: We need to abstract template parameters better! 810 bool HasDefaultArg = false; 811 NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam( 812 LastDeducibleArgument - 1); 813 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) 814 HasDefaultArg = TTP->hasDefaultArgument(); 815 else if (NonTypeTemplateParmDecl *NTTP 816 = dyn_cast<NonTypeTemplateParmDecl>(Param)) 817 HasDefaultArg = NTTP->hasDefaultArgument(); 818 else { 819 assert(isa<TemplateTemplateParmDecl>(Param)); 820 HasDefaultArg 821 = cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument(); 822 } 823 824 if (!HasDefaultArg) 825 break; 826 } 827 } 828 829 if (LastDeducibleArgument) { 830 // Some of the function template arguments cannot be deduced from a 831 // function call, so we introduce an explicit template argument list 832 // containing all of the arguments up to the first deducible argument. 833 Result->AddTextChunk("<"); 834 AddTemplateParameterChunks(S.Context, FunTmpl, Result, 835 LastDeducibleArgument); 836 Result->AddTextChunk(">"); 837 } 838 839 // Add the function parameters 840 Result->AddTextChunk("("); 841 AddFunctionParameterChunks(S.Context, Function, Result); 842 Result->AddTextChunk(")"); 843 return Result; 844 } 845 846 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(ND)) { 847 CodeCompletionString *Result = new CodeCompletionString; 848 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative, 849 S.Context); 850 Result->AddTextChunk(Template->getNameAsString().c_str()); 851 Result->AddTextChunk("<"); 852 AddTemplateParameterChunks(S.Context, Template, Result); 853 Result->AddTextChunk(">"); 854 return Result; 855 } 856 857 if (Qualifier || StartsNestedNameSpecifier) { 858 CodeCompletionString *Result = new CodeCompletionString; 859 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative, 860 S.Context); 861 Result->AddTextChunk(ND->getNameAsString().c_str()); 862 if (StartsNestedNameSpecifier) 863 Result->AddTextChunk("::"); 864 return Result; 865 } 866 867 return 0; 868} 869 870namespace { 871 struct SortCodeCompleteResult { 872 typedef CodeCompleteConsumer::Result Result; 873 874 bool operator()(const Result &X, const Result &Y) const { 875 // Sort first by rank. 876 if (X.Rank < Y.Rank) 877 return true; 878 else if (X.Rank > Y.Rank) 879 return false; 880 881 // Result kinds are ordered by decreasing importance. 882 if (X.Kind < Y.Kind) 883 return true; 884 else if (X.Kind > Y.Kind) 885 return false; 886 887 // Non-hidden names precede hidden names. 888 if (X.Hidden != Y.Hidden) 889 return !X.Hidden; 890 891 // Ordering depends on the kind of result. 892 switch (X.Kind) { 893 case Result::RK_Declaration: 894 // Order based on the declaration names. 895 return X.Declaration->getDeclName() < Y.Declaration->getDeclName(); 896 897 case Result::RK_Keyword: 898 return strcmp(X.Keyword, Y.Keyword) == -1; 899 } 900 901 // Silence GCC warning. 902 return false; 903 } 904 }; 905} 906 907static void HandleCodeCompleteResults(CodeCompleteConsumer *CodeCompleter, 908 CodeCompleteConsumer::Result *Results, 909 unsigned NumResults) { 910 // Sort the results by rank/kind/etc. 911 std::stable_sort(Results, Results + NumResults, SortCodeCompleteResult()); 912 913 if (CodeCompleter) 914 CodeCompleter->ProcessCodeCompleteResults(Results, NumResults); 915} 916 917void Sema::CodeCompleteOrdinaryName(Scope *S) { 918 ResultBuilder Results(*this, &ResultBuilder::IsOrdinaryName); 919 CollectLookupResults(S, Context.getTranslationUnitDecl(), 0, CurContext, 920 Results); 921 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size()); 922} 923 924void Sema::CodeCompleteMemberReferenceExpr(Scope *S, ExprTy *BaseE, 925 SourceLocation OpLoc, 926 bool IsArrow) { 927 if (!BaseE || !CodeCompleter) 928 return; 929 930 typedef CodeCompleteConsumer::Result Result; 931 932 Expr *Base = static_cast<Expr *>(BaseE); 933 QualType BaseType = Base->getType(); 934 935 if (IsArrow) { 936 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) 937 BaseType = Ptr->getPointeeType(); 938 else if (BaseType->isObjCObjectPointerType()) 939 /*Do nothing*/ ; 940 else 941 return; 942 } 943 944 ResultBuilder Results(*this); 945 unsigned NextRank = 0; 946 947 if (const RecordType *Record = BaseType->getAs<RecordType>()) { 948 NextRank = CollectMemberLookupResults(Record->getDecl(), NextRank, 949 Record->getDecl(), Results); 950 951 if (getLangOptions().CPlusPlus) { 952 if (!Results.empty()) { 953 // The "template" keyword can follow "->" or "." in the grammar. 954 // However, we only want to suggest the template keyword if something 955 // is dependent. 956 bool IsDependent = BaseType->isDependentType(); 957 if (!IsDependent) { 958 for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent()) 959 if (DeclContext *Ctx = (DeclContext *)DepScope->getEntity()) { 960 IsDependent = Ctx->isDependentContext(); 961 break; 962 } 963 } 964 965 if (IsDependent) 966 Results.MaybeAddResult(Result("template", NextRank++)); 967 } 968 969 // We could have the start of a nested-name-specifier. Add those 970 // results as well. 971 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier); 972 CollectLookupResults(S, Context.getTranslationUnitDecl(), NextRank, 973 CurContext, Results); 974 } 975 976 // Hand off the results found for code completion. 977 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size()); 978 979 // We're done! 980 return; 981 } 982} 983 984void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) { 985 if (!CodeCompleter) 986 return; 987 988 typedef CodeCompleteConsumer::Result Result; 989 ResultBuilder::LookupFilter Filter = 0; 990 switch ((DeclSpec::TST)TagSpec) { 991 case DeclSpec::TST_enum: 992 Filter = &ResultBuilder::IsEnum; 993 break; 994 995 case DeclSpec::TST_union: 996 Filter = &ResultBuilder::IsUnion; 997 break; 998 999 case DeclSpec::TST_struct: 1000 case DeclSpec::TST_class: 1001 Filter = &ResultBuilder::IsClassOrStruct; 1002 break; 1003 1004 default: 1005 assert(false && "Unknown type specifier kind in CodeCompleteTag"); 1006 return; 1007 } 1008 1009 ResultBuilder Results(*this, Filter); 1010 unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(), 1011 0, CurContext, Results); 1012 1013 if (getLangOptions().CPlusPlus) { 1014 // We could have the start of a nested-name-specifier. Add those 1015 // results as well. 1016 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier); 1017 CollectLookupResults(S, Context.getTranslationUnitDecl(), NextRank, 1018 CurContext, Results); 1019 } 1020 1021 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size()); 1022} 1023 1024void Sema::CodeCompleteCase(Scope *S) { 1025 if (getSwitchStack().empty() || !CodeCompleter) 1026 return; 1027 1028 SwitchStmt *Switch = getSwitchStack().back(); 1029 if (!Switch->getCond()->getType()->isEnumeralType()) 1030 return; 1031 1032 // Code-complete the cases of a switch statement over an enumeration type 1033 // by providing the list of 1034 EnumDecl *Enum = Switch->getCond()->getType()->getAs<EnumType>()->getDecl(); 1035 1036 // Determine which enumerators we have already seen in the switch statement. 1037 // FIXME: Ideally, we would also be able to look *past* the code-completion 1038 // token, in case we are code-completing in the middle of the switch and not 1039 // at the end. However, we aren't able to do so at the moment. 1040 llvm::SmallPtrSet<EnumConstantDecl *, 8> EnumeratorsSeen; 1041 NestedNameSpecifier *Qualifier = 0; 1042 for (SwitchCase *SC = Switch->getSwitchCaseList(); SC; 1043 SC = SC->getNextSwitchCase()) { 1044 CaseStmt *Case = dyn_cast<CaseStmt>(SC); 1045 if (!Case) 1046 continue; 1047 1048 Expr *CaseVal = Case->getLHS()->IgnoreParenCasts(); 1049 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseVal)) 1050 if (EnumConstantDecl *Enumerator 1051 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 1052 // We look into the AST of the case statement to determine which 1053 // enumerator was named. Alternatively, we could compute the value of 1054 // the integral constant expression, then compare it against the 1055 // values of each enumerator. However, value-based approach would not 1056 // work as well with C++ templates where enumerators declared within a 1057 // template are type- and value-dependent. 1058 EnumeratorsSeen.insert(Enumerator); 1059 1060 // If this is a qualified-id, keep track of the nested-name-specifier 1061 // so that we can reproduce it as part of code completion, e.g., 1062 // 1063 // switch (TagD.getKind()) { 1064 // case TagDecl::TK_enum: 1065 // break; 1066 // case XXX 1067 // 1068 // At the XXX, our completions are TagDecl::TK_union, 1069 // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union, 1070 // TK_struct, and TK_class. 1071 if (QualifiedDeclRefExpr *QDRE = dyn_cast<QualifiedDeclRefExpr>(DRE)) 1072 Qualifier = QDRE->getQualifier(); 1073 } 1074 } 1075 1076 if (getLangOptions().CPlusPlus && !Qualifier && EnumeratorsSeen.empty()) { 1077 // If there are no prior enumerators in C++, check whether we have to 1078 // qualify the names of the enumerators that we suggest, because they 1079 // may not be visible in this scope. 1080 Qualifier = getRequiredQualification(Context, CurContext, 1081 Enum->getDeclContext()); 1082 1083 // FIXME: Scoped enums need to start with "EnumDecl" as the context! 1084 } 1085 1086 // Add any enumerators that have not yet been mentioned. 1087 ResultBuilder Results(*this); 1088 Results.EnterNewScope(); 1089 for (EnumDecl::enumerator_iterator E = Enum->enumerator_begin(), 1090 EEnd = Enum->enumerator_end(); 1091 E != EEnd; ++E) { 1092 if (EnumeratorsSeen.count(*E)) 1093 continue; 1094 1095 Results.MaybeAddResult(CodeCompleteConsumer::Result(*E, 0, Qualifier)); 1096 } 1097 Results.ExitScope(); 1098 1099 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size()); 1100} 1101 1102namespace { 1103 struct IsBetterOverloadCandidate { 1104 Sema &S; 1105 1106 public: 1107 explicit IsBetterOverloadCandidate(Sema &S) : S(S) { } 1108 1109 bool 1110 operator()(const OverloadCandidate &X, const OverloadCandidate &Y) const { 1111 return S.isBetterOverloadCandidate(X, Y); 1112 } 1113 }; 1114} 1115 1116void Sema::CodeCompleteCall(Scope *S, ExprTy *FnIn, 1117 ExprTy **ArgsIn, unsigned NumArgs) { 1118 if (!CodeCompleter) 1119 return; 1120 1121 Expr *Fn = (Expr *)FnIn; 1122 Expr **Args = (Expr **)ArgsIn; 1123 1124 // Ignore type-dependent call expressions entirely. 1125 if (Fn->isTypeDependent() || 1126 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) 1127 return; 1128 1129 NamedDecl *Function; 1130 DeclarationName UnqualifiedName; 1131 NestedNameSpecifier *Qualifier; 1132 SourceRange QualifierRange; 1133 bool ArgumentDependentLookup; 1134 bool HasExplicitTemplateArgs; 1135 const TemplateArgument *ExplicitTemplateArgs; 1136 unsigned NumExplicitTemplateArgs; 1137 1138 DeconstructCallFunction(Fn, 1139 Function, UnqualifiedName, Qualifier, QualifierRange, 1140 ArgumentDependentLookup, HasExplicitTemplateArgs, 1141 ExplicitTemplateArgs, NumExplicitTemplateArgs); 1142 1143 1144 // FIXME: What if we're calling something that isn't a function declaration? 1145 // FIXME: What if we're calling a pseudo-destructor? 1146 // FIXME: What if we're calling a member function? 1147 1148 // Build an overload candidate set based on the functions we find. 1149 OverloadCandidateSet CandidateSet; 1150 AddOverloadedCallCandidates(Function, UnqualifiedName, 1151 ArgumentDependentLookup, HasExplicitTemplateArgs, 1152 ExplicitTemplateArgs, NumExplicitTemplateArgs, 1153 Args, NumArgs, 1154 CandidateSet, 1155 /*PartialOverloading=*/true); 1156 1157 // Sort the overload candidate set by placing the best overloads first. 1158 std::stable_sort(CandidateSet.begin(), CandidateSet.end(), 1159 IsBetterOverloadCandidate(*this)); 1160 1161 // Add the remaining viable overload candidates as code-completion reslults. 1162 typedef CodeCompleteConsumer::Result Result; 1163 ResultBuilder Results(*this); 1164 Results.EnterNewScope(); 1165 1166 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 1167 CandEnd = CandidateSet.end(); 1168 Cand != CandEnd; ++Cand) { 1169 if (Cand->Viable) 1170 Results.MaybeAddResult(Result(Cand->Function, 0), 0); 1171 } 1172 1173 Results.ExitScope(); 1174 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size()); 1175} 1176 1177void Sema::CodeCompleteQualifiedId(Scope *S, const CXXScopeSpec &SS, 1178 bool EnteringContext) { 1179 if (!SS.getScopeRep() || !CodeCompleter) 1180 return; 1181 1182 DeclContext *Ctx = computeDeclContext(SS, EnteringContext); 1183 if (!Ctx) 1184 return; 1185 1186 ResultBuilder Results(*this); 1187 unsigned NextRank = CollectMemberLookupResults(Ctx, 0, Ctx, Results); 1188 1189 // The "template" keyword can follow "::" in the grammar, but only 1190 // put it into the grammar if the nested-name-specifier is dependent. 1191 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep(); 1192 if (!Results.empty() && NNS->isDependent()) 1193 Results.MaybeAddResult(CodeCompleteConsumer::Result("template", NextRank)); 1194 1195 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size()); 1196} 1197 1198void Sema::CodeCompleteUsing(Scope *S) { 1199 if (!CodeCompleter) 1200 return; 1201 1202 ResultBuilder Results(*this, &ResultBuilder::IsNestedNameSpecifier); 1203 1204 // If we aren't in class scope, we could see the "namespace" keyword. 1205 if (!S->isClassScope()) 1206 Results.MaybeAddResult(CodeCompleteConsumer::Result("namespace", 0)); 1207 1208 // After "using", we can see anything that would start a 1209 // nested-name-specifier. 1210 CollectLookupResults(S, Context.getTranslationUnitDecl(), 0, 1211 CurContext, Results); 1212 1213 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size()); 1214} 1215 1216void Sema::CodeCompleteUsingDirective(Scope *S) { 1217 if (!CodeCompleter) 1218 return; 1219 1220 // After "using namespace", we expect to see a namespace name or namespace 1221 // alias. 1222 ResultBuilder Results(*this, &ResultBuilder::IsNamespaceOrAlias); 1223 CollectLookupResults(S, Context.getTranslationUnitDecl(), 0, CurContext, 1224 Results); 1225 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size()); 1226} 1227 1228void Sema::CodeCompleteNamespaceDecl(Scope *S) { 1229 if (!CodeCompleter) 1230 return; 1231 1232 ResultBuilder Results(*this, &ResultBuilder::IsNamespace); 1233 DeclContext *Ctx = (DeclContext *)S->getEntity(); 1234 if (!S->getParent()) 1235 Ctx = Context.getTranslationUnitDecl(); 1236 1237 if (Ctx && Ctx->isFileContext()) { 1238 // We only want to see those namespaces that have already been defined 1239 // within this scope, because its likely that the user is creating an 1240 // extended namespace declaration. Keep track of the most recent 1241 // definition of each namespace. 1242 std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest; 1243 for (DeclContext::specific_decl_iterator<NamespaceDecl> 1244 NS(Ctx->decls_begin()), NSEnd(Ctx->decls_end()); 1245 NS != NSEnd; ++NS) 1246 OrigToLatest[NS->getOriginalNamespace()] = *NS; 1247 1248 // Add the most recent definition (or extended definition) of each 1249 // namespace to the list of results. 1250 for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator 1251 NS = OrigToLatest.begin(), NSEnd = OrigToLatest.end(); 1252 NS != NSEnd; ++NS) 1253 Results.MaybeAddResult(CodeCompleteConsumer::Result(NS->second, 0), 1254 CurContext); 1255 } 1256 1257 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size()); 1258} 1259 1260void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) { 1261 if (!CodeCompleter) 1262 return; 1263 1264 // After "namespace", we expect to see a namespace or alias. 1265 ResultBuilder Results(*this, &ResultBuilder::IsNamespaceOrAlias); 1266 CollectLookupResults(S, Context.getTranslationUnitDecl(), 0, CurContext, 1267 Results); 1268 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size()); 1269} 1270 1271void Sema::CodeCompleteOperatorName(Scope *S) { 1272 if (!CodeCompleter) 1273 return; 1274 1275 typedef CodeCompleteConsumer::Result Result; 1276 ResultBuilder Results(*this, &ResultBuilder::IsType); 1277 1278 // Add the names of overloadable operators. 1279#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 1280 if (std::strcmp(Spelling, "?")) \ 1281 Results.MaybeAddResult(Result(Spelling, 0)); 1282#include "clang/Basic/OperatorKinds.def" 1283 1284 // Add any type names visible from the current scope 1285 unsigned NextRank = CollectLookupResults(S, Context.getTranslationUnitDecl(), 1286 0, CurContext, Results); 1287 1288 // Add any type specifiers 1289 AddTypeSpecifierResults(getLangOptions(), 0, Results); 1290 1291 // Add any nested-name-specifiers 1292 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier); 1293 CollectLookupResults(S, Context.getTranslationUnitDecl(), NextRank + 1, 1294 CurContext, Results); 1295 1296 HandleCodeCompleteResults(CodeCompleter, Results.data(), Results.size()); 1297} 1298 1299