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