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