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