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