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 "Lookup.h" 15 #include "clang/Sema/CodeCompleteConsumer.h" 16 #include "clang/Sema/ExternalSemaSource.h" 17 #include "clang/AST/ExprCXX.h" 18 #include "clang/AST/ExprObjC.h" 19 #include "clang/Lex/MacroInfo.h" 20 #include "clang/Lex/Preprocessor.h" 21 #include "llvm/ADT/SmallPtrSet.h" 22 #include "llvm/ADT/StringExtras.h" 23 #include "llvm/ADT/StringSwitch.h" 24 #include <list> 25 #include <map> 26 #include <vector> 27 28 using namespace clang; 29 30 namespace { 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 typedef std::pair<NamedDecl *, unsigned> DeclIndexPair; 52 53 /// \brief An entry in the shadow map, which is optimized to store 54 /// a single (declaration, index) mapping (the common case) but 55 /// can also store a list of (declaration, index) mappings. 56 class ShadowMapEntry { 57 typedef llvm::SmallVector<DeclIndexPair, 4> DeclIndexPairVector; 58 59 /// \brief Contains either the solitary NamedDecl * or a vector 60 /// of (declaration, index) pairs. 61 llvm::PointerUnion<NamedDecl *, DeclIndexPairVector*> DeclOrVector; 62 63 /// \brief When the entry contains a single declaration, this is 64 /// the index associated with that entry. 65 unsigned SingleDeclIndex; 66 67 public: 68 ShadowMapEntry() : DeclOrVector(), SingleDeclIndex(0) { } 69 70 void Add(NamedDecl *ND, unsigned Index) { 71 if (DeclOrVector.isNull()) { 72 // 0 - > 1 elements: just set the single element information. 73 DeclOrVector = ND; 74 SingleDeclIndex = Index; 75 return; 76 } 77 78 if (NamedDecl *PrevND = DeclOrVector.dyn_cast<NamedDecl *>()) { 79 // 1 -> 2 elements: create the vector of results and push in the 80 // existing declaration. 81 DeclIndexPairVector *Vec = new DeclIndexPairVector; 82 Vec->push_back(DeclIndexPair(PrevND, SingleDeclIndex)); 83 DeclOrVector = Vec; 84 } 85 86 // Add the new element to the end of the vector. 87 DeclOrVector.get<DeclIndexPairVector*>()->push_back( 88 DeclIndexPair(ND, Index)); 89 } 90 91 void Destroy() { 92 if (DeclIndexPairVector *Vec 93 = DeclOrVector.dyn_cast<DeclIndexPairVector *>()) { 94 delete Vec; 95 DeclOrVector = ((NamedDecl *)0); 96 } 97 } 98 99 // Iteration. 100 class iterator; 101 iterator begin() const; 102 iterator end() const; 103 }; 104 105 /// \brief A mapping from declaration names to the declarations that have 106 /// this name within a particular scope and their index within the list of 107 /// results. 108 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap; 109 110 /// \brief The semantic analysis object for which results are being 111 /// produced. 112 Sema &SemaRef; 113 114 /// \brief If non-NULL, a filter function used to remove any code-completion 115 /// results that are not desirable. 116 LookupFilter Filter; 117 118 /// \brief Whether we should allow declarations as 119 /// nested-name-specifiers that would otherwise be filtered out. 120 bool AllowNestedNameSpecifiers; 121 122 /// \brief A list of shadow maps, which is used to model name hiding at 123 /// different levels of, e.g., the inheritance hierarchy. 124 std::list<ShadowMap> ShadowMaps; 125 126 public: 127 explicit ResultBuilder(Sema &SemaRef, LookupFilter Filter = 0) 128 : SemaRef(SemaRef), Filter(Filter), AllowNestedNameSpecifiers(false) { } 129 130 /// \brief Whether we should include code patterns in the completion 131 /// results. 132 bool includeCodePatterns() const { 133 return SemaRef.CodeCompleter && 134 SemaRef.CodeCompleter->includeCodePatterns(); 135 } 136 137 /// \brief Set the filter used for code-completion results. 138 void setFilter(LookupFilter Filter) { 139 this->Filter = Filter; 140 } 141 142 typedef std::vector<Result>::iterator iterator; 143 iterator begin() { return Results.begin(); } 144 iterator end() { return Results.end(); } 145 146 Result *data() { return Results.empty()? 0 : &Results.front(); } 147 unsigned size() const { return Results.size(); } 148 bool empty() const { return Results.empty(); } 149 150 /// \brief Specify whether nested-name-specifiers are allowed. 151 void allowNestedNameSpecifiers(bool Allow = true) { 152 AllowNestedNameSpecifiers = Allow; 153 } 154 155 /// \brief Determine whether the given declaration is at all interesting 156 /// as a code-completion result. 157 /// 158 /// \param ND the declaration that we are inspecting. 159 /// 160 /// \param AsNestedNameSpecifier will be set true if this declaration is 161 /// only interesting when it is a nested-name-specifier. 162 bool isInterestingDecl(NamedDecl *ND, bool &AsNestedNameSpecifier) const; 163 164 /// \brief Check whether the result is hidden by the Hiding declaration. 165 /// 166 /// \returns true if the result is hidden and cannot be found, false if 167 /// the hidden result could still be found. When false, \p R may be 168 /// modified to describe how the result can be found (e.g., via extra 169 /// qualification). 170 bool CheckHiddenResult(Result &R, DeclContext *CurContext, 171 NamedDecl *Hiding); 172 173 /// \brief Add a new result to this result set (if it isn't already in one 174 /// of the shadow maps), or replace an existing result (for, e.g., a 175 /// redeclaration). 176 /// 177 /// \param CurContext the result to add (if it is unique). 178 /// 179 /// \param R the context in which this result will be named. 180 void MaybeAddResult(Result R, DeclContext *CurContext = 0); 181 182 /// \brief Add a new result to this result set, where we already know 183 /// the hiding declation (if any). 184 /// 185 /// \param R the result to add (if it is unique). 186 /// 187 /// \param CurContext the context in which this result will be named. 188 /// 189 /// \param Hiding the declaration that hides the result. 190 /// 191 /// \param InBaseClass whether the result was found in a base 192 /// class of the searched context. 193 void AddResult(Result R, DeclContext *CurContext, NamedDecl *Hiding, 194 bool InBaseClass); 195 196 /// \brief Add a new non-declaration result to this result set. 197 void AddResult(Result R); 198 199 /// \brief Enter into a new scope. 200 void EnterNewScope(); 201 202 /// \brief Exit from the current scope. 203 void ExitScope(); 204 205 /// \brief Ignore this declaration, if it is seen again. 206 void Ignore(Decl *D) { AllDeclsFound.insert(D->getCanonicalDecl()); } 207 208 /// \name Name lookup predicates 209 /// 210 /// These predicates can be passed to the name lookup functions to filter the 211 /// results of name lookup. All of the predicates have the same type, so that 212 /// 213 //@{ 214 bool IsOrdinaryName(NamedDecl *ND) const; 215 bool IsOrdinaryNonValueName(NamedDecl *ND) const; 216 bool IsNestedNameSpecifier(NamedDecl *ND) const; 217 bool IsEnum(NamedDecl *ND) const; 218 bool IsClassOrStruct(NamedDecl *ND) const; 219 bool IsUnion(NamedDecl *ND) const; 220 bool IsNamespace(NamedDecl *ND) const; 221 bool IsNamespaceOrAlias(NamedDecl *ND) const; 222 bool IsType(NamedDecl *ND) const; 223 bool IsMember(NamedDecl *ND) const; 224 bool IsObjCIvar(NamedDecl *ND) const; 225 //@} 226 }; 227 } 228 229 class ResultBuilder::ShadowMapEntry::iterator { 230 llvm::PointerUnion<NamedDecl*, const DeclIndexPair*> DeclOrIterator; 231 unsigned SingleDeclIndex; 232 233 public: 234 typedef DeclIndexPair value_type; 235 typedef value_type reference; 236 typedef std::ptrdiff_t difference_type; 237 typedef std::input_iterator_tag iterator_category; 238 239 class pointer { 240 DeclIndexPair Value; 241 242 public: 243 pointer(const DeclIndexPair &Value) : Value(Value) { } 244 245 const DeclIndexPair *operator->() const { 246 return &Value; 247 } 248 }; 249 250 iterator() : DeclOrIterator((NamedDecl *)0), SingleDeclIndex(0) { } 251 252 iterator(NamedDecl *SingleDecl, unsigned Index) 253 : DeclOrIterator(SingleDecl), SingleDeclIndex(Index) { } 254 255 iterator(const DeclIndexPair *Iterator) 256 : DeclOrIterator(Iterator), SingleDeclIndex(0) { } 257 258 iterator &operator++() { 259 if (DeclOrIterator.is<NamedDecl *>()) { 260 DeclOrIterator = (NamedDecl *)0; 261 SingleDeclIndex = 0; 262 return *this; 263 } 264 265 const DeclIndexPair *I = DeclOrIterator.get<const DeclIndexPair*>(); 266 ++I; 267 DeclOrIterator = I; 268 return *this; 269 } 270 271 iterator operator++(int) { 272 iterator tmp(*this); 273 ++(*this); 274 return tmp; 275 } 276 277 reference operator*() const { 278 if (NamedDecl *ND = DeclOrIterator.dyn_cast<NamedDecl *>()) 279 return reference(ND, SingleDeclIndex); 280 281 return *DeclOrIterator.get<const DeclIndexPair*>(); 282 } 283 284 pointer operator->() const { 285 return pointer(**this); 286 } 287 288 friend bool operator==(const iterator &X, const iterator &Y) { 289 return X.DeclOrIterator.getOpaqueValue() 290 == Y.DeclOrIterator.getOpaqueValue() && 291 X.SingleDeclIndex == Y.SingleDeclIndex; 292 } 293 294 friend bool operator!=(const iterator &X, const iterator &Y) { 295 return !(X == Y); 296 } 297 }; 298 299 ResultBuilder::ShadowMapEntry::iterator 300 ResultBuilder::ShadowMapEntry::begin() const { 301 if (DeclOrVector.isNull()) 302 return iterator(); 303 304 if (NamedDecl *ND = DeclOrVector.dyn_cast<NamedDecl *>()) 305 return iterator(ND, SingleDeclIndex); 306 307 return iterator(DeclOrVector.get<DeclIndexPairVector *>()->begin()); 308 } 309 310 ResultBuilder::ShadowMapEntry::iterator 311 ResultBuilder::ShadowMapEntry::end() const { 312 if (DeclOrVector.is<NamedDecl *>() || DeclOrVector.isNull()) 313 return iterator(); 314 315 return iterator(DeclOrVector.get<DeclIndexPairVector *>()->end()); 316 } 317 318 /// \brief Compute the qualification required to get from the current context 319 /// (\p CurContext) to the target context (\p TargetContext). 320 /// 321 /// \param Context the AST context in which the qualification will be used. 322 /// 323 /// \param CurContext the context where an entity is being named, which is 324 /// typically based on the current scope. 325 /// 326 /// \param TargetContext the context in which the named entity actually 327 /// resides. 328 /// 329 /// \returns a nested name specifier that refers into the target context, or 330 /// NULL if no qualification is needed. 331 static NestedNameSpecifier * 332 getRequiredQualification(ASTContext &Context, 333 DeclContext *CurContext, 334 DeclContext *TargetContext) { 335 llvm::SmallVector<DeclContext *, 4> TargetParents; 336 337 for (DeclContext *CommonAncestor = TargetContext; 338 CommonAncestor && !CommonAncestor->Encloses(CurContext); 339 CommonAncestor = CommonAncestor->getLookupParent()) { 340 if (CommonAncestor->isTransparentContext() || 341 CommonAncestor->isFunctionOrMethod()) 342 continue; 343 344 TargetParents.push_back(CommonAncestor); 345 } 346 347 NestedNameSpecifier *Result = 0; 348 while (!TargetParents.empty()) { 349 DeclContext *Parent = TargetParents.back(); 350 TargetParents.pop_back(); 351 352 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Parent)) 353 Result = NestedNameSpecifier::Create(Context, Result, Namespace); 354 else if (TagDecl *TD = dyn_cast<TagDecl>(Parent)) 355 Result = NestedNameSpecifier::Create(Context, Result, 356 false, 357 Context.getTypeDeclType(TD).getTypePtr()); 358 else 359 assert(Parent->isTranslationUnit()); 360 } 361 return Result; 362 } 363 364 bool ResultBuilder::isInterestingDecl(NamedDecl *ND, 365 bool &AsNestedNameSpecifier) const { 366 AsNestedNameSpecifier = false; 367 368 ND = ND->getUnderlyingDecl(); 369 unsigned IDNS = ND->getIdentifierNamespace(); 370 371 // Skip unnamed entities. 372 if (!ND->getDeclName()) 373 return false; 374 375 // Friend declarations and declarations introduced due to friends are never 376 // added as results. 377 if (IDNS & (Decl::IDNS_OrdinaryFriend | Decl::IDNS_TagFriend)) 378 return false; 379 380 // Class template (partial) specializations are never added as results. 381 if (isa<ClassTemplateSpecializationDecl>(ND) || 382 isa<ClassTemplatePartialSpecializationDecl>(ND)) 383 return false; 384 385 // Using declarations themselves are never added as results. 386 if (isa<UsingDecl>(ND)) 387 return false; 388 389 // Some declarations have reserved names that we don't want to ever show. 390 if (const IdentifierInfo *Id = ND->getIdentifier()) { 391 // __va_list_tag is a freak of nature. Find it and skip it. 392 if (Id->isStr("__va_list_tag") || Id->isStr("__builtin_va_list")) 393 return false; 394 395 // Filter out names reserved for the implementation (C99 7.1.3, 396 // C++ [lib.global.names]). Users don't need to see those. 397 // 398 // FIXME: Add predicate for this. 399 if (Id->getLength() >= 2) { 400 const char *Name = Id->getNameStart(); 401 if (Name[0] == '_' && 402 (Name[1] == '_' || (Name[1] >= 'A' && Name[1] <= 'Z'))) 403 return false; 404 } 405 } 406 407 // C++ constructors are never found by name lookup. 408 if (isa<CXXConstructorDecl>(ND)) 409 return false; 410 411 // Filter out any unwanted results. 412 if (Filter && !(this->*Filter)(ND)) { 413 // Check whether it is interesting as a nested-name-specifier. 414 if (AllowNestedNameSpecifiers && SemaRef.getLangOptions().CPlusPlus && 415 IsNestedNameSpecifier(ND) && 416 (Filter != &ResultBuilder::IsMember || 417 (isa<CXXRecordDecl>(ND) && 418 cast<CXXRecordDecl>(ND)->isInjectedClassName()))) { 419 AsNestedNameSpecifier = true; 420 return true; 421 } 422 423 return false; 424 } 425 426 if (Filter == &ResultBuilder::IsNestedNameSpecifier) 427 AsNestedNameSpecifier = true; 428 429 // ... then it must be interesting! 430 return true; 431 } 432 433 bool ResultBuilder::CheckHiddenResult(Result &R, DeclContext *CurContext, 434 NamedDecl *Hiding) { 435 // In C, there is no way to refer to a hidden name. 436 // FIXME: This isn't true; we can find a tag name hidden by an ordinary 437 // name if we introduce the tag type. 438 if (!SemaRef.getLangOptions().CPlusPlus) 439 return true; 440 441 DeclContext *HiddenCtx = R.Declaration->getDeclContext()->getLookupContext(); 442 443 // There is no way to qualify a name declared in a function or method. 444 if (HiddenCtx->isFunctionOrMethod()) 445 return true; 446 447 if (HiddenCtx == Hiding->getDeclContext()->getLookupContext()) 448 return true; 449 450 // We can refer to the result with the appropriate qualification. Do it. 451 R.Hidden = true; 452 R.QualifierIsInformative = false; 453 454 if (!R.Qualifier) 455 R.Qualifier = getRequiredQualification(SemaRef.Context, 456 CurContext, 457 R.Declaration->getDeclContext()); 458 return false; 459 } 460 461 void ResultBuilder::MaybeAddResult(Result R, DeclContext *CurContext) { 462 assert(!ShadowMaps.empty() && "Must enter into a results scope"); 463 464 if (R.Kind != Result::RK_Declaration) { 465 // For non-declaration results, just add the result. 466 Results.push_back(R); 467 return; 468 } 469 470 // Look through using declarations. 471 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) { 472 MaybeAddResult(Result(Using->getTargetDecl(), R.Qualifier), CurContext); 473 return; 474 } 475 476 Decl *CanonDecl = R.Declaration->getCanonicalDecl(); 477 unsigned IDNS = CanonDecl->getIdentifierNamespace(); 478 479 bool AsNestedNameSpecifier = false; 480 if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier)) 481 return; 482 483 ShadowMap &SMap = ShadowMaps.back(); 484 ShadowMapEntry::iterator I, IEnd; 485 ShadowMap::iterator NamePos = SMap.find(R.Declaration->getDeclName()); 486 if (NamePos != SMap.end()) { 487 I = NamePos->second.begin(); 488 IEnd = NamePos->second.end(); 489 } 490 491 for (; I != IEnd; ++I) { 492 NamedDecl *ND = I->first; 493 unsigned Index = I->second; 494 if (ND->getCanonicalDecl() == CanonDecl) { 495 // This is a redeclaration. Always pick the newer declaration. 496 Results[Index].Declaration = R.Declaration; 497 498 // We're done. 499 return; 500 } 501 } 502 503 // This is a new declaration in this scope. However, check whether this 504 // declaration name is hidden by a similarly-named declaration in an outer 505 // scope. 506 std::list<ShadowMap>::iterator SM, SMEnd = ShadowMaps.end(); 507 --SMEnd; 508 for (SM = ShadowMaps.begin(); SM != SMEnd; ++SM) { 509 ShadowMapEntry::iterator I, IEnd; 510 ShadowMap::iterator NamePos = SM->find(R.Declaration->getDeclName()); 511 if (NamePos != SM->end()) { 512 I = NamePos->second.begin(); 513 IEnd = NamePos->second.end(); 514 } 515 for (; I != IEnd; ++I) { 516 // A tag declaration does not hide a non-tag declaration. 517 if (I->first->hasTagIdentifierNamespace() && 518 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary | 519 Decl::IDNS_ObjCProtocol))) 520 continue; 521 522 // Protocols are in distinct namespaces from everything else. 523 if (((I->first->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol) 524 || (IDNS & Decl::IDNS_ObjCProtocol)) && 525 I->first->getIdentifierNamespace() != IDNS) 526 continue; 527 528 // The newly-added result is hidden by an entry in the shadow map. 529 if (CheckHiddenResult(R, CurContext, I->first)) 530 return; 531 532 break; 533 } 534 } 535 536 // Make sure that any given declaration only shows up in the result set once. 537 if (!AllDeclsFound.insert(CanonDecl)) 538 return; 539 540 // If the filter is for nested-name-specifiers, then this result starts a 541 // nested-name-specifier. 542 if (AsNestedNameSpecifier) { 543 R.StartsNestedNameSpecifier = true; 544 R.Priority = CCP_NestedNameSpecifier; 545 } 546 547 // If this result is supposed to have an informative qualifier, add one. 548 if (R.QualifierIsInformative && !R.Qualifier && 549 !R.StartsNestedNameSpecifier) { 550 DeclContext *Ctx = R.Declaration->getDeclContext(); 551 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx)) 552 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, Namespace); 553 else if (TagDecl *Tag = dyn_cast<TagDecl>(Ctx)) 554 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, false, 555 SemaRef.Context.getTypeDeclType(Tag).getTypePtr()); 556 else 557 R.QualifierIsInformative = false; 558 } 559 560 // Insert this result into the set of results and into the current shadow 561 // map. 562 SMap[R.Declaration->getDeclName()].Add(R.Declaration, Results.size()); 563 Results.push_back(R); 564 } 565 566 void ResultBuilder::AddResult(Result R, DeclContext *CurContext, 567 NamedDecl *Hiding, bool InBaseClass = false) { 568 if (R.Kind != Result::RK_Declaration) { 569 // For non-declaration results, just add the result. 570 Results.push_back(R); 571 return; 572 } 573 574 // Look through using declarations. 575 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) { 576 AddResult(Result(Using->getTargetDecl(), R.Qualifier), CurContext, Hiding); 577 return; 578 } 579 580 bool AsNestedNameSpecifier = false; 581 if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier)) 582 return; 583 584 if (Hiding && CheckHiddenResult(R, CurContext, Hiding)) 585 return; 586 587 // Make sure that any given declaration only shows up in the result set once. 588 if (!AllDeclsFound.insert(R.Declaration->getCanonicalDecl())) 589 return; 590 591 // If the filter is for nested-name-specifiers, then this result starts a 592 // nested-name-specifier. 593 if (AsNestedNameSpecifier) { 594 R.StartsNestedNameSpecifier = true; 595 R.Priority = CCP_NestedNameSpecifier; 596 } 597 else if (Filter == &ResultBuilder::IsMember && !R.Qualifier && InBaseClass && 598 isa<CXXRecordDecl>(R.Declaration->getDeclContext() 599 ->getLookupContext())) 600 R.QualifierIsInformative = true; 601 602 // If this result is supposed to have an informative qualifier, add one. 603 if (R.QualifierIsInformative && !R.Qualifier && 604 !R.StartsNestedNameSpecifier) { 605 DeclContext *Ctx = R.Declaration->getDeclContext(); 606 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx)) 607 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, Namespace); 608 else if (TagDecl *Tag = dyn_cast<TagDecl>(Ctx)) 609 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, false, 610 SemaRef.Context.getTypeDeclType(Tag).getTypePtr()); 611 else 612 R.QualifierIsInformative = false; 613 } 614 615 // Adjust the priority if this result comes from a base class. 616 if (InBaseClass) 617 R.Priority += CCD_InBaseClass; 618 619 // Insert this result into the set of results. 620 Results.push_back(R); 621 } 622 623 void ResultBuilder::AddResult(Result R) { 624 assert(R.Kind != Result::RK_Declaration && 625 "Declaration results need more context"); 626 Results.push_back(R); 627 } 628 629 /// \brief Enter into a new scope. 630 void ResultBuilder::EnterNewScope() { 631 ShadowMaps.push_back(ShadowMap()); 632 } 633 634 /// \brief Exit from the current scope. 635 void ResultBuilder::ExitScope() { 636 for (ShadowMap::iterator E = ShadowMaps.back().begin(), 637 EEnd = ShadowMaps.back().end(); 638 E != EEnd; 639 ++E) 640 E->second.Destroy(); 641 642 ShadowMaps.pop_back(); 643 } 644 645 /// \brief Determines whether this given declaration will be found by 646 /// ordinary name lookup. 647 bool ResultBuilder::IsOrdinaryName(NamedDecl *ND) const { 648 unsigned IDNS = Decl::IDNS_Ordinary; 649 if (SemaRef.getLangOptions().CPlusPlus) 650 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace; 651 else if (SemaRef.getLangOptions().ObjC1 && isa<ObjCIvarDecl>(ND)) 652 return true; 653 654 return ND->getIdentifierNamespace() & IDNS; 655 } 656 657 /// \brief Determines whether this given declaration will be found by 658 /// ordinary name lookup. 659 bool ResultBuilder::IsOrdinaryNonValueName(NamedDecl *ND) const { 660 unsigned IDNS = Decl::IDNS_Ordinary; 661 if (SemaRef.getLangOptions().CPlusPlus) 662 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace; 663 664 return (ND->getIdentifierNamespace() & IDNS) && 665 !isa<ValueDecl>(ND) && !isa<FunctionTemplateDecl>(ND); 666 } 667 668 /// \brief Determines whether the given declaration is suitable as the 669 /// start of a C++ nested-name-specifier, e.g., a class or namespace. 670 bool ResultBuilder::IsNestedNameSpecifier(NamedDecl *ND) const { 671 // Allow us to find class templates, too. 672 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND)) 673 ND = ClassTemplate->getTemplatedDecl(); 674 675 return SemaRef.isAcceptableNestedNameSpecifier(ND); 676 } 677 678 /// \brief Determines whether the given declaration is an enumeration. 679 bool ResultBuilder::IsEnum(NamedDecl *ND) const { 680 return isa<EnumDecl>(ND); 681 } 682 683 /// \brief Determines whether the given declaration is a class or struct. 684 bool ResultBuilder::IsClassOrStruct(NamedDecl *ND) const { 685 // Allow us to find class templates, too. 686 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND)) 687 ND = ClassTemplate->getTemplatedDecl(); 688 689 if (RecordDecl *RD = dyn_cast<RecordDecl>(ND)) 690 return RD->getTagKind() == TTK_Class || 691 RD->getTagKind() == TTK_Struct; 692 693 return false; 694 } 695 696 /// \brief Determines whether the given declaration is a union. 697 bool ResultBuilder::IsUnion(NamedDecl *ND) const { 698 // Allow us to find class templates, too. 699 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND)) 700 ND = ClassTemplate->getTemplatedDecl(); 701 702 if (RecordDecl *RD = dyn_cast<RecordDecl>(ND)) 703 return RD->getTagKind() == TTK_Union; 704 705 return false; 706 } 707 708 /// \brief Determines whether the given declaration is a namespace. 709 bool ResultBuilder::IsNamespace(NamedDecl *ND) const { 710 return isa<NamespaceDecl>(ND); 711 } 712 713 /// \brief Determines whether the given declaration is a namespace or 714 /// namespace alias. 715 bool ResultBuilder::IsNamespaceOrAlias(NamedDecl *ND) const { 716 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND); 717 } 718 719 /// \brief Determines whether the given declaration is a type. 720 bool ResultBuilder::IsType(NamedDecl *ND) const { 721 return isa<TypeDecl>(ND); 722 } 723 724 /// \brief Determines which members of a class should be visible via 725 /// "." or "->". Only value declarations, nested name specifiers, and 726 /// using declarations thereof should show up. 727 bool ResultBuilder::IsMember(NamedDecl *ND) const { 728 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(ND)) 729 ND = Using->getTargetDecl(); 730 731 return isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND) || 732 isa<ObjCPropertyDecl>(ND); 733 } 734 735 /// \rief Determines whether the given declaration is an Objective-C 736 /// instance variable. 737 bool ResultBuilder::IsObjCIvar(NamedDecl *ND) const { 738 return isa<ObjCIvarDecl>(ND); 739 } 740 741 namespace { 742 /// \brief Visible declaration consumer that adds a code-completion result 743 /// for each visible declaration. 744 class CodeCompletionDeclConsumer : public VisibleDeclConsumer { 745 ResultBuilder &Results; 746 DeclContext *CurContext; 747 748 public: 749 CodeCompletionDeclConsumer(ResultBuilder &Results, DeclContext *CurContext) 750 : Results(Results), CurContext(CurContext) { } 751 752 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, bool InBaseClass) { 753 Results.AddResult(ND, CurContext, Hiding, InBaseClass); 754 } 755 }; 756 } 757 758 /// \brief Add type specifiers for the current language as keyword results. 759 static void AddTypeSpecifierResults(const LangOptions &LangOpts, 760 ResultBuilder &Results) { 761 typedef CodeCompleteConsumer::Result Result; 762 Results.AddResult(Result("short", CCP_Type)); 763 Results.AddResult(Result("long", CCP_Type)); 764 Results.AddResult(Result("signed", CCP_Type)); 765 Results.AddResult(Result("unsigned", CCP_Type)); 766 Results.AddResult(Result("void", CCP_Type)); 767 Results.AddResult(Result("char", CCP_Type)); 768 Results.AddResult(Result("int", CCP_Type)); 769 Results.AddResult(Result("float", CCP_Type)); 770 Results.AddResult(Result("double", CCP_Type)); 771 Results.AddResult(Result("enum", CCP_Type)); 772 Results.AddResult(Result("struct", CCP_Type)); 773 Results.AddResult(Result("union", CCP_Type)); 774 Results.AddResult(Result("const", CCP_Type)); 775 Results.AddResult(Result("volatile", CCP_Type)); 776 777 if (LangOpts.C99) { 778 // C99-specific 779 Results.AddResult(Result("_Complex", CCP_Type)); 780 Results.AddResult(Result("_Imaginary", CCP_Type)); 781 Results.AddResult(Result("_Bool", CCP_Type)); 782 Results.AddResult(Result("restrict", CCP_Type)); 783 } 784 785 if (LangOpts.CPlusPlus) { 786 // C++-specific 787 Results.AddResult(Result("bool", CCP_Type)); 788 Results.AddResult(Result("class", CCP_Type)); 789 Results.AddResult(Result("wchar_t", CCP_Type)); 790 791 if (Results.includeCodePatterns()) { 792 // typename qualified-id 793 CodeCompletionString *Pattern = new CodeCompletionString; 794 Pattern->AddTypedTextChunk("typename"); 795 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace); 796 Pattern->AddPlaceholderChunk("qualified-id"); 797 Results.AddResult(Result(Pattern)); 798 } 799 800 if (LangOpts.CPlusPlus0x) { 801 Results.AddResult(Result("auto", CCP_Type)); 802 Results.AddResult(Result("char16_t", CCP_Type)); 803 Results.AddResult(Result("char32_t", CCP_Type)); 804 if (Results.includeCodePatterns()) { 805 CodeCompletionString *Pattern = new CodeCompletionString; 806 Pattern->AddTypedTextChunk("decltype"); 807 Pattern->AddChunk(CodeCompletionString::CK_LeftParen); 808 Pattern->AddPlaceholderChunk("expression-or-type"); 809 Pattern->AddChunk(CodeCompletionString::CK_RightParen); 810 Results.AddResult(Result(Pattern)); 811 } 812 } 813 } 814 815 // GNU extensions 816 if (LangOpts.GNUMode) { 817 // FIXME: Enable when we actually support decimal floating point. 818 // Results.AddResult(Result("_Decimal32")); 819 // Results.AddResult(Result("_Decimal64")); 820 // Results.AddResult(Result("_Decimal128")); 821 822 if (Results.includeCodePatterns()) { 823 CodeCompletionString *Pattern = new CodeCompletionString; 824 Pattern->AddTypedTextChunk("typeof"); 825 Pattern->AddChunk(CodeCompletionString::CK_LeftParen); 826 Pattern->AddPlaceholderChunk("expression-or-type"); 827 Pattern->AddChunk(CodeCompletionString::CK_RightParen); 828 Results.AddResult(Result(Pattern)); 829 } 830 } 831 } 832 833 static void AddStorageSpecifiers(Action::CodeCompletionContext CCC, 834 const LangOptions &LangOpts, 835 ResultBuilder &Results) { 836 typedef CodeCompleteConsumer::Result Result; 837 // Note: we don't suggest either "auto" or "register", because both 838 // are pointless as storage specifiers. Elsewhere, we suggest "auto" 839 // in C++0x as a type specifier. 840 Results.AddResult(Result("extern")); 841 Results.AddResult(Result("static")); 842 } 843 844 static void AddFunctionSpecifiers(Action::CodeCompletionContext CCC, 845 const LangOptions &LangOpts, 846 ResultBuilder &Results) { 847 typedef CodeCompleteConsumer::Result Result; 848 switch (CCC) { 849 case Action::CCC_Class: 850 case Action::CCC_MemberTemplate: 851 if (LangOpts.CPlusPlus) { 852 Results.AddResult(Result("explicit")); 853 Results.AddResult(Result("friend")); 854 Results.AddResult(Result("mutable")); 855 Results.AddResult(Result("virtual")); 856 } 857 // Fall through 858 859 case Action::CCC_ObjCInterface: 860 case Action::CCC_ObjCImplementation: 861 case Action::CCC_Namespace: 862 case Action::CCC_Template: 863 if (LangOpts.CPlusPlus || LangOpts.C99) 864 Results.AddResult(Result("inline")); 865 break; 866 867 case Action::CCC_ObjCInstanceVariableList: 868 case Action::CCC_Expression: 869 case Action::CCC_Statement: 870 case Action::CCC_ForInit: 871 case Action::CCC_Condition: 872 case Action::CCC_RecoveryInFunction: 873 break; 874 } 875 } 876 877 static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt); 878 static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt); 879 static void AddObjCVisibilityResults(const LangOptions &LangOpts, 880 ResultBuilder &Results, 881 bool NeedAt); 882 static void AddObjCImplementationResults(const LangOptions &LangOpts, 883 ResultBuilder &Results, 884 bool NeedAt); 885 static void AddObjCInterfaceResults(const LangOptions &LangOpts, 886 ResultBuilder &Results, 887 bool NeedAt); 888 static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt); 889 890 /// \brief Add language constructs that show up for "ordinary" names. 891 static void AddOrdinaryNameResults(Action::CodeCompletionContext CCC, 892 Scope *S, 893 Sema &SemaRef, 894 ResultBuilder &Results) { 895 typedef CodeCompleteConsumer::Result Result; 896 switch (CCC) { 897 case Action::CCC_Namespace: 898 if (SemaRef.getLangOptions().CPlusPlus && Results.includeCodePatterns()) { 899 // namespace <identifier> { } 900 CodeCompletionString *Pattern = new CodeCompletionString; 901 Pattern->AddTypedTextChunk("namespace"); 902 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace); 903 Pattern->AddPlaceholderChunk("identifier"); 904 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace); 905 Pattern->AddPlaceholderChunk("declarations"); 906 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace); 907 Pattern->AddChunk(CodeCompletionString::CK_RightBrace); 908 Results.AddResult(Result(Pattern)); 909 910 // namespace identifier = identifier ; 911 Pattern = new CodeCompletionString; 912 Pattern->AddTypedTextChunk("namespace"); 913 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace); 914 Pattern->AddPlaceholderChunk("identifier"); 915 Pattern->AddChunk(CodeCompletionString::CK_Equal); 916 Pattern->AddPlaceholderChunk("identifier"); 917 Results.AddResult(Result(Pattern)); 918 919 // Using directives 920 Pattern = new CodeCompletionString; 921 Pattern->AddTypedTextChunk("using"); 922 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace); 923 Pattern->AddTextChunk("namespace"); 924 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace); 925 Pattern->AddPlaceholderChunk("identifier"); 926 Results.AddResult(Result(Pattern)); 927 928 // asm(string-literal) 929 Pattern = new CodeCompletionString; 930 Pattern->AddTypedTextChunk("asm"); 931 Pattern->AddChunk(CodeCompletionString::CK_LeftParen); 932 Pattern->AddPlaceholderChunk("string-literal"); 933 Pattern->AddChunk(CodeCompletionString::CK_RightParen); 934 Results.AddResult(Result(Pattern)); 935 936 // Explicit template instantiation 937 Pattern = new CodeCompletionString; 938 Pattern->AddTypedTextChunk("template"); 939 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace); 940 Pattern->AddPlaceholderChunk("declaration"); 941 Results.AddResult(Result(Pattern)); 942 } 943 944 if (SemaRef.getLangOptions().ObjC1) 945 AddObjCTopLevelResults(Results, true); 946 947 // Fall through 948 949 case Action::CCC_Class: 950 if (Results.includeCodePatterns()) 951 Results.AddResult(Result("typedef")); 952 953 if (SemaRef.getLangOptions().CPlusPlus && Results.includeCodePatterns()) { 954 // Using declaration 955 CodeCompletionString *Pattern = new CodeCompletionString; 956 Pattern->AddTypedTextChunk("using"); 957 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace); 958 Pattern->AddPlaceholderChunk("qualified-id"); 959 Results.AddResult(Result(Pattern)); 960 961 // using typename qualified-id; (only in a dependent context) 962 if (SemaRef.CurContext->isDependentContext()) { 963 Pattern = new CodeCompletionString; 964 Pattern->AddTypedTextChunk("using"); 965 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace); 966 Pattern->AddTextChunk("typename"); 967 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace); 968 Pattern->AddPlaceholderChunk("qualified-id"); 969 Results.AddResult(Result(Pattern)); 970 } 971 972 if (CCC == Action::CCC_Class) { 973 // public: 974 Pattern = new CodeCompletionString; 975 Pattern->AddTypedTextChunk("public"); 976 Pattern->AddChunk(CodeCompletionString::CK_Colon); 977 Results.AddResult(Result(Pattern)); 978 979 // protected: 980 Pattern = new CodeCompletionString; 981 Pattern->AddTypedTextChunk("protected"); 982 Pattern->AddChunk(CodeCompletionString::CK_Colon); 983 Results.AddResult(Result(Pattern)); 984 985 // private: 986 Pattern = new CodeCompletionString; 987 Pattern->AddTypedTextChunk("private"); 988 Pattern->AddChunk(CodeCompletionString::CK_Colon); 989 Results.AddResult(Result(Pattern)); 990 } 991 } 992 // Fall through 993 994 case Action::CCC_Template: 995 case Action::CCC_MemberTemplate: 996 if (SemaRef.getLangOptions().CPlusPlus && Results.includeCodePatterns()) { 997 // template < parameters > 998 CodeCompletionString *Pattern = new CodeCompletionString; 999 Pattern->AddTypedTextChunk("template"); 1000 Pattern->AddChunk(CodeCompletionString::CK_LeftAngle); 1001 Pattern->AddPlaceholderChunk("parameters"); 1002 Pattern->AddChunk(CodeCompletionString::CK_RightAngle); 1003 Results.AddResult(Result(Pattern)); 1004 } 1005 1006 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results); 1007 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results); 1008 break; 1009 1010 case Action::CCC_ObjCInterface: 1011 AddObjCInterfaceResults(SemaRef.getLangOptions(), Results, true); 1012 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results); 1013 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results); 1014 break; 1015 1016 case Action::CCC_ObjCImplementation: 1017 AddObjCImplementationResults(SemaRef.getLangOptions(), Results, true); 1018 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results); 1019 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results); 1020 break; 1021 1022 case Action::CCC_ObjCInstanceVariableList: 1023 AddObjCVisibilityResults(SemaRef.getLangOptions(), Results, true); 1024 break; 1025 1026 case Action::CCC_RecoveryInFunction: 1027 case Action::CCC_Statement: { 1028 if (Results.includeCodePatterns()) 1029 Results.AddResult(Result("typedef")); 1030 1031 CodeCompletionString *Pattern = 0; 1032 if (SemaRef.getLangOptions().CPlusPlus && Results.includeCodePatterns()) { 1033 Pattern = new CodeCompletionString; 1034 Pattern->AddTypedTextChunk("try"); 1035 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace); 1036 Pattern->AddPlaceholderChunk("statements"); 1037 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace); 1038 Pattern->AddChunk(CodeCompletionString::CK_RightBrace); 1039 Pattern->AddTextChunk("catch"); 1040 Pattern->AddChunk(CodeCompletionString::CK_LeftParen); 1041 Pattern->AddPlaceholderChunk("declaration"); 1042 Pattern->AddChunk(CodeCompletionString::CK_RightParen); 1043 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace); 1044 Pattern->AddPlaceholderChunk("statements"); 1045 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace); 1046 Pattern->AddChunk(CodeCompletionString::CK_RightBrace); 1047 Results.AddResult(Result(Pattern)); 1048 } 1049 if (SemaRef.getLangOptions().ObjC1) 1050 AddObjCStatementResults(Results, true); 1051 1052 if (Results.includeCodePatterns()) { 1053 // if (condition) { statements } 1054 Pattern = new CodeCompletionString; 1055 Pattern->AddTypedTextChunk("if"); 1056 Pattern->AddChunk(CodeCompletionString::CK_LeftParen); 1057 if (SemaRef.getLangOptions().CPlusPlus) 1058 Pattern->AddPlaceholderChunk("condition"); 1059 else 1060 Pattern->AddPlaceholderChunk("expression"); 1061 Pattern->AddChunk(CodeCompletionString::CK_RightParen); 1062 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace); 1063 Pattern->AddPlaceholderChunk("statements"); 1064 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace); 1065 Pattern->AddChunk(CodeCompletionString::CK_RightBrace); 1066 Results.AddResult(Result(Pattern)); 1067 1068 // switch (condition) { } 1069 Pattern = new CodeCompletionString; 1070 Pattern->AddTypedTextChunk("switch"); 1071 Pattern->AddChunk(CodeCompletionString::CK_LeftParen); 1072 if (SemaRef.getLangOptions().CPlusPlus) 1073 Pattern->AddPlaceholderChunk("condition"); 1074 else 1075 Pattern->AddPlaceholderChunk("expression"); 1076 Pattern->AddChunk(CodeCompletionString::CK_RightParen); 1077 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace); 1078 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace); 1079 Pattern->AddChunk(CodeCompletionString::CK_RightBrace); 1080 Results.AddResult(Result(Pattern)); 1081 } 1082 1083 // Switch-specific statements. 1084 if (!SemaRef.getSwitchStack().empty() && Results.includeCodePatterns()) { 1085 // case expression: 1086 Pattern = new CodeCompletionString; 1087 Pattern->AddTypedTextChunk("case"); 1088 Pattern->AddPlaceholderChunk("expression"); 1089 Pattern->AddChunk(CodeCompletionString::CK_Colon); 1090 Results.AddResult(Result(Pattern)); 1091 1092 // default: 1093 Pattern = new CodeCompletionString; 1094 Pattern->AddTypedTextChunk("default"); 1095 Pattern->AddChunk(CodeCompletionString::CK_Colon); 1096 Results.AddResult(Result(Pattern)); 1097 } 1098 1099 if (Results.includeCodePatterns()) { 1100 /// while (condition) { statements } 1101 Pattern = new CodeCompletionString; 1102 Pattern->AddTypedTextChunk("while"); 1103 Pattern->AddChunk(CodeCompletionString::CK_LeftParen); 1104 if (SemaRef.getLangOptions().CPlusPlus) 1105 Pattern->AddPlaceholderChunk("condition"); 1106 else 1107 Pattern->AddPlaceholderChunk("expression"); 1108 Pattern->AddChunk(CodeCompletionString::CK_RightParen); 1109 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace); 1110 Pattern->AddPlaceholderChunk("statements"); 1111 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace); 1112 Pattern->AddChunk(CodeCompletionString::CK_RightBrace); 1113 Results.AddResult(Result(Pattern)); 1114 1115 // do { statements } while ( expression ); 1116 Pattern = new CodeCompletionString; 1117 Pattern->AddTypedTextChunk("do"); 1118 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace); 1119 Pattern->AddPlaceholderChunk("statements"); 1120 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace); 1121 Pattern->AddChunk(CodeCompletionString::CK_RightBrace); 1122 Pattern->AddTextChunk("while"); 1123 Pattern->AddChunk(CodeCompletionString::CK_LeftParen); 1124 Pattern->AddPlaceholderChunk("expression"); 1125 Pattern->AddChunk(CodeCompletionString::CK_RightParen); 1126 Results.AddResult(Result(Pattern)); 1127 1128 // for ( for-init-statement ; condition ; expression ) { statements } 1129 Pattern = new CodeCompletionString; 1130 Pattern->AddTypedTextChunk("for"); 1131 Pattern->AddChunk(CodeCompletionString::CK_LeftParen); 1132 if (SemaRef.getLangOptions().CPlusPlus || SemaRef.getLangOptions().C99) 1133 Pattern->AddPlaceholderChunk("init-statement"); 1134 else 1135 Pattern->AddPlaceholderChunk("init-expression"); 1136 Pattern->AddChunk(CodeCompletionString::CK_SemiColon); 1137 Pattern->AddPlaceholderChunk("condition"); 1138 Pattern->AddChunk(CodeCompletionString::CK_SemiColon); 1139 Pattern->AddPlaceholderChunk("inc-expression"); 1140 Pattern->AddChunk(CodeCompletionString::CK_RightParen); 1141 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace); 1142 Pattern->AddPlaceholderChunk("statements"); 1143 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace); 1144 Pattern->AddChunk(CodeCompletionString::CK_RightBrace); 1145 Results.AddResult(Result(Pattern)); 1146 } 1147 1148 if (S->getContinueParent()) { 1149 // continue ; 1150 Pattern = new CodeCompletionString; 1151 Pattern->AddTypedTextChunk("continue"); 1152 Results.AddResult(Result(Pattern)); 1153 } 1154 1155 if (S->getBreakParent()) { 1156 // break ; 1157 Pattern = new CodeCompletionString; 1158 Pattern->AddTypedTextChunk("break"); 1159 Results.AddResult(Result(Pattern)); 1160 } 1161 1162 // "return expression ;" or "return ;", depending on whether we 1163 // know the function is void or not. 1164 bool isVoid = false; 1165 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(SemaRef.CurContext)) 1166 isVoid = Function->getResultType()->isVoidType(); 1167 else if (ObjCMethodDecl *Method 1168 = dyn_cast<ObjCMethodDecl>(SemaRef.CurContext)) 1169 isVoid = Method->getResultType()->isVoidType(); 1170 else if (SemaRef.getCurBlock() && 1171 !SemaRef.getCurBlock()->ReturnType.isNull()) 1172 isVoid = SemaRef.getCurBlock()->ReturnType->isVoidType(); 1173 Pattern = new CodeCompletionString; 1174 Pattern->AddTypedTextChunk("return"); 1175 if (!isVoid) { 1176 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace); 1177 Pattern->AddPlaceholderChunk("expression"); 1178 } 1179 Results.AddResult(Result(Pattern)); 1180 1181 if (Results.includeCodePatterns()) { 1182 // goto identifier ; 1183 Pattern = new CodeCompletionString; 1184 Pattern->AddTypedTextChunk("goto"); 1185 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace); 1186 Pattern->AddPlaceholderChunk("identifier"); 1187 Results.AddResult(Result(Pattern)); 1188 1189 // Using directives 1190 Pattern = new CodeCompletionString; 1191 Pattern->AddTypedTextChunk("using"); 1192 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace); 1193 Pattern->AddTextChunk("namespace"); 1194 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace); 1195 Pattern->AddPlaceholderChunk("identifier"); 1196 Results.AddResult(Result(Pattern)); 1197 } 1198 } 1199 1200 // Fall through (for statement expressions). 1201 case Action::CCC_ForInit: 1202 case Action::CCC_Condition: 1203 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results); 1204 // Fall through: conditions and statements can have expressions. 1205 1206 case Action::CCC_Expression: { 1207 CodeCompletionString *Pattern = 0; 1208 if (SemaRef.getLangOptions().CPlusPlus) { 1209 // 'this', if we're in a non-static member function. 1210 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(SemaRef.CurContext)) 1211 if (!Method->isStatic()) 1212 Results.AddResult(Result("this")); 1213 1214 // true, false 1215 Results.AddResult(Result("true")); 1216 Results.AddResult(Result("false")); 1217 1218 if (Results.includeCodePatterns()) { 1219 // dynamic_cast < type-id > ( expression ) 1220 Pattern = new CodeCompletionString; 1221 Pattern->AddTypedTextChunk("dynamic_cast"); 1222 Pattern->AddChunk(CodeCompletionString::CK_LeftAngle); 1223 Pattern->AddPlaceholderChunk("type-id"); 1224 Pattern->AddChunk(CodeCompletionString::CK_RightAngle); 1225 Pattern->AddChunk(CodeCompletionString::CK_LeftParen); 1226 Pattern->AddPlaceholderChunk("expression"); 1227 Pattern->AddChunk(CodeCompletionString::CK_RightParen); 1228 Results.AddResult(Result(Pattern)); 1229 1230 // static_cast < type-id > ( expression ) 1231 Pattern = new CodeCompletionString; 1232 Pattern->AddTypedTextChunk("static_cast"); 1233 Pattern->AddChunk(CodeCompletionString::CK_LeftAngle); 1234 Pattern->AddPlaceholderChunk("type-id"); 1235 Pattern->AddChunk(CodeCompletionString::CK_RightAngle); 1236 Pattern->AddChunk(CodeCompletionString::CK_LeftParen); 1237 Pattern->AddPlaceholderChunk("expression"); 1238 Pattern->AddChunk(CodeCompletionString::CK_RightParen); 1239 Results.AddResult(Result(Pattern)); 1240 1241 // reinterpret_cast < type-id > ( expression ) 1242 Pattern = new CodeCompletionString; 1243 Pattern->AddTypedTextChunk("reinterpret_cast"); 1244 Pattern->AddChunk(CodeCompletionString::CK_LeftAngle); 1245 Pattern->AddPlaceholderChunk("type-id"); 1246 Pattern->AddChunk(CodeCompletionString::CK_RightAngle); 1247 Pattern->AddChunk(CodeCompletionString::CK_LeftParen); 1248 Pattern->AddPlaceholderChunk("expression"); 1249 Pattern->AddChunk(CodeCompletionString::CK_RightParen); 1250 Results.AddResult(Result(Pattern)); 1251 1252 // const_cast < type-id > ( expression ) 1253 Pattern = new CodeCompletionString; 1254 Pattern->AddTypedTextChunk("const_cast"); 1255 Pattern->AddChunk(CodeCompletionString::CK_LeftAngle); 1256 Pattern->AddPlaceholderChunk("type-id"); 1257 Pattern->AddChunk(CodeCompletionString::CK_RightAngle); 1258 Pattern->AddChunk(CodeCompletionString::CK_LeftParen); 1259 Pattern->AddPlaceholderChunk("expression"); 1260 Pattern->AddChunk(CodeCompletionString::CK_RightParen); 1261 Results.AddResult(Result(Pattern)); 1262 1263 // typeid ( expression-or-type ) 1264 Pattern = new CodeCompletionString; 1265 Pattern->AddTypedTextChunk("typeid"); 1266 Pattern->AddChunk(CodeCompletionString::CK_LeftParen); 1267 Pattern->AddPlaceholderChunk("expression-or-type"); 1268 Pattern->AddChunk(CodeCompletionString::CK_RightParen); 1269 Results.AddResult(Result(Pattern)); 1270 1271 // new T ( ... ) 1272 Pattern = new CodeCompletionString; 1273 Pattern->AddTypedTextChunk("new"); 1274 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace); 1275 Pattern->AddPlaceholderChunk("type-id"); 1276 Pattern->AddChunk(CodeCompletionString::CK_LeftParen); 1277 Pattern->AddPlaceholderChunk("expressions"); 1278 Pattern->AddChunk(CodeCompletionString::CK_RightParen); 1279 Results.AddResult(Result(Pattern)); 1280 1281 // new T [ ] ( ... ) 1282 Pattern = new CodeCompletionString; 1283 Pattern->AddTypedTextChunk("new"); 1284 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace); 1285 Pattern->AddPlaceholderChunk("type-id"); 1286 Pattern->AddChunk(CodeCompletionString::CK_LeftBracket); 1287 Pattern->AddPlaceholderChunk("size"); 1288 Pattern->AddChunk(CodeCompletionString::CK_RightBracket); 1289 Pattern->AddChunk(CodeCompletionString::CK_LeftParen); 1290 Pattern->AddPlaceholderChunk("expressions"); 1291 Pattern->AddChunk(CodeCompletionString::CK_RightParen); 1292 Results.AddResult(Result(Pattern)); 1293 1294 // delete expression 1295 Pattern = new CodeCompletionString; 1296 Pattern->AddTypedTextChunk("delete"); 1297 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace); 1298 Pattern->AddPlaceholderChunk("expression"); 1299 Results.AddResult(Result(Pattern)); 1300 1301 // delete [] expression 1302 Pattern = new CodeCompletionString; 1303 Pattern->AddTypedTextChunk("delete"); 1304 Pattern->AddChunk(CodeCompletionString::CK_LeftBracket); 1305 Pattern->AddChunk(CodeCompletionString::CK_RightBracket); 1306 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace); 1307 Pattern->AddPlaceholderChunk("expression"); 1308 Results.AddResult(Result(Pattern)); 1309 1310 // throw expression 1311 Pattern = new CodeCompletionString; 1312 Pattern->AddTypedTextChunk("throw"); 1313 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace); 1314 Pattern->AddPlaceholderChunk("expression"); 1315 Results.AddResult(Result(Pattern)); 1316 } 1317 1318 // FIXME: Rethrow? 1319 } 1320 1321 if (SemaRef.getLangOptions().ObjC1) { 1322 // Add "super", if we're in an Objective-C class with a superclass. 1323 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) 1324 if (Method->getClassInterface()->getSuperClass()) 1325 Results.AddResult(Result("super")); 1326 1327 AddObjCExpressionResults(Results, true); 1328 } 1329 1330 if (Results.includeCodePatterns()) { 1331 // sizeof expression 1332 Pattern = new CodeCompletionString; 1333 Pattern->AddTypedTextChunk("sizeof"); 1334 Pattern->AddChunk(CodeCompletionString::CK_LeftParen); 1335 Pattern->AddPlaceholderChunk("expression-or-type"); 1336 Pattern->AddChunk(CodeCompletionString::CK_RightParen); 1337 Results.AddResult(Result(Pattern)); 1338 } 1339 break; 1340 } 1341 } 1342 1343 AddTypeSpecifierResults(SemaRef.getLangOptions(), Results); 1344 1345 if (SemaRef.getLangOptions().CPlusPlus) 1346 Results.AddResult(Result("operator")); 1347 } 1348 1349 /// \brief If the given declaration has an associated type, add it as a result 1350 /// type chunk. 1351 static void AddResultTypeChunk(ASTContext &Context, 1352 NamedDecl *ND, 1353 CodeCompletionString *Result) { 1354 if (!ND) 1355 return; 1356 1357 // Determine the type of the declaration (if it has a type). 1358 QualType T; 1359 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND)) 1360 T = Function->getResultType(); 1361 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND)) 1362 T = Method->getResultType(); 1363 else if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND)) 1364 T = FunTmpl->getTemplatedDecl()->getResultType(); 1365 else if (EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND)) 1366 T = Context.getTypeDeclType(cast<TypeDecl>(Enumerator->getDeclContext())); 1367 else if (isa<UnresolvedUsingValueDecl>(ND)) { 1368 /* Do nothing: ignore unresolved using declarations*/ 1369 } else if (ValueDecl *Value = dyn_cast<ValueDecl>(ND)) 1370 T = Value->getType(); 1371 else if (ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND)) 1372 T = Property->getType(); 1373 1374 if (T.isNull() || Context.hasSameType(T, Context.DependentTy)) 1375 return; 1376 1377 PrintingPolicy Policy(Context.PrintingPolicy); 1378 Policy.AnonymousTagLocations = false; 1379 1380 std::string TypeStr; 1381 T.getAsStringInternal(TypeStr, Policy); 1382 Result->AddResultTypeChunk(TypeStr); 1383 } 1384 1385 /// \brief Add function parameter chunks to the given code completion string. 1386 static void AddFunctionParameterChunks(ASTContext &Context, 1387 FunctionDecl *Function, 1388 CodeCompletionString *Result) { 1389 typedef CodeCompletionString::Chunk Chunk; 1390 1391 CodeCompletionString *CCStr = Result; 1392 1393 for (unsigned P = 0, N = Function->getNumParams(); P != N; ++P) { 1394 ParmVarDecl *Param = Function->getParamDecl(P); 1395 1396 if (Param->hasDefaultArg()) { 1397 // When we see an optional default argument, put that argument and 1398 // the remaining default arguments into a new, optional string. 1399 CodeCompletionString *Opt = new CodeCompletionString; 1400 CCStr->AddOptionalChunk(std::auto_ptr<CodeCompletionString>(Opt)); 1401 CCStr = Opt; 1402 } 1403 1404 if (P != 0) 1405 CCStr->AddChunk(Chunk(CodeCompletionString::CK_Comma)); 1406 1407 // Format the placeholder string. 1408 std::string PlaceholderStr; 1409 if (Param->getIdentifier()) 1410 PlaceholderStr = Param->getIdentifier()->getName(); 1411 1412 Param->getType().getAsStringInternal(PlaceholderStr, 1413 Context.PrintingPolicy); 1414 1415 // Add the placeholder string. 1416 CCStr->AddPlaceholderChunk(PlaceholderStr); 1417 } 1418 1419 if (const FunctionProtoType *Proto 1420 = Function->getType()->getAs<FunctionProtoType>()) 1421 if (Proto->isVariadic()) 1422 CCStr->AddPlaceholderChunk(", ..."); 1423 } 1424 1425 /// \brief Add template parameter chunks to the given code completion string. 1426 static void AddTemplateParameterChunks(ASTContext &Context, 1427 TemplateDecl *Template, 1428 CodeCompletionString *Result, 1429 unsigned MaxParameters = 0) { 1430 typedef CodeCompletionString::Chunk Chunk; 1431 1432 CodeCompletionString *CCStr = Result; 1433 bool FirstParameter = true; 1434 1435 TemplateParameterList *Params = Template->getTemplateParameters(); 1436 TemplateParameterList::iterator PEnd = Params->end(); 1437 if (MaxParameters) 1438 PEnd = Params->begin() + MaxParameters; 1439 for (TemplateParameterList::iterator P = Params->begin(); P != PEnd; ++P) { 1440 bool HasDefaultArg = false; 1441 std::string PlaceholderStr; 1442 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) { 1443 if (TTP->wasDeclaredWithTypename()) 1444 PlaceholderStr = "typename"; 1445 else 1446 PlaceholderStr = "class"; 1447 1448 if (TTP->getIdentifier()) { 1449 PlaceholderStr += ' '; 1450 PlaceholderStr += TTP->getIdentifier()->getName(); 1451 } 1452 1453 HasDefaultArg = TTP->hasDefaultArgument(); 1454 } else if (NonTypeTemplateParmDecl *NTTP 1455 = dyn_cast<NonTypeTemplateParmDecl>(*P)) { 1456 if (NTTP->getIdentifier()) 1457 PlaceholderStr = NTTP->getIdentifier()->getName(); 1458 NTTP->getType().getAsStringInternal(PlaceholderStr, 1459 Context.PrintingPolicy); 1460 HasDefaultArg = NTTP->hasDefaultArgument(); 1461 } else { 1462 assert(isa<TemplateTemplateParmDecl>(*P)); 1463 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P); 1464 1465 // Since putting the template argument list into the placeholder would 1466 // be very, very long, we just use an abbreviation. 1467 PlaceholderStr = "template<...> class"; 1468 if (TTP->getIdentifier()) { 1469 PlaceholderStr += ' '; 1470 PlaceholderStr += TTP->getIdentifier()->getName(); 1471 } 1472 1473 HasDefaultArg = TTP->hasDefaultArgument(); 1474 } 1475 1476 if (HasDefaultArg) { 1477 // When we see an optional default argument, put that argument and 1478 // the remaining default arguments into a new, optional string. 1479 CodeCompletionString *Opt = new CodeCompletionString; 1480 CCStr->AddOptionalChunk(std::auto_ptr<CodeCompletionString>(Opt)); 1481 CCStr = Opt; 1482 } 1483 1484 if (FirstParameter) 1485 FirstParameter = false; 1486 else 1487 CCStr->AddChunk(Chunk(CodeCompletionString::CK_Comma)); 1488 1489 // Add the placeholder string. 1490 CCStr->AddPlaceholderChunk(PlaceholderStr); 1491 } 1492 } 1493 1494 /// \brief Add a qualifier to the given code-completion string, if the 1495 /// provided nested-name-specifier is non-NULL. 1496 static void 1497 AddQualifierToCompletionString(CodeCompletionString *Result, 1498 NestedNameSpecifier *Qualifier, 1499 bool QualifierIsInformative, 1500 ASTContext &Context) { 1501 if (!Qualifier) 1502 return; 1503 1504 std::string PrintedNNS; 1505 { 1506 llvm::raw_string_ostream OS(PrintedNNS); 1507 Qualifier->print(OS, Context.PrintingPolicy); 1508 } 1509 if (QualifierIsInformative) 1510 Result->AddInformativeChunk(PrintedNNS); 1511 else 1512 Result->AddTextChunk(PrintedNNS); 1513 } 1514 1515 static void AddFunctionTypeQualsToCompletionString(CodeCompletionString *Result, 1516 FunctionDecl *Function) { 1517 const FunctionProtoType *Proto 1518 = Function->getType()->getAs<FunctionProtoType>(); 1519 if (!Proto || !Proto->getTypeQuals()) 1520 return; 1521 1522 std::string QualsStr; 1523 if (Proto->getTypeQuals() & Qualifiers::Const) 1524 QualsStr += " const"; 1525 if (Proto->getTypeQuals() & Qualifiers::Volatile) 1526 QualsStr += " volatile"; 1527 if (Proto->getTypeQuals() & Qualifiers::Restrict) 1528 QualsStr += " restrict"; 1529 Result->AddInformativeChunk(QualsStr); 1530 } 1531 1532 /// \brief If possible, create a new code completion string for the given 1533 /// result. 1534 /// 1535 /// \returns Either a new, heap-allocated code completion string describing 1536 /// how to use this result, or NULL to indicate that the string or name of the 1537 /// result is all that is needed. 1538 CodeCompletionString * 1539 CodeCompleteConsumer::Result::CreateCodeCompletionString(Sema &S) { 1540 typedef CodeCompletionString::Chunk Chunk; 1541 1542 if (Kind == RK_Pattern) 1543 return Pattern->Clone(); 1544 1545 CodeCompletionString *Result = new CodeCompletionString; 1546 1547 if (Kind == RK_Keyword) { 1548 Result->AddTypedTextChunk(Keyword); 1549 return Result; 1550 } 1551 1552 if (Kind == RK_Macro) { 1553 MacroInfo *MI = S.PP.getMacroInfo(Macro); 1554 assert(MI && "Not a macro?"); 1555 1556 Result->AddTypedTextChunk(Macro->getName()); 1557 1558 if (!MI->isFunctionLike()) 1559 return Result; 1560 1561 // Format a function-like macro with placeholders for the arguments. 1562 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen)); 1563 for (MacroInfo::arg_iterator A = MI->arg_begin(), AEnd = MI->arg_end(); 1564 A != AEnd; ++A) { 1565 if (A != MI->arg_begin()) 1566 Result->AddChunk(Chunk(CodeCompletionString::CK_Comma)); 1567 1568 if (!MI->isVariadic() || A != AEnd - 1) { 1569 // Non-variadic argument. 1570 Result->AddPlaceholderChunk((*A)->getName()); 1571 continue; 1572 } 1573 1574 // Variadic argument; cope with the different between GNU and C99 1575 // variadic macros, providing a single placeholder for the rest of the 1576 // arguments. 1577 if ((*A)->isStr("__VA_ARGS__")) 1578 Result->AddPlaceholderChunk("..."); 1579 else { 1580 std::string Arg = (*A)->getName(); 1581 Arg += "..."; 1582 Result->AddPlaceholderChunk(Arg); 1583 } 1584 } 1585 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen)); 1586 return Result; 1587 } 1588 1589 assert(Kind == RK_Declaration && "Missed a result kind?"); 1590 NamedDecl *ND = Declaration; 1591 1592 if (StartsNestedNameSpecifier) { 1593 Result->AddTypedTextChunk(ND->getNameAsString()); 1594 Result->AddTextChunk("::"); 1595 return Result; 1596 } 1597 1598 AddResultTypeChunk(S.Context, ND, Result); 1599 1600 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND)) { 1601 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative, 1602 S.Context); 1603 Result->AddTypedTextChunk(Function->getNameAsString()); 1604 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen)); 1605 AddFunctionParameterChunks(S.Context, Function, Result); 1606 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen)); 1607 AddFunctionTypeQualsToCompletionString(Result, Function); 1608 return Result; 1609 } 1610 1611 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND)) { 1612 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative, 1613 S.Context); 1614 FunctionDecl *Function = FunTmpl->getTemplatedDecl(); 1615 Result->AddTypedTextChunk(Function->getNameAsString()); 1616 1617 // Figure out which template parameters are deduced (or have default 1618 // arguments). 1619 llvm::SmallVector<bool, 16> Deduced; 1620 S.MarkDeducedTemplateParameters(FunTmpl, Deduced); 1621 unsigned LastDeducibleArgument; 1622 for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0; 1623 --LastDeducibleArgument) { 1624 if (!Deduced[LastDeducibleArgument - 1]) { 1625 // C++0x: Figure out if the template argument has a default. If so, 1626 // the user doesn't need to type this argument. 1627 // FIXME: We need to abstract template parameters better! 1628 bool HasDefaultArg = false; 1629 NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam( 1630 LastDeducibleArgument - 1); 1631 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) 1632 HasDefaultArg = TTP->hasDefaultArgument(); 1633 else if (NonTypeTemplateParmDecl *NTTP 1634 = dyn_cast<NonTypeTemplateParmDecl>(Param)) 1635 HasDefaultArg = NTTP->hasDefaultArgument(); 1636 else { 1637 assert(isa<TemplateTemplateParmDecl>(Param)); 1638 HasDefaultArg 1639 = cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument(); 1640 } 1641 1642 if (!HasDefaultArg) 1643 break; 1644 } 1645 } 1646 1647 if (LastDeducibleArgument) { 1648 // Some of the function template arguments cannot be deduced from a 1649 // function call, so we introduce an explicit template argument list 1650 // containing all of the arguments up to the first deducible argument. 1651 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftAngle)); 1652 AddTemplateParameterChunks(S.Context, FunTmpl, Result, 1653 LastDeducibleArgument); 1654 Result->AddChunk(Chunk(CodeCompletionString::CK_RightAngle)); 1655 } 1656 1657 // Add the function parameters 1658 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen)); 1659 AddFunctionParameterChunks(S.Context, Function, Result); 1660 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen)); 1661 AddFunctionTypeQualsToCompletionString(Result, Function); 1662 return Result; 1663 } 1664 1665 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(ND)) { 1666 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative, 1667 S.Context); 1668 Result->AddTypedTextChunk(Template->getNameAsString()); 1669 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftAngle)); 1670 AddTemplateParameterChunks(S.Context, Template, Result); 1671 Result->AddChunk(Chunk(CodeCompletionString::CK_RightAngle)); 1672 return Result; 1673 } 1674 1675 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND)) { 1676 Selector Sel = Method->getSelector(); 1677 if (Sel.isUnarySelector()) { 1678 Result->AddTypedTextChunk(Sel.getIdentifierInfoForSlot(0)->getName()); 1679 return Result; 1680 } 1681 1682 std::string SelName = Sel.getIdentifierInfoForSlot(0)->getName().str(); 1683 SelName += ':'; 1684 if (StartParameter == 0) 1685 Result->AddTypedTextChunk(SelName); 1686 else { 1687 Result->AddInformativeChunk(SelName); 1688 1689 // If there is only one parameter, and we're past it, add an empty 1690 // typed-text chunk since there is nothing to type. 1691 if (Method->param_size() == 1) 1692 Result->AddTypedTextChunk(""); 1693 } 1694 unsigned Idx = 0; 1695 for (ObjCMethodDecl::param_iterator P = Method->param_begin(), 1696 PEnd = Method->param_end(); 1697 P != PEnd; (void)++P, ++Idx) { 1698 if (Idx > 0) { 1699 std::string Keyword; 1700 if (Idx > StartParameter) 1701 Result->AddChunk(CodeCompletionString::CK_HorizontalSpace); 1702 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(Idx)) 1703 Keyword += II->getName().str(); 1704 Keyword += ":"; 1705 if (Idx < StartParameter || AllParametersAreInformative) { 1706 Result->AddInformativeChunk(Keyword); 1707 } else if (Idx == StartParameter) 1708 Result->AddTypedTextChunk(Keyword); 1709 else 1710 Result->AddTextChunk(Keyword); 1711 } 1712 1713 // If we're before the starting parameter, skip the placeholder. 1714 if (Idx < StartParameter) 1715 continue; 1716 1717 std::string Arg; 1718 (*P)->getType().getAsStringInternal(Arg, S.Context.PrintingPolicy); 1719 Arg = "(" + Arg + ")"; 1720 if (IdentifierInfo *II = (*P)->getIdentifier()) 1721 Arg += II->getName().str(); 1722 if (AllParametersAreInformative) 1723 Result->AddInformativeChunk(Arg); 1724 else 1725 Result->AddPlaceholderChunk(Arg); 1726 } 1727 1728 if (Method->isVariadic()) { 1729 if (AllParametersAreInformative) 1730 Result->AddInformativeChunk(", ..."); 1731 else 1732 Result->AddPlaceholderChunk(", ..."); 1733 } 1734 1735 return Result; 1736 } 1737 1738 if (Qualifier) 1739 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative, 1740 S.Context); 1741 1742 Result->AddTypedTextChunk(ND->getNameAsString()); 1743 return Result; 1744 } 1745 1746 CodeCompletionString * 1747 CodeCompleteConsumer::OverloadCandidate::CreateSignatureString( 1748 unsigned CurrentArg, 1749 Sema &S) const { 1750 typedef CodeCompletionString::Chunk Chunk; 1751 1752 CodeCompletionString *Result = new CodeCompletionString; 1753 FunctionDecl *FDecl = getFunction(); 1754 AddResultTypeChunk(S.Context, FDecl, Result); 1755 const FunctionProtoType *Proto 1756 = dyn_cast<FunctionProtoType>(getFunctionType()); 1757 if (!FDecl && !Proto) { 1758 // Function without a prototype. Just give the return type and a 1759 // highlighted ellipsis. 1760 const FunctionType *FT = getFunctionType(); 1761 Result->AddTextChunk( 1762 FT->getResultType().getAsString(S.Context.PrintingPolicy)); 1763 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen)); 1764 Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "...")); 1765 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen)); 1766 return Result; 1767 } 1768 1769 if (FDecl) 1770 Result->AddTextChunk(FDecl->getNameAsString()); 1771 else 1772 Result->AddTextChunk( 1773 Proto->getResultType().getAsString(S.Context.PrintingPolicy)); 1774 1775 Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen)); 1776 unsigned NumParams = FDecl? FDecl->getNumParams() : Proto->getNumArgs(); 1777 for (unsigned I = 0; I != NumParams; ++I) { 1778 if (I) 1779 Result->AddChunk(Chunk(CodeCompletionString::CK_Comma)); 1780 1781 std::string ArgString; 1782 QualType ArgType; 1783 1784 if (FDecl) { 1785 ArgString = FDecl->getParamDecl(I)->getNameAsString(); 1786 ArgType = FDecl->getParamDecl(I)->getOriginalType(); 1787 } else { 1788 ArgType = Proto->getArgType(I); 1789 } 1790 1791 ArgType.getAsStringInternal(ArgString, S.Context.PrintingPolicy); 1792 1793 if (I == CurrentArg) 1794 Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, 1795 ArgString)); 1796 else 1797 Result->AddTextChunk(ArgString); 1798 } 1799 1800 if (Proto && Proto->isVariadic()) { 1801 Result->AddChunk(Chunk(CodeCompletionString::CK_Comma)); 1802 if (CurrentArg < NumParams) 1803 Result->AddTextChunk("..."); 1804 else 1805 Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "...")); 1806 } 1807 Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen)); 1808 1809 return Result; 1810 } 1811 1812 namespace { 1813 struct SortCodeCompleteResult { 1814 typedef CodeCompleteConsumer::Result Result; 1815 1816 bool isEarlierDeclarationName(DeclarationName X, DeclarationName Y) const { 1817 Selector XSel = X.getObjCSelector(); 1818 Selector YSel = Y.getObjCSelector(); 1819 if (!XSel.isNull() && !YSel.isNull()) { 1820 // We are comparing two selectors. 1821 unsigned N = std::min(XSel.getNumArgs(), YSel.getNumArgs()); 1822 if (N == 0) 1823 ++N; 1824 for (unsigned I = 0; I != N; ++I) { 1825 IdentifierInfo *XId = XSel.getIdentifierInfoForSlot(I); 1826 IdentifierInfo *YId = YSel.getIdentifierInfoForSlot(I); 1827 if (!XId || !YId) 1828 return XId && !YId; 1829 1830 switch (XId->getName().compare_lower(YId->getName())) { 1831 case -1: return true; 1832 case 1: return false; 1833 default: break; 1834 } 1835 } 1836 1837 return XSel.getNumArgs() < YSel.getNumArgs(); 1838 } 1839 1840 // For non-selectors, order by kind. 1841 if (X.getNameKind() != Y.getNameKind()) 1842 return X.getNameKind() < Y.getNameKind(); 1843 1844 // Order identifiers by comparison of their lowercased names. 1845 if (IdentifierInfo *XId = X.getAsIdentifierInfo()) 1846 return XId->getName().compare_lower( 1847 Y.getAsIdentifierInfo()->getName()) < 0; 1848 1849 // Order overloaded operators by the order in which they appear 1850 // in our list of operators. 1851 if (OverloadedOperatorKind XOp = X.getCXXOverloadedOperator()) 1852 return XOp < Y.getCXXOverloadedOperator(); 1853 1854 // Order C++0x user-defined literal operators lexically by their 1855 // lowercased suffixes. 1856 if (IdentifierInfo *XLit = X.getCXXLiteralIdentifier()) 1857 return XLit->getName().compare_lower( 1858 Y.getCXXLiteralIdentifier()->getName()) < 0; 1859 1860 // The only stable ordering we have is to turn the name into a 1861 // string and then compare the lower-case strings. This is 1862 // inefficient, but thankfully does not happen too often. 1863 return llvm::StringRef(X.getAsString()).compare_lower( 1864 Y.getAsString()) < 0; 1865 } 1866 1867 /// \brief Retrieve the name that should be used to order a result. 1868 /// 1869 /// If the name needs to be constructed as a string, that string will be 1870 /// saved into Saved and the returned StringRef will refer to it. 1871 static llvm::StringRef getOrderedName(const Result &R, 1872 std::string &Saved) { 1873 switch (R.Kind) { 1874 case Result::RK_Keyword: 1875 return R.Keyword; 1876 1877 case Result::RK_Pattern: 1878 return R.Pattern->getTypedText(); 1879 1880 case Result::RK_Macro: 1881 return R.Macro->getName(); 1882 1883 case Result::RK_Declaration: 1884 // Handle declarations below. 1885 break; 1886 } 1887 1888 DeclarationName Name = R.Declaration->getDeclName(); 1889 1890 // If the name is a simple identifier (by far the common case), or a 1891 // zero-argument selector, just return a reference to that identifier. 1892 if (IdentifierInfo *Id = Name.getAsIdentifierInfo()) 1893 return Id->getName(); 1894 if (Name.isObjCZeroArgSelector()) 1895 if (IdentifierInfo *Id 1896 = Name.getObjCSelector().getIdentifierInfoForSlot(0)) 1897 return Id->getName(); 1898 1899 Saved = Name.getAsString(); 1900 return Saved; 1901 } 1902 1903 bool operator()(const Result &X, const Result &Y) const { 1904 std::string XSaved, YSaved; 1905 llvm::StringRef XStr = getOrderedName(X, XSaved); 1906 llvm::StringRef YStr = getOrderedName(Y, YSaved); 1907 int cmp = XStr.compare_lower(YStr); 1908 if (cmp) 1909 return cmp < 0; 1910 1911 // Non-hidden names precede hidden names. 1912 if (X.Hidden != Y.Hidden) 1913 return !X.Hidden; 1914 1915 // Non-nested-name-specifiers precede nested-name-specifiers. 1916 if (X.StartsNestedNameSpecifier != Y.StartsNestedNameSpecifier) 1917 return !X.StartsNestedNameSpecifier; 1918 1919 return false; 1920 } 1921 }; 1922 } 1923 1924 static void AddMacroResults(Preprocessor &PP, ResultBuilder &Results) { 1925 Results.EnterNewScope(); 1926 for (Preprocessor::macro_iterator M = PP.macro_begin(), 1927 MEnd = PP.macro_end(); 1928 M != MEnd; ++M) 1929 Results.AddResult(M->first); 1930 Results.ExitScope(); 1931 } 1932 1933 static void HandleCodeCompleteResults(Sema *S, 1934 CodeCompleteConsumer *CodeCompleter, 1935 CodeCompleteConsumer::Result *Results, 1936 unsigned NumResults) { 1937 std::stable_sort(Results, Results + NumResults, SortCodeCompleteResult()); 1938 1939 if (CodeCompleter) 1940 CodeCompleter->ProcessCodeCompleteResults(*S, Results, NumResults); 1941 1942 for (unsigned I = 0; I != NumResults; ++I) 1943 Results[I].Destroy(); 1944 } 1945 1946 void Sema::CodeCompleteOrdinaryName(Scope *S, 1947 CodeCompletionContext CompletionContext) { 1948 typedef CodeCompleteConsumer::Result Result; 1949 ResultBuilder Results(*this); 1950 1951 // Determine how to filter results, e.g., so that the names of 1952 // values (functions, enumerators, function templates, etc.) are 1953 // only allowed where we can have an expression. 1954 switch (CompletionContext) { 1955 case CCC_Namespace: 1956 case CCC_Class: 1957 case CCC_ObjCInterface: 1958 case CCC_ObjCImplementation: 1959 case CCC_ObjCInstanceVariableList: 1960 case CCC_Template: 1961 case CCC_MemberTemplate: 1962 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName); 1963 break; 1964 1965 case CCC_Expression: 1966 case CCC_Statement: 1967 case CCC_ForInit: 1968 case CCC_Condition: 1969 Results.setFilter(&ResultBuilder::IsOrdinaryName); 1970 break; 1971 1972 case CCC_RecoveryInFunction: 1973 // Unfiltered 1974 break; 1975 } 1976 1977 CodeCompletionDeclConsumer Consumer(Results, CurContext); 1978 LookupVisibleDecls(S, LookupOrdinaryName, Consumer); 1979 1980 Results.EnterNewScope(); 1981 AddOrdinaryNameResults(CompletionContext, S, *this, Results); 1982 Results.ExitScope(); 1983 1984 if (CodeCompleter->includeMacros()) 1985 AddMacroResults(PP, Results); 1986 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size()); 1987 } 1988 1989 static void AddObjCProperties(ObjCContainerDecl *Container, 1990 bool AllowCategories, 1991 DeclContext *CurContext, 1992 ResultBuilder &Results) { 1993 typedef CodeCompleteConsumer::Result Result; 1994 1995 // Add properties in this container. 1996 for (ObjCContainerDecl::prop_iterator P = Container->prop_begin(), 1997 PEnd = Container->prop_end(); 1998 P != PEnd; 1999 ++P) 2000 Results.MaybeAddResult(Result(*P, 0), CurContext); 2001 2002 // Add properties in referenced protocols. 2003 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) { 2004 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(), 2005 PEnd = Protocol->protocol_end(); 2006 P != PEnd; ++P) 2007 AddObjCProperties(*P, AllowCategories, CurContext, Results); 2008 } else if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)){ 2009 if (AllowCategories) { 2010 // Look through categories. 2011 for (ObjCCategoryDecl *Category = IFace->getCategoryList(); 2012 Category; Category = Category->getNextClassCategory()) 2013 AddObjCProperties(Category, AllowCategories, CurContext, Results); 2014 } 2015 2016 // Look through protocols. 2017 for (ObjCInterfaceDecl::protocol_iterator I = IFace->protocol_begin(), 2018 E = IFace->protocol_end(); 2019 I != E; ++I) 2020 AddObjCProperties(*I, AllowCategories, CurContext, Results); 2021 2022 // Look in the superclass. 2023 if (IFace->getSuperClass()) 2024 AddObjCProperties(IFace->getSuperClass(), AllowCategories, CurContext, 2025 Results); 2026 } else if (const ObjCCategoryDecl *Category 2027 = dyn_cast<ObjCCategoryDecl>(Container)) { 2028 // Look through protocols. 2029 for (ObjCInterfaceDecl::protocol_iterator P = Category->protocol_begin(), 2030 PEnd = Category->protocol_end(); 2031 P != PEnd; ++P) 2032 AddObjCProperties(*P, AllowCategories, CurContext, Results); 2033 } 2034 } 2035 2036 void Sema::CodeCompleteMemberReferenceExpr(Scope *S, ExprTy *BaseE, 2037 SourceLocation OpLoc, 2038 bool IsArrow) { 2039 if (!BaseE || !CodeCompleter) 2040 return; 2041 2042 typedef CodeCompleteConsumer::Result Result; 2043 2044 Expr *Base = static_cast<Expr *>(BaseE); 2045 QualType BaseType = Base->getType(); 2046 2047 if (IsArrow) { 2048 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) 2049 BaseType = Ptr->getPointeeType(); 2050 else if (BaseType->isObjCObjectPointerType()) 2051 /*Do nothing*/ ; 2052 else 2053 return; 2054 } 2055 2056 ResultBuilder Results(*this, &ResultBuilder::IsMember); 2057 Results.EnterNewScope(); 2058 if (const RecordType *Record = BaseType->getAs<RecordType>()) { 2059 // Access to a C/C++ class, struct, or union. 2060 Results.allowNestedNameSpecifiers(); 2061 CodeCompletionDeclConsumer Consumer(Results, CurContext); 2062 LookupVisibleDecls(Record->getDecl(), LookupMemberName, Consumer); 2063 2064 if (getLangOptions().CPlusPlus) { 2065 if (!Results.empty()) { 2066 // The "template" keyword can follow "->" or "." in the grammar. 2067 // However, we only want to suggest the template keyword if something 2068 // is dependent. 2069 bool IsDependent = BaseType->isDependentType(); 2070 if (!IsDependent) { 2071 for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent()) 2072 if (DeclContext *Ctx = (DeclContext *)DepScope->getEntity()) { 2073 IsDependent = Ctx->isDependentContext(); 2074 break; 2075 } 2076 } 2077 2078 if (IsDependent) 2079 Results.AddResult(Result("template")); 2080 } 2081 } 2082 } else if (!IsArrow && BaseType->getAsObjCInterfacePointerType()) { 2083 // Objective-C property reference. 2084 2085 // Add property results based on our interface. 2086 const ObjCObjectPointerType *ObjCPtr 2087 = BaseType->getAsObjCInterfacePointerType(); 2088 assert(ObjCPtr && "Non-NULL pointer guaranteed above!"); 2089 AddObjCProperties(ObjCPtr->getInterfaceDecl(), true, CurContext, Results); 2090 2091 // Add properties from the protocols in a qualified interface. 2092 for (ObjCObjectPointerType::qual_iterator I = ObjCPtr->qual_begin(), 2093 E = ObjCPtr->qual_end(); 2094 I != E; ++I) 2095 AddObjCProperties(*I, true, CurContext, Results); 2096 } else if ((IsArrow && BaseType->isObjCObjectPointerType()) || 2097 (!IsArrow && BaseType->isObjCObjectType())) { 2098 // Objective-C instance variable access. 2099 ObjCInterfaceDecl *Class = 0; 2100 if (const ObjCObjectPointerType *ObjCPtr 2101 = BaseType->getAs<ObjCObjectPointerType>()) 2102 Class = ObjCPtr->getInterfaceDecl(); 2103 else 2104 Class = BaseType->getAs<ObjCObjectType>()->getInterface(); 2105 2106 // Add all ivars from this class and its superclasses. 2107 if (Class) { 2108 CodeCompletionDeclConsumer Consumer(Results, CurContext); 2109 Results.setFilter(&ResultBuilder::IsObjCIvar); 2110 LookupVisibleDecls(Class, LookupMemberName, Consumer); 2111 } 2112 } 2113 2114 // FIXME: How do we cope with isa? 2115 2116 Results.ExitScope(); 2117 2118 // Hand off the results found for code completion. 2119 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size()); 2120 } 2121 2122 void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) { 2123 if (!CodeCompleter) 2124 return; 2125 2126 typedef CodeCompleteConsumer::Result Result; 2127 ResultBuilder::LookupFilter Filter = 0; 2128 switch ((DeclSpec::TST)TagSpec) { 2129 case DeclSpec::TST_enum: 2130 Filter = &ResultBuilder::IsEnum; 2131 break; 2132 2133 case DeclSpec::TST_union: 2134 Filter = &ResultBuilder::IsUnion; 2135 break; 2136 2137 case DeclSpec::TST_struct: 2138 case DeclSpec::TST_class: 2139 Filter = &ResultBuilder::IsClassOrStruct; 2140 break; 2141 2142 default: 2143 assert(false && "Unknown type specifier kind in CodeCompleteTag"); 2144 return; 2145 } 2146 2147 ResultBuilder Results(*this); 2148 CodeCompletionDeclConsumer Consumer(Results, CurContext); 2149 2150 // First pass: look for tags. 2151 Results.setFilter(Filter); 2152 LookupVisibleDecls(S, LookupTagName, Consumer); 2153 2154 // Second pass: look for nested name specifiers. 2155 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier); 2156 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer); 2157 2158 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size()); 2159 } 2160 2161 void Sema::CodeCompleteCase(Scope *S) { 2162 if (getSwitchStack().empty() || !CodeCompleter) 2163 return; 2164 2165 SwitchStmt *Switch = getSwitchStack().back(); 2166 if (!Switch->getCond()->getType()->isEnumeralType()) 2167 return; 2168 2169 // Code-complete the cases of a switch statement over an enumeration type 2170 // by providing the list of 2171 EnumDecl *Enum = Switch->getCond()->getType()->getAs<EnumType>()->getDecl(); 2172 2173 // Determine which enumerators we have already seen in the switch statement. 2174 // FIXME: Ideally, we would also be able to look *past* the code-completion 2175 // token, in case we are code-completing in the middle of the switch and not 2176 // at the end. However, we aren't able to do so at the moment. 2177 llvm::SmallPtrSet<EnumConstantDecl *, 8> EnumeratorsSeen; 2178 NestedNameSpecifier *Qualifier = 0; 2179 for (SwitchCase *SC = Switch->getSwitchCaseList(); SC; 2180 SC = SC->getNextSwitchCase()) { 2181 CaseStmt *Case = dyn_cast<CaseStmt>(SC); 2182 if (!Case) 2183 continue; 2184 2185 Expr *CaseVal = Case->getLHS()->IgnoreParenCasts(); 2186 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseVal)) 2187 if (EnumConstantDecl *Enumerator 2188 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 2189 // We look into the AST of the case statement to determine which 2190 // enumerator was named. Alternatively, we could compute the value of 2191 // the integral constant expression, then compare it against the 2192 // values of each enumerator. However, value-based approach would not 2193 // work as well with C++ templates where enumerators declared within a 2194 // template are type- and value-dependent. 2195 EnumeratorsSeen.insert(Enumerator); 2196 2197 // If this is a qualified-id, keep track of the nested-name-specifier 2198 // so that we can reproduce it as part of code completion, e.g., 2199 // 2200 // switch (TagD.getKind()) { 2201 // case TagDecl::TK_enum: 2202 // break; 2203 // case XXX 2204 // 2205 // At the XXX, our completions are TagDecl::TK_union, 2206 // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union, 2207 // TK_struct, and TK_class. 2208 Qualifier = DRE->getQualifier(); 2209 } 2210 } 2211 2212 if (getLangOptions().CPlusPlus && !Qualifier && EnumeratorsSeen.empty()) { 2213 // If there are no prior enumerators in C++, check whether we have to 2214 // qualify the names of the enumerators that we suggest, because they 2215 // may not be visible in this scope. 2216 Qualifier = getRequiredQualification(Context, CurContext, 2217 Enum->getDeclContext()); 2218 2219 // FIXME: Scoped enums need to start with "EnumDecl" as the context! 2220 } 2221 2222 // Add any enumerators that have not yet been mentioned. 2223 ResultBuilder Results(*this); 2224 Results.EnterNewScope(); 2225 for (EnumDecl::enumerator_iterator E = Enum->enumerator_begin(), 2226 EEnd = Enum->enumerator_end(); 2227 E != EEnd; ++E) { 2228 if (EnumeratorsSeen.count(*E)) 2229 continue; 2230 2231 Results.AddResult(CodeCompleteConsumer::Result(*E, Qualifier), 2232 CurContext, 0, false); 2233 } 2234 Results.ExitScope(); 2235 2236 if (CodeCompleter->includeMacros()) 2237 AddMacroResults(PP, Results); 2238 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size()); 2239 } 2240 2241 namespace { 2242 struct IsBetterOverloadCandidate { 2243 Sema &S; 2244 SourceLocation Loc; 2245 2246 public: 2247 explicit IsBetterOverloadCandidate(Sema &S, SourceLocation Loc) 2248 : S(S), Loc(Loc) { } 2249 2250 bool 2251 operator()(const OverloadCandidate &X, const OverloadCandidate &Y) const { 2252 return S.isBetterOverloadCandidate(X, Y, Loc); 2253 } 2254 }; 2255 } 2256 2257 void Sema::CodeCompleteCall(Scope *S, ExprTy *FnIn, 2258 ExprTy **ArgsIn, unsigned NumArgs) { 2259 if (!CodeCompleter) 2260 return; 2261 2262 // When we're code-completing for a call, we fall back to ordinary 2263 // name code-completion whenever we can't produce specific 2264 // results. We may want to revisit this strategy in the future, 2265 // e.g., by merging the two kinds of results. 2266 2267 Expr *Fn = (Expr *)FnIn; 2268 Expr **Args = (Expr **)ArgsIn; 2269 2270 // Ignore type-dependent call expressions entirely. 2271 if (Fn->isTypeDependent() || 2272 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) { 2273 CodeCompleteOrdinaryName(S, CCC_Expression); 2274 return; 2275 } 2276 2277 // Build an overload candidate set based on the functions we find. 2278 SourceLocation Loc = Fn->getExprLoc(); 2279 OverloadCandidateSet CandidateSet(Loc); 2280 2281 // FIXME: What if we're calling something that isn't a function declaration? 2282 // FIXME: What if we're calling a pseudo-destructor? 2283 // FIXME: What if we're calling a member function? 2284 2285 typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate; 2286 llvm::SmallVector<ResultCandidate, 8> Results; 2287 2288 Expr *NakedFn = Fn->IgnoreParenCasts(); 2289 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(NakedFn)) 2290 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet, 2291 /*PartialOverloading=*/ true); 2292 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(NakedFn)) { 2293 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl()); 2294 if (FDecl) { 2295 if (!FDecl->getType()->getAs<FunctionProtoType>()) 2296 Results.push_back(ResultCandidate(FDecl)); 2297 else 2298 // FIXME: access? 2299 AddOverloadCandidate(FDecl, DeclAccessPair::make(FDecl, AS_none), 2300 Args, NumArgs, CandidateSet, 2301 false, /*PartialOverloading*/true); 2302 } 2303 } 2304 2305 if (!CandidateSet.empty()) { 2306 // Sort the overload candidate set by placing the best overloads first. 2307 std::stable_sort(CandidateSet.begin(), CandidateSet.end(), 2308 IsBetterOverloadCandidate(*this, Loc)); 2309 2310 // Add the remaining viable overload candidates as code-completion reslults. 2311 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 2312 CandEnd = CandidateSet.end(); 2313 Cand != CandEnd; ++Cand) { 2314 if (Cand->Viable) 2315 Results.push_back(ResultCandidate(Cand->Function)); 2316 } 2317 } 2318 2319 CodeCompleteOrdinaryName(S, CCC_Expression); 2320 if (!Results.empty()) 2321 CodeCompleter->ProcessOverloadCandidates(*this, NumArgs, Results.data(), 2322 Results.size()); 2323 } 2324 2325 void Sema::CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS, 2326 bool EnteringContext) { 2327 if (!SS.getScopeRep() || !CodeCompleter) 2328 return; 2329 2330 DeclContext *Ctx = computeDeclContext(SS, EnteringContext); 2331 if (!Ctx) 2332 return; 2333 2334 // Try to instantiate any non-dependent declaration contexts before 2335 // we look in them. 2336 if (!isDependentScopeSpecifier(SS) && RequireCompleteDeclContext(SS, Ctx)) 2337 return; 2338 2339 ResultBuilder Results(*this); 2340 CodeCompletionDeclConsumer Consumer(Results, CurContext); 2341 LookupVisibleDecls(Ctx, LookupOrdinaryName, Consumer); 2342 2343 // The "template" keyword can follow "::" in the grammar, but only 2344 // put it into the grammar if the nested-name-specifier is dependent. 2345 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep(); 2346 if (!Results.empty() && NNS->isDependent()) 2347 Results.AddResult("template"); 2348 2349 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size()); 2350 } 2351 2352 void Sema::CodeCompleteUsing(Scope *S) { 2353 if (!CodeCompleter) 2354 return; 2355 2356 ResultBuilder Results(*this, &ResultBuilder::IsNestedNameSpecifier); 2357 Results.EnterNewScope(); 2358 2359 // If we aren't in class scope, we could see the "namespace" keyword. 2360 if (!S->isClassScope()) 2361 Results.AddResult(CodeCompleteConsumer::Result("namespace")); 2362 2363 // After "using", we can see anything that would start a 2364 // nested-name-specifier. 2365 CodeCompletionDeclConsumer Consumer(Results, CurContext); 2366 LookupVisibleDecls(S, LookupOrdinaryName, Consumer); 2367 Results.ExitScope(); 2368 2369 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size()); 2370 } 2371 2372 void Sema::CodeCompleteUsingDirective(Scope *S) { 2373 if (!CodeCompleter) 2374 return; 2375 2376 // After "using namespace", we expect to see a namespace name or namespace 2377 // alias. 2378 ResultBuilder Results(*this, &ResultBuilder::IsNamespaceOrAlias); 2379 Results.EnterNewScope(); 2380 CodeCompletionDeclConsumer Consumer(Results, CurContext); 2381 LookupVisibleDecls(S, LookupOrdinaryName, Consumer); 2382 Results.ExitScope(); 2383 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size()); 2384 } 2385 2386 void Sema::CodeCompleteNamespaceDecl(Scope *S) { 2387 if (!CodeCompleter) 2388 return; 2389 2390 ResultBuilder Results(*this, &ResultBuilder::IsNamespace); 2391 DeclContext *Ctx = (DeclContext *)S->getEntity(); 2392 if (!S->getParent()) 2393 Ctx = Context.getTranslationUnitDecl(); 2394 2395 if (Ctx && Ctx->isFileContext()) { 2396 // We only want to see those namespaces that have already been defined 2397 // within this scope, because its likely that the user is creating an 2398 // extended namespace declaration. Keep track of the most recent 2399 // definition of each namespace. 2400 std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest; 2401 for (DeclContext::specific_decl_iterator<NamespaceDecl> 2402 NS(Ctx->decls_begin()), NSEnd(Ctx->decls_end()); 2403 NS != NSEnd; ++NS) 2404 OrigToLatest[NS->getOriginalNamespace()] = *NS; 2405 2406 // Add the most recent definition (or extended definition) of each 2407 // namespace to the list of results. 2408 Results.EnterNewScope(); 2409 for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator 2410 NS = OrigToLatest.begin(), NSEnd = OrigToLatest.end(); 2411 NS != NSEnd; ++NS) 2412 Results.AddResult(CodeCompleteConsumer::Result(NS->second, 0), 2413 CurContext, 0, false); 2414 Results.ExitScope(); 2415 } 2416 2417 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size()); 2418 } 2419 2420 void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) { 2421 if (!CodeCompleter) 2422 return; 2423 2424 // After "namespace", we expect to see a namespace or alias. 2425 ResultBuilder Results(*this, &ResultBuilder::IsNamespaceOrAlias); 2426 CodeCompletionDeclConsumer Consumer(Results, CurContext); 2427 LookupVisibleDecls(S, LookupOrdinaryName, Consumer); 2428 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size()); 2429 } 2430 2431 void Sema::CodeCompleteOperatorName(Scope *S) { 2432 if (!CodeCompleter) 2433 return; 2434 2435 typedef CodeCompleteConsumer::Result Result; 2436 ResultBuilder Results(*this, &ResultBuilder::IsType); 2437 Results.EnterNewScope(); 2438 2439 // Add the names of overloadable operators. 2440 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 2441 if (std::strcmp(Spelling, "?")) \ 2442 Results.AddResult(Result(Spelling)); 2443 #include "clang/Basic/OperatorKinds.def" 2444 2445 // Add any type names visible from the current scope 2446 Results.allowNestedNameSpecifiers(); 2447 CodeCompletionDeclConsumer Consumer(Results, CurContext); 2448 LookupVisibleDecls(S, LookupOrdinaryName, Consumer); 2449 2450 // Add any type specifiers 2451 AddTypeSpecifierResults(getLangOptions(), Results); 2452 Results.ExitScope(); 2453 2454 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size()); 2455 } 2456 2457 // Macro that expands to @Keyword or Keyword, depending on whether NeedAt is 2458 // true or false. 2459 #define OBJC_AT_KEYWORD_NAME(NeedAt,Keyword) NeedAt? "@" #Keyword : #Keyword 2460 static void AddObjCImplementationResults(const LangOptions &LangOpts, 2461 ResultBuilder &Results, 2462 bool NeedAt) { 2463 if (!Results.includeCodePatterns()) 2464 return; 2465 2466 typedef CodeCompleteConsumer::Result Result; 2467 // Since we have an implementation, we can end it. 2468 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,end))); 2469 2470 CodeCompletionString *Pattern = 0; 2471 if (LangOpts.ObjC2) { 2472 // @dynamic 2473 Pattern = new CodeCompletionString; 2474 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,dynamic)); 2475 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace); 2476 Pattern->AddPlaceholderChunk("property"); 2477 Results.AddResult(Result(Pattern)); 2478 2479 // @synthesize 2480 Pattern = new CodeCompletionString; 2481 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,synthesize)); 2482 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace); 2483 Pattern->AddPlaceholderChunk("property"); 2484 Results.AddResult(Result(Pattern)); 2485 } 2486 } 2487 2488 static void AddObjCInterfaceResults(const LangOptions &LangOpts, 2489 ResultBuilder &Results, 2490 bool NeedAt) { 2491 if (!Results.includeCodePatterns()) 2492 return; 2493 2494 typedef CodeCompleteConsumer::Result Result; 2495 2496 // Since we have an interface or protocol, we can end it. 2497 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,end))); 2498 2499 if (LangOpts.ObjC2) { 2500 // @property 2501 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,property))); 2502 2503 // @required 2504 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,required))); 2505 2506 // @optional 2507 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,optional))); 2508 } 2509 } 2510 2511 static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt) { 2512 if (!Results.includeCodePatterns()) 2513 return; 2514 2515 typedef CodeCompleteConsumer::Result Result; 2516 CodeCompletionString *Pattern = 0; 2517 2518 // @class name ; 2519 Pattern = new CodeCompletionString; 2520 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,class)); 2521 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace); 2522 Pattern->AddPlaceholderChunk("identifier"); 2523 Results.AddResult(Result(Pattern)); 2524 2525 // @interface name 2526 // FIXME: Could introduce the whole pattern, including superclasses and 2527 // such. 2528 Pattern = new CodeCompletionString; 2529 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,interface)); 2530 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace); 2531 Pattern->AddPlaceholderChunk("class"); 2532 Results.AddResult(Result(Pattern)); 2533 2534 // @protocol name 2535 Pattern = new CodeCompletionString; 2536 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,protocol)); 2537 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace); 2538 Pattern->AddPlaceholderChunk("protocol"); 2539 Results.AddResult(Result(Pattern)); 2540 2541 // @implementation name 2542 Pattern = new CodeCompletionString; 2543 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,implementation)); 2544 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace); 2545 Pattern->AddPlaceholderChunk("class"); 2546 Results.AddResult(Result(Pattern)); 2547 2548 // @compatibility_alias name 2549 Pattern = new CodeCompletionString; 2550 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,compatibility_alias)); 2551 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace); 2552 Pattern->AddPlaceholderChunk("alias"); 2553 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace); 2554 Pattern->AddPlaceholderChunk("class"); 2555 Results.AddResult(Result(Pattern)); 2556 } 2557 2558 void Sema::CodeCompleteObjCAtDirective(Scope *S, DeclPtrTy ObjCImpDecl, 2559 bool InInterface) { 2560 typedef CodeCompleteConsumer::Result Result; 2561 ResultBuilder Results(*this); 2562 Results.EnterNewScope(); 2563 if (ObjCImpDecl) 2564 AddObjCImplementationResults(getLangOptions(), Results, false); 2565 else if (InInterface) 2566 AddObjCInterfaceResults(getLangOptions(), Results, false); 2567 else 2568 AddObjCTopLevelResults(Results, false); 2569 Results.ExitScope(); 2570 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size()); 2571 } 2572 2573 static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt) { 2574 if (!Results.includeCodePatterns()) 2575 return; 2576 2577 typedef CodeCompleteConsumer::Result Result; 2578 CodeCompletionString *Pattern = 0; 2579 2580 // @encode ( type-name ) 2581 Pattern = new CodeCompletionString; 2582 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,encode)); 2583 Pattern->AddChunk(CodeCompletionString::CK_LeftParen); 2584 Pattern->AddPlaceholderChunk("type-name"); 2585 Pattern->AddChunk(CodeCompletionString::CK_RightParen); 2586 Results.AddResult(Result(Pattern)); 2587 2588 // @protocol ( protocol-name ) 2589 Pattern = new CodeCompletionString; 2590 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,protocol)); 2591 Pattern->AddChunk(CodeCompletionString::CK_LeftParen); 2592 Pattern->AddPlaceholderChunk("protocol-name"); 2593 Pattern->AddChunk(CodeCompletionString::CK_RightParen); 2594 Results.AddResult(Result(Pattern)); 2595 2596 // @selector ( selector ) 2597 Pattern = new CodeCompletionString; 2598 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,selector)); 2599 Pattern->AddChunk(CodeCompletionString::CK_LeftParen); 2600 Pattern->AddPlaceholderChunk("selector"); 2601 Pattern->AddChunk(CodeCompletionString::CK_RightParen); 2602 Results.AddResult(Result(Pattern)); 2603 } 2604 2605 static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt) { 2606 if (!Results.includeCodePatterns()) 2607 return; 2608 2609 typedef CodeCompleteConsumer::Result Result; 2610 CodeCompletionString *Pattern = 0; 2611 2612 // @try { statements } @catch ( declaration ) { statements } @finally 2613 // { statements } 2614 Pattern = new CodeCompletionString; 2615 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,try)); 2616 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace); 2617 Pattern->AddPlaceholderChunk("statements"); 2618 Pattern->AddChunk(CodeCompletionString::CK_RightBrace); 2619 Pattern->AddTextChunk("@catch"); 2620 Pattern->AddChunk(CodeCompletionString::CK_LeftParen); 2621 Pattern->AddPlaceholderChunk("parameter"); 2622 Pattern->AddChunk(CodeCompletionString::CK_RightParen); 2623 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace); 2624 Pattern->AddPlaceholderChunk("statements"); 2625 Pattern->AddChunk(CodeCompletionString::CK_RightBrace); 2626 Pattern->AddTextChunk("@finally"); 2627 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace); 2628 Pattern->AddPlaceholderChunk("statements"); 2629 Pattern->AddChunk(CodeCompletionString::CK_RightBrace); 2630 Results.AddResult(Result(Pattern)); 2631 2632 // @throw 2633 Pattern = new CodeCompletionString; 2634 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,throw)); 2635 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace); 2636 Pattern->AddPlaceholderChunk("expression"); 2637 Results.AddResult(Result(Pattern)); 2638 2639 // @synchronized ( expression ) { statements } 2640 Pattern = new CodeCompletionString; 2641 Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,synchronized)); 2642 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace); 2643 Pattern->AddChunk(CodeCompletionString::CK_LeftParen); 2644 Pattern->AddPlaceholderChunk("expression"); 2645 Pattern->AddChunk(CodeCompletionString::CK_RightParen); 2646 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace); 2647 Pattern->AddPlaceholderChunk("statements"); 2648 Pattern->AddChunk(CodeCompletionString::CK_RightBrace); 2649 Results.AddResult(Result(Pattern)); 2650 } 2651 2652 static void AddObjCVisibilityResults(const LangOptions &LangOpts, 2653 ResultBuilder &Results, 2654 bool NeedAt) { 2655 if (!Results.includeCodePatterns()) 2656 return; 2657 2658 typedef CodeCompleteConsumer::Result Result; 2659 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,private))); 2660 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,protected))); 2661 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,public))); 2662 if (LangOpts.ObjC2) 2663 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,package))); 2664 } 2665 2666 void Sema::CodeCompleteObjCAtVisibility(Scope *S) { 2667 ResultBuilder Results(*this); 2668 Results.EnterNewScope(); 2669 AddObjCVisibilityResults(getLangOptions(), Results, false); 2670 Results.ExitScope(); 2671 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size()); 2672 } 2673 2674 void Sema::CodeCompleteObjCAtStatement(Scope *S) { 2675 ResultBuilder Results(*this); 2676 Results.EnterNewScope(); 2677 AddObjCStatementResults(Results, false); 2678 AddObjCExpressionResults(Results, false); 2679 Results.ExitScope(); 2680 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size()); 2681 } 2682 2683 void Sema::CodeCompleteObjCAtExpression(Scope *S) { 2684 ResultBuilder Results(*this); 2685 Results.EnterNewScope(); 2686 AddObjCExpressionResults(Results, false); 2687 Results.ExitScope(); 2688 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size()); 2689 } 2690 2691 /// \brief Determine whether the addition of the given flag to an Objective-C 2692 /// property's attributes will cause a conflict. 2693 static bool ObjCPropertyFlagConflicts(unsigned Attributes, unsigned NewFlag) { 2694 // Check if we've already added this flag. 2695 if (Attributes & NewFlag) 2696 return true; 2697 2698 Attributes |= NewFlag; 2699 2700 // Check for collisions with "readonly". 2701 if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) && 2702 (Attributes & (ObjCDeclSpec::DQ_PR_readwrite | 2703 ObjCDeclSpec::DQ_PR_assign | 2704 ObjCDeclSpec::DQ_PR_copy | 2705 ObjCDeclSpec::DQ_PR_retain))) 2706 return true; 2707 2708 // Check for more than one of { assign, copy, retain }. 2709 unsigned AssignCopyRetMask = Attributes & (ObjCDeclSpec::DQ_PR_assign | 2710 ObjCDeclSpec::DQ_PR_copy | 2711 ObjCDeclSpec::DQ_PR_retain); 2712 if (AssignCopyRetMask && 2713 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_assign && 2714 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_copy && 2715 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_retain) 2716 return true; 2717 2718 return false; 2719 } 2720 2721 void Sema::CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS) { 2722 if (!CodeCompleter) 2723 return; 2724 2725 unsigned Attributes = ODS.getPropertyAttributes(); 2726 2727 typedef CodeCompleteConsumer::Result Result; 2728 ResultBuilder Results(*this); 2729 Results.EnterNewScope(); 2730 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readonly)) 2731 Results.AddResult(CodeCompleteConsumer::Result("readonly")); 2732 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_assign)) 2733 Results.AddResult(CodeCompleteConsumer::Result("assign")); 2734 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readwrite)) 2735 Results.AddResult(CodeCompleteConsumer::Result("readwrite")); 2736 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_retain)) 2737 Results.AddResult(CodeCompleteConsumer::Result("retain")); 2738 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_copy)) 2739 Results.AddResult(CodeCompleteConsumer::Result("copy")); 2740 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nonatomic)) 2741 Results.AddResult(CodeCompleteConsumer::Result("nonatomic")); 2742 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_setter)) { 2743 CodeCompletionString *Setter = new CodeCompletionString; 2744 Setter->AddTypedTextChunk("setter"); 2745 Setter->AddTextChunk(" = "); 2746 Setter->AddPlaceholderChunk("method"); 2747 Results.AddResult(CodeCompleteConsumer::Result(Setter)); 2748 } 2749 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_getter)) { 2750 CodeCompletionString *Getter = new CodeCompletionString; 2751 Getter->AddTypedTextChunk("getter"); 2752 Getter->AddTextChunk(" = "); 2753 Getter->AddPlaceholderChunk("method"); 2754 Results.AddResult(CodeCompleteConsumer::Result(Getter)); 2755 } 2756 Results.ExitScope(); 2757 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size()); 2758 } 2759 2760 /// \brief Descripts the kind of Objective-C method that we want to find 2761 /// via code completion. 2762 enum ObjCMethodKind { 2763 MK_Any, //< Any kind of method, provided it means other specified criteria. 2764 MK_ZeroArgSelector, //< Zero-argument (unary) selector. 2765 MK_OneArgSelector //< One-argument selector. 2766 }; 2767 2768 static bool isAcceptableObjCMethod(ObjCMethodDecl *Method, 2769 ObjCMethodKind WantKind, 2770 IdentifierInfo **SelIdents, 2771 unsigned NumSelIdents) { 2772 Selector Sel = Method->getSelector(); 2773 if (NumSelIdents > Sel.getNumArgs()) 2774 return false; 2775 2776 switch (WantKind) { 2777 case MK_Any: break; 2778 case MK_ZeroArgSelector: return Sel.isUnarySelector(); 2779 case MK_OneArgSelector: return Sel.getNumArgs() == 1; 2780 } 2781 2782 for (unsigned I = 0; I != NumSelIdents; ++I) 2783 if (SelIdents[I] != Sel.getIdentifierInfoForSlot(I)) 2784 return false; 2785 2786 return true; 2787 } 2788 2789 /// \brief Add all of the Objective-C methods in the given Objective-C 2790 /// container to the set of results. 2791 /// 2792 /// The container will be a class, protocol, category, or implementation of 2793 /// any of the above. This mether will recurse to include methods from 2794 /// the superclasses of classes along with their categories, protocols, and 2795 /// implementations. 2796 /// 2797 /// \param Container the container in which we'll look to find methods. 2798 /// 2799 /// \param WantInstance whether to add instance methods (only); if false, this 2800 /// routine will add factory methods (only). 2801 /// 2802 /// \param CurContext the context in which we're performing the lookup that 2803 /// finds methods. 2804 /// 2805 /// \param Results the structure into which we'll add results. 2806 static void AddObjCMethods(ObjCContainerDecl *Container, 2807 bool WantInstanceMethods, 2808 ObjCMethodKind WantKind, 2809 IdentifierInfo **SelIdents, 2810 unsigned NumSelIdents, 2811 DeclContext *CurContext, 2812 ResultBuilder &Results) { 2813 typedef CodeCompleteConsumer::Result Result; 2814 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(), 2815 MEnd = Container->meth_end(); 2816 M != MEnd; ++M) { 2817 if ((*M)->isInstanceMethod() == WantInstanceMethods) { 2818 // Check whether the selector identifiers we've been given are a 2819 // subset of the identifiers for this particular method. 2820 if (!isAcceptableObjCMethod(*M, WantKind, SelIdents, NumSelIdents)) 2821 continue; 2822 2823 Result R = Result(*M, 0); 2824 R.StartParameter = NumSelIdents; 2825 R.AllParametersAreInformative = (WantKind != MK_Any); 2826 Results.MaybeAddResult(R, CurContext); 2827 } 2828 } 2829 2830 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container); 2831 if (!IFace) 2832 return; 2833 2834 // Add methods in protocols. 2835 const ObjCList<ObjCProtocolDecl> &Protocols= IFace->getReferencedProtocols(); 2836 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(), 2837 E = Protocols.end(); 2838 I != E; ++I) 2839 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, NumSelIdents, 2840 CurContext, Results); 2841 2842 // Add methods in categories. 2843 for (ObjCCategoryDecl *CatDecl = IFace->getCategoryList(); CatDecl; 2844 CatDecl = CatDecl->getNextClassCategory()) { 2845 AddObjCMethods(CatDecl, WantInstanceMethods, WantKind, SelIdents, 2846 NumSelIdents, CurContext, Results); 2847 2848 // Add a categories protocol methods. 2849 const ObjCList<ObjCProtocolDecl> &Protocols 2850 = CatDecl->getReferencedProtocols(); 2851 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(), 2852 E = Protocols.end(); 2853 I != E; ++I) 2854 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, 2855 NumSelIdents, CurContext, Results); 2856 2857 // Add methods in category implementations. 2858 if (ObjCCategoryImplDecl *Impl = CatDecl->getImplementation()) 2859 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents, 2860 NumSelIdents, CurContext, Results); 2861 } 2862 2863 // Add methods in superclass. 2864 if (IFace->getSuperClass()) 2865 AddObjCMethods(IFace->getSuperClass(), WantInstanceMethods, WantKind, 2866 SelIdents, NumSelIdents, CurContext, Results); 2867 2868 // Add methods in our implementation, if any. 2869 if (ObjCImplementationDecl *Impl = IFace->getImplementation()) 2870 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents, 2871 NumSelIdents, CurContext, Results); 2872 } 2873 2874 2875 void Sema::CodeCompleteObjCPropertyGetter(Scope *S, DeclPtrTy ClassDecl, 2876 DeclPtrTy *Methods, 2877 unsigned NumMethods) { 2878 typedef CodeCompleteConsumer::Result Result; 2879 2880 // Try to find the interface where getters might live. 2881 ObjCInterfaceDecl *Class 2882 = dyn_cast_or_null<ObjCInterfaceDecl>(ClassDecl.getAs<Decl>()); 2883 if (!Class) { 2884 if (ObjCCategoryDecl *Category 2885 = dyn_cast_or_null<ObjCCategoryDecl>(ClassDecl.getAs<Decl>())) 2886 Class = Category->getClassInterface(); 2887 2888 if (!Class) 2889 return; 2890 } 2891 2892 // Find all of the potential getters. 2893 ResultBuilder Results(*this); 2894 Results.EnterNewScope(); 2895 2896 // FIXME: We need to do this because Objective-C methods don't get 2897 // pushed into DeclContexts early enough. Argh! 2898 for (unsigned I = 0; I != NumMethods; ++I) { 2899 if (ObjCMethodDecl *Method 2900 = dyn_cast_or_null<ObjCMethodDecl>(Methods[I].getAs<Decl>())) 2901 if (Method->isInstanceMethod() && 2902 isAcceptableObjCMethod(Method, MK_ZeroArgSelector, 0, 0)) { 2903 Result R = Result(Method, 0); 2904 R.AllParametersAreInformative = true; 2905 Results.MaybeAddResult(R, CurContext); 2906 } 2907 } 2908 2909 AddObjCMethods(Class, true, MK_ZeroArgSelector, 0, 0, CurContext, Results); 2910 Results.ExitScope(); 2911 HandleCodeCompleteResults(this, CodeCompleter,Results.data(),Results.size()); 2912 } 2913 2914 void Sema::CodeCompleteObjCPropertySetter(Scope *S, DeclPtrTy ObjCImplDecl, 2915 DeclPtrTy *Methods, 2916 unsigned NumMethods) { 2917 typedef CodeCompleteConsumer::Result Result; 2918 2919 // Try to find the interface where setters might live. 2920 ObjCInterfaceDecl *Class 2921 = dyn_cast_or_null<ObjCInterfaceDecl>(ObjCImplDecl.getAs<Decl>()); 2922 if (!Class) { 2923 if (ObjCCategoryDecl *Category 2924 = dyn_cast_or_null<ObjCCategoryDecl>(ObjCImplDecl.getAs<Decl>())) 2925 Class = Category->getClassInterface(); 2926 2927 if (!Class) 2928 return; 2929 } 2930 2931 // Find all of the potential getters. 2932 ResultBuilder Results(*this); 2933 Results.EnterNewScope(); 2934 2935 // FIXME: We need to do this because Objective-C methods don't get 2936 // pushed into DeclContexts early enough. Argh! 2937 for (unsigned I = 0; I != NumMethods; ++I) { 2938 if (ObjCMethodDecl *Method 2939 = dyn_cast_or_null<ObjCMethodDecl>(Methods[I].getAs<Decl>())) 2940 if (Method->isInstanceMethod() && 2941 isAcceptableObjCMethod(Method, MK_OneArgSelector, 0, 0)) { 2942 Result R = Result(Method, 0); 2943 R.AllParametersAreInformative = true; 2944 Results.MaybeAddResult(R, CurContext); 2945 } 2946 } 2947 2948 AddObjCMethods(Class, true, MK_OneArgSelector, 0, 0, CurContext, Results); 2949 2950 Results.ExitScope(); 2951 HandleCodeCompleteResults(this, CodeCompleter,Results.data(),Results.size()); 2952 } 2953 2954 /// \brief When we have an expression with type "id", we may assume 2955 /// that it has some more-specific class type based on knowledge of 2956 /// common uses of Objective-C. This routine returns that class type, 2957 /// or NULL if no better result could be determined. 2958 static ObjCInterfaceDecl *GetAssumedMessageSendExprType(Expr *E) { 2959 ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E); 2960 if (!Msg) 2961 return 0; 2962 2963 Selector Sel = Msg->getSelector(); 2964 if (Sel.isNull()) 2965 return 0; 2966 2967 IdentifierInfo *Id = Sel.getIdentifierInfoForSlot(0); 2968 if (!Id) 2969 return 0; 2970 2971 ObjCMethodDecl *Method = Msg->getMethodDecl(); 2972 if (!Method) 2973 return 0; 2974 2975 // Determine the class that we're sending the message to. 2976 ObjCInterfaceDecl *IFace = 0; 2977 switch (Msg->getReceiverKind()) { 2978 case ObjCMessageExpr::Class: 2979 if (const ObjCObjectType *ObjType 2980 = Msg->getClassReceiver()->getAs<ObjCObjectType>()) 2981 IFace = ObjType->getInterface(); 2982 break; 2983 2984 case ObjCMessageExpr::Instance: { 2985 QualType T = Msg->getInstanceReceiver()->getType(); 2986 if (const ObjCObjectPointerType *Ptr = T->getAs<ObjCObjectPointerType>()) 2987 IFace = Ptr->getInterfaceDecl(); 2988 break; 2989 } 2990 2991 case ObjCMessageExpr::SuperInstance: 2992 case ObjCMessageExpr::SuperClass: 2993 break; 2994 } 2995 2996 if (!IFace) 2997 return 0; 2998 2999 ObjCInterfaceDecl *Super = IFace->getSuperClass(); 3000 if (Method->isInstanceMethod()) 3001 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName()) 3002 .Case("retain", IFace) 3003 .Case("autorelease", IFace) 3004 .Case("copy", IFace) 3005 .Case("copyWithZone", IFace) 3006 .Case("mutableCopy", IFace) 3007 .Case("mutableCopyWithZone", IFace) 3008 .Case("awakeFromCoder", IFace) 3009 .Case("replacementObjectFromCoder", IFace) 3010 .Case("class", IFace) 3011 .Case("classForCoder", IFace) 3012 .Case("superclass", Super) 3013 .Default(0); 3014 3015 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName()) 3016 .Case("new", IFace) 3017 .Case("alloc", IFace) 3018 .Case("allocWithZone", IFace) 3019 .Case("class", IFace) 3020 .Case("superclass", Super) 3021 .Default(0); 3022 } 3023 3024 void Sema::CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc, 3025 IdentifierInfo **SelIdents, 3026 unsigned NumSelIdents) { 3027 ObjCInterfaceDecl *CDecl = 0; 3028 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) { 3029 // Figure out which interface we're in. 3030 CDecl = CurMethod->getClassInterface(); 3031 if (!CDecl) 3032 return; 3033 3034 // Find the superclass of this class. 3035 CDecl = CDecl->getSuperClass(); 3036 if (!CDecl) 3037 return; 3038 3039 if (CurMethod->isInstanceMethod()) { 3040 // We are inside an instance method, which means that the message 3041 // send [super ...] is actually calling an instance method on the 3042 // current object. Build the super expression and handle this like 3043 // an instance method. 3044 QualType SuperTy = Context.getObjCInterfaceType(CDecl); 3045 SuperTy = Context.getObjCObjectPointerType(SuperTy); 3046 OwningExprResult Super 3047 = Owned(new (Context) ObjCSuperExpr(SuperLoc, SuperTy)); 3048 return CodeCompleteObjCInstanceMessage(S, (Expr *)Super.get(), 3049 SelIdents, NumSelIdents); 3050 } 3051 3052 // Fall through to send to the superclass in CDecl. 3053 } else { 3054 // "super" may be the name of a type or variable. Figure out which 3055 // it is. 3056 IdentifierInfo *Super = &Context.Idents.get("super"); 3057 NamedDecl *ND = LookupSingleName(S, Super, SuperLoc, 3058 LookupOrdinaryName); 3059 if ((CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(ND))) { 3060 // "super" names an interface. Use it. 3061 } else if (TypeDecl *TD = dyn_cast_or_null<TypeDecl>(ND)) { 3062 if (const ObjCObjectType *Iface 3063 = Context.getTypeDeclType(TD)->getAs<ObjCObjectType>()) 3064 CDecl = Iface->getInterface(); 3065 } else if (ND && isa<UnresolvedUsingTypenameDecl>(ND)) { 3066 // "super" names an unresolved type; we can't be more specific. 3067 } else { 3068 // Assume that "super" names some kind of value and parse that way. 3069 CXXScopeSpec SS; 3070 UnqualifiedId id; 3071 id.setIdentifier(Super, SuperLoc); 3072 OwningExprResult SuperExpr = ActOnIdExpression(S, SS, id, false, false); 3073 return CodeCompleteObjCInstanceMessage(S, (Expr *)SuperExpr.get(), 3074 SelIdents, NumSelIdents); 3075 } 3076 3077 // Fall through 3078 } 3079 3080 TypeTy *Receiver = 0; 3081 if (CDecl) 3082 Receiver = Context.getObjCInterfaceType(CDecl).getAsOpaquePtr(); 3083 return CodeCompleteObjCClassMessage(S, Receiver, SelIdents, 3084 NumSelIdents); 3085 } 3086 3087 void Sema::CodeCompleteObjCClassMessage(Scope *S, TypeTy *Receiver, 3088 IdentifierInfo **SelIdents, 3089 unsigned NumSelIdents) { 3090 typedef CodeCompleteConsumer::Result Result; 3091 ObjCInterfaceDecl *CDecl = 0; 3092 3093 // If the given name refers to an interface type, retrieve the 3094 // corresponding declaration. 3095 if (Receiver) { 3096 QualType T = GetTypeFromParser(Receiver, 0); 3097 if (!T.isNull()) 3098 if (const ObjCObjectType *Interface = T->getAs<ObjCObjectType>()) 3099 CDecl = Interface->getInterface(); 3100 } 3101 3102 // Add all of the factory methods in this Objective-C class, its protocols, 3103 // superclasses, categories, implementation, etc. 3104 ResultBuilder Results(*this); 3105 Results.EnterNewScope(); 3106 3107 if (CDecl) 3108 AddObjCMethods(CDecl, false, MK_Any, SelIdents, NumSelIdents, CurContext, 3109 Results); 3110 else { 3111 // We're messaging "id" as a type; provide all class/factory methods. 3112 3113 // If we have an external source, load the entire class method 3114 // pool from the PCH file. 3115 if (ExternalSource) { 3116 for (uint32_t I = 0, N = ExternalSource->GetNumKnownSelectors(); I != N; 3117 ++I) { 3118 Selector Sel = ExternalSource->GetSelector(I); 3119 if (Sel.isNull() || FactoryMethodPool.count(Sel) || 3120 InstanceMethodPool.count(Sel)) 3121 continue; 3122 3123 ReadMethodPool(Sel, /*isInstance=*/false); 3124 } 3125 } 3126 3127 for (llvm::DenseMap<Selector, ObjCMethodList>::iterator 3128 M = FactoryMethodPool.begin(), 3129 MEnd = FactoryMethodPool.end(); 3130 M != MEnd; 3131 ++M) { 3132 for (ObjCMethodList *MethList = &M->second; MethList && MethList->Method; 3133 MethList = MethList->Next) { 3134 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents, 3135 NumSelIdents)) 3136 continue; 3137 3138 Result R(MethList->Method, 0); 3139 R.StartParameter = NumSelIdents; 3140 R.AllParametersAreInformative = false; 3141 Results.MaybeAddResult(R, CurContext); 3142 } 3143 } 3144 } 3145 3146 Results.ExitScope(); 3147 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size()); 3148 } 3149 3150 void Sema::CodeCompleteObjCInstanceMessage(Scope *S, ExprTy *Receiver, 3151 IdentifierInfo **SelIdents, 3152 unsigned NumSelIdents) { 3153 typedef CodeCompleteConsumer::Result Result; 3154 3155 Expr *RecExpr = static_cast<Expr *>(Receiver); 3156 3157 // If necessary, apply function/array conversion to the receiver. 3158 // C99 6.7.5.3p[7,8]. 3159 DefaultFunctionArrayLvalueConversion(RecExpr); 3160 QualType ReceiverType = RecExpr->getType(); 3161 3162 // Build the set of methods we can see. 3163 ResultBuilder Results(*this); 3164 Results.EnterNewScope(); 3165 3166 // If we're messaging an expression with type "id" or "Class", check 3167 // whether we know something special about the receiver that allows 3168 // us to assume a more-specific receiver type. 3169 if (ReceiverType->isObjCIdType() || ReceiverType->isObjCClassType()) 3170 if (ObjCInterfaceDecl *IFace = GetAssumedMessageSendExprType(RecExpr)) 3171 ReceiverType = Context.getObjCObjectPointerType( 3172 Context.getObjCInterfaceType(IFace)); 3173 3174 // Handle messages to Class. This really isn't a message to an instance 3175 // method, so we treat it the same way we would treat a message send to a 3176 // class method. 3177 if (ReceiverType->isObjCClassType() || 3178 ReceiverType->isObjCQualifiedClassType()) { 3179 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) { 3180 if (ObjCInterfaceDecl *ClassDecl = CurMethod->getClassInterface()) 3181 AddObjCMethods(ClassDecl, false, MK_Any, SelIdents, NumSelIdents, 3182 CurContext, Results); 3183 } 3184 } 3185 // Handle messages to a qualified ID ("id<foo>"). 3186 else if (const ObjCObjectPointerType *QualID 3187 = ReceiverType->getAsObjCQualifiedIdType()) { 3188 // Search protocols for instance methods. 3189 for (ObjCObjectPointerType::qual_iterator I = QualID->qual_begin(), 3190 E = QualID->qual_end(); 3191 I != E; ++I) 3192 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext, 3193 Results); 3194 } 3195 // Handle messages to a pointer to interface type. 3196 else if (const ObjCObjectPointerType *IFacePtr 3197 = ReceiverType->getAsObjCInterfacePointerType()) { 3198 // Search the class, its superclasses, etc., for instance methods. 3199 AddObjCMethods(IFacePtr->getInterfaceDecl(), true, MK_Any, SelIdents, 3200 NumSelIdents, CurContext, Results); 3201 3202 // Search protocols for instance methods. 3203 for (ObjCObjectPointerType::qual_iterator I = IFacePtr->qual_begin(), 3204 E = IFacePtr->qual_end(); 3205 I != E; ++I) 3206 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext, 3207 Results); 3208 } 3209 // Handle messages to "id". 3210 else if (ReceiverType->isObjCIdType()) { 3211 // We're messaging "id", so provide all instance methods we know 3212 // about as code-completion results. 3213 3214 // If we have an external source, load the entire class method 3215 // pool from the PCH file. 3216 if (ExternalSource) { 3217 for (uint32_t I = 0, N = ExternalSource->GetNumKnownSelectors(); I != N; 3218 ++I) { 3219 Selector Sel = ExternalSource->GetSelector(I); 3220 if (Sel.isNull() || InstanceMethodPool.count(Sel) || 3221 FactoryMethodPool.count(Sel)) 3222 continue; 3223 3224 ReadMethodPool(Sel, /*isInstance=*/true); 3225 } 3226 } 3227 3228 for (llvm::DenseMap<Selector, ObjCMethodList>::iterator 3229 M = InstanceMethodPool.begin(), 3230 MEnd = InstanceMethodPool.end(); 3231 M != MEnd; 3232 ++M) { 3233 for (ObjCMethodList *MethList = &M->second; MethList && MethList->Method; 3234 MethList = MethList->Next) { 3235 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents, 3236 NumSelIdents)) 3237 continue; 3238 3239 Result R(MethList->Method, 0); 3240 R.StartParameter = NumSelIdents; 3241 R.AllParametersAreInformative = false; 3242 Results.MaybeAddResult(R, CurContext); 3243 } 3244 } 3245 } 3246 3247 Results.ExitScope(); 3248 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size()); 3249 } 3250 3251 /// \brief Add all of the protocol declarations that we find in the given 3252 /// (translation unit) context. 3253 static void AddProtocolResults(DeclContext *Ctx, DeclContext *CurContext, 3254 bool OnlyForwardDeclarations, 3255 ResultBuilder &Results) { 3256 typedef CodeCompleteConsumer::Result Result; 3257 3258 for (DeclContext::decl_iterator D = Ctx->decls_begin(), 3259 DEnd = Ctx->decls_end(); 3260 D != DEnd; ++D) { 3261 // Record any protocols we find. 3262 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*D)) 3263 if (!OnlyForwardDeclarations || Proto->isForwardDecl()) 3264 Results.AddResult(Result(Proto, 0), CurContext, 0, false); 3265 3266 // Record any forward-declared protocols we find. 3267 if (ObjCForwardProtocolDecl *Forward 3268 = dyn_cast<ObjCForwardProtocolDecl>(*D)) { 3269 for (ObjCForwardProtocolDecl::protocol_iterator 3270 P = Forward->protocol_begin(), 3271 PEnd = Forward->protocol_end(); 3272 P != PEnd; ++P) 3273 if (!OnlyForwardDeclarations || (*P)->isForwardDecl()) 3274 Results.AddResult(Result(*P, 0), CurContext, 0, false); 3275 } 3276 } 3277 } 3278 3279 void Sema::CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols, 3280 unsigned NumProtocols) { 3281 ResultBuilder Results(*this); 3282 Results.EnterNewScope(); 3283 3284 // Tell the result set to ignore all of the protocols we have 3285 // already seen. 3286 for (unsigned I = 0; I != NumProtocols; ++I) 3287 if (ObjCProtocolDecl *Protocol = LookupProtocol(Protocols[I].first, 3288 Protocols[I].second)) 3289 Results.Ignore(Protocol); 3290 3291 // Add all protocols. 3292 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, false, 3293 Results); 3294 3295 Results.ExitScope(); 3296 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size()); 3297 } 3298 3299 void Sema::CodeCompleteObjCProtocolDecl(Scope *) { 3300 ResultBuilder Results(*this); 3301 Results.EnterNewScope(); 3302 3303 // Add all protocols. 3304 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, true, 3305 Results); 3306 3307 Results.ExitScope(); 3308 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size()); 3309 } 3310 3311 /// \brief Add all of the Objective-C interface declarations that we find in 3312 /// the given (translation unit) context. 3313 static void AddInterfaceResults(DeclContext *Ctx, DeclContext *CurContext, 3314 bool OnlyForwardDeclarations, 3315 bool OnlyUnimplemented, 3316 ResultBuilder &Results) { 3317 typedef CodeCompleteConsumer::Result Result; 3318 3319 for (DeclContext::decl_iterator D = Ctx->decls_begin(), 3320 DEnd = Ctx->decls_end(); 3321 D != DEnd; ++D) { 3322 // Record any interfaces we find. 3323 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*D)) 3324 if ((!OnlyForwardDeclarations || Class->isForwardDecl()) && 3325 (!OnlyUnimplemented || !Class->getImplementation())) 3326 Results.AddResult(Result(Class, 0), CurContext, 0, false); 3327 3328 // Record any forward-declared interfaces we find. 3329 if (ObjCClassDecl *Forward = dyn_cast<ObjCClassDecl>(*D)) { 3330 for (ObjCClassDecl::iterator C = Forward->begin(), CEnd = Forward->end(); 3331 C != CEnd; ++C) 3332 if ((!OnlyForwardDeclarations || C->getInterface()->isForwardDecl()) && 3333 (!OnlyUnimplemented || !C->getInterface()->getImplementation())) 3334 Results.AddResult(Result(C->getInterface(), 0), CurContext, 3335 0, false); 3336 } 3337 } 3338 } 3339 3340 void Sema::CodeCompleteObjCInterfaceDecl(Scope *S) { 3341 ResultBuilder Results(*this); 3342 Results.EnterNewScope(); 3343 3344 // Add all classes. 3345 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, true, 3346 false, Results); 3347 3348 Results.ExitScope(); 3349 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size()); 3350 } 3351 3352 void Sema::CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName, 3353 SourceLocation ClassNameLoc) { 3354 ResultBuilder Results(*this); 3355 Results.EnterNewScope(); 3356 3357 // Make sure that we ignore the class we're currently defining. 3358 NamedDecl *CurClass 3359 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName); 3360 if (CurClass && isa<ObjCInterfaceDecl>(CurClass)) 3361 Results.Ignore(CurClass); 3362 3363 // Add all classes. 3364 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false, 3365 false, Results); 3366 3367 Results.ExitScope(); 3368 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size()); 3369 } 3370 3371 void Sema::CodeCompleteObjCImplementationDecl(Scope *S) { 3372 ResultBuilder Results(*this); 3373 Results.EnterNewScope(); 3374 3375 // Add all unimplemented classes. 3376 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false, 3377 true, Results); 3378 3379 Results.ExitScope(); 3380 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size()); 3381 } 3382 3383 void Sema::CodeCompleteObjCInterfaceCategory(Scope *S, 3384 IdentifierInfo *ClassName, 3385 SourceLocation ClassNameLoc) { 3386 typedef CodeCompleteConsumer::Result Result; 3387 3388 ResultBuilder Results(*this); 3389 3390 // Ignore any categories we find that have already been implemented by this 3391 // interface. 3392 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames; 3393 NamedDecl *CurClass 3394 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName); 3395 if (ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass)) 3396 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category; 3397 Category = Category->getNextClassCategory()) 3398 CategoryNames.insert(Category->getIdentifier()); 3399 3400 // Add all of the categories we know about. 3401 Results.EnterNewScope(); 3402 TranslationUnitDecl *TU = Context.getTranslationUnitDecl(); 3403 for (DeclContext::decl_iterator D = TU->decls_begin(), 3404 DEnd = TU->decls_end(); 3405 D != DEnd; ++D) 3406 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(*D)) 3407 if (CategoryNames.insert(Category->getIdentifier())) 3408 Results.AddResult(Result(Category, 0), CurContext, 0, false); 3409 Results.ExitScope(); 3410 3411 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size()); 3412 } 3413 3414 void Sema::CodeCompleteObjCImplementationCategory(Scope *S, 3415 IdentifierInfo *ClassName, 3416 SourceLocation ClassNameLoc) { 3417 typedef CodeCompleteConsumer::Result Result; 3418 3419 // Find the corresponding interface. If we couldn't find the interface, the 3420 // program itself is ill-formed. However, we'll try to be helpful still by 3421 // providing the list of all of the categories we know about. 3422 NamedDecl *CurClass 3423 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName); 3424 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass); 3425 if (!Class) 3426 return CodeCompleteObjCInterfaceCategory(S, ClassName, ClassNameLoc); 3427 3428 ResultBuilder Results(*this); 3429 3430 // Add all of the categories that have have corresponding interface 3431 // declarations in this class and any of its superclasses, except for 3432 // already-implemented categories in the class itself. 3433 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames; 3434 Results.EnterNewScope(); 3435 bool IgnoreImplemented = true; 3436 while (Class) { 3437 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category; 3438 Category = Category->getNextClassCategory()) 3439 if ((!IgnoreImplemented || !Category->getImplementation()) && 3440 CategoryNames.insert(Category->getIdentifier())) 3441 Results.AddResult(Result(Category, 0), CurContext, 0, false); 3442 3443 Class = Class->getSuperClass(); 3444 IgnoreImplemented = false; 3445 } 3446 Results.ExitScope(); 3447 3448 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size()); 3449 } 3450 3451 void Sema::CodeCompleteObjCPropertyDefinition(Scope *S, DeclPtrTy ObjCImpDecl) { 3452 typedef CodeCompleteConsumer::Result Result; 3453 ResultBuilder Results(*this); 3454 3455 // Figure out where this @synthesize lives. 3456 ObjCContainerDecl *Container 3457 = dyn_cast_or_null<ObjCContainerDecl>(ObjCImpDecl.getAs<Decl>()); 3458 if (!Container || 3459 (!isa<ObjCImplementationDecl>(Container) && 3460 !isa<ObjCCategoryImplDecl>(Container))) 3461 return; 3462 3463 // Ignore any properties that have already been implemented. 3464 for (DeclContext::decl_iterator D = Container->decls_begin(), 3465 DEnd = Container->decls_end(); 3466 D != DEnd; ++D) 3467 if (ObjCPropertyImplDecl *PropertyImpl = dyn_cast<ObjCPropertyImplDecl>(*D)) 3468 Results.Ignore(PropertyImpl->getPropertyDecl()); 3469 3470 // Add any properties that we find. 3471 Results.EnterNewScope(); 3472 if (ObjCImplementationDecl *ClassImpl 3473 = dyn_cast<ObjCImplementationDecl>(Container)) 3474 AddObjCProperties(ClassImpl->getClassInterface(), false, CurContext, 3475 Results); 3476 else 3477 AddObjCProperties(cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl(), 3478 false, CurContext, Results); 3479 Results.ExitScope(); 3480 3481 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size()); 3482 } 3483 3484 void Sema::CodeCompleteObjCPropertySynthesizeIvar(Scope *S, 3485 IdentifierInfo *PropertyName, 3486 DeclPtrTy ObjCImpDecl) { 3487 typedef CodeCompleteConsumer::Result Result; 3488 ResultBuilder Results(*this); 3489 3490 // Figure out where this @synthesize lives. 3491 ObjCContainerDecl *Container 3492 = dyn_cast_or_null<ObjCContainerDecl>(ObjCImpDecl.getAs<Decl>()); 3493 if (!Container || 3494 (!isa<ObjCImplementationDecl>(Container) && 3495 !isa<ObjCCategoryImplDecl>(Container))) 3496 return; 3497 3498 // Figure out which interface we're looking into. 3499 ObjCInterfaceDecl *Class = 0; 3500 if (ObjCImplementationDecl *ClassImpl 3501 = dyn_cast<ObjCImplementationDecl>(Container)) 3502 Class = ClassImpl->getClassInterface(); 3503 else 3504 Class = cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl() 3505 ->getClassInterface(); 3506 3507 // Add all of the instance variables in this class and its superclasses. 3508 Results.EnterNewScope(); 3509 for(; Class; Class = Class->getSuperClass()) { 3510 // FIXME: We could screen the type of each ivar for compatibility with 3511 // the property, but is that being too paternal? 3512 for (ObjCInterfaceDecl::ivar_iterator IVar = Class->ivar_begin(), 3513 IVarEnd = Class->ivar_end(); 3514 IVar != IVarEnd; ++IVar) 3515 Results.AddResult(Result(*IVar, 0), CurContext, 0, false); 3516 } 3517 Results.ExitScope(); 3518 3519 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size()); 3520 } 3521 3522 typedef llvm::DenseMap<Selector, ObjCMethodDecl *> KnownMethodsMap; 3523 3524 /// \brief Find all of the methods that reside in the given container 3525 /// (and its superclasses, protocols, etc.) that meet the given 3526 /// criteria. Insert those methods into the map of known methods, 3527 /// indexed by selector so they can be easily found. 3528 static void FindImplementableMethods(ASTContext &Context, 3529 ObjCContainerDecl *Container, 3530 bool WantInstanceMethods, 3531 QualType ReturnType, 3532 bool IsInImplementation, 3533 KnownMethodsMap &KnownMethods) { 3534 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)) { 3535 // Recurse into protocols. 3536 const ObjCList<ObjCProtocolDecl> &Protocols 3537 = IFace->getReferencedProtocols(); 3538 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(), 3539 E = Protocols.end(); 3540 I != E; ++I) 3541 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType, 3542 IsInImplementation, KnownMethods); 3543 3544 // If we're not in the implementation of a class, also visit the 3545 // superclass. 3546 if (!IsInImplementation && IFace->getSuperClass()) 3547 FindImplementableMethods(Context, IFace->getSuperClass(), 3548 WantInstanceMethods, ReturnType, 3549 IsInImplementation, KnownMethods); 3550 3551 // Add methods from any class extensions (but not from categories; 3552 // those should go into category implementations). 3553 for (ObjCCategoryDecl *Cat = IFace->getCategoryList(); Cat; 3554 Cat = Cat->getNextClassCategory()) { 3555 if (!Cat->IsClassExtension()) 3556 continue; 3557 3558 FindImplementableMethods(Context, Cat, WantInstanceMethods, ReturnType, 3559 IsInImplementation, KnownMethods); 3560 } 3561 } 3562 3563 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) { 3564 // Recurse into protocols. 3565 const ObjCList<ObjCProtocolDecl> &Protocols 3566 = Category->getReferencedProtocols(); 3567 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(), 3568 E = Protocols.end(); 3569 I != E; ++I) 3570 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType, 3571 IsInImplementation, KnownMethods); 3572 } 3573 3574 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) { 3575 // Recurse into protocols. 3576 const ObjCList<ObjCProtocolDecl> &Protocols 3577 = Protocol->getReferencedProtocols(); 3578 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(), 3579 E = Protocols.end(); 3580 I != E; ++I) 3581 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType, 3582 IsInImplementation, KnownMethods); 3583 } 3584 3585 // Add methods in this container. This operation occurs last because 3586 // we want the methods from this container to override any methods 3587 // we've previously seen with the same selector. 3588 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(), 3589 MEnd = Container->meth_end(); 3590 M != MEnd; ++M) { 3591 if ((*M)->isInstanceMethod() == WantInstanceMethods) { 3592 if (!ReturnType.isNull() && 3593 !Context.hasSameUnqualifiedType(ReturnType, (*M)->getResultType())) 3594 continue; 3595 3596 KnownMethods[(*M)->getSelector()] = *M; 3597 } 3598 } 3599 } 3600 3601 void Sema::CodeCompleteObjCMethodDecl(Scope *S, 3602 bool IsInstanceMethod, 3603 TypeTy *ReturnTy, 3604 DeclPtrTy IDecl) { 3605 // Determine the return type of the method we're declaring, if 3606 // provided. 3607 QualType ReturnType = GetTypeFromParser(ReturnTy); 3608 3609 // Determine where we should start searching for methods, and where we 3610 ObjCContainerDecl *SearchDecl = 0, *CurrentDecl = 0; 3611 bool IsInImplementation = false; 3612 if (Decl *D = IDecl.getAs<Decl>()) { 3613 if (ObjCImplementationDecl *Impl = dyn_cast<ObjCImplementationDecl>(D)) { 3614 SearchDecl = Impl->getClassInterface(); 3615 CurrentDecl = Impl; 3616 IsInImplementation = true; 3617 } else if (ObjCCategoryImplDecl *CatImpl 3618 = dyn_cast<ObjCCategoryImplDecl>(D)) { 3619 SearchDecl = CatImpl->getCategoryDecl(); 3620 CurrentDecl = CatImpl; 3621 IsInImplementation = true; 3622 } else { 3623 SearchDecl = dyn_cast<ObjCContainerDecl>(D); 3624 CurrentDecl = SearchDecl; 3625 } 3626 } 3627 3628 if (!SearchDecl && S) { 3629 if (DeclContext *DC = static_cast<DeclContext *>(S->getEntity())) { 3630 SearchDecl = dyn_cast<ObjCContainerDecl>(DC); 3631 CurrentDecl = SearchDecl; 3632 } 3633 } 3634 3635 if (!SearchDecl || !CurrentDecl) { 3636 HandleCodeCompleteResults(this, CodeCompleter, 0, 0); 3637 return; 3638 } 3639 3640 // Find all of the methods that we could declare/implement here. 3641 KnownMethodsMap KnownMethods; 3642 FindImplementableMethods(Context, SearchDecl, IsInstanceMethod, 3643 ReturnType, IsInImplementation, KnownMethods); 3644 3645 // Erase any methods that have already been declared or 3646 // implemented here. 3647 for (ObjCContainerDecl::method_iterator M = CurrentDecl->meth_begin(), 3648 MEnd = CurrentDecl->meth_end(); 3649 M != MEnd; ++M) { 3650 if ((*M)->isInstanceMethod() != IsInstanceMethod) 3651 continue; 3652 3653 KnownMethodsMap::iterator Pos = KnownMethods.find((*M)->getSelector()); 3654 if (Pos != KnownMethods.end()) 3655 KnownMethods.erase(Pos); 3656 } 3657 3658 // Add declarations or definitions for each of the known methods. 3659 typedef CodeCompleteConsumer::Result Result; 3660 ResultBuilder Results(*this); 3661 Results.EnterNewScope(); 3662 PrintingPolicy Policy(Context.PrintingPolicy); 3663 Policy.AnonymousTagLocations = false; 3664 for (KnownMethodsMap::iterator M = KnownMethods.begin(), 3665 MEnd = KnownMethods.end(); 3666 M != MEnd; ++M) { 3667 ObjCMethodDecl *Method = M->second; 3668 CodeCompletionString *Pattern = new CodeCompletionString; 3669 3670 // If the result type was not already provided, add it to the 3671 // pattern as (type). 3672 if (ReturnType.isNull()) { 3673 std::string TypeStr; 3674 Method->getResultType().getAsStringInternal(TypeStr, Policy); 3675 Pattern->AddChunk(CodeCompletionString::CK_LeftParen); 3676 Pattern->AddTextChunk(TypeStr); 3677 Pattern->AddChunk(CodeCompletionString::CK_RightParen); 3678 } 3679 3680 Selector Sel = Method->getSelector(); 3681 3682 // Add the first part of the selector to the pattern. 3683 Pattern->AddTypedTextChunk(Sel.getIdentifierInfoForSlot(0)->getName()); 3684 3685 // Add parameters to the pattern. 3686 unsigned I = 0; 3687 for (ObjCMethodDecl::param_iterator P = Method->param_begin(), 3688 PEnd = Method->param_end(); 3689 P != PEnd; (void)++P, ++I) { 3690 // Add the part of the selector name. 3691 if (I == 0) 3692 Pattern->AddChunk(CodeCompletionString::CK_Colon); 3693 else if (I < Sel.getNumArgs()) { 3694 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace); 3695 Pattern->AddTextChunk(Sel.getIdentifierInfoForSlot(1)->getName()); 3696 Pattern->AddChunk(CodeCompletionString::CK_Colon); 3697 } else 3698 break; 3699 3700 // Add the parameter type. 3701 std::string TypeStr; 3702 (*P)->getOriginalType().getAsStringInternal(TypeStr, Policy); 3703 Pattern->AddChunk(CodeCompletionString::CK_LeftParen); 3704 Pattern->AddTextChunk(TypeStr); 3705 Pattern->AddChunk(CodeCompletionString::CK_RightParen); 3706 3707 if (IdentifierInfo *Id = (*P)->getIdentifier()) 3708 Pattern->AddTextChunk(Id->getName()); 3709 } 3710 3711 if (Method->isVariadic()) { 3712 if (Method->param_size() > 0) 3713 Pattern->AddChunk(CodeCompletionString::CK_Comma); 3714 Pattern->AddTextChunk("..."); 3715 } 3716 3717 if (IsInImplementation) { 3718 // We will be defining the method here, so add a compound statement. 3719 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace); 3720 Pattern->AddChunk(CodeCompletionString::CK_LeftBrace); 3721 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace); 3722 if (!Method->getResultType()->isVoidType()) { 3723 // If the result type is not void, add a return clause. 3724 Pattern->AddTextChunk("return"); 3725 Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace); 3726 Pattern->AddPlaceholderChunk("expression"); 3727 Pattern->AddChunk(CodeCompletionString::CK_SemiColon); 3728 } else 3729 Pattern->AddPlaceholderChunk("statements"); 3730 3731 Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace); 3732 Pattern->AddChunk(CodeCompletionString::CK_RightBrace); 3733 } 3734 3735 Results.AddResult(Result(Pattern)); 3736 } 3737 3738 Results.ExitScope(); 3739 3740 HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size()); 3741 } 3742