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