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