SemaCodeComplete.cpp revision 830072c2de881aadfe0f6efd3baccc9129a77e37
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/SemaInternal.h" 14#include "clang/Sema/Lookup.h" 15#include "clang/Sema/Overload.h" 16#include "clang/Sema/CodeCompleteConsumer.h" 17#include "clang/Sema/ExternalSemaSource.h" 18#include "clang/Sema/Scope.h" 19#include "clang/Sema/ScopeInfo.h" 20#include "clang/AST/DeclObjC.h" 21#include "clang/AST/ExprCXX.h" 22#include "clang/AST/ExprObjC.h" 23#include "clang/Lex/MacroInfo.h" 24#include "clang/Lex/Preprocessor.h" 25#include "llvm/ADT/DenseSet.h" 26#include "llvm/ADT/SmallPtrSet.h" 27#include "llvm/ADT/StringExtras.h" 28#include "llvm/ADT/StringSwitch.h" 29#include "llvm/ADT/Twine.h" 30#include <list> 31#include <map> 32#include <vector> 33 34using namespace clang; 35using namespace sema; 36 37namespace { 38 /// \brief A container of code-completion results. 39 class ResultBuilder { 40 public: 41 /// \brief The type of a name-lookup filter, which can be provided to the 42 /// name-lookup routines to specify which declarations should be included in 43 /// the result set (when it returns true) and which declarations should be 44 /// filtered out (returns false). 45 typedef bool (ResultBuilder::*LookupFilter)(NamedDecl *) const; 46 47 typedef CodeCompletionResult Result; 48 49 private: 50 /// \brief The actual results we have found. 51 std::vector<Result> Results; 52 53 /// \brief A record of all of the declarations we have found and placed 54 /// into the result set, used to ensure that no declaration ever gets into 55 /// the result set twice. 56 llvm::SmallPtrSet<Decl*, 16> AllDeclsFound; 57 58 typedef std::pair<NamedDecl *, unsigned> DeclIndexPair; 59 60 /// \brief An entry in the shadow map, which is optimized to store 61 /// a single (declaration, index) mapping (the common case) but 62 /// can also store a list of (declaration, index) mappings. 63 class ShadowMapEntry { 64 typedef llvm::SmallVector<DeclIndexPair, 4> DeclIndexPairVector; 65 66 /// \brief Contains either the solitary NamedDecl * or a vector 67 /// of (declaration, index) pairs. 68 llvm::PointerUnion<NamedDecl *, DeclIndexPairVector*> DeclOrVector; 69 70 /// \brief When the entry contains a single declaration, this is 71 /// the index associated with that entry. 72 unsigned SingleDeclIndex; 73 74 public: 75 ShadowMapEntry() : DeclOrVector(), SingleDeclIndex(0) { } 76 77 void Add(NamedDecl *ND, unsigned Index) { 78 if (DeclOrVector.isNull()) { 79 // 0 - > 1 elements: just set the single element information. 80 DeclOrVector = ND; 81 SingleDeclIndex = Index; 82 return; 83 } 84 85 if (NamedDecl *PrevND = DeclOrVector.dyn_cast<NamedDecl *>()) { 86 // 1 -> 2 elements: create the vector of results and push in the 87 // existing declaration. 88 DeclIndexPairVector *Vec = new DeclIndexPairVector; 89 Vec->push_back(DeclIndexPair(PrevND, SingleDeclIndex)); 90 DeclOrVector = Vec; 91 } 92 93 // Add the new element to the end of the vector. 94 DeclOrVector.get<DeclIndexPairVector*>()->push_back( 95 DeclIndexPair(ND, Index)); 96 } 97 98 void Destroy() { 99 if (DeclIndexPairVector *Vec 100 = DeclOrVector.dyn_cast<DeclIndexPairVector *>()) { 101 delete Vec; 102 DeclOrVector = ((NamedDecl *)0); 103 } 104 } 105 106 // Iteration. 107 class iterator; 108 iterator begin() const; 109 iterator end() const; 110 }; 111 112 /// \brief A mapping from declaration names to the declarations that have 113 /// this name within a particular scope and their index within the list of 114 /// results. 115 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap; 116 117 /// \brief The semantic analysis object for which results are being 118 /// produced. 119 Sema &SemaRef; 120 121 /// \brief The allocator used to allocate new code-completion strings. 122 CodeCompletionAllocator &Allocator; 123 124 /// \brief If non-NULL, a filter function used to remove any code-completion 125 /// results that are not desirable. 126 LookupFilter Filter; 127 128 /// \brief Whether we should allow declarations as 129 /// nested-name-specifiers that would otherwise be filtered out. 130 bool AllowNestedNameSpecifiers; 131 132 /// \brief If set, the type that we would prefer our resulting value 133 /// declarations to have. 134 /// 135 /// Closely matching the preferred type gives a boost to a result's 136 /// priority. 137 CanQualType PreferredType; 138 139 /// \brief A list of shadow maps, which is used to model name hiding at 140 /// different levels of, e.g., the inheritance hierarchy. 141 std::list<ShadowMap> ShadowMaps; 142 143 /// \brief If we're potentially referring to a C++ member function, the set 144 /// of qualifiers applied to the object type. 145 Qualifiers ObjectTypeQualifiers; 146 147 /// \brief Whether the \p ObjectTypeQualifiers field is active. 148 bool HasObjectTypeQualifiers; 149 150 /// \brief The selector that we prefer. 151 Selector PreferredSelector; 152 153 /// \brief The completion context in which we are gathering results. 154 CodeCompletionContext CompletionContext; 155 156 /// \brief If we are in an instance method definition, the @implementation 157 /// object. 158 ObjCImplementationDecl *ObjCImplementation; 159 160 void AdjustResultPriorityForDecl(Result &R); 161 162 void MaybeAddConstructorResults(Result R); 163 164 public: 165 explicit ResultBuilder(Sema &SemaRef, CodeCompletionAllocator &Allocator, 166 const CodeCompletionContext &CompletionContext, 167 LookupFilter Filter = 0) 168 : SemaRef(SemaRef), Allocator(Allocator), Filter(Filter), 169 AllowNestedNameSpecifiers(false), HasObjectTypeQualifiers(false), 170 CompletionContext(CompletionContext), 171 ObjCImplementation(0) 172 { 173 // If this is an Objective-C instance method definition, dig out the 174 // corresponding implementation. 175 switch (CompletionContext.getKind()) { 176 case CodeCompletionContext::CCC_Expression: 177 case CodeCompletionContext::CCC_ObjCMessageReceiver: 178 case CodeCompletionContext::CCC_ParenthesizedExpression: 179 case CodeCompletionContext::CCC_Statement: 180 case CodeCompletionContext::CCC_Recovery: 181 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) 182 if (Method->isInstanceMethod()) 183 if (ObjCInterfaceDecl *Interface = Method->getClassInterface()) 184 ObjCImplementation = Interface->getImplementation(); 185 break; 186 187 default: 188 break; 189 } 190 } 191 192 /// \brief Whether we should include code patterns in the completion 193 /// results. 194 bool includeCodePatterns() const { 195 return SemaRef.CodeCompleter && 196 SemaRef.CodeCompleter->includeCodePatterns(); 197 } 198 199 /// \brief Set the filter used for code-completion results. 200 void setFilter(LookupFilter Filter) { 201 this->Filter = Filter; 202 } 203 204 Result *data() { return Results.empty()? 0 : &Results.front(); } 205 unsigned size() const { return Results.size(); } 206 bool empty() const { return Results.empty(); } 207 208 /// \brief Specify the preferred type. 209 void setPreferredType(QualType T) { 210 PreferredType = SemaRef.Context.getCanonicalType(T); 211 } 212 213 /// \brief Set the cv-qualifiers on the object type, for us in filtering 214 /// calls to member functions. 215 /// 216 /// When there are qualifiers in this set, they will be used to filter 217 /// out member functions that aren't available (because there will be a 218 /// cv-qualifier mismatch) or prefer functions with an exact qualifier 219 /// match. 220 void setObjectTypeQualifiers(Qualifiers Quals) { 221 ObjectTypeQualifiers = Quals; 222 HasObjectTypeQualifiers = true; 223 } 224 225 /// \brief Set the preferred selector. 226 /// 227 /// When an Objective-C method declaration result is added, and that 228 /// method's selector matches this preferred selector, we give that method 229 /// a slight priority boost. 230 void setPreferredSelector(Selector Sel) { 231 PreferredSelector = Sel; 232 } 233 234 /// \brief Retrieve the code-completion context for which results are 235 /// being collected. 236 const CodeCompletionContext &getCompletionContext() const { 237 return CompletionContext; 238 } 239 240 /// \brief Specify whether nested-name-specifiers are allowed. 241 void allowNestedNameSpecifiers(bool Allow = true) { 242 AllowNestedNameSpecifiers = Allow; 243 } 244 245 /// \brief Return the semantic analysis object for which we are collecting 246 /// code completion results. 247 Sema &getSema() const { return SemaRef; } 248 249 /// \brief Retrieve the allocator used to allocate code completion strings. 250 CodeCompletionAllocator &getAllocator() const { return Allocator; } 251 252 /// \brief Determine whether the given declaration is at all interesting 253 /// as a code-completion result. 254 /// 255 /// \param ND the declaration that we are inspecting. 256 /// 257 /// \param AsNestedNameSpecifier will be set true if this declaration is 258 /// only interesting when it is a nested-name-specifier. 259 bool isInterestingDecl(NamedDecl *ND, bool &AsNestedNameSpecifier) const; 260 261 /// \brief Check whether the result is hidden by the Hiding declaration. 262 /// 263 /// \returns true if the result is hidden and cannot be found, false if 264 /// the hidden result could still be found. When false, \p R may be 265 /// modified to describe how the result can be found (e.g., via extra 266 /// qualification). 267 bool CheckHiddenResult(Result &R, DeclContext *CurContext, 268 NamedDecl *Hiding); 269 270 /// \brief Add a new result to this result set (if it isn't already in one 271 /// of the shadow maps), or replace an existing result (for, e.g., a 272 /// redeclaration). 273 /// 274 /// \param CurContext the result to add (if it is unique). 275 /// 276 /// \param R the context in which this result will be named. 277 void MaybeAddResult(Result R, DeclContext *CurContext = 0); 278 279 /// \brief Add a new result to this result set, where we already know 280 /// the hiding declation (if any). 281 /// 282 /// \param R the result to add (if it is unique). 283 /// 284 /// \param CurContext the context in which this result will be named. 285 /// 286 /// \param Hiding the declaration that hides the result. 287 /// 288 /// \param InBaseClass whether the result was found in a base 289 /// class of the searched context. 290 void AddResult(Result R, DeclContext *CurContext, NamedDecl *Hiding, 291 bool InBaseClass); 292 293 /// \brief Add a new non-declaration result to this result set. 294 void AddResult(Result R); 295 296 /// \brief Enter into a new scope. 297 void EnterNewScope(); 298 299 /// \brief Exit from the current scope. 300 void ExitScope(); 301 302 /// \brief Ignore this declaration, if it is seen again. 303 void Ignore(Decl *D) { AllDeclsFound.insert(D->getCanonicalDecl()); } 304 305 /// \name Name lookup predicates 306 /// 307 /// These predicates can be passed to the name lookup functions to filter the 308 /// results of name lookup. All of the predicates have the same type, so that 309 /// 310 //@{ 311 bool IsOrdinaryName(NamedDecl *ND) const; 312 bool IsOrdinaryNonTypeName(NamedDecl *ND) const; 313 bool IsIntegralConstantValue(NamedDecl *ND) const; 314 bool IsOrdinaryNonValueName(NamedDecl *ND) const; 315 bool IsNestedNameSpecifier(NamedDecl *ND) const; 316 bool IsEnum(NamedDecl *ND) const; 317 bool IsClassOrStruct(NamedDecl *ND) const; 318 bool IsUnion(NamedDecl *ND) const; 319 bool IsNamespace(NamedDecl *ND) const; 320 bool IsNamespaceOrAlias(NamedDecl *ND) const; 321 bool IsType(NamedDecl *ND) const; 322 bool IsMember(NamedDecl *ND) const; 323 bool IsObjCIvar(NamedDecl *ND) const; 324 bool IsObjCMessageReceiver(NamedDecl *ND) const; 325 bool IsObjCCollection(NamedDecl *ND) const; 326 bool IsImpossibleToSatisfy(NamedDecl *ND) const; 327 //@} 328 }; 329} 330 331class ResultBuilder::ShadowMapEntry::iterator { 332 llvm::PointerUnion<NamedDecl*, const DeclIndexPair*> DeclOrIterator; 333 unsigned SingleDeclIndex; 334 335public: 336 typedef DeclIndexPair value_type; 337 typedef value_type reference; 338 typedef std::ptrdiff_t difference_type; 339 typedef std::input_iterator_tag iterator_category; 340 341 class pointer { 342 DeclIndexPair Value; 343 344 public: 345 pointer(const DeclIndexPair &Value) : Value(Value) { } 346 347 const DeclIndexPair *operator->() const { 348 return &Value; 349 } 350 }; 351 352 iterator() : DeclOrIterator((NamedDecl *)0), SingleDeclIndex(0) { } 353 354 iterator(NamedDecl *SingleDecl, unsigned Index) 355 : DeclOrIterator(SingleDecl), SingleDeclIndex(Index) { } 356 357 iterator(const DeclIndexPair *Iterator) 358 : DeclOrIterator(Iterator), SingleDeclIndex(0) { } 359 360 iterator &operator++() { 361 if (DeclOrIterator.is<NamedDecl *>()) { 362 DeclOrIterator = (NamedDecl *)0; 363 SingleDeclIndex = 0; 364 return *this; 365 } 366 367 const DeclIndexPair *I = DeclOrIterator.get<const DeclIndexPair*>(); 368 ++I; 369 DeclOrIterator = I; 370 return *this; 371 } 372 373 /*iterator operator++(int) { 374 iterator tmp(*this); 375 ++(*this); 376 return tmp; 377 }*/ 378 379 reference operator*() const { 380 if (NamedDecl *ND = DeclOrIterator.dyn_cast<NamedDecl *>()) 381 return reference(ND, SingleDeclIndex); 382 383 return *DeclOrIterator.get<const DeclIndexPair*>(); 384 } 385 386 pointer operator->() const { 387 return pointer(**this); 388 } 389 390 friend bool operator==(const iterator &X, const iterator &Y) { 391 return X.DeclOrIterator.getOpaqueValue() 392 == Y.DeclOrIterator.getOpaqueValue() && 393 X.SingleDeclIndex == Y.SingleDeclIndex; 394 } 395 396 friend bool operator!=(const iterator &X, const iterator &Y) { 397 return !(X == Y); 398 } 399}; 400 401ResultBuilder::ShadowMapEntry::iterator 402ResultBuilder::ShadowMapEntry::begin() const { 403 if (DeclOrVector.isNull()) 404 return iterator(); 405 406 if (NamedDecl *ND = DeclOrVector.dyn_cast<NamedDecl *>()) 407 return iterator(ND, SingleDeclIndex); 408 409 return iterator(DeclOrVector.get<DeclIndexPairVector *>()->begin()); 410} 411 412ResultBuilder::ShadowMapEntry::iterator 413ResultBuilder::ShadowMapEntry::end() const { 414 if (DeclOrVector.is<NamedDecl *>() || DeclOrVector.isNull()) 415 return iterator(); 416 417 return iterator(DeclOrVector.get<DeclIndexPairVector *>()->end()); 418} 419 420/// \brief Compute the qualification required to get from the current context 421/// (\p CurContext) to the target context (\p TargetContext). 422/// 423/// \param Context the AST context in which the qualification will be used. 424/// 425/// \param CurContext the context where an entity is being named, which is 426/// typically based on the current scope. 427/// 428/// \param TargetContext the context in which the named entity actually 429/// resides. 430/// 431/// \returns a nested name specifier that refers into the target context, or 432/// NULL if no qualification is needed. 433static NestedNameSpecifier * 434getRequiredQualification(ASTContext &Context, 435 DeclContext *CurContext, 436 DeclContext *TargetContext) { 437 llvm::SmallVector<DeclContext *, 4> TargetParents; 438 439 for (DeclContext *CommonAncestor = TargetContext; 440 CommonAncestor && !CommonAncestor->Encloses(CurContext); 441 CommonAncestor = CommonAncestor->getLookupParent()) { 442 if (CommonAncestor->isTransparentContext() || 443 CommonAncestor->isFunctionOrMethod()) 444 continue; 445 446 TargetParents.push_back(CommonAncestor); 447 } 448 449 NestedNameSpecifier *Result = 0; 450 while (!TargetParents.empty()) { 451 DeclContext *Parent = TargetParents.back(); 452 TargetParents.pop_back(); 453 454 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Parent)) { 455 if (!Namespace->getIdentifier()) 456 continue; 457 458 Result = NestedNameSpecifier::Create(Context, Result, Namespace); 459 } 460 else if (TagDecl *TD = dyn_cast<TagDecl>(Parent)) 461 Result = NestedNameSpecifier::Create(Context, Result, 462 false, 463 Context.getTypeDeclType(TD).getTypePtr()); 464 } 465 return Result; 466} 467 468bool ResultBuilder::isInterestingDecl(NamedDecl *ND, 469 bool &AsNestedNameSpecifier) const { 470 AsNestedNameSpecifier = false; 471 472 ND = ND->getUnderlyingDecl(); 473 unsigned IDNS = ND->getIdentifierNamespace(); 474 475 // Skip unnamed entities. 476 if (!ND->getDeclName()) 477 return false; 478 479 // Friend declarations and declarations introduced due to friends are never 480 // added as results. 481 if (IDNS & (Decl::IDNS_OrdinaryFriend | Decl::IDNS_TagFriend)) 482 return false; 483 484 // Class template (partial) specializations are never added as results. 485 if (isa<ClassTemplateSpecializationDecl>(ND) || 486 isa<ClassTemplatePartialSpecializationDecl>(ND)) 487 return false; 488 489 // Using declarations themselves are never added as results. 490 if (isa<UsingDecl>(ND)) 491 return false; 492 493 // Some declarations have reserved names that we don't want to ever show. 494 if (const IdentifierInfo *Id = ND->getIdentifier()) { 495 // __va_list_tag is a freak of nature. Find it and skip it. 496 if (Id->isStr("__va_list_tag") || Id->isStr("__builtin_va_list")) 497 return false; 498 499 // Filter out names reserved for the implementation (C99 7.1.3, 500 // C++ [lib.global.names]) if they come from a system header. 501 // 502 // FIXME: Add predicate for this. 503 if (Id->getLength() >= 2) { 504 const char *Name = Id->getNameStart(); 505 if (Name[0] == '_' && 506 (Name[1] == '_' || (Name[1] >= 'A' && Name[1] <= 'Z')) && 507 (ND->getLocation().isInvalid() || 508 SemaRef.SourceMgr.isInSystemHeader( 509 SemaRef.SourceMgr.getSpellingLoc(ND->getLocation())))) 510 return false; 511 } 512 } 513 514 // Skip out-of-line declarations and definitions. 515 // NOTE: Unless it's an Objective-C property, method, or ivar, where 516 // the contexts can be messy. 517 if (!ND->getDeclContext()->Equals(ND->getLexicalDeclContext()) && 518 !(isa<ObjCPropertyDecl>(ND) || isa<ObjCIvarDecl>(ND) || 519 isa<ObjCMethodDecl>(ND))) 520 return false; 521 522 if (Filter == &ResultBuilder::IsNestedNameSpecifier || 523 ((isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) && 524 Filter != &ResultBuilder::IsNamespace && 525 Filter != &ResultBuilder::IsNamespaceOrAlias && 526 Filter != 0)) 527 AsNestedNameSpecifier = true; 528 529 // Filter out any unwanted results. 530 if (Filter && !(this->*Filter)(ND)) { 531 // Check whether it is interesting as a nested-name-specifier. 532 if (AllowNestedNameSpecifiers && SemaRef.getLangOptions().CPlusPlus && 533 IsNestedNameSpecifier(ND) && 534 (Filter != &ResultBuilder::IsMember || 535 (isa<CXXRecordDecl>(ND) && 536 cast<CXXRecordDecl>(ND)->isInjectedClassName()))) { 537 AsNestedNameSpecifier = true; 538 return true; 539 } 540 541 return false; 542 } 543 // ... then it must be interesting! 544 return true; 545} 546 547bool ResultBuilder::CheckHiddenResult(Result &R, DeclContext *CurContext, 548 NamedDecl *Hiding) { 549 // In C, there is no way to refer to a hidden name. 550 // FIXME: This isn't true; we can find a tag name hidden by an ordinary 551 // name if we introduce the tag type. 552 if (!SemaRef.getLangOptions().CPlusPlus) 553 return true; 554 555 DeclContext *HiddenCtx = R.Declaration->getDeclContext()->getRedeclContext(); 556 557 // There is no way to qualify a name declared in a function or method. 558 if (HiddenCtx->isFunctionOrMethod()) 559 return true; 560 561 if (HiddenCtx == Hiding->getDeclContext()->getRedeclContext()) 562 return true; 563 564 // We can refer to the result with the appropriate qualification. Do it. 565 R.Hidden = true; 566 R.QualifierIsInformative = false; 567 568 if (!R.Qualifier) 569 R.Qualifier = getRequiredQualification(SemaRef.Context, 570 CurContext, 571 R.Declaration->getDeclContext()); 572 return false; 573} 574 575/// \brief A simplified classification of types used to determine whether two 576/// types are "similar enough" when adjusting priorities. 577SimplifiedTypeClass clang::getSimplifiedTypeClass(CanQualType T) { 578 switch (T->getTypeClass()) { 579 case Type::Builtin: 580 switch (cast<BuiltinType>(T)->getKind()) { 581 case BuiltinType::Void: 582 return STC_Void; 583 584 case BuiltinType::NullPtr: 585 return STC_Pointer; 586 587 case BuiltinType::Overload: 588 case BuiltinType::Dependent: 589 case BuiltinType::UndeducedAuto: 590 return STC_Other; 591 592 case BuiltinType::ObjCId: 593 case BuiltinType::ObjCClass: 594 case BuiltinType::ObjCSel: 595 return STC_ObjectiveC; 596 597 default: 598 return STC_Arithmetic; 599 } 600 return STC_Other; 601 602 case Type::Complex: 603 return STC_Arithmetic; 604 605 case Type::Pointer: 606 return STC_Pointer; 607 608 case Type::BlockPointer: 609 return STC_Block; 610 611 case Type::LValueReference: 612 case Type::RValueReference: 613 return getSimplifiedTypeClass(T->getAs<ReferenceType>()->getPointeeType()); 614 615 case Type::ConstantArray: 616 case Type::IncompleteArray: 617 case Type::VariableArray: 618 case Type::DependentSizedArray: 619 return STC_Array; 620 621 case Type::DependentSizedExtVector: 622 case Type::Vector: 623 case Type::ExtVector: 624 return STC_Arithmetic; 625 626 case Type::FunctionProto: 627 case Type::FunctionNoProto: 628 return STC_Function; 629 630 case Type::Record: 631 return STC_Record; 632 633 case Type::Enum: 634 return STC_Arithmetic; 635 636 case Type::ObjCObject: 637 case Type::ObjCInterface: 638 case Type::ObjCObjectPointer: 639 return STC_ObjectiveC; 640 641 default: 642 return STC_Other; 643 } 644} 645 646/// \brief Get the type that a given expression will have if this declaration 647/// is used as an expression in its "typical" code-completion form. 648QualType clang::getDeclUsageType(ASTContext &C, NamedDecl *ND) { 649 ND = cast<NamedDecl>(ND->getUnderlyingDecl()); 650 651 if (TypeDecl *Type = dyn_cast<TypeDecl>(ND)) 652 return C.getTypeDeclType(Type); 653 if (ObjCInterfaceDecl *Iface = dyn_cast<ObjCInterfaceDecl>(ND)) 654 return C.getObjCInterfaceType(Iface); 655 656 QualType T; 657 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND)) 658 T = Function->getCallResultType(); 659 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND)) 660 T = Method->getSendResultType(); 661 else if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND)) 662 T = FunTmpl->getTemplatedDecl()->getCallResultType(); 663 else if (EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND)) 664 T = C.getTypeDeclType(cast<EnumDecl>(Enumerator->getDeclContext())); 665 else if (ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND)) 666 T = Property->getType(); 667 else if (ValueDecl *Value = dyn_cast<ValueDecl>(ND)) 668 T = Value->getType(); 669 else 670 return QualType(); 671 672 return T.getNonReferenceType(); 673} 674 675void ResultBuilder::AdjustResultPriorityForDecl(Result &R) { 676 // If this is an Objective-C method declaration whose selector matches our 677 // preferred selector, give it a priority boost. 678 if (!PreferredSelector.isNull()) 679 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(R.Declaration)) 680 if (PreferredSelector == Method->getSelector()) 681 R.Priority += CCD_SelectorMatch; 682 683 // If we have a preferred type, adjust the priority for results with exactly- 684 // matching or nearly-matching types. 685 if (!PreferredType.isNull()) { 686 QualType T = getDeclUsageType(SemaRef.Context, R.Declaration); 687 if (!T.isNull()) { 688 CanQualType TC = SemaRef.Context.getCanonicalType(T); 689 // Check for exactly-matching types (modulo qualifiers). 690 if (SemaRef.Context.hasSameUnqualifiedType(PreferredType, TC)) 691 R.Priority /= CCF_ExactTypeMatch; 692 // Check for nearly-matching types, based on classification of each. 693 else if ((getSimplifiedTypeClass(PreferredType) 694 == getSimplifiedTypeClass(TC)) && 695 !(PreferredType->isEnumeralType() && TC->isEnumeralType())) 696 R.Priority /= CCF_SimilarTypeMatch; 697 } 698 } 699} 700 701void ResultBuilder::MaybeAddConstructorResults(Result R) { 702 if (!SemaRef.getLangOptions().CPlusPlus || !R.Declaration || 703 !CompletionContext.wantConstructorResults()) 704 return; 705 706 ASTContext &Context = SemaRef.Context; 707 NamedDecl *D = R.Declaration; 708 CXXRecordDecl *Record = 0; 709 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) 710 Record = ClassTemplate->getTemplatedDecl(); 711 else if ((Record = dyn_cast<CXXRecordDecl>(D))) { 712 // Skip specializations and partial specializations. 713 if (isa<ClassTemplateSpecializationDecl>(Record)) 714 return; 715 } else { 716 // There are no constructors here. 717 return; 718 } 719 720 Record = Record->getDefinition(); 721 if (!Record) 722 return; 723 724 725 QualType RecordTy = Context.getTypeDeclType(Record); 726 DeclarationName ConstructorName 727 = Context.DeclarationNames.getCXXConstructorName( 728 Context.getCanonicalType(RecordTy)); 729 for (DeclContext::lookup_result Ctors = Record->lookup(ConstructorName); 730 Ctors.first != Ctors.second; ++Ctors.first) { 731 R.Declaration = *Ctors.first; 732 R.CursorKind = getCursorKindForDecl(R.Declaration); 733 Results.push_back(R); 734 } 735} 736 737void ResultBuilder::MaybeAddResult(Result R, DeclContext *CurContext) { 738 assert(!ShadowMaps.empty() && "Must enter into a results scope"); 739 740 if (R.Kind != Result::RK_Declaration) { 741 // For non-declaration results, just add the result. 742 Results.push_back(R); 743 return; 744 } 745 746 // Look through using declarations. 747 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) { 748 MaybeAddResult(Result(Using->getTargetDecl(), R.Qualifier), CurContext); 749 return; 750 } 751 752 Decl *CanonDecl = R.Declaration->getCanonicalDecl(); 753 unsigned IDNS = CanonDecl->getIdentifierNamespace(); 754 755 bool AsNestedNameSpecifier = false; 756 if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier)) 757 return; 758 759 // C++ constructors are never found by name lookup. 760 if (isa<CXXConstructorDecl>(R.Declaration)) 761 return; 762 763 ShadowMap &SMap = ShadowMaps.back(); 764 ShadowMapEntry::iterator I, IEnd; 765 ShadowMap::iterator NamePos = SMap.find(R.Declaration->getDeclName()); 766 if (NamePos != SMap.end()) { 767 I = NamePos->second.begin(); 768 IEnd = NamePos->second.end(); 769 } 770 771 for (; I != IEnd; ++I) { 772 NamedDecl *ND = I->first; 773 unsigned Index = I->second; 774 if (ND->getCanonicalDecl() == CanonDecl) { 775 // This is a redeclaration. Always pick the newer declaration. 776 Results[Index].Declaration = R.Declaration; 777 778 // We're done. 779 return; 780 } 781 } 782 783 // This is a new declaration in this scope. However, check whether this 784 // declaration name is hidden by a similarly-named declaration in an outer 785 // scope. 786 std::list<ShadowMap>::iterator SM, SMEnd = ShadowMaps.end(); 787 --SMEnd; 788 for (SM = ShadowMaps.begin(); SM != SMEnd; ++SM) { 789 ShadowMapEntry::iterator I, IEnd; 790 ShadowMap::iterator NamePos = SM->find(R.Declaration->getDeclName()); 791 if (NamePos != SM->end()) { 792 I = NamePos->second.begin(); 793 IEnd = NamePos->second.end(); 794 } 795 for (; I != IEnd; ++I) { 796 // A tag declaration does not hide a non-tag declaration. 797 if (I->first->hasTagIdentifierNamespace() && 798 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary | 799 Decl::IDNS_ObjCProtocol))) 800 continue; 801 802 // Protocols are in distinct namespaces from everything else. 803 if (((I->first->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol) 804 || (IDNS & Decl::IDNS_ObjCProtocol)) && 805 I->first->getIdentifierNamespace() != IDNS) 806 continue; 807 808 // The newly-added result is hidden by an entry in the shadow map. 809 if (CheckHiddenResult(R, CurContext, I->first)) 810 return; 811 812 break; 813 } 814 } 815 816 // Make sure that any given declaration only shows up in the result set once. 817 if (!AllDeclsFound.insert(CanonDecl)) 818 return; 819 820 // If the filter is for nested-name-specifiers, then this result starts a 821 // nested-name-specifier. 822 if (AsNestedNameSpecifier) { 823 R.StartsNestedNameSpecifier = true; 824 R.Priority = CCP_NestedNameSpecifier; 825 } else 826 AdjustResultPriorityForDecl(R); 827 828 // If this result is supposed to have an informative qualifier, add one. 829 if (R.QualifierIsInformative && !R.Qualifier && 830 !R.StartsNestedNameSpecifier) { 831 DeclContext *Ctx = R.Declaration->getDeclContext(); 832 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx)) 833 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, Namespace); 834 else if (TagDecl *Tag = dyn_cast<TagDecl>(Ctx)) 835 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, false, 836 SemaRef.Context.getTypeDeclType(Tag).getTypePtr()); 837 else 838 R.QualifierIsInformative = false; 839 } 840 841 // Insert this result into the set of results and into the current shadow 842 // map. 843 SMap[R.Declaration->getDeclName()].Add(R.Declaration, Results.size()); 844 Results.push_back(R); 845 846 if (!AsNestedNameSpecifier) 847 MaybeAddConstructorResults(R); 848} 849 850void ResultBuilder::AddResult(Result R, DeclContext *CurContext, 851 NamedDecl *Hiding, bool InBaseClass = false) { 852 if (R.Kind != Result::RK_Declaration) { 853 // For non-declaration results, just add the result. 854 Results.push_back(R); 855 return; 856 } 857 858 // Look through using declarations. 859 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) { 860 AddResult(Result(Using->getTargetDecl(), R.Qualifier), CurContext, Hiding); 861 return; 862 } 863 864 bool AsNestedNameSpecifier = false; 865 if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier)) 866 return; 867 868 // C++ constructors are never found by name lookup. 869 if (isa<CXXConstructorDecl>(R.Declaration)) 870 return; 871 872 if (Hiding && CheckHiddenResult(R, CurContext, Hiding)) 873 return; 874 875 // Make sure that any given declaration only shows up in the result set once. 876 if (!AllDeclsFound.insert(R.Declaration->getCanonicalDecl())) 877 return; 878 879 // If the filter is for nested-name-specifiers, then this result starts a 880 // nested-name-specifier. 881 if (AsNestedNameSpecifier) { 882 R.StartsNestedNameSpecifier = true; 883 R.Priority = CCP_NestedNameSpecifier; 884 } 885 else if (Filter == &ResultBuilder::IsMember && !R.Qualifier && InBaseClass && 886 isa<CXXRecordDecl>(R.Declaration->getDeclContext() 887 ->getRedeclContext())) 888 R.QualifierIsInformative = true; 889 890 // If this result is supposed to have an informative qualifier, add one. 891 if (R.QualifierIsInformative && !R.Qualifier && 892 !R.StartsNestedNameSpecifier) { 893 DeclContext *Ctx = R.Declaration->getDeclContext(); 894 if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx)) 895 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, Namespace); 896 else if (TagDecl *Tag = dyn_cast<TagDecl>(Ctx)) 897 R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, false, 898 SemaRef.Context.getTypeDeclType(Tag).getTypePtr()); 899 else 900 R.QualifierIsInformative = false; 901 } 902 903 // Adjust the priority if this result comes from a base class. 904 if (InBaseClass) 905 R.Priority += CCD_InBaseClass; 906 907 AdjustResultPriorityForDecl(R); 908 909 if (HasObjectTypeQualifiers) 910 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(R.Declaration)) 911 if (Method->isInstance()) { 912 Qualifiers MethodQuals 913 = Qualifiers::fromCVRMask(Method->getTypeQualifiers()); 914 if (ObjectTypeQualifiers == MethodQuals) 915 R.Priority += CCD_ObjectQualifierMatch; 916 else if (ObjectTypeQualifiers - MethodQuals) { 917 // The method cannot be invoked, because doing so would drop 918 // qualifiers. 919 return; 920 } 921 } 922 923 // Insert this result into the set of results. 924 Results.push_back(R); 925 926 if (!AsNestedNameSpecifier) 927 MaybeAddConstructorResults(R); 928} 929 930void ResultBuilder::AddResult(Result R) { 931 assert(R.Kind != Result::RK_Declaration && 932 "Declaration results need more context"); 933 Results.push_back(R); 934} 935 936/// \brief Enter into a new scope. 937void ResultBuilder::EnterNewScope() { 938 ShadowMaps.push_back(ShadowMap()); 939} 940 941/// \brief Exit from the current scope. 942void ResultBuilder::ExitScope() { 943 for (ShadowMap::iterator E = ShadowMaps.back().begin(), 944 EEnd = ShadowMaps.back().end(); 945 E != EEnd; 946 ++E) 947 E->second.Destroy(); 948 949 ShadowMaps.pop_back(); 950} 951 952/// \brief Determines whether this given declaration will be found by 953/// ordinary name lookup. 954bool ResultBuilder::IsOrdinaryName(NamedDecl *ND) const { 955 ND = cast<NamedDecl>(ND->getUnderlyingDecl()); 956 957 unsigned IDNS = Decl::IDNS_Ordinary; 958 if (SemaRef.getLangOptions().CPlusPlus) 959 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member; 960 else if (SemaRef.getLangOptions().ObjC1) { 961 if (isa<ObjCIvarDecl>(ND)) 962 return true; 963 if (isa<ObjCPropertyDecl>(ND) && 964 SemaRef.canSynthesizeProvisionalIvar(cast<ObjCPropertyDecl>(ND))) 965 return true; 966 } 967 968 return ND->getIdentifierNamespace() & IDNS; 969} 970 971/// \brief Determines whether this given declaration will be found by 972/// ordinary name lookup but is not a type name. 973bool ResultBuilder::IsOrdinaryNonTypeName(NamedDecl *ND) const { 974 ND = cast<NamedDecl>(ND->getUnderlyingDecl()); 975 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) 976 return false; 977 978 unsigned IDNS = Decl::IDNS_Ordinary; 979 if (SemaRef.getLangOptions().CPlusPlus) 980 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member; 981 else if (SemaRef.getLangOptions().ObjC1) { 982 if (isa<ObjCIvarDecl>(ND)) 983 return true; 984 if (isa<ObjCPropertyDecl>(ND) && 985 SemaRef.canSynthesizeProvisionalIvar(cast<ObjCPropertyDecl>(ND))) 986 return true; 987 } 988 989 return ND->getIdentifierNamespace() & IDNS; 990} 991 992bool ResultBuilder::IsIntegralConstantValue(NamedDecl *ND) const { 993 if (!IsOrdinaryNonTypeName(ND)) 994 return 0; 995 996 if (ValueDecl *VD = dyn_cast<ValueDecl>(ND->getUnderlyingDecl())) 997 if (VD->getType()->isIntegralOrEnumerationType()) 998 return true; 999 1000 return false; 1001} 1002 1003/// \brief Determines whether this given declaration will be found by 1004/// ordinary name lookup. 1005bool ResultBuilder::IsOrdinaryNonValueName(NamedDecl *ND) const { 1006 ND = cast<NamedDecl>(ND->getUnderlyingDecl()); 1007 1008 unsigned IDNS = Decl::IDNS_Ordinary; 1009 if (SemaRef.getLangOptions().CPlusPlus) 1010 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace; 1011 1012 return (ND->getIdentifierNamespace() & IDNS) && 1013 !isa<ValueDecl>(ND) && !isa<FunctionTemplateDecl>(ND) && 1014 !isa<ObjCPropertyDecl>(ND); 1015} 1016 1017/// \brief Determines whether the given declaration is suitable as the 1018/// start of a C++ nested-name-specifier, e.g., a class or namespace. 1019bool ResultBuilder::IsNestedNameSpecifier(NamedDecl *ND) const { 1020 // Allow us to find class templates, too. 1021 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND)) 1022 ND = ClassTemplate->getTemplatedDecl(); 1023 1024 return SemaRef.isAcceptableNestedNameSpecifier(ND); 1025} 1026 1027/// \brief Determines whether the given declaration is an enumeration. 1028bool ResultBuilder::IsEnum(NamedDecl *ND) const { 1029 return isa<EnumDecl>(ND); 1030} 1031 1032/// \brief Determines whether the given declaration is a class or struct. 1033bool ResultBuilder::IsClassOrStruct(NamedDecl *ND) const { 1034 // Allow us to find class templates, too. 1035 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND)) 1036 ND = ClassTemplate->getTemplatedDecl(); 1037 1038 if (RecordDecl *RD = dyn_cast<RecordDecl>(ND)) 1039 return RD->getTagKind() == TTK_Class || 1040 RD->getTagKind() == TTK_Struct; 1041 1042 return false; 1043} 1044 1045/// \brief Determines whether the given declaration is a union. 1046bool ResultBuilder::IsUnion(NamedDecl *ND) const { 1047 // Allow us to find class templates, too. 1048 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND)) 1049 ND = ClassTemplate->getTemplatedDecl(); 1050 1051 if (RecordDecl *RD = dyn_cast<RecordDecl>(ND)) 1052 return RD->getTagKind() == TTK_Union; 1053 1054 return false; 1055} 1056 1057/// \brief Determines whether the given declaration is a namespace. 1058bool ResultBuilder::IsNamespace(NamedDecl *ND) const { 1059 return isa<NamespaceDecl>(ND); 1060} 1061 1062/// \brief Determines whether the given declaration is a namespace or 1063/// namespace alias. 1064bool ResultBuilder::IsNamespaceOrAlias(NamedDecl *ND) const { 1065 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND); 1066} 1067 1068/// \brief Determines whether the given declaration is a type. 1069bool ResultBuilder::IsType(NamedDecl *ND) const { 1070 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(ND)) 1071 ND = Using->getTargetDecl(); 1072 1073 return isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND); 1074} 1075 1076/// \brief Determines which members of a class should be visible via 1077/// "." or "->". Only value declarations, nested name specifiers, and 1078/// using declarations thereof should show up. 1079bool ResultBuilder::IsMember(NamedDecl *ND) const { 1080 if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(ND)) 1081 ND = Using->getTargetDecl(); 1082 1083 return isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND) || 1084 isa<ObjCPropertyDecl>(ND); 1085} 1086 1087static bool isObjCReceiverType(ASTContext &C, QualType T) { 1088 T = C.getCanonicalType(T); 1089 switch (T->getTypeClass()) { 1090 case Type::ObjCObject: 1091 case Type::ObjCInterface: 1092 case Type::ObjCObjectPointer: 1093 return true; 1094 1095 case Type::Builtin: 1096 switch (cast<BuiltinType>(T)->getKind()) { 1097 case BuiltinType::ObjCId: 1098 case BuiltinType::ObjCClass: 1099 case BuiltinType::ObjCSel: 1100 return true; 1101 1102 default: 1103 break; 1104 } 1105 return false; 1106 1107 default: 1108 break; 1109 } 1110 1111 if (!C.getLangOptions().CPlusPlus) 1112 return false; 1113 1114 // FIXME: We could perform more analysis here to determine whether a 1115 // particular class type has any conversions to Objective-C types. For now, 1116 // just accept all class types. 1117 return T->isDependentType() || T->isRecordType(); 1118} 1119 1120bool ResultBuilder::IsObjCMessageReceiver(NamedDecl *ND) const { 1121 QualType T = getDeclUsageType(SemaRef.Context, ND); 1122 if (T.isNull()) 1123 return false; 1124 1125 T = SemaRef.Context.getBaseElementType(T); 1126 return isObjCReceiverType(SemaRef.Context, T); 1127} 1128 1129bool ResultBuilder::IsObjCCollection(NamedDecl *ND) const { 1130 if ((SemaRef.getLangOptions().CPlusPlus && !IsOrdinaryName(ND)) || 1131 (!SemaRef.getLangOptions().CPlusPlus && !IsOrdinaryNonTypeName(ND))) 1132 return false; 1133 1134 QualType T = getDeclUsageType(SemaRef.Context, ND); 1135 if (T.isNull()) 1136 return false; 1137 1138 T = SemaRef.Context.getBaseElementType(T); 1139 return T->isObjCObjectType() || T->isObjCObjectPointerType() || 1140 T->isObjCIdType() || 1141 (SemaRef.getLangOptions().CPlusPlus && T->isRecordType()); 1142} 1143 1144bool ResultBuilder::IsImpossibleToSatisfy(NamedDecl *ND) const { 1145 return false; 1146} 1147 1148/// \rief Determines whether the given declaration is an Objective-C 1149/// instance variable. 1150bool ResultBuilder::IsObjCIvar(NamedDecl *ND) const { 1151 return isa<ObjCIvarDecl>(ND); 1152} 1153 1154namespace { 1155 /// \brief Visible declaration consumer that adds a code-completion result 1156 /// for each visible declaration. 1157 class CodeCompletionDeclConsumer : public VisibleDeclConsumer { 1158 ResultBuilder &Results; 1159 DeclContext *CurContext; 1160 1161 public: 1162 CodeCompletionDeclConsumer(ResultBuilder &Results, DeclContext *CurContext) 1163 : Results(Results), CurContext(CurContext) { } 1164 1165 virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, bool InBaseClass) { 1166 Results.AddResult(ND, CurContext, Hiding, InBaseClass); 1167 } 1168 }; 1169} 1170 1171/// \brief Add type specifiers for the current language as keyword results. 1172static void AddTypeSpecifierResults(const LangOptions &LangOpts, 1173 ResultBuilder &Results) { 1174 typedef CodeCompletionResult Result; 1175 Results.AddResult(Result("short", CCP_Type)); 1176 Results.AddResult(Result("long", CCP_Type)); 1177 Results.AddResult(Result("signed", CCP_Type)); 1178 Results.AddResult(Result("unsigned", CCP_Type)); 1179 Results.AddResult(Result("void", CCP_Type)); 1180 Results.AddResult(Result("char", CCP_Type)); 1181 Results.AddResult(Result("int", CCP_Type)); 1182 Results.AddResult(Result("float", CCP_Type)); 1183 Results.AddResult(Result("double", CCP_Type)); 1184 Results.AddResult(Result("enum", CCP_Type)); 1185 Results.AddResult(Result("struct", CCP_Type)); 1186 Results.AddResult(Result("union", CCP_Type)); 1187 Results.AddResult(Result("const", CCP_Type)); 1188 Results.AddResult(Result("volatile", CCP_Type)); 1189 1190 if (LangOpts.C99) { 1191 // C99-specific 1192 Results.AddResult(Result("_Complex", CCP_Type)); 1193 Results.AddResult(Result("_Imaginary", CCP_Type)); 1194 Results.AddResult(Result("_Bool", CCP_Type)); 1195 Results.AddResult(Result("restrict", CCP_Type)); 1196 } 1197 1198 CodeCompletionBuilder Builder(Results.getAllocator()); 1199 if (LangOpts.CPlusPlus) { 1200 // C++-specific 1201 Results.AddResult(Result("bool", CCP_Type + 1202 (LangOpts.ObjC1? CCD_bool_in_ObjC : 0))); 1203 Results.AddResult(Result("class", CCP_Type)); 1204 Results.AddResult(Result("wchar_t", CCP_Type)); 1205 1206 // typename qualified-id 1207 Builder.AddTypedTextChunk("typename"); 1208 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 1209 Builder.AddPlaceholderChunk("qualifier"); 1210 Builder.AddTextChunk("::"); 1211 Builder.AddPlaceholderChunk("name"); 1212 Results.AddResult(Result(Builder.TakeString())); 1213 1214 if (LangOpts.CPlusPlus0x) { 1215 Results.AddResult(Result("auto", CCP_Type)); 1216 Results.AddResult(Result("char16_t", CCP_Type)); 1217 Results.AddResult(Result("char32_t", CCP_Type)); 1218 1219 Builder.AddTypedTextChunk("decltype"); 1220 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 1221 Builder.AddPlaceholderChunk("expression"); 1222 Builder.AddChunk(CodeCompletionString::CK_RightParen); 1223 Results.AddResult(Result(Builder.TakeString())); 1224 } 1225 } 1226 1227 // GNU extensions 1228 if (LangOpts.GNUMode) { 1229 // FIXME: Enable when we actually support decimal floating point. 1230 // Results.AddResult(Result("_Decimal32")); 1231 // Results.AddResult(Result("_Decimal64")); 1232 // Results.AddResult(Result("_Decimal128")); 1233 1234 Builder.AddTypedTextChunk("typeof"); 1235 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 1236 Builder.AddPlaceholderChunk("expression"); 1237 Results.AddResult(Result(Builder.TakeString())); 1238 1239 Builder.AddTypedTextChunk("typeof"); 1240 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 1241 Builder.AddPlaceholderChunk("type"); 1242 Builder.AddChunk(CodeCompletionString::CK_RightParen); 1243 Results.AddResult(Result(Builder.TakeString())); 1244 } 1245} 1246 1247static void AddStorageSpecifiers(Sema::ParserCompletionContext CCC, 1248 const LangOptions &LangOpts, 1249 ResultBuilder &Results) { 1250 typedef CodeCompletionResult Result; 1251 // Note: we don't suggest either "auto" or "register", because both 1252 // are pointless as storage specifiers. Elsewhere, we suggest "auto" 1253 // in C++0x as a type specifier. 1254 Results.AddResult(Result("extern")); 1255 Results.AddResult(Result("static")); 1256} 1257 1258static void AddFunctionSpecifiers(Sema::ParserCompletionContext CCC, 1259 const LangOptions &LangOpts, 1260 ResultBuilder &Results) { 1261 typedef CodeCompletionResult Result; 1262 switch (CCC) { 1263 case Sema::PCC_Class: 1264 case Sema::PCC_MemberTemplate: 1265 if (LangOpts.CPlusPlus) { 1266 Results.AddResult(Result("explicit")); 1267 Results.AddResult(Result("friend")); 1268 Results.AddResult(Result("mutable")); 1269 Results.AddResult(Result("virtual")); 1270 } 1271 // Fall through 1272 1273 case Sema::PCC_ObjCInterface: 1274 case Sema::PCC_ObjCImplementation: 1275 case Sema::PCC_Namespace: 1276 case Sema::PCC_Template: 1277 if (LangOpts.CPlusPlus || LangOpts.C99) 1278 Results.AddResult(Result("inline")); 1279 break; 1280 1281 case Sema::PCC_ObjCInstanceVariableList: 1282 case Sema::PCC_Expression: 1283 case Sema::PCC_Statement: 1284 case Sema::PCC_ForInit: 1285 case Sema::PCC_Condition: 1286 case Sema::PCC_RecoveryInFunction: 1287 case Sema::PCC_Type: 1288 case Sema::PCC_ParenthesizedExpression: 1289 case Sema::PCC_LocalDeclarationSpecifiers: 1290 break; 1291 } 1292} 1293 1294static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt); 1295static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt); 1296static void AddObjCVisibilityResults(const LangOptions &LangOpts, 1297 ResultBuilder &Results, 1298 bool NeedAt); 1299static void AddObjCImplementationResults(const LangOptions &LangOpts, 1300 ResultBuilder &Results, 1301 bool NeedAt); 1302static void AddObjCInterfaceResults(const LangOptions &LangOpts, 1303 ResultBuilder &Results, 1304 bool NeedAt); 1305static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt); 1306 1307static void AddTypedefResult(ResultBuilder &Results) { 1308 CodeCompletionBuilder Builder(Results.getAllocator()); 1309 Builder.AddTypedTextChunk("typedef"); 1310 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 1311 Builder.AddPlaceholderChunk("type"); 1312 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 1313 Builder.AddPlaceholderChunk("name"); 1314 Results.AddResult(CodeCompletionResult(Builder.TakeString())); 1315} 1316 1317static bool WantTypesInContext(Sema::ParserCompletionContext CCC, 1318 const LangOptions &LangOpts) { 1319 switch (CCC) { 1320 case Sema::PCC_Namespace: 1321 case Sema::PCC_Class: 1322 case Sema::PCC_ObjCInstanceVariableList: 1323 case Sema::PCC_Template: 1324 case Sema::PCC_MemberTemplate: 1325 case Sema::PCC_Statement: 1326 case Sema::PCC_RecoveryInFunction: 1327 case Sema::PCC_Type: 1328 case Sema::PCC_ParenthesizedExpression: 1329 case Sema::PCC_LocalDeclarationSpecifiers: 1330 return true; 1331 1332 case Sema::PCC_Expression: 1333 case Sema::PCC_Condition: 1334 return LangOpts.CPlusPlus; 1335 1336 case Sema::PCC_ObjCInterface: 1337 case Sema::PCC_ObjCImplementation: 1338 return false; 1339 1340 case Sema::PCC_ForInit: 1341 return LangOpts.CPlusPlus || LangOpts.ObjC1 || LangOpts.C99; 1342 } 1343 1344 return false; 1345} 1346 1347/// \brief Add language constructs that show up for "ordinary" names. 1348static void AddOrdinaryNameResults(Sema::ParserCompletionContext CCC, 1349 Scope *S, 1350 Sema &SemaRef, 1351 ResultBuilder &Results) { 1352 CodeCompletionBuilder Builder(Results.getAllocator()); 1353 1354 typedef CodeCompletionResult Result; 1355 switch (CCC) { 1356 case Sema::PCC_Namespace: 1357 if (SemaRef.getLangOptions().CPlusPlus) { 1358 if (Results.includeCodePatterns()) { 1359 // namespace <identifier> { declarations } 1360 Builder.AddTypedTextChunk("namespace"); 1361 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 1362 Builder.AddPlaceholderChunk("identifier"); 1363 Builder.AddChunk(CodeCompletionString::CK_LeftBrace); 1364 Builder.AddPlaceholderChunk("declarations"); 1365 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); 1366 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 1367 Results.AddResult(Result(Builder.TakeString())); 1368 } 1369 1370 // namespace identifier = identifier ; 1371 Builder.AddTypedTextChunk("namespace"); 1372 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 1373 Builder.AddPlaceholderChunk("name"); 1374 Builder.AddChunk(CodeCompletionString::CK_Equal); 1375 Builder.AddPlaceholderChunk("namespace"); 1376 Results.AddResult(Result(Builder.TakeString())); 1377 1378 // Using directives 1379 Builder.AddTypedTextChunk("using"); 1380 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 1381 Builder.AddTextChunk("namespace"); 1382 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 1383 Builder.AddPlaceholderChunk("identifier"); 1384 Results.AddResult(Result(Builder.TakeString())); 1385 1386 // asm(string-literal) 1387 Builder.AddTypedTextChunk("asm"); 1388 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 1389 Builder.AddPlaceholderChunk("string-literal"); 1390 Builder.AddChunk(CodeCompletionString::CK_RightParen); 1391 Results.AddResult(Result(Builder.TakeString())); 1392 1393 if (Results.includeCodePatterns()) { 1394 // Explicit template instantiation 1395 Builder.AddTypedTextChunk("template"); 1396 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 1397 Builder.AddPlaceholderChunk("declaration"); 1398 Results.AddResult(Result(Builder.TakeString())); 1399 } 1400 } 1401 1402 if (SemaRef.getLangOptions().ObjC1) 1403 AddObjCTopLevelResults(Results, true); 1404 1405 AddTypedefResult(Results); 1406 // Fall through 1407 1408 case Sema::PCC_Class: 1409 if (SemaRef.getLangOptions().CPlusPlus) { 1410 // Using declaration 1411 Builder.AddTypedTextChunk("using"); 1412 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 1413 Builder.AddPlaceholderChunk("qualifier"); 1414 Builder.AddTextChunk("::"); 1415 Builder.AddPlaceholderChunk("name"); 1416 Results.AddResult(Result(Builder.TakeString())); 1417 1418 // using typename qualifier::name (only in a dependent context) 1419 if (SemaRef.CurContext->isDependentContext()) { 1420 Builder.AddTypedTextChunk("using"); 1421 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 1422 Builder.AddTextChunk("typename"); 1423 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 1424 Builder.AddPlaceholderChunk("qualifier"); 1425 Builder.AddTextChunk("::"); 1426 Builder.AddPlaceholderChunk("name"); 1427 Results.AddResult(Result(Builder.TakeString())); 1428 } 1429 1430 if (CCC == Sema::PCC_Class) { 1431 AddTypedefResult(Results); 1432 1433 // public: 1434 Builder.AddTypedTextChunk("public"); 1435 Builder.AddChunk(CodeCompletionString::CK_Colon); 1436 Results.AddResult(Result(Builder.TakeString())); 1437 1438 // protected: 1439 Builder.AddTypedTextChunk("protected"); 1440 Builder.AddChunk(CodeCompletionString::CK_Colon); 1441 Results.AddResult(Result(Builder.TakeString())); 1442 1443 // private: 1444 Builder.AddTypedTextChunk("private"); 1445 Builder.AddChunk(CodeCompletionString::CK_Colon); 1446 Results.AddResult(Result(Builder.TakeString())); 1447 } 1448 } 1449 // Fall through 1450 1451 case Sema::PCC_Template: 1452 case Sema::PCC_MemberTemplate: 1453 if (SemaRef.getLangOptions().CPlusPlus && Results.includeCodePatterns()) { 1454 // template < parameters > 1455 Builder.AddTypedTextChunk("template"); 1456 Builder.AddChunk(CodeCompletionString::CK_LeftAngle); 1457 Builder.AddPlaceholderChunk("parameters"); 1458 Builder.AddChunk(CodeCompletionString::CK_RightAngle); 1459 Results.AddResult(Result(Builder.TakeString())); 1460 } 1461 1462 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results); 1463 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results); 1464 break; 1465 1466 case Sema::PCC_ObjCInterface: 1467 AddObjCInterfaceResults(SemaRef.getLangOptions(), Results, true); 1468 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results); 1469 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results); 1470 break; 1471 1472 case Sema::PCC_ObjCImplementation: 1473 AddObjCImplementationResults(SemaRef.getLangOptions(), Results, true); 1474 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results); 1475 AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results); 1476 break; 1477 1478 case Sema::PCC_ObjCInstanceVariableList: 1479 AddObjCVisibilityResults(SemaRef.getLangOptions(), Results, true); 1480 break; 1481 1482 case Sema::PCC_RecoveryInFunction: 1483 case Sema::PCC_Statement: { 1484 AddTypedefResult(Results); 1485 1486 if (SemaRef.getLangOptions().CPlusPlus && Results.includeCodePatterns()) { 1487 Builder.AddTypedTextChunk("try"); 1488 Builder.AddChunk(CodeCompletionString::CK_LeftBrace); 1489 Builder.AddPlaceholderChunk("statements"); 1490 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); 1491 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 1492 Builder.AddTextChunk("catch"); 1493 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 1494 Builder.AddPlaceholderChunk("declaration"); 1495 Builder.AddChunk(CodeCompletionString::CK_RightParen); 1496 Builder.AddChunk(CodeCompletionString::CK_LeftBrace); 1497 Builder.AddPlaceholderChunk("statements"); 1498 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); 1499 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 1500 Results.AddResult(Result(Builder.TakeString())); 1501 } 1502 if (SemaRef.getLangOptions().ObjC1) 1503 AddObjCStatementResults(Results, true); 1504 1505 if (Results.includeCodePatterns()) { 1506 // if (condition) { statements } 1507 Builder.AddTypedTextChunk("if"); 1508 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 1509 if (SemaRef.getLangOptions().CPlusPlus) 1510 Builder.AddPlaceholderChunk("condition"); 1511 else 1512 Builder.AddPlaceholderChunk("expression"); 1513 Builder.AddChunk(CodeCompletionString::CK_RightParen); 1514 Builder.AddChunk(CodeCompletionString::CK_LeftBrace); 1515 Builder.AddPlaceholderChunk("statements"); 1516 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); 1517 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 1518 Results.AddResult(Result(Builder.TakeString())); 1519 1520 // switch (condition) { } 1521 Builder.AddTypedTextChunk("switch"); 1522 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 1523 if (SemaRef.getLangOptions().CPlusPlus) 1524 Builder.AddPlaceholderChunk("condition"); 1525 else 1526 Builder.AddPlaceholderChunk("expression"); 1527 Builder.AddChunk(CodeCompletionString::CK_RightParen); 1528 Builder.AddChunk(CodeCompletionString::CK_LeftBrace); 1529 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); 1530 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 1531 Results.AddResult(Result(Builder.TakeString())); 1532 } 1533 1534 // Switch-specific statements. 1535 if (!SemaRef.getCurFunction()->SwitchStack.empty()) { 1536 // case expression: 1537 Builder.AddTypedTextChunk("case"); 1538 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 1539 Builder.AddPlaceholderChunk("expression"); 1540 Builder.AddChunk(CodeCompletionString::CK_Colon); 1541 Results.AddResult(Result(Builder.TakeString())); 1542 1543 // default: 1544 Builder.AddTypedTextChunk("default"); 1545 Builder.AddChunk(CodeCompletionString::CK_Colon); 1546 Results.AddResult(Result(Builder.TakeString())); 1547 } 1548 1549 if (Results.includeCodePatterns()) { 1550 /// while (condition) { statements } 1551 Builder.AddTypedTextChunk("while"); 1552 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 1553 if (SemaRef.getLangOptions().CPlusPlus) 1554 Builder.AddPlaceholderChunk("condition"); 1555 else 1556 Builder.AddPlaceholderChunk("expression"); 1557 Builder.AddChunk(CodeCompletionString::CK_RightParen); 1558 Builder.AddChunk(CodeCompletionString::CK_LeftBrace); 1559 Builder.AddPlaceholderChunk("statements"); 1560 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); 1561 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 1562 Results.AddResult(Result(Builder.TakeString())); 1563 1564 // do { statements } while ( expression ); 1565 Builder.AddTypedTextChunk("do"); 1566 Builder.AddChunk(CodeCompletionString::CK_LeftBrace); 1567 Builder.AddPlaceholderChunk("statements"); 1568 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); 1569 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 1570 Builder.AddTextChunk("while"); 1571 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 1572 Builder.AddPlaceholderChunk("expression"); 1573 Builder.AddChunk(CodeCompletionString::CK_RightParen); 1574 Results.AddResult(Result(Builder.TakeString())); 1575 1576 // for ( for-init-statement ; condition ; expression ) { statements } 1577 Builder.AddTypedTextChunk("for"); 1578 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 1579 if (SemaRef.getLangOptions().CPlusPlus || SemaRef.getLangOptions().C99) 1580 Builder.AddPlaceholderChunk("init-statement"); 1581 else 1582 Builder.AddPlaceholderChunk("init-expression"); 1583 Builder.AddChunk(CodeCompletionString::CK_SemiColon); 1584 Builder.AddPlaceholderChunk("condition"); 1585 Builder.AddChunk(CodeCompletionString::CK_SemiColon); 1586 Builder.AddPlaceholderChunk("inc-expression"); 1587 Builder.AddChunk(CodeCompletionString::CK_RightParen); 1588 Builder.AddChunk(CodeCompletionString::CK_LeftBrace); 1589 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); 1590 Builder.AddPlaceholderChunk("statements"); 1591 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); 1592 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 1593 Results.AddResult(Result(Builder.TakeString())); 1594 } 1595 1596 if (S->getContinueParent()) { 1597 // continue ; 1598 Builder.AddTypedTextChunk("continue"); 1599 Results.AddResult(Result(Builder.TakeString())); 1600 } 1601 1602 if (S->getBreakParent()) { 1603 // break ; 1604 Builder.AddTypedTextChunk("break"); 1605 Results.AddResult(Result(Builder.TakeString())); 1606 } 1607 1608 // "return expression ;" or "return ;", depending on whether we 1609 // know the function is void or not. 1610 bool isVoid = false; 1611 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(SemaRef.CurContext)) 1612 isVoid = Function->getResultType()->isVoidType(); 1613 else if (ObjCMethodDecl *Method 1614 = dyn_cast<ObjCMethodDecl>(SemaRef.CurContext)) 1615 isVoid = Method->getResultType()->isVoidType(); 1616 else if (SemaRef.getCurBlock() && 1617 !SemaRef.getCurBlock()->ReturnType.isNull()) 1618 isVoid = SemaRef.getCurBlock()->ReturnType->isVoidType(); 1619 Builder.AddTypedTextChunk("return"); 1620 if (!isVoid) { 1621 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 1622 Builder.AddPlaceholderChunk("expression"); 1623 } 1624 Results.AddResult(Result(Builder.TakeString())); 1625 1626 // goto identifier ; 1627 Builder.AddTypedTextChunk("goto"); 1628 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 1629 Builder.AddPlaceholderChunk("label"); 1630 Results.AddResult(Result(Builder.TakeString())); 1631 1632 // Using directives 1633 Builder.AddTypedTextChunk("using"); 1634 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 1635 Builder.AddTextChunk("namespace"); 1636 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 1637 Builder.AddPlaceholderChunk("identifier"); 1638 Results.AddResult(Result(Builder.TakeString())); 1639 } 1640 1641 // Fall through (for statement expressions). 1642 case Sema::PCC_ForInit: 1643 case Sema::PCC_Condition: 1644 AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results); 1645 // Fall through: conditions and statements can have expressions. 1646 1647 case Sema::PCC_ParenthesizedExpression: 1648 case Sema::PCC_Expression: { 1649 if (SemaRef.getLangOptions().CPlusPlus) { 1650 // 'this', if we're in a non-static member function. 1651 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(SemaRef.CurContext)) 1652 if (!Method->isStatic()) 1653 Results.AddResult(Result("this")); 1654 1655 // true, false 1656 Results.AddResult(Result("true")); 1657 Results.AddResult(Result("false")); 1658 1659 // dynamic_cast < type-id > ( expression ) 1660 Builder.AddTypedTextChunk("dynamic_cast"); 1661 Builder.AddChunk(CodeCompletionString::CK_LeftAngle); 1662 Builder.AddPlaceholderChunk("type"); 1663 Builder.AddChunk(CodeCompletionString::CK_RightAngle); 1664 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 1665 Builder.AddPlaceholderChunk("expression"); 1666 Builder.AddChunk(CodeCompletionString::CK_RightParen); 1667 Results.AddResult(Result(Builder.TakeString())); 1668 1669 // static_cast < type-id > ( expression ) 1670 Builder.AddTypedTextChunk("static_cast"); 1671 Builder.AddChunk(CodeCompletionString::CK_LeftAngle); 1672 Builder.AddPlaceholderChunk("type"); 1673 Builder.AddChunk(CodeCompletionString::CK_RightAngle); 1674 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 1675 Builder.AddPlaceholderChunk("expression"); 1676 Builder.AddChunk(CodeCompletionString::CK_RightParen); 1677 Results.AddResult(Result(Builder.TakeString())); 1678 1679 // reinterpret_cast < type-id > ( expression ) 1680 Builder.AddTypedTextChunk("reinterpret_cast"); 1681 Builder.AddChunk(CodeCompletionString::CK_LeftAngle); 1682 Builder.AddPlaceholderChunk("type"); 1683 Builder.AddChunk(CodeCompletionString::CK_RightAngle); 1684 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 1685 Builder.AddPlaceholderChunk("expression"); 1686 Builder.AddChunk(CodeCompletionString::CK_RightParen); 1687 Results.AddResult(Result(Builder.TakeString())); 1688 1689 // const_cast < type-id > ( expression ) 1690 Builder.AddTypedTextChunk("const_cast"); 1691 Builder.AddChunk(CodeCompletionString::CK_LeftAngle); 1692 Builder.AddPlaceholderChunk("type"); 1693 Builder.AddChunk(CodeCompletionString::CK_RightAngle); 1694 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 1695 Builder.AddPlaceholderChunk("expression"); 1696 Builder.AddChunk(CodeCompletionString::CK_RightParen); 1697 Results.AddResult(Result(Builder.TakeString())); 1698 1699 // typeid ( expression-or-type ) 1700 Builder.AddTypedTextChunk("typeid"); 1701 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 1702 Builder.AddPlaceholderChunk("expression-or-type"); 1703 Builder.AddChunk(CodeCompletionString::CK_RightParen); 1704 Results.AddResult(Result(Builder.TakeString())); 1705 1706 // new T ( ... ) 1707 Builder.AddTypedTextChunk("new"); 1708 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 1709 Builder.AddPlaceholderChunk("type"); 1710 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 1711 Builder.AddPlaceholderChunk("expressions"); 1712 Builder.AddChunk(CodeCompletionString::CK_RightParen); 1713 Results.AddResult(Result(Builder.TakeString())); 1714 1715 // new T [ ] ( ... ) 1716 Builder.AddTypedTextChunk("new"); 1717 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 1718 Builder.AddPlaceholderChunk("type"); 1719 Builder.AddChunk(CodeCompletionString::CK_LeftBracket); 1720 Builder.AddPlaceholderChunk("size"); 1721 Builder.AddChunk(CodeCompletionString::CK_RightBracket); 1722 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 1723 Builder.AddPlaceholderChunk("expressions"); 1724 Builder.AddChunk(CodeCompletionString::CK_RightParen); 1725 Results.AddResult(Result(Builder.TakeString())); 1726 1727 // delete expression 1728 Builder.AddTypedTextChunk("delete"); 1729 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 1730 Builder.AddPlaceholderChunk("expression"); 1731 Results.AddResult(Result(Builder.TakeString())); 1732 1733 // delete [] expression 1734 Builder.AddTypedTextChunk("delete"); 1735 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 1736 Builder.AddChunk(CodeCompletionString::CK_LeftBracket); 1737 Builder.AddChunk(CodeCompletionString::CK_RightBracket); 1738 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 1739 Builder.AddPlaceholderChunk("expression"); 1740 Results.AddResult(Result(Builder.TakeString())); 1741 1742 // throw expression 1743 Builder.AddTypedTextChunk("throw"); 1744 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 1745 Builder.AddPlaceholderChunk("expression"); 1746 Results.AddResult(Result(Builder.TakeString())); 1747 1748 // FIXME: Rethrow? 1749 } 1750 1751 if (SemaRef.getLangOptions().ObjC1) { 1752 // Add "super", if we're in an Objective-C class with a superclass. 1753 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) { 1754 // The interface can be NULL. 1755 if (ObjCInterfaceDecl *ID = Method->getClassInterface()) 1756 if (ID->getSuperClass()) 1757 Results.AddResult(Result("super")); 1758 } 1759 1760 AddObjCExpressionResults(Results, true); 1761 } 1762 1763 // sizeof expression 1764 Builder.AddTypedTextChunk("sizeof"); 1765 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 1766 Builder.AddPlaceholderChunk("expression-or-type"); 1767 Builder.AddChunk(CodeCompletionString::CK_RightParen); 1768 Results.AddResult(Result(Builder.TakeString())); 1769 break; 1770 } 1771 1772 case Sema::PCC_Type: 1773 case Sema::PCC_LocalDeclarationSpecifiers: 1774 break; 1775 } 1776 1777 if (WantTypesInContext(CCC, SemaRef.getLangOptions())) 1778 AddTypeSpecifierResults(SemaRef.getLangOptions(), Results); 1779 1780 if (SemaRef.getLangOptions().CPlusPlus && CCC != Sema::PCC_Type) 1781 Results.AddResult(Result("operator")); 1782} 1783 1784/// \brief Retrieve the string representation of the given type as a string 1785/// that has the appropriate lifetime for code completion. 1786/// 1787/// This routine provides a fast path where we provide constant strings for 1788/// common type names. 1789const char *GetCompletionTypeString(QualType T, 1790 ASTContext &Context, 1791 CodeCompletionAllocator &Allocator) { 1792 PrintingPolicy Policy(Context.PrintingPolicy); 1793 Policy.AnonymousTagLocations = false; 1794 1795 if (!T.getLocalQualifiers()) { 1796 // Built-in type names are constant strings. 1797 if (const BuiltinType *BT = dyn_cast<BuiltinType>(T)) 1798 return BT->getName(Context.getLangOptions()); 1799 1800 // Anonymous tag types are constant strings. 1801 if (const TagType *TagT = dyn_cast<TagType>(T)) 1802 if (TagDecl *Tag = TagT->getDecl()) 1803 if (!Tag->getIdentifier() && !Tag->getTypedefForAnonDecl()) { 1804 switch (Tag->getTagKind()) { 1805 case TTK_Struct: return "struct <anonymous>"; 1806 case TTK_Class: return "class <anonymous>"; 1807 case TTK_Union: return "union <anonymous>"; 1808 case TTK_Enum: return "enum <anonymous>"; 1809 } 1810 } 1811 } 1812 1813 // Slow path: format the type as a string. 1814 std::string Result; 1815 T.getAsStringInternal(Result, Policy); 1816 return Allocator.CopyString(Result); 1817} 1818 1819/// \brief If the given declaration has an associated type, add it as a result 1820/// type chunk. 1821static void AddResultTypeChunk(ASTContext &Context, 1822 NamedDecl *ND, 1823 CodeCompletionBuilder &Result) { 1824 if (!ND) 1825 return; 1826 1827 // Skip constructors and conversion functions, which have their return types 1828 // built into their names. 1829 if (isa<CXXConstructorDecl>(ND) || isa<CXXConversionDecl>(ND)) 1830 return; 1831 1832 // Determine the type of the declaration (if it has a type). 1833 QualType T; 1834 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND)) 1835 T = Function->getResultType(); 1836 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND)) 1837 T = Method->getResultType(); 1838 else if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND)) 1839 T = FunTmpl->getTemplatedDecl()->getResultType(); 1840 else if (EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND)) 1841 T = Context.getTypeDeclType(cast<TypeDecl>(Enumerator->getDeclContext())); 1842 else if (isa<UnresolvedUsingValueDecl>(ND)) { 1843 /* Do nothing: ignore unresolved using declarations*/ 1844 } else if (ValueDecl *Value = dyn_cast<ValueDecl>(ND)) 1845 T = Value->getType(); 1846 else if (ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND)) 1847 T = Property->getType(); 1848 1849 if (T.isNull() || Context.hasSameType(T, Context.DependentTy)) 1850 return; 1851 1852 Result.AddResultTypeChunk(GetCompletionTypeString(T, Context, 1853 Result.getAllocator())); 1854} 1855 1856static void MaybeAddSentinel(ASTContext &Context, NamedDecl *FunctionOrMethod, 1857 CodeCompletionBuilder &Result) { 1858 if (SentinelAttr *Sentinel = FunctionOrMethod->getAttr<SentinelAttr>()) 1859 if (Sentinel->getSentinel() == 0) { 1860 if (Context.getLangOptions().ObjC1 && 1861 Context.Idents.get("nil").hasMacroDefinition()) 1862 Result.AddTextChunk(", nil"); 1863 else if (Context.Idents.get("NULL").hasMacroDefinition()) 1864 Result.AddTextChunk(", NULL"); 1865 else 1866 Result.AddTextChunk(", (void*)0"); 1867 } 1868} 1869 1870static std::string FormatFunctionParameter(ASTContext &Context, 1871 ParmVarDecl *Param, 1872 bool SuppressName = false) { 1873 bool ObjCMethodParam = isa<ObjCMethodDecl>(Param->getDeclContext()); 1874 if (Param->getType()->isDependentType() || 1875 !Param->getType()->isBlockPointerType()) { 1876 // The argument for a dependent or non-block parameter is a placeholder 1877 // containing that parameter's type. 1878 std::string Result; 1879 1880 if (Param->getIdentifier() && !ObjCMethodParam && !SuppressName) 1881 Result = Param->getIdentifier()->getName(); 1882 1883 Param->getType().getAsStringInternal(Result, 1884 Context.PrintingPolicy); 1885 1886 if (ObjCMethodParam) { 1887 Result = "(" + Result; 1888 Result += ")"; 1889 if (Param->getIdentifier() && !SuppressName) 1890 Result += Param->getIdentifier()->getName(); 1891 } 1892 return Result; 1893 } 1894 1895 // The argument for a block pointer parameter is a block literal with 1896 // the appropriate type. 1897 FunctionTypeLoc *Block = 0; 1898 FunctionProtoTypeLoc *BlockProto = 0; 1899 TypeLoc TL; 1900 if (TypeSourceInfo *TSInfo = Param->getTypeSourceInfo()) { 1901 TL = TSInfo->getTypeLoc().getUnqualifiedLoc(); 1902 while (true) { 1903 // Look through typedefs. 1904 if (TypedefTypeLoc *TypedefTL = dyn_cast<TypedefTypeLoc>(&TL)) { 1905 if (TypeSourceInfo *InnerTSInfo 1906 = TypedefTL->getTypedefDecl()->getTypeSourceInfo()) { 1907 TL = InnerTSInfo->getTypeLoc().getUnqualifiedLoc(); 1908 continue; 1909 } 1910 } 1911 1912 // Look through qualified types 1913 if (QualifiedTypeLoc *QualifiedTL = dyn_cast<QualifiedTypeLoc>(&TL)) { 1914 TL = QualifiedTL->getUnqualifiedLoc(); 1915 continue; 1916 } 1917 1918 // Try to get the function prototype behind the block pointer type, 1919 // then we're done. 1920 if (BlockPointerTypeLoc *BlockPtr 1921 = dyn_cast<BlockPointerTypeLoc>(&TL)) { 1922 TL = BlockPtr->getPointeeLoc().IgnoreParens(); 1923 Block = dyn_cast<FunctionTypeLoc>(&TL); 1924 BlockProto = dyn_cast<FunctionProtoTypeLoc>(&TL); 1925 } 1926 break; 1927 } 1928 } 1929 1930 if (!Block) { 1931 // We were unable to find a FunctionProtoTypeLoc with parameter names 1932 // for the block; just use the parameter type as a placeholder. 1933 std::string Result; 1934 Param->getType().getUnqualifiedType(). 1935 getAsStringInternal(Result, Context.PrintingPolicy); 1936 1937 if (ObjCMethodParam) { 1938 Result = "(" + Result; 1939 Result += ")"; 1940 if (Param->getIdentifier()) 1941 Result += Param->getIdentifier()->getName(); 1942 } 1943 1944 return Result; 1945 } 1946 1947 // We have the function prototype behind the block pointer type, as it was 1948 // written in the source. 1949 std::string Result; 1950 QualType ResultType = Block->getTypePtr()->getResultType(); 1951 if (!ResultType->isVoidType()) 1952 ResultType.getAsStringInternal(Result, Context.PrintingPolicy); 1953 1954 Result = '^' + Result; 1955 if (!BlockProto || Block->getNumArgs() == 0) { 1956 if (BlockProto && BlockProto->getTypePtr()->isVariadic()) 1957 Result += "(...)"; 1958 else 1959 Result += "(void)"; 1960 } else { 1961 Result += "("; 1962 for (unsigned I = 0, N = Block->getNumArgs(); I != N; ++I) { 1963 if (I) 1964 Result += ", "; 1965 Result += FormatFunctionParameter(Context, Block->getArg(I)); 1966 1967 if (I == N - 1 && BlockProto->getTypePtr()->isVariadic()) 1968 Result += ", ..."; 1969 } 1970 Result += ")"; 1971 } 1972 1973 if (Param->getIdentifier()) 1974 Result += Param->getIdentifier()->getName(); 1975 1976 return Result; 1977} 1978 1979/// \brief Add function parameter chunks to the given code completion string. 1980static void AddFunctionParameterChunks(ASTContext &Context, 1981 FunctionDecl *Function, 1982 CodeCompletionBuilder &Result, 1983 unsigned Start = 0, 1984 bool InOptional = false) { 1985 typedef CodeCompletionString::Chunk Chunk; 1986 bool FirstParameter = true; 1987 1988 for (unsigned P = Start, N = Function->getNumParams(); P != N; ++P) { 1989 ParmVarDecl *Param = Function->getParamDecl(P); 1990 1991 if (Param->hasDefaultArg() && !InOptional) { 1992 // When we see an optional default argument, put that argument and 1993 // the remaining default arguments into a new, optional string. 1994 CodeCompletionBuilder Opt(Result.getAllocator()); 1995 if (!FirstParameter) 1996 Opt.AddChunk(Chunk(CodeCompletionString::CK_Comma)); 1997 AddFunctionParameterChunks(Context, Function, Opt, P, true); 1998 Result.AddOptionalChunk(Opt.TakeString()); 1999 break; 2000 } 2001 2002 if (FirstParameter) 2003 FirstParameter = false; 2004 else 2005 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma)); 2006 2007 InOptional = false; 2008 2009 // Format the placeholder string. 2010 std::string PlaceholderStr = FormatFunctionParameter(Context, Param); 2011 2012 if (Function->isVariadic() && P == N - 1) 2013 PlaceholderStr += ", ..."; 2014 2015 // Add the placeholder string. 2016 Result.AddPlaceholderChunk( 2017 Result.getAllocator().CopyString(PlaceholderStr)); 2018 } 2019 2020 if (const FunctionProtoType *Proto 2021 = Function->getType()->getAs<FunctionProtoType>()) 2022 if (Proto->isVariadic()) { 2023 if (Proto->getNumArgs() == 0) 2024 Result.AddPlaceholderChunk("..."); 2025 2026 MaybeAddSentinel(Context, Function, Result); 2027 } 2028} 2029 2030/// \brief Add template parameter chunks to the given code completion string. 2031static void AddTemplateParameterChunks(ASTContext &Context, 2032 TemplateDecl *Template, 2033 CodeCompletionBuilder &Result, 2034 unsigned MaxParameters = 0, 2035 unsigned Start = 0, 2036 bool InDefaultArg = false) { 2037 typedef CodeCompletionString::Chunk Chunk; 2038 bool FirstParameter = true; 2039 2040 TemplateParameterList *Params = Template->getTemplateParameters(); 2041 TemplateParameterList::iterator PEnd = Params->end(); 2042 if (MaxParameters) 2043 PEnd = Params->begin() + MaxParameters; 2044 for (TemplateParameterList::iterator P = Params->begin() + Start; 2045 P != PEnd; ++P) { 2046 bool HasDefaultArg = false; 2047 std::string PlaceholderStr; 2048 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) { 2049 if (TTP->wasDeclaredWithTypename()) 2050 PlaceholderStr = "typename"; 2051 else 2052 PlaceholderStr = "class"; 2053 2054 if (TTP->getIdentifier()) { 2055 PlaceholderStr += ' '; 2056 PlaceholderStr += TTP->getIdentifier()->getName(); 2057 } 2058 2059 HasDefaultArg = TTP->hasDefaultArgument(); 2060 } else if (NonTypeTemplateParmDecl *NTTP 2061 = dyn_cast<NonTypeTemplateParmDecl>(*P)) { 2062 if (NTTP->getIdentifier()) 2063 PlaceholderStr = NTTP->getIdentifier()->getName(); 2064 NTTP->getType().getAsStringInternal(PlaceholderStr, 2065 Context.PrintingPolicy); 2066 HasDefaultArg = NTTP->hasDefaultArgument(); 2067 } else { 2068 assert(isa<TemplateTemplateParmDecl>(*P)); 2069 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P); 2070 2071 // Since putting the template argument list into the placeholder would 2072 // be very, very long, we just use an abbreviation. 2073 PlaceholderStr = "template<...> class"; 2074 if (TTP->getIdentifier()) { 2075 PlaceholderStr += ' '; 2076 PlaceholderStr += TTP->getIdentifier()->getName(); 2077 } 2078 2079 HasDefaultArg = TTP->hasDefaultArgument(); 2080 } 2081 2082 if (HasDefaultArg && !InDefaultArg) { 2083 // When we see an optional default argument, put that argument and 2084 // the remaining default arguments into a new, optional string. 2085 CodeCompletionBuilder Opt(Result.getAllocator()); 2086 if (!FirstParameter) 2087 Opt.AddChunk(Chunk(CodeCompletionString::CK_Comma)); 2088 AddTemplateParameterChunks(Context, Template, Opt, MaxParameters, 2089 P - Params->begin(), true); 2090 Result.AddOptionalChunk(Opt.TakeString()); 2091 break; 2092 } 2093 2094 InDefaultArg = false; 2095 2096 if (FirstParameter) 2097 FirstParameter = false; 2098 else 2099 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma)); 2100 2101 // Add the placeholder string. 2102 Result.AddPlaceholderChunk( 2103 Result.getAllocator().CopyString(PlaceholderStr)); 2104 } 2105} 2106 2107/// \brief Add a qualifier to the given code-completion string, if the 2108/// provided nested-name-specifier is non-NULL. 2109static void 2110AddQualifierToCompletionString(CodeCompletionBuilder &Result, 2111 NestedNameSpecifier *Qualifier, 2112 bool QualifierIsInformative, 2113 ASTContext &Context) { 2114 if (!Qualifier) 2115 return; 2116 2117 std::string PrintedNNS; 2118 { 2119 llvm::raw_string_ostream OS(PrintedNNS); 2120 Qualifier->print(OS, Context.PrintingPolicy); 2121 } 2122 if (QualifierIsInformative) 2123 Result.AddInformativeChunk(Result.getAllocator().CopyString(PrintedNNS)); 2124 else 2125 Result.AddTextChunk(Result.getAllocator().CopyString(PrintedNNS)); 2126} 2127 2128static void 2129AddFunctionTypeQualsToCompletionString(CodeCompletionBuilder &Result, 2130 FunctionDecl *Function) { 2131 const FunctionProtoType *Proto 2132 = Function->getType()->getAs<FunctionProtoType>(); 2133 if (!Proto || !Proto->getTypeQuals()) 2134 return; 2135 2136 // FIXME: Add ref-qualifier! 2137 2138 // Handle single qualifiers without copying 2139 if (Proto->getTypeQuals() == Qualifiers::Const) { 2140 Result.AddInformativeChunk(" const"); 2141 return; 2142 } 2143 2144 if (Proto->getTypeQuals() == Qualifiers::Volatile) { 2145 Result.AddInformativeChunk(" volatile"); 2146 return; 2147 } 2148 2149 if (Proto->getTypeQuals() == Qualifiers::Restrict) { 2150 Result.AddInformativeChunk(" restrict"); 2151 return; 2152 } 2153 2154 // Handle multiple qualifiers. 2155 std::string QualsStr; 2156 if (Proto->getTypeQuals() & Qualifiers::Const) 2157 QualsStr += " const"; 2158 if (Proto->getTypeQuals() & Qualifiers::Volatile) 2159 QualsStr += " volatile"; 2160 if (Proto->getTypeQuals() & Qualifiers::Restrict) 2161 QualsStr += " restrict"; 2162 Result.AddInformativeChunk(Result.getAllocator().CopyString(QualsStr)); 2163} 2164 2165/// \brief Add the name of the given declaration 2166static void AddTypedNameChunk(ASTContext &Context, NamedDecl *ND, 2167 CodeCompletionBuilder &Result) { 2168 typedef CodeCompletionString::Chunk Chunk; 2169 2170 DeclarationName Name = ND->getDeclName(); 2171 if (!Name) 2172 return; 2173 2174 switch (Name.getNameKind()) { 2175 case DeclarationName::CXXOperatorName: { 2176 const char *OperatorName = 0; 2177 switch (Name.getCXXOverloadedOperator()) { 2178 case OO_None: 2179 case OO_Conditional: 2180 case NUM_OVERLOADED_OPERATORS: 2181 OperatorName = "operator"; 2182 break; 2183 2184#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 2185 case OO_##Name: OperatorName = "operator" Spelling; break; 2186#define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly) 2187#include "clang/Basic/OperatorKinds.def" 2188 2189 case OO_New: OperatorName = "operator new"; break; 2190 case OO_Delete: OperatorName = "operator delete"; break; 2191 case OO_Array_New: OperatorName = "operator new[]"; break; 2192 case OO_Array_Delete: OperatorName = "operator delete[]"; break; 2193 case OO_Call: OperatorName = "operator()"; break; 2194 case OO_Subscript: OperatorName = "operator[]"; break; 2195 } 2196 Result.AddTypedTextChunk(OperatorName); 2197 break; 2198 } 2199 2200 case DeclarationName::Identifier: 2201 case DeclarationName::CXXConversionFunctionName: 2202 case DeclarationName::CXXDestructorName: 2203 case DeclarationName::CXXLiteralOperatorName: 2204 Result.AddTypedTextChunk( 2205 Result.getAllocator().CopyString(ND->getNameAsString())); 2206 break; 2207 2208 case DeclarationName::CXXUsingDirective: 2209 case DeclarationName::ObjCZeroArgSelector: 2210 case DeclarationName::ObjCOneArgSelector: 2211 case DeclarationName::ObjCMultiArgSelector: 2212 break; 2213 2214 case DeclarationName::CXXConstructorName: { 2215 CXXRecordDecl *Record = 0; 2216 QualType Ty = Name.getCXXNameType(); 2217 if (const RecordType *RecordTy = Ty->getAs<RecordType>()) 2218 Record = cast<CXXRecordDecl>(RecordTy->getDecl()); 2219 else if (const InjectedClassNameType *InjectedTy 2220 = Ty->getAs<InjectedClassNameType>()) 2221 Record = InjectedTy->getDecl(); 2222 else { 2223 Result.AddTypedTextChunk( 2224 Result.getAllocator().CopyString(ND->getNameAsString())); 2225 break; 2226 } 2227 2228 Result.AddTypedTextChunk( 2229 Result.getAllocator().CopyString(Record->getNameAsString())); 2230 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) { 2231 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftAngle)); 2232 AddTemplateParameterChunks(Context, Template, Result); 2233 Result.AddChunk(Chunk(CodeCompletionString::CK_RightAngle)); 2234 } 2235 break; 2236 } 2237 } 2238} 2239 2240/// \brief If possible, create a new code completion string for the given 2241/// result. 2242/// 2243/// \returns Either a new, heap-allocated code completion string describing 2244/// how to use this result, or NULL to indicate that the string or name of the 2245/// result is all that is needed. 2246CodeCompletionString * 2247CodeCompletionResult::CreateCodeCompletionString(Sema &S, 2248 CodeCompletionAllocator &Allocator) { 2249 typedef CodeCompletionString::Chunk Chunk; 2250 CodeCompletionBuilder Result(Allocator, Priority, Availability); 2251 2252 if (Kind == RK_Pattern) { 2253 Pattern->Priority = Priority; 2254 Pattern->Availability = Availability; 2255 return Pattern; 2256 } 2257 2258 if (Kind == RK_Keyword) { 2259 Result.AddTypedTextChunk(Keyword); 2260 return Result.TakeString(); 2261 } 2262 2263 if (Kind == RK_Macro) { 2264 MacroInfo *MI = S.PP.getMacroInfo(Macro); 2265 assert(MI && "Not a macro?"); 2266 2267 Result.AddTypedTextChunk( 2268 Result.getAllocator().CopyString(Macro->getName())); 2269 2270 if (!MI->isFunctionLike()) 2271 return Result.TakeString(); 2272 2273 // Format a function-like macro with placeholders for the arguments. 2274 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen)); 2275 for (MacroInfo::arg_iterator A = MI->arg_begin(), AEnd = MI->arg_end(); 2276 A != AEnd; ++A) { 2277 if (A != MI->arg_begin()) 2278 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma)); 2279 2280 if (!MI->isVariadic() || A != AEnd - 1) { 2281 // Non-variadic argument. 2282 Result.AddPlaceholderChunk( 2283 Result.getAllocator().CopyString((*A)->getName())); 2284 continue; 2285 } 2286 2287 // Variadic argument; cope with the different between GNU and C99 2288 // variadic macros, providing a single placeholder for the rest of the 2289 // arguments. 2290 if ((*A)->isStr("__VA_ARGS__")) 2291 Result.AddPlaceholderChunk("..."); 2292 else { 2293 std::string Arg = (*A)->getName(); 2294 Arg += "..."; 2295 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg)); 2296 } 2297 } 2298 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen)); 2299 return Result.TakeString(); 2300 } 2301 2302 assert(Kind == RK_Declaration && "Missed a result kind?"); 2303 NamedDecl *ND = Declaration; 2304 2305 if (StartsNestedNameSpecifier) { 2306 Result.AddTypedTextChunk( 2307 Result.getAllocator().CopyString(ND->getNameAsString())); 2308 Result.AddTextChunk("::"); 2309 return Result.TakeString(); 2310 } 2311 2312 AddResultTypeChunk(S.Context, ND, Result); 2313 2314 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND)) { 2315 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative, 2316 S.Context); 2317 AddTypedNameChunk(S.Context, ND, Result); 2318 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen)); 2319 AddFunctionParameterChunks(S.Context, Function, Result); 2320 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen)); 2321 AddFunctionTypeQualsToCompletionString(Result, Function); 2322 return Result.TakeString(); 2323 } 2324 2325 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND)) { 2326 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative, 2327 S.Context); 2328 FunctionDecl *Function = FunTmpl->getTemplatedDecl(); 2329 AddTypedNameChunk(S.Context, Function, Result); 2330 2331 // Figure out which template parameters are deduced (or have default 2332 // arguments). 2333 llvm::SmallVector<bool, 16> Deduced; 2334 S.MarkDeducedTemplateParameters(FunTmpl, Deduced); 2335 unsigned LastDeducibleArgument; 2336 for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0; 2337 --LastDeducibleArgument) { 2338 if (!Deduced[LastDeducibleArgument - 1]) { 2339 // C++0x: Figure out if the template argument has a default. If so, 2340 // the user doesn't need to type this argument. 2341 // FIXME: We need to abstract template parameters better! 2342 bool HasDefaultArg = false; 2343 NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam( 2344 LastDeducibleArgument - 1); 2345 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) 2346 HasDefaultArg = TTP->hasDefaultArgument(); 2347 else if (NonTypeTemplateParmDecl *NTTP 2348 = dyn_cast<NonTypeTemplateParmDecl>(Param)) 2349 HasDefaultArg = NTTP->hasDefaultArgument(); 2350 else { 2351 assert(isa<TemplateTemplateParmDecl>(Param)); 2352 HasDefaultArg 2353 = cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument(); 2354 } 2355 2356 if (!HasDefaultArg) 2357 break; 2358 } 2359 } 2360 2361 if (LastDeducibleArgument) { 2362 // Some of the function template arguments cannot be deduced from a 2363 // function call, so we introduce an explicit template argument list 2364 // containing all of the arguments up to the first deducible argument. 2365 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftAngle)); 2366 AddTemplateParameterChunks(S.Context, FunTmpl, Result, 2367 LastDeducibleArgument); 2368 Result.AddChunk(Chunk(CodeCompletionString::CK_RightAngle)); 2369 } 2370 2371 // Add the function parameters 2372 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen)); 2373 AddFunctionParameterChunks(S.Context, Function, Result); 2374 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen)); 2375 AddFunctionTypeQualsToCompletionString(Result, Function); 2376 return Result.TakeString(); 2377 } 2378 2379 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(ND)) { 2380 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative, 2381 S.Context); 2382 Result.AddTypedTextChunk( 2383 Result.getAllocator().CopyString(Template->getNameAsString())); 2384 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftAngle)); 2385 AddTemplateParameterChunks(S.Context, Template, Result); 2386 Result.AddChunk(Chunk(CodeCompletionString::CK_RightAngle)); 2387 return Result.TakeString(); 2388 } 2389 2390 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND)) { 2391 Selector Sel = Method->getSelector(); 2392 if (Sel.isUnarySelector()) { 2393 Result.AddTypedTextChunk(Result.getAllocator().CopyString( 2394 Sel.getIdentifierInfoForSlot(0)->getName())); 2395 return Result.TakeString(); 2396 } 2397 2398 std::string SelName = Sel.getIdentifierInfoForSlot(0)->getName().str(); 2399 SelName += ':'; 2400 if (StartParameter == 0) 2401 Result.AddTypedTextChunk(Result.getAllocator().CopyString(SelName)); 2402 else { 2403 Result.AddInformativeChunk(Result.getAllocator().CopyString(SelName)); 2404 2405 // If there is only one parameter, and we're past it, add an empty 2406 // typed-text chunk since there is nothing to type. 2407 if (Method->param_size() == 1) 2408 Result.AddTypedTextChunk(""); 2409 } 2410 unsigned Idx = 0; 2411 for (ObjCMethodDecl::param_iterator P = Method->param_begin(), 2412 PEnd = Method->param_end(); 2413 P != PEnd; (void)++P, ++Idx) { 2414 if (Idx > 0) { 2415 std::string Keyword; 2416 if (Idx > StartParameter) 2417 Result.AddChunk(CodeCompletionString::CK_HorizontalSpace); 2418 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(Idx)) 2419 Keyword += II->getName().str(); 2420 Keyword += ":"; 2421 if (Idx < StartParameter || AllParametersAreInformative) 2422 Result.AddInformativeChunk(Result.getAllocator().CopyString(Keyword)); 2423 else 2424 Result.AddTypedTextChunk(Result.getAllocator().CopyString(Keyword)); 2425 } 2426 2427 // If we're before the starting parameter, skip the placeholder. 2428 if (Idx < StartParameter) 2429 continue; 2430 2431 std::string Arg; 2432 2433 if ((*P)->getType()->isBlockPointerType() && !DeclaringEntity) 2434 Arg = FormatFunctionParameter(S.Context, *P, true); 2435 else { 2436 (*P)->getType().getAsStringInternal(Arg, S.Context.PrintingPolicy); 2437 Arg = "(" + Arg + ")"; 2438 if (IdentifierInfo *II = (*P)->getIdentifier()) 2439 if (DeclaringEntity || AllParametersAreInformative) 2440 Arg += II->getName().str(); 2441 } 2442 2443 if (Method->isVariadic() && (P + 1) == PEnd) 2444 Arg += ", ..."; 2445 2446 if (DeclaringEntity) 2447 Result.AddTextChunk(Result.getAllocator().CopyString(Arg)); 2448 else if (AllParametersAreInformative) 2449 Result.AddInformativeChunk(Result.getAllocator().CopyString(Arg)); 2450 else 2451 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg)); 2452 } 2453 2454 if (Method->isVariadic()) { 2455 if (Method->param_size() == 0) { 2456 if (DeclaringEntity) 2457 Result.AddTextChunk(", ..."); 2458 else if (AllParametersAreInformative) 2459 Result.AddInformativeChunk(", ..."); 2460 else 2461 Result.AddPlaceholderChunk(", ..."); 2462 } 2463 2464 MaybeAddSentinel(S.Context, Method, Result); 2465 } 2466 2467 return Result.TakeString(); 2468 } 2469 2470 if (Qualifier) 2471 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative, 2472 S.Context); 2473 2474 Result.AddTypedTextChunk( 2475 Result.getAllocator().CopyString(ND->getNameAsString())); 2476 return Result.TakeString(); 2477} 2478 2479CodeCompletionString * 2480CodeCompleteConsumer::OverloadCandidate::CreateSignatureString( 2481 unsigned CurrentArg, 2482 Sema &S, 2483 CodeCompletionAllocator &Allocator) const { 2484 typedef CodeCompletionString::Chunk Chunk; 2485 2486 // FIXME: Set priority, availability appropriately. 2487 CodeCompletionBuilder Result(Allocator, 1, CXAvailability_Available); 2488 FunctionDecl *FDecl = getFunction(); 2489 AddResultTypeChunk(S.Context, FDecl, Result); 2490 const FunctionProtoType *Proto 2491 = dyn_cast<FunctionProtoType>(getFunctionType()); 2492 if (!FDecl && !Proto) { 2493 // Function without a prototype. Just give the return type and a 2494 // highlighted ellipsis. 2495 const FunctionType *FT = getFunctionType(); 2496 Result.AddTextChunk(GetCompletionTypeString(FT->getResultType(), 2497 S.Context, 2498 Result.getAllocator())); 2499 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen)); 2500 Result.AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "...")); 2501 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen)); 2502 return Result.TakeString(); 2503 } 2504 2505 if (FDecl) 2506 Result.AddTextChunk( 2507 Result.getAllocator().CopyString(FDecl->getNameAsString())); 2508 else 2509 Result.AddTextChunk( 2510 Result.getAllocator().CopyString( 2511 Proto->getResultType().getAsString(S.Context.PrintingPolicy))); 2512 2513 Result.AddChunk(Chunk(CodeCompletionString::CK_LeftParen)); 2514 unsigned NumParams = FDecl? FDecl->getNumParams() : Proto->getNumArgs(); 2515 for (unsigned I = 0; I != NumParams; ++I) { 2516 if (I) 2517 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma)); 2518 2519 std::string ArgString; 2520 QualType ArgType; 2521 2522 if (FDecl) { 2523 ArgString = FDecl->getParamDecl(I)->getNameAsString(); 2524 ArgType = FDecl->getParamDecl(I)->getOriginalType(); 2525 } else { 2526 ArgType = Proto->getArgType(I); 2527 } 2528 2529 ArgType.getAsStringInternal(ArgString, S.Context.PrintingPolicy); 2530 2531 if (I == CurrentArg) 2532 Result.AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, 2533 Result.getAllocator().CopyString(ArgString))); 2534 else 2535 Result.AddTextChunk(Result.getAllocator().CopyString(ArgString)); 2536 } 2537 2538 if (Proto && Proto->isVariadic()) { 2539 Result.AddChunk(Chunk(CodeCompletionString::CK_Comma)); 2540 if (CurrentArg < NumParams) 2541 Result.AddTextChunk("..."); 2542 else 2543 Result.AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "...")); 2544 } 2545 Result.AddChunk(Chunk(CodeCompletionString::CK_RightParen)); 2546 2547 return Result.TakeString(); 2548} 2549 2550unsigned clang::getMacroUsagePriority(llvm::StringRef MacroName, 2551 const LangOptions &LangOpts, 2552 bool PreferredTypeIsPointer) { 2553 unsigned Priority = CCP_Macro; 2554 2555 // Treat the "nil", "Nil" and "NULL" macros as null pointer constants. 2556 if (MacroName.equals("nil") || MacroName.equals("NULL") || 2557 MacroName.equals("Nil")) { 2558 Priority = CCP_Constant; 2559 if (PreferredTypeIsPointer) 2560 Priority = Priority / CCF_SimilarTypeMatch; 2561 } 2562 // Treat "YES", "NO", "true", and "false" as constants. 2563 else if (MacroName.equals("YES") || MacroName.equals("NO") || 2564 MacroName.equals("true") || MacroName.equals("false")) 2565 Priority = CCP_Constant; 2566 // Treat "bool" as a type. 2567 else if (MacroName.equals("bool")) 2568 Priority = CCP_Type + (LangOpts.ObjC1? CCD_bool_in_ObjC : 0); 2569 2570 2571 return Priority; 2572} 2573 2574CXCursorKind clang::getCursorKindForDecl(Decl *D) { 2575 if (!D) 2576 return CXCursor_UnexposedDecl; 2577 2578 switch (D->getKind()) { 2579 case Decl::Enum: return CXCursor_EnumDecl; 2580 case Decl::EnumConstant: return CXCursor_EnumConstantDecl; 2581 case Decl::Field: return CXCursor_FieldDecl; 2582 case Decl::Function: 2583 return CXCursor_FunctionDecl; 2584 case Decl::ObjCCategory: return CXCursor_ObjCCategoryDecl; 2585 case Decl::ObjCCategoryImpl: return CXCursor_ObjCCategoryImplDecl; 2586 case Decl::ObjCClass: 2587 // FIXME 2588 return CXCursor_UnexposedDecl; 2589 case Decl::ObjCForwardProtocol: 2590 // FIXME 2591 return CXCursor_UnexposedDecl; 2592 case Decl::ObjCImplementation: return CXCursor_ObjCImplementationDecl; 2593 case Decl::ObjCInterface: return CXCursor_ObjCInterfaceDecl; 2594 case Decl::ObjCIvar: return CXCursor_ObjCIvarDecl; 2595 case Decl::ObjCMethod: 2596 return cast<ObjCMethodDecl>(D)->isInstanceMethod() 2597 ? CXCursor_ObjCInstanceMethodDecl : CXCursor_ObjCClassMethodDecl; 2598 case Decl::CXXMethod: return CXCursor_CXXMethod; 2599 case Decl::CXXConstructor: return CXCursor_Constructor; 2600 case Decl::CXXDestructor: return CXCursor_Destructor; 2601 case Decl::CXXConversion: return CXCursor_ConversionFunction; 2602 case Decl::ObjCProperty: return CXCursor_ObjCPropertyDecl; 2603 case Decl::ObjCProtocol: return CXCursor_ObjCProtocolDecl; 2604 case Decl::ParmVar: return CXCursor_ParmDecl; 2605 case Decl::Typedef: return CXCursor_TypedefDecl; 2606 case Decl::Var: return CXCursor_VarDecl; 2607 case Decl::Namespace: return CXCursor_Namespace; 2608 case Decl::NamespaceAlias: return CXCursor_NamespaceAlias; 2609 case Decl::TemplateTypeParm: return CXCursor_TemplateTypeParameter; 2610 case Decl::NonTypeTemplateParm:return CXCursor_NonTypeTemplateParameter; 2611 case Decl::TemplateTemplateParm:return CXCursor_TemplateTemplateParameter; 2612 case Decl::FunctionTemplate: return CXCursor_FunctionTemplate; 2613 case Decl::ClassTemplate: return CXCursor_ClassTemplate; 2614 case Decl::ClassTemplatePartialSpecialization: 2615 return CXCursor_ClassTemplatePartialSpecialization; 2616 case Decl::UsingDirective: return CXCursor_UsingDirective; 2617 2618 case Decl::Using: 2619 case Decl::UnresolvedUsingValue: 2620 case Decl::UnresolvedUsingTypename: 2621 return CXCursor_UsingDeclaration; 2622 2623 default: 2624 if (TagDecl *TD = dyn_cast<TagDecl>(D)) { 2625 switch (TD->getTagKind()) { 2626 case TTK_Struct: return CXCursor_StructDecl; 2627 case TTK_Class: return CXCursor_ClassDecl; 2628 case TTK_Union: return CXCursor_UnionDecl; 2629 case TTK_Enum: return CXCursor_EnumDecl; 2630 } 2631 } 2632 } 2633 2634 return CXCursor_UnexposedDecl; 2635} 2636 2637static void AddMacroResults(Preprocessor &PP, ResultBuilder &Results, 2638 bool TargetTypeIsPointer = false) { 2639 typedef CodeCompletionResult Result; 2640 2641 Results.EnterNewScope(); 2642 2643 for (Preprocessor::macro_iterator M = PP.macro_begin(), 2644 MEnd = PP.macro_end(); 2645 M != MEnd; ++M) { 2646 Results.AddResult(Result(M->first, 2647 getMacroUsagePriority(M->first->getName(), 2648 PP.getLangOptions(), 2649 TargetTypeIsPointer))); 2650 } 2651 2652 Results.ExitScope(); 2653 2654} 2655 2656static void AddPrettyFunctionResults(const LangOptions &LangOpts, 2657 ResultBuilder &Results) { 2658 typedef CodeCompletionResult Result; 2659 2660 Results.EnterNewScope(); 2661 2662 Results.AddResult(Result("__PRETTY_FUNCTION__", CCP_Constant)); 2663 Results.AddResult(Result("__FUNCTION__", CCP_Constant)); 2664 if (LangOpts.C99 || LangOpts.CPlusPlus0x) 2665 Results.AddResult(Result("__func__", CCP_Constant)); 2666 Results.ExitScope(); 2667} 2668 2669static void HandleCodeCompleteResults(Sema *S, 2670 CodeCompleteConsumer *CodeCompleter, 2671 CodeCompletionContext Context, 2672 CodeCompletionResult *Results, 2673 unsigned NumResults) { 2674 if (CodeCompleter) 2675 CodeCompleter->ProcessCodeCompleteResults(*S, Context, Results, NumResults); 2676} 2677 2678static enum CodeCompletionContext::Kind mapCodeCompletionContext(Sema &S, 2679 Sema::ParserCompletionContext PCC) { 2680 switch (PCC) { 2681 case Sema::PCC_Namespace: 2682 return CodeCompletionContext::CCC_TopLevel; 2683 2684 case Sema::PCC_Class: 2685 return CodeCompletionContext::CCC_ClassStructUnion; 2686 2687 case Sema::PCC_ObjCInterface: 2688 return CodeCompletionContext::CCC_ObjCInterface; 2689 2690 case Sema::PCC_ObjCImplementation: 2691 return CodeCompletionContext::CCC_ObjCImplementation; 2692 2693 case Sema::PCC_ObjCInstanceVariableList: 2694 return CodeCompletionContext::CCC_ObjCIvarList; 2695 2696 case Sema::PCC_Template: 2697 case Sema::PCC_MemberTemplate: 2698 if (S.CurContext->isFileContext()) 2699 return CodeCompletionContext::CCC_TopLevel; 2700 else if (S.CurContext->isRecord()) 2701 return CodeCompletionContext::CCC_ClassStructUnion; 2702 else 2703 return CodeCompletionContext::CCC_Other; 2704 2705 case Sema::PCC_RecoveryInFunction: 2706 return CodeCompletionContext::CCC_Recovery; 2707 2708 case Sema::PCC_ForInit: 2709 if (S.getLangOptions().CPlusPlus || S.getLangOptions().C99 || 2710 S.getLangOptions().ObjC1) 2711 return CodeCompletionContext::CCC_ParenthesizedExpression; 2712 else 2713 return CodeCompletionContext::CCC_Expression; 2714 2715 case Sema::PCC_Expression: 2716 case Sema::PCC_Condition: 2717 return CodeCompletionContext::CCC_Expression; 2718 2719 case Sema::PCC_Statement: 2720 return CodeCompletionContext::CCC_Statement; 2721 2722 case Sema::PCC_Type: 2723 return CodeCompletionContext::CCC_Type; 2724 2725 case Sema::PCC_ParenthesizedExpression: 2726 return CodeCompletionContext::CCC_ParenthesizedExpression; 2727 2728 case Sema::PCC_LocalDeclarationSpecifiers: 2729 return CodeCompletionContext::CCC_Type; 2730 } 2731 2732 return CodeCompletionContext::CCC_Other; 2733} 2734 2735/// \brief If we're in a C++ virtual member function, add completion results 2736/// that invoke the functions we override, since it's common to invoke the 2737/// overridden function as well as adding new functionality. 2738/// 2739/// \param S The semantic analysis object for which we are generating results. 2740/// 2741/// \param InContext This context in which the nested-name-specifier preceding 2742/// the code-completion point 2743static void MaybeAddOverrideCalls(Sema &S, DeclContext *InContext, 2744 ResultBuilder &Results) { 2745 // Look through blocks. 2746 DeclContext *CurContext = S.CurContext; 2747 while (isa<BlockDecl>(CurContext)) 2748 CurContext = CurContext->getParent(); 2749 2750 2751 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(CurContext); 2752 if (!Method || !Method->isVirtual()) 2753 return; 2754 2755 // We need to have names for all of the parameters, if we're going to 2756 // generate a forwarding call. 2757 for (CXXMethodDecl::param_iterator P = Method->param_begin(), 2758 PEnd = Method->param_end(); 2759 P != PEnd; 2760 ++P) { 2761 if (!(*P)->getDeclName()) 2762 return; 2763 } 2764 2765 for (CXXMethodDecl::method_iterator M = Method->begin_overridden_methods(), 2766 MEnd = Method->end_overridden_methods(); 2767 M != MEnd; ++M) { 2768 CodeCompletionBuilder Builder(Results.getAllocator()); 2769 CXXMethodDecl *Overridden = const_cast<CXXMethodDecl *>(*M); 2770 if (Overridden->getCanonicalDecl() == Method->getCanonicalDecl()) 2771 continue; 2772 2773 // If we need a nested-name-specifier, add one now. 2774 if (!InContext) { 2775 NestedNameSpecifier *NNS 2776 = getRequiredQualification(S.Context, CurContext, 2777 Overridden->getDeclContext()); 2778 if (NNS) { 2779 std::string Str; 2780 llvm::raw_string_ostream OS(Str); 2781 NNS->print(OS, S.Context.PrintingPolicy); 2782 Builder.AddTextChunk(Results.getAllocator().CopyString(OS.str())); 2783 } 2784 } else if (!InContext->Equals(Overridden->getDeclContext())) 2785 continue; 2786 2787 Builder.AddTypedTextChunk(Results.getAllocator().CopyString( 2788 Overridden->getNameAsString())); 2789 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 2790 bool FirstParam = true; 2791 for (CXXMethodDecl::param_iterator P = Method->param_begin(), 2792 PEnd = Method->param_end(); 2793 P != PEnd; ++P) { 2794 if (FirstParam) 2795 FirstParam = false; 2796 else 2797 Builder.AddChunk(CodeCompletionString::CK_Comma); 2798 2799 Builder.AddPlaceholderChunk(Results.getAllocator().CopyString( 2800 (*P)->getIdentifier()->getName())); 2801 } 2802 Builder.AddChunk(CodeCompletionString::CK_RightParen); 2803 Results.AddResult(CodeCompletionResult(Builder.TakeString(), 2804 CCP_SuperCompletion, 2805 CXCursor_CXXMethod)); 2806 Results.Ignore(Overridden); 2807 } 2808} 2809 2810void Sema::CodeCompleteOrdinaryName(Scope *S, 2811 ParserCompletionContext CompletionContext) { 2812 typedef CodeCompletionResult Result; 2813 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 2814 mapCodeCompletionContext(*this, CompletionContext)); 2815 Results.EnterNewScope(); 2816 2817 // Determine how to filter results, e.g., so that the names of 2818 // values (functions, enumerators, function templates, etc.) are 2819 // only allowed where we can have an expression. 2820 switch (CompletionContext) { 2821 case PCC_Namespace: 2822 case PCC_Class: 2823 case PCC_ObjCInterface: 2824 case PCC_ObjCImplementation: 2825 case PCC_ObjCInstanceVariableList: 2826 case PCC_Template: 2827 case PCC_MemberTemplate: 2828 case PCC_Type: 2829 case PCC_LocalDeclarationSpecifiers: 2830 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName); 2831 break; 2832 2833 case PCC_Statement: 2834 case PCC_ParenthesizedExpression: 2835 case PCC_Expression: 2836 case PCC_ForInit: 2837 case PCC_Condition: 2838 if (WantTypesInContext(CompletionContext, getLangOptions())) 2839 Results.setFilter(&ResultBuilder::IsOrdinaryName); 2840 else 2841 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName); 2842 2843 if (getLangOptions().CPlusPlus) 2844 MaybeAddOverrideCalls(*this, /*InContext=*/0, Results); 2845 break; 2846 2847 case PCC_RecoveryInFunction: 2848 // Unfiltered 2849 break; 2850 } 2851 2852 // If we are in a C++ non-static member function, check the qualifiers on 2853 // the member function to filter/prioritize the results list. 2854 if (CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext)) 2855 if (CurMethod->isInstance()) 2856 Results.setObjectTypeQualifiers( 2857 Qualifiers::fromCVRMask(CurMethod->getTypeQualifiers())); 2858 2859 CodeCompletionDeclConsumer Consumer(Results, CurContext); 2860 LookupVisibleDecls(S, LookupOrdinaryName, Consumer, 2861 CodeCompleter->includeGlobals()); 2862 2863 AddOrdinaryNameResults(CompletionContext, S, *this, Results); 2864 Results.ExitScope(); 2865 2866 switch (CompletionContext) { 2867 case PCC_ParenthesizedExpression: 2868 case PCC_Expression: 2869 case PCC_Statement: 2870 case PCC_RecoveryInFunction: 2871 if (S->getFnParent()) 2872 AddPrettyFunctionResults(PP.getLangOptions(), Results); 2873 break; 2874 2875 case PCC_Namespace: 2876 case PCC_Class: 2877 case PCC_ObjCInterface: 2878 case PCC_ObjCImplementation: 2879 case PCC_ObjCInstanceVariableList: 2880 case PCC_Template: 2881 case PCC_MemberTemplate: 2882 case PCC_ForInit: 2883 case PCC_Condition: 2884 case PCC_Type: 2885 case PCC_LocalDeclarationSpecifiers: 2886 break; 2887 } 2888 2889 if (CodeCompleter->includeMacros()) 2890 AddMacroResults(PP, Results); 2891 2892 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 2893 Results.data(),Results.size()); 2894} 2895 2896static void AddClassMessageCompletions(Sema &SemaRef, Scope *S, 2897 ParsedType Receiver, 2898 IdentifierInfo **SelIdents, 2899 unsigned NumSelIdents, 2900 bool AtArgumentExpression, 2901 bool IsSuper, 2902 ResultBuilder &Results); 2903 2904void Sema::CodeCompleteDeclSpec(Scope *S, DeclSpec &DS, 2905 bool AllowNonIdentifiers, 2906 bool AllowNestedNameSpecifiers) { 2907 typedef CodeCompletionResult Result; 2908 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 2909 AllowNestedNameSpecifiers 2910 ? CodeCompletionContext::CCC_PotentiallyQualifiedName 2911 : CodeCompletionContext::CCC_Name); 2912 Results.EnterNewScope(); 2913 2914 // Type qualifiers can come after names. 2915 Results.AddResult(Result("const")); 2916 Results.AddResult(Result("volatile")); 2917 if (getLangOptions().C99) 2918 Results.AddResult(Result("restrict")); 2919 2920 if (getLangOptions().CPlusPlus) { 2921 if (AllowNonIdentifiers) { 2922 Results.AddResult(Result("operator")); 2923 } 2924 2925 // Add nested-name-specifiers. 2926 if (AllowNestedNameSpecifiers) { 2927 Results.allowNestedNameSpecifiers(); 2928 Results.setFilter(&ResultBuilder::IsImpossibleToSatisfy); 2929 CodeCompletionDeclConsumer Consumer(Results, CurContext); 2930 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer, 2931 CodeCompleter->includeGlobals()); 2932 Results.setFilter(0); 2933 } 2934 } 2935 Results.ExitScope(); 2936 2937 // If we're in a context where we might have an expression (rather than a 2938 // declaration), and what we've seen so far is an Objective-C type that could 2939 // be a receiver of a class message, this may be a class message send with 2940 // the initial opening bracket '[' missing. Add appropriate completions. 2941 if (AllowNonIdentifiers && !AllowNestedNameSpecifiers && 2942 DS.getTypeSpecType() == DeclSpec::TST_typename && 2943 DS.getStorageClassSpecAsWritten() == DeclSpec::SCS_unspecified && 2944 !DS.isThreadSpecified() && !DS.isExternInLinkageSpec() && 2945 DS.getTypeSpecComplex() == DeclSpec::TSC_unspecified && 2946 DS.getTypeSpecSign() == DeclSpec::TSS_unspecified && 2947 DS.getTypeQualifiers() == 0 && 2948 S && 2949 (S->getFlags() & Scope::DeclScope) != 0 && 2950 (S->getFlags() & (Scope::ClassScope | Scope::TemplateParamScope | 2951 Scope::FunctionPrototypeScope | 2952 Scope::AtCatchScope)) == 0) { 2953 ParsedType T = DS.getRepAsType(); 2954 if (!T.get().isNull() && T.get()->isObjCObjectOrInterfaceType()) 2955 AddClassMessageCompletions(*this, S, T, 0, 0, false, false, Results); 2956 } 2957 2958 // Note that we intentionally suppress macro results here, since we do not 2959 // encourage using macros to produce the names of entities. 2960 2961 HandleCodeCompleteResults(this, CodeCompleter, 2962 Results.getCompletionContext(), 2963 Results.data(), Results.size()); 2964} 2965 2966struct Sema::CodeCompleteExpressionData { 2967 CodeCompleteExpressionData(QualType PreferredType = QualType()) 2968 : PreferredType(PreferredType), IntegralConstantExpression(false), 2969 ObjCCollection(false) { } 2970 2971 QualType PreferredType; 2972 bool IntegralConstantExpression; 2973 bool ObjCCollection; 2974 llvm::SmallVector<Decl *, 4> IgnoreDecls; 2975}; 2976 2977/// \brief Perform code-completion in an expression context when we know what 2978/// type we're looking for. 2979/// 2980/// \param IntegralConstantExpression Only permit integral constant 2981/// expressions. 2982void Sema::CodeCompleteExpression(Scope *S, 2983 const CodeCompleteExpressionData &Data) { 2984 typedef CodeCompletionResult Result; 2985 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 2986 CodeCompletionContext::CCC_Expression); 2987 if (Data.ObjCCollection) 2988 Results.setFilter(&ResultBuilder::IsObjCCollection); 2989 else if (Data.IntegralConstantExpression) 2990 Results.setFilter(&ResultBuilder::IsIntegralConstantValue); 2991 else if (WantTypesInContext(PCC_Expression, getLangOptions())) 2992 Results.setFilter(&ResultBuilder::IsOrdinaryName); 2993 else 2994 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName); 2995 2996 if (!Data.PreferredType.isNull()) 2997 Results.setPreferredType(Data.PreferredType.getNonReferenceType()); 2998 2999 // Ignore any declarations that we were told that we don't care about. 3000 for (unsigned I = 0, N = Data.IgnoreDecls.size(); I != N; ++I) 3001 Results.Ignore(Data.IgnoreDecls[I]); 3002 3003 CodeCompletionDeclConsumer Consumer(Results, CurContext); 3004 LookupVisibleDecls(S, LookupOrdinaryName, Consumer, 3005 CodeCompleter->includeGlobals()); 3006 3007 Results.EnterNewScope(); 3008 AddOrdinaryNameResults(PCC_Expression, S, *this, Results); 3009 Results.ExitScope(); 3010 3011 bool PreferredTypeIsPointer = false; 3012 if (!Data.PreferredType.isNull()) 3013 PreferredTypeIsPointer = Data.PreferredType->isAnyPointerType() 3014 || Data.PreferredType->isMemberPointerType() 3015 || Data.PreferredType->isBlockPointerType(); 3016 3017 if (S->getFnParent() && 3018 !Data.ObjCCollection && 3019 !Data.IntegralConstantExpression) 3020 AddPrettyFunctionResults(PP.getLangOptions(), Results); 3021 3022 if (CodeCompleter->includeMacros()) 3023 AddMacroResults(PP, Results, PreferredTypeIsPointer); 3024 HandleCodeCompleteResults(this, CodeCompleter, 3025 CodeCompletionContext(CodeCompletionContext::CCC_Expression, 3026 Data.PreferredType), 3027 Results.data(),Results.size()); 3028} 3029 3030void Sema::CodeCompletePostfixExpression(Scope *S, ExprResult E) { 3031 if (E.isInvalid()) 3032 CodeCompleteOrdinaryName(S, PCC_RecoveryInFunction); 3033 else if (getLangOptions().ObjC1) 3034 CodeCompleteObjCInstanceMessage(S, E.take(), 0, 0, false); 3035} 3036 3037/// \brief The set of properties that have already been added, referenced by 3038/// property name. 3039typedef llvm::SmallPtrSet<IdentifierInfo*, 16> AddedPropertiesSet; 3040 3041static void AddObjCProperties(ObjCContainerDecl *Container, 3042 bool AllowCategories, 3043 DeclContext *CurContext, 3044 AddedPropertiesSet &AddedProperties, 3045 ResultBuilder &Results) { 3046 typedef CodeCompletionResult Result; 3047 3048 // Add properties in this container. 3049 for (ObjCContainerDecl::prop_iterator P = Container->prop_begin(), 3050 PEnd = Container->prop_end(); 3051 P != PEnd; 3052 ++P) { 3053 if (AddedProperties.insert(P->getIdentifier())) 3054 Results.MaybeAddResult(Result(*P, 0), CurContext); 3055 } 3056 3057 // Add properties in referenced protocols. 3058 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) { 3059 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(), 3060 PEnd = Protocol->protocol_end(); 3061 P != PEnd; ++P) 3062 AddObjCProperties(*P, AllowCategories, CurContext, AddedProperties, 3063 Results); 3064 } else if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)){ 3065 if (AllowCategories) { 3066 // Look through categories. 3067 for (ObjCCategoryDecl *Category = IFace->getCategoryList(); 3068 Category; Category = Category->getNextClassCategory()) 3069 AddObjCProperties(Category, AllowCategories, CurContext, 3070 AddedProperties, Results); 3071 } 3072 3073 // Look through protocols. 3074 for (ObjCInterfaceDecl::all_protocol_iterator 3075 I = IFace->all_referenced_protocol_begin(), 3076 E = IFace->all_referenced_protocol_end(); I != E; ++I) 3077 AddObjCProperties(*I, AllowCategories, CurContext, AddedProperties, 3078 Results); 3079 3080 // Look in the superclass. 3081 if (IFace->getSuperClass()) 3082 AddObjCProperties(IFace->getSuperClass(), AllowCategories, CurContext, 3083 AddedProperties, Results); 3084 } else if (const ObjCCategoryDecl *Category 3085 = dyn_cast<ObjCCategoryDecl>(Container)) { 3086 // Look through protocols. 3087 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(), 3088 PEnd = Category->protocol_end(); 3089 P != PEnd; ++P) 3090 AddObjCProperties(*P, AllowCategories, CurContext, AddedProperties, 3091 Results); 3092 } 3093} 3094 3095void Sema::CodeCompleteMemberReferenceExpr(Scope *S, ExprTy *BaseE, 3096 SourceLocation OpLoc, 3097 bool IsArrow) { 3098 if (!BaseE || !CodeCompleter) 3099 return; 3100 3101 typedef CodeCompletionResult Result; 3102 3103 Expr *Base = static_cast<Expr *>(BaseE); 3104 QualType BaseType = Base->getType(); 3105 3106 if (IsArrow) { 3107 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) 3108 BaseType = Ptr->getPointeeType(); 3109 else if (BaseType->isObjCObjectPointerType()) 3110 /*Do nothing*/ ; 3111 else 3112 return; 3113 } 3114 3115 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 3116 CodeCompletionContext(CodeCompletionContext::CCC_MemberAccess, 3117 BaseType), 3118 &ResultBuilder::IsMember); 3119 Results.EnterNewScope(); 3120 if (const RecordType *Record = BaseType->getAs<RecordType>()) { 3121 // Indicate that we are performing a member access, and the cv-qualifiers 3122 // for the base object type. 3123 Results.setObjectTypeQualifiers(BaseType.getQualifiers()); 3124 3125 // Access to a C/C++ class, struct, or union. 3126 Results.allowNestedNameSpecifiers(); 3127 CodeCompletionDeclConsumer Consumer(Results, CurContext); 3128 LookupVisibleDecls(Record->getDecl(), LookupMemberName, Consumer, 3129 CodeCompleter->includeGlobals()); 3130 3131 if (getLangOptions().CPlusPlus) { 3132 if (!Results.empty()) { 3133 // The "template" keyword can follow "->" or "." in the grammar. 3134 // However, we only want to suggest the template keyword if something 3135 // is dependent. 3136 bool IsDependent = BaseType->isDependentType(); 3137 if (!IsDependent) { 3138 for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent()) 3139 if (DeclContext *Ctx = (DeclContext *)DepScope->getEntity()) { 3140 IsDependent = Ctx->isDependentContext(); 3141 break; 3142 } 3143 } 3144 3145 if (IsDependent) 3146 Results.AddResult(Result("template")); 3147 } 3148 } 3149 } else if (!IsArrow && BaseType->getAsObjCInterfacePointerType()) { 3150 // Objective-C property reference. 3151 AddedPropertiesSet AddedProperties; 3152 3153 // Add property results based on our interface. 3154 const ObjCObjectPointerType *ObjCPtr 3155 = BaseType->getAsObjCInterfacePointerType(); 3156 assert(ObjCPtr && "Non-NULL pointer guaranteed above!"); 3157 AddObjCProperties(ObjCPtr->getInterfaceDecl(), true, CurContext, 3158 AddedProperties, Results); 3159 3160 // Add properties from the protocols in a qualified interface. 3161 for (ObjCObjectPointerType::qual_iterator I = ObjCPtr->qual_begin(), 3162 E = ObjCPtr->qual_end(); 3163 I != E; ++I) 3164 AddObjCProperties(*I, true, CurContext, AddedProperties, Results); 3165 } else if ((IsArrow && BaseType->isObjCObjectPointerType()) || 3166 (!IsArrow && BaseType->isObjCObjectType())) { 3167 // Objective-C instance variable access. 3168 ObjCInterfaceDecl *Class = 0; 3169 if (const ObjCObjectPointerType *ObjCPtr 3170 = BaseType->getAs<ObjCObjectPointerType>()) 3171 Class = ObjCPtr->getInterfaceDecl(); 3172 else 3173 Class = BaseType->getAs<ObjCObjectType>()->getInterface(); 3174 3175 // Add all ivars from this class and its superclasses. 3176 if (Class) { 3177 CodeCompletionDeclConsumer Consumer(Results, CurContext); 3178 Results.setFilter(&ResultBuilder::IsObjCIvar); 3179 LookupVisibleDecls(Class, LookupMemberName, Consumer, 3180 CodeCompleter->includeGlobals()); 3181 } 3182 } 3183 3184 // FIXME: How do we cope with isa? 3185 3186 Results.ExitScope(); 3187 3188 // Hand off the results found for code completion. 3189 HandleCodeCompleteResults(this, CodeCompleter, 3190 Results.getCompletionContext(), 3191 Results.data(),Results.size()); 3192} 3193 3194void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) { 3195 if (!CodeCompleter) 3196 return; 3197 3198 typedef CodeCompletionResult Result; 3199 ResultBuilder::LookupFilter Filter = 0; 3200 enum CodeCompletionContext::Kind ContextKind 3201 = CodeCompletionContext::CCC_Other; 3202 switch ((DeclSpec::TST)TagSpec) { 3203 case DeclSpec::TST_enum: 3204 Filter = &ResultBuilder::IsEnum; 3205 ContextKind = CodeCompletionContext::CCC_EnumTag; 3206 break; 3207 3208 case DeclSpec::TST_union: 3209 Filter = &ResultBuilder::IsUnion; 3210 ContextKind = CodeCompletionContext::CCC_UnionTag; 3211 break; 3212 3213 case DeclSpec::TST_struct: 3214 case DeclSpec::TST_class: 3215 Filter = &ResultBuilder::IsClassOrStruct; 3216 ContextKind = CodeCompletionContext::CCC_ClassOrStructTag; 3217 break; 3218 3219 default: 3220 assert(false && "Unknown type specifier kind in CodeCompleteTag"); 3221 return; 3222 } 3223 3224 ResultBuilder Results(*this, CodeCompleter->getAllocator(), ContextKind); 3225 CodeCompletionDeclConsumer Consumer(Results, CurContext); 3226 3227 // First pass: look for tags. 3228 Results.setFilter(Filter); 3229 LookupVisibleDecls(S, LookupTagName, Consumer, 3230 CodeCompleter->includeGlobals()); 3231 3232 if (CodeCompleter->includeGlobals()) { 3233 // Second pass: look for nested name specifiers. 3234 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier); 3235 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer); 3236 } 3237 3238 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 3239 Results.data(),Results.size()); 3240} 3241 3242void Sema::CodeCompleteTypeQualifiers(DeclSpec &DS) { 3243 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 3244 CodeCompletionContext::CCC_TypeQualifiers); 3245 Results.EnterNewScope(); 3246 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_const)) 3247 Results.AddResult("const"); 3248 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_volatile)) 3249 Results.AddResult("volatile"); 3250 if (getLangOptions().C99 && 3251 !(DS.getTypeQualifiers() & DeclSpec::TQ_restrict)) 3252 Results.AddResult("restrict"); 3253 Results.ExitScope(); 3254 HandleCodeCompleteResults(this, CodeCompleter, 3255 Results.getCompletionContext(), 3256 Results.data(), Results.size()); 3257} 3258 3259void Sema::CodeCompleteCase(Scope *S) { 3260 if (getCurFunction()->SwitchStack.empty() || !CodeCompleter) 3261 return; 3262 3263 SwitchStmt *Switch = getCurFunction()->SwitchStack.back(); 3264 if (!Switch->getCond()->getType()->isEnumeralType()) { 3265 CodeCompleteExpressionData Data(Switch->getCond()->getType()); 3266 Data.IntegralConstantExpression = true; 3267 CodeCompleteExpression(S, Data); 3268 return; 3269 } 3270 3271 // Code-complete the cases of a switch statement over an enumeration type 3272 // by providing the list of 3273 EnumDecl *Enum = Switch->getCond()->getType()->getAs<EnumType>()->getDecl(); 3274 3275 // Determine which enumerators we have already seen in the switch statement. 3276 // FIXME: Ideally, we would also be able to look *past* the code-completion 3277 // token, in case we are code-completing in the middle of the switch and not 3278 // at the end. However, we aren't able to do so at the moment. 3279 llvm::SmallPtrSet<EnumConstantDecl *, 8> EnumeratorsSeen; 3280 NestedNameSpecifier *Qualifier = 0; 3281 for (SwitchCase *SC = Switch->getSwitchCaseList(); SC; 3282 SC = SC->getNextSwitchCase()) { 3283 CaseStmt *Case = dyn_cast<CaseStmt>(SC); 3284 if (!Case) 3285 continue; 3286 3287 Expr *CaseVal = Case->getLHS()->IgnoreParenCasts(); 3288 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseVal)) 3289 if (EnumConstantDecl *Enumerator 3290 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 3291 // We look into the AST of the case statement to determine which 3292 // enumerator was named. Alternatively, we could compute the value of 3293 // the integral constant expression, then compare it against the 3294 // values of each enumerator. However, value-based approach would not 3295 // work as well with C++ templates where enumerators declared within a 3296 // template are type- and value-dependent. 3297 EnumeratorsSeen.insert(Enumerator); 3298 3299 // If this is a qualified-id, keep track of the nested-name-specifier 3300 // so that we can reproduce it as part of code completion, e.g., 3301 // 3302 // switch (TagD.getKind()) { 3303 // case TagDecl::TK_enum: 3304 // break; 3305 // case XXX 3306 // 3307 // At the XXX, our completions are TagDecl::TK_union, 3308 // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union, 3309 // TK_struct, and TK_class. 3310 Qualifier = DRE->getQualifier(); 3311 } 3312 } 3313 3314 if (getLangOptions().CPlusPlus && !Qualifier && EnumeratorsSeen.empty()) { 3315 // If there are no prior enumerators in C++, check whether we have to 3316 // qualify the names of the enumerators that we suggest, because they 3317 // may not be visible in this scope. 3318 Qualifier = getRequiredQualification(Context, CurContext, 3319 Enum->getDeclContext()); 3320 3321 // FIXME: Scoped enums need to start with "EnumDecl" as the context! 3322 } 3323 3324 // Add any enumerators that have not yet been mentioned. 3325 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 3326 CodeCompletionContext::CCC_Expression); 3327 Results.EnterNewScope(); 3328 for (EnumDecl::enumerator_iterator E = Enum->enumerator_begin(), 3329 EEnd = Enum->enumerator_end(); 3330 E != EEnd; ++E) { 3331 if (EnumeratorsSeen.count(*E)) 3332 continue; 3333 3334 Results.AddResult(CodeCompletionResult(*E, Qualifier), 3335 CurContext, 0, false); 3336 } 3337 Results.ExitScope(); 3338 3339 if (CodeCompleter->includeMacros()) 3340 AddMacroResults(PP, Results); 3341 HandleCodeCompleteResults(this, CodeCompleter, 3342 CodeCompletionContext::CCC_Expression, 3343 Results.data(),Results.size()); 3344} 3345 3346namespace { 3347 struct IsBetterOverloadCandidate { 3348 Sema &S; 3349 SourceLocation Loc; 3350 3351 public: 3352 explicit IsBetterOverloadCandidate(Sema &S, SourceLocation Loc) 3353 : S(S), Loc(Loc) { } 3354 3355 bool 3356 operator()(const OverloadCandidate &X, const OverloadCandidate &Y) const { 3357 return isBetterOverloadCandidate(S, X, Y, Loc); 3358 } 3359 }; 3360} 3361 3362static bool anyNullArguments(Expr **Args, unsigned NumArgs) { 3363 if (NumArgs && !Args) 3364 return true; 3365 3366 for (unsigned I = 0; I != NumArgs; ++I) 3367 if (!Args[I]) 3368 return true; 3369 3370 return false; 3371} 3372 3373void Sema::CodeCompleteCall(Scope *S, ExprTy *FnIn, 3374 ExprTy **ArgsIn, unsigned NumArgs) { 3375 if (!CodeCompleter) 3376 return; 3377 3378 // When we're code-completing for a call, we fall back to ordinary 3379 // name code-completion whenever we can't produce specific 3380 // results. We may want to revisit this strategy in the future, 3381 // e.g., by merging the two kinds of results. 3382 3383 Expr *Fn = (Expr *)FnIn; 3384 Expr **Args = (Expr **)ArgsIn; 3385 3386 // Ignore type-dependent call expressions entirely. 3387 if (!Fn || Fn->isTypeDependent() || anyNullArguments(Args, NumArgs) || 3388 Expr::hasAnyTypeDependentArguments(Args, NumArgs)) { 3389 CodeCompleteOrdinaryName(S, PCC_Expression); 3390 return; 3391 } 3392 3393 // Build an overload candidate set based on the functions we find. 3394 SourceLocation Loc = Fn->getExprLoc(); 3395 OverloadCandidateSet CandidateSet(Loc); 3396 3397 // FIXME: What if we're calling something that isn't a function declaration? 3398 // FIXME: What if we're calling a pseudo-destructor? 3399 // FIXME: What if we're calling a member function? 3400 3401 typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate; 3402 llvm::SmallVector<ResultCandidate, 8> Results; 3403 3404 Expr *NakedFn = Fn->IgnoreParenCasts(); 3405 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(NakedFn)) 3406 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet, 3407 /*PartialOverloading=*/ true); 3408 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(NakedFn)) { 3409 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl()); 3410 if (FDecl) { 3411 if (!getLangOptions().CPlusPlus || 3412 !FDecl->getType()->getAs<FunctionProtoType>()) 3413 Results.push_back(ResultCandidate(FDecl)); 3414 else 3415 // FIXME: access? 3416 AddOverloadCandidate(FDecl, DeclAccessPair::make(FDecl, AS_none), 3417 Args, NumArgs, CandidateSet, 3418 false, /*PartialOverloading*/true); 3419 } 3420 } 3421 3422 QualType ParamType; 3423 3424 if (!CandidateSet.empty()) { 3425 // Sort the overload candidate set by placing the best overloads first. 3426 std::stable_sort(CandidateSet.begin(), CandidateSet.end(), 3427 IsBetterOverloadCandidate(*this, Loc)); 3428 3429 // Add the remaining viable overload candidates as code-completion reslults. 3430 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 3431 CandEnd = CandidateSet.end(); 3432 Cand != CandEnd; ++Cand) { 3433 if (Cand->Viable) 3434 Results.push_back(ResultCandidate(Cand->Function)); 3435 } 3436 3437 // From the viable candidates, try to determine the type of this parameter. 3438 for (unsigned I = 0, N = Results.size(); I != N; ++I) { 3439 if (const FunctionType *FType = Results[I].getFunctionType()) 3440 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FType)) 3441 if (NumArgs < Proto->getNumArgs()) { 3442 if (ParamType.isNull()) 3443 ParamType = Proto->getArgType(NumArgs); 3444 else if (!Context.hasSameUnqualifiedType( 3445 ParamType.getNonReferenceType(), 3446 Proto->getArgType(NumArgs).getNonReferenceType())) { 3447 ParamType = QualType(); 3448 break; 3449 } 3450 } 3451 } 3452 } else { 3453 // Try to determine the parameter type from the type of the expression 3454 // being called. 3455 QualType FunctionType = Fn->getType(); 3456 if (const PointerType *Ptr = FunctionType->getAs<PointerType>()) 3457 FunctionType = Ptr->getPointeeType(); 3458 else if (const BlockPointerType *BlockPtr 3459 = FunctionType->getAs<BlockPointerType>()) 3460 FunctionType = BlockPtr->getPointeeType(); 3461 else if (const MemberPointerType *MemPtr 3462 = FunctionType->getAs<MemberPointerType>()) 3463 FunctionType = MemPtr->getPointeeType(); 3464 3465 if (const FunctionProtoType *Proto 3466 = FunctionType->getAs<FunctionProtoType>()) { 3467 if (NumArgs < Proto->getNumArgs()) 3468 ParamType = Proto->getArgType(NumArgs); 3469 } 3470 } 3471 3472 if (ParamType.isNull()) 3473 CodeCompleteOrdinaryName(S, PCC_Expression); 3474 else 3475 CodeCompleteExpression(S, ParamType); 3476 3477 if (!Results.empty()) 3478 CodeCompleter->ProcessOverloadCandidates(*this, NumArgs, Results.data(), 3479 Results.size()); 3480} 3481 3482void Sema::CodeCompleteInitializer(Scope *S, Decl *D) { 3483 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D); 3484 if (!VD) { 3485 CodeCompleteOrdinaryName(S, PCC_Expression); 3486 return; 3487 } 3488 3489 CodeCompleteExpression(S, VD->getType()); 3490} 3491 3492void Sema::CodeCompleteReturn(Scope *S) { 3493 QualType ResultType; 3494 if (isa<BlockDecl>(CurContext)) { 3495 if (BlockScopeInfo *BSI = getCurBlock()) 3496 ResultType = BSI->ReturnType; 3497 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(CurContext)) 3498 ResultType = Function->getResultType(); 3499 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(CurContext)) 3500 ResultType = Method->getResultType(); 3501 3502 if (ResultType.isNull()) 3503 CodeCompleteOrdinaryName(S, PCC_Expression); 3504 else 3505 CodeCompleteExpression(S, ResultType); 3506} 3507 3508void Sema::CodeCompleteAssignmentRHS(Scope *S, ExprTy *LHS) { 3509 if (LHS) 3510 CodeCompleteExpression(S, static_cast<Expr *>(LHS)->getType()); 3511 else 3512 CodeCompleteOrdinaryName(S, PCC_Expression); 3513} 3514 3515void Sema::CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS, 3516 bool EnteringContext) { 3517 if (!SS.getScopeRep() || !CodeCompleter) 3518 return; 3519 3520 DeclContext *Ctx = computeDeclContext(SS, EnteringContext); 3521 if (!Ctx) 3522 return; 3523 3524 // Try to instantiate any non-dependent declaration contexts before 3525 // we look in them. 3526 if (!isDependentScopeSpecifier(SS) && RequireCompleteDeclContext(SS, Ctx)) 3527 return; 3528 3529 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 3530 CodeCompletionContext::CCC_Name); 3531 Results.EnterNewScope(); 3532 3533 // The "template" keyword can follow "::" in the grammar, but only 3534 // put it into the grammar if the nested-name-specifier is dependent. 3535 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep(); 3536 if (!Results.empty() && NNS->isDependent()) 3537 Results.AddResult("template"); 3538 3539 // Add calls to overridden virtual functions, if there are any. 3540 // 3541 // FIXME: This isn't wonderful, because we don't know whether we're actually 3542 // in a context that permits expressions. This is a general issue with 3543 // qualified-id completions. 3544 if (!EnteringContext) 3545 MaybeAddOverrideCalls(*this, Ctx, Results); 3546 Results.ExitScope(); 3547 3548 CodeCompletionDeclConsumer Consumer(Results, CurContext); 3549 LookupVisibleDecls(Ctx, LookupOrdinaryName, Consumer); 3550 3551 HandleCodeCompleteResults(this, CodeCompleter, 3552 CodeCompletionContext::CCC_Name, 3553 Results.data(),Results.size()); 3554} 3555 3556void Sema::CodeCompleteUsing(Scope *S) { 3557 if (!CodeCompleter) 3558 return; 3559 3560 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 3561 CodeCompletionContext::CCC_PotentiallyQualifiedName, 3562 &ResultBuilder::IsNestedNameSpecifier); 3563 Results.EnterNewScope(); 3564 3565 // If we aren't in class scope, we could see the "namespace" keyword. 3566 if (!S->isClassScope()) 3567 Results.AddResult(CodeCompletionResult("namespace")); 3568 3569 // After "using", we can see anything that would start a 3570 // nested-name-specifier. 3571 CodeCompletionDeclConsumer Consumer(Results, CurContext); 3572 LookupVisibleDecls(S, LookupOrdinaryName, Consumer, 3573 CodeCompleter->includeGlobals()); 3574 Results.ExitScope(); 3575 3576 HandleCodeCompleteResults(this, CodeCompleter, 3577 CodeCompletionContext::CCC_PotentiallyQualifiedName, 3578 Results.data(),Results.size()); 3579} 3580 3581void Sema::CodeCompleteUsingDirective(Scope *S) { 3582 if (!CodeCompleter) 3583 return; 3584 3585 // After "using namespace", we expect to see a namespace name or namespace 3586 // alias. 3587 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 3588 CodeCompletionContext::CCC_Namespace, 3589 &ResultBuilder::IsNamespaceOrAlias); 3590 Results.EnterNewScope(); 3591 CodeCompletionDeclConsumer Consumer(Results, CurContext); 3592 LookupVisibleDecls(S, LookupOrdinaryName, Consumer, 3593 CodeCompleter->includeGlobals()); 3594 Results.ExitScope(); 3595 HandleCodeCompleteResults(this, CodeCompleter, 3596 CodeCompletionContext::CCC_Namespace, 3597 Results.data(),Results.size()); 3598} 3599 3600void Sema::CodeCompleteNamespaceDecl(Scope *S) { 3601 if (!CodeCompleter) 3602 return; 3603 3604 DeclContext *Ctx = (DeclContext *)S->getEntity(); 3605 if (!S->getParent()) 3606 Ctx = Context.getTranslationUnitDecl(); 3607 3608 bool SuppressedGlobalResults 3609 = Ctx && !CodeCompleter->includeGlobals() && isa<TranslationUnitDecl>(Ctx); 3610 3611 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 3612 SuppressedGlobalResults 3613 ? CodeCompletionContext::CCC_Namespace 3614 : CodeCompletionContext::CCC_Other, 3615 &ResultBuilder::IsNamespace); 3616 3617 if (Ctx && Ctx->isFileContext() && !SuppressedGlobalResults) { 3618 // We only want to see those namespaces that have already been defined 3619 // within this scope, because its likely that the user is creating an 3620 // extended namespace declaration. Keep track of the most recent 3621 // definition of each namespace. 3622 std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest; 3623 for (DeclContext::specific_decl_iterator<NamespaceDecl> 3624 NS(Ctx->decls_begin()), NSEnd(Ctx->decls_end()); 3625 NS != NSEnd; ++NS) 3626 OrigToLatest[NS->getOriginalNamespace()] = *NS; 3627 3628 // Add the most recent definition (or extended definition) of each 3629 // namespace to the list of results. 3630 Results.EnterNewScope(); 3631 for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator 3632 NS = OrigToLatest.begin(), NSEnd = OrigToLatest.end(); 3633 NS != NSEnd; ++NS) 3634 Results.AddResult(CodeCompletionResult(NS->second, 0), 3635 CurContext, 0, false); 3636 Results.ExitScope(); 3637 } 3638 3639 HandleCodeCompleteResults(this, CodeCompleter, 3640 Results.getCompletionContext(), 3641 Results.data(),Results.size()); 3642} 3643 3644void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) { 3645 if (!CodeCompleter) 3646 return; 3647 3648 // After "namespace", we expect to see a namespace or alias. 3649 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 3650 CodeCompletionContext::CCC_Namespace, 3651 &ResultBuilder::IsNamespaceOrAlias); 3652 CodeCompletionDeclConsumer Consumer(Results, CurContext); 3653 LookupVisibleDecls(S, LookupOrdinaryName, Consumer, 3654 CodeCompleter->includeGlobals()); 3655 HandleCodeCompleteResults(this, CodeCompleter, 3656 Results.getCompletionContext(), 3657 Results.data(),Results.size()); 3658} 3659 3660void Sema::CodeCompleteOperatorName(Scope *S) { 3661 if (!CodeCompleter) 3662 return; 3663 3664 typedef CodeCompletionResult Result; 3665 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 3666 CodeCompletionContext::CCC_Type, 3667 &ResultBuilder::IsType); 3668 Results.EnterNewScope(); 3669 3670 // Add the names of overloadable operators. 3671#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 3672 if (std::strcmp(Spelling, "?")) \ 3673 Results.AddResult(Result(Spelling)); 3674#include "clang/Basic/OperatorKinds.def" 3675 3676 // Add any type names visible from the current scope 3677 Results.allowNestedNameSpecifiers(); 3678 CodeCompletionDeclConsumer Consumer(Results, CurContext); 3679 LookupVisibleDecls(S, LookupOrdinaryName, Consumer, 3680 CodeCompleter->includeGlobals()); 3681 3682 // Add any type specifiers 3683 AddTypeSpecifierResults(getLangOptions(), Results); 3684 Results.ExitScope(); 3685 3686 HandleCodeCompleteResults(this, CodeCompleter, 3687 CodeCompletionContext::CCC_Type, 3688 Results.data(),Results.size()); 3689} 3690 3691void Sema::CodeCompleteConstructorInitializer(Decl *ConstructorD, 3692 CXXCtorInitializer** Initializers, 3693 unsigned NumInitializers) { 3694 CXXConstructorDecl *Constructor 3695 = static_cast<CXXConstructorDecl *>(ConstructorD); 3696 if (!Constructor) 3697 return; 3698 3699 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 3700 CodeCompletionContext::CCC_PotentiallyQualifiedName); 3701 Results.EnterNewScope(); 3702 3703 // Fill in any already-initialized fields or base classes. 3704 llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields; 3705 llvm::SmallPtrSet<CanQualType, 4> InitializedBases; 3706 for (unsigned I = 0; I != NumInitializers; ++I) { 3707 if (Initializers[I]->isBaseInitializer()) 3708 InitializedBases.insert( 3709 Context.getCanonicalType(QualType(Initializers[I]->getBaseClass(), 0))); 3710 else 3711 InitializedFields.insert(cast<FieldDecl>( 3712 Initializers[I]->getAnyMember())); 3713 } 3714 3715 // Add completions for base classes. 3716 CodeCompletionBuilder Builder(Results.getAllocator()); 3717 bool SawLastInitializer = (NumInitializers == 0); 3718 CXXRecordDecl *ClassDecl = Constructor->getParent(); 3719 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(), 3720 BaseEnd = ClassDecl->bases_end(); 3721 Base != BaseEnd; ++Base) { 3722 if (!InitializedBases.insert(Context.getCanonicalType(Base->getType()))) { 3723 SawLastInitializer 3724 = NumInitializers > 0 && 3725 Initializers[NumInitializers - 1]->isBaseInitializer() && 3726 Context.hasSameUnqualifiedType(Base->getType(), 3727 QualType(Initializers[NumInitializers - 1]->getBaseClass(), 0)); 3728 continue; 3729 } 3730 3731 Builder.AddTypedTextChunk( 3732 Results.getAllocator().CopyString( 3733 Base->getType().getAsString(Context.PrintingPolicy))); 3734 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 3735 Builder.AddPlaceholderChunk("args"); 3736 Builder.AddChunk(CodeCompletionString::CK_RightParen); 3737 Results.AddResult(CodeCompletionResult(Builder.TakeString(), 3738 SawLastInitializer? CCP_NextInitializer 3739 : CCP_MemberDeclaration)); 3740 SawLastInitializer = false; 3741 } 3742 3743 // Add completions for virtual base classes. 3744 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(), 3745 BaseEnd = ClassDecl->vbases_end(); 3746 Base != BaseEnd; ++Base) { 3747 if (!InitializedBases.insert(Context.getCanonicalType(Base->getType()))) { 3748 SawLastInitializer 3749 = NumInitializers > 0 && 3750 Initializers[NumInitializers - 1]->isBaseInitializer() && 3751 Context.hasSameUnqualifiedType(Base->getType(), 3752 QualType(Initializers[NumInitializers - 1]->getBaseClass(), 0)); 3753 continue; 3754 } 3755 3756 Builder.AddTypedTextChunk( 3757 Builder.getAllocator().CopyString( 3758 Base->getType().getAsString(Context.PrintingPolicy))); 3759 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 3760 Builder.AddPlaceholderChunk("args"); 3761 Builder.AddChunk(CodeCompletionString::CK_RightParen); 3762 Results.AddResult(CodeCompletionResult(Builder.TakeString(), 3763 SawLastInitializer? CCP_NextInitializer 3764 : CCP_MemberDeclaration)); 3765 SawLastInitializer = false; 3766 } 3767 3768 // Add completions for members. 3769 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 3770 FieldEnd = ClassDecl->field_end(); 3771 Field != FieldEnd; ++Field) { 3772 if (!InitializedFields.insert(cast<FieldDecl>(Field->getCanonicalDecl()))) { 3773 SawLastInitializer 3774 = NumInitializers > 0 && 3775 Initializers[NumInitializers - 1]->isAnyMemberInitializer() && 3776 Initializers[NumInitializers - 1]->getAnyMember() == *Field; 3777 continue; 3778 } 3779 3780 if (!Field->getDeclName()) 3781 continue; 3782 3783 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString( 3784 Field->getIdentifier()->getName())); 3785 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 3786 Builder.AddPlaceholderChunk("args"); 3787 Builder.AddChunk(CodeCompletionString::CK_RightParen); 3788 Results.AddResult(CodeCompletionResult(Builder.TakeString(), 3789 SawLastInitializer? CCP_NextInitializer 3790 : CCP_MemberDeclaration, 3791 CXCursor_MemberRef)); 3792 SawLastInitializer = false; 3793 } 3794 Results.ExitScope(); 3795 3796 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 3797 Results.data(), Results.size()); 3798} 3799 3800// Macro that expands to @Keyword or Keyword, depending on whether NeedAt is 3801// true or false. 3802#define OBJC_AT_KEYWORD_NAME(NeedAt,Keyword) NeedAt? "@" #Keyword : #Keyword 3803static void AddObjCImplementationResults(const LangOptions &LangOpts, 3804 ResultBuilder &Results, 3805 bool NeedAt) { 3806 typedef CodeCompletionResult Result; 3807 // Since we have an implementation, we can end it. 3808 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,end))); 3809 3810 CodeCompletionBuilder Builder(Results.getAllocator()); 3811 if (LangOpts.ObjC2) { 3812 // @dynamic 3813 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,dynamic)); 3814 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 3815 Builder.AddPlaceholderChunk("property"); 3816 Results.AddResult(Result(Builder.TakeString())); 3817 3818 // @synthesize 3819 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,synthesize)); 3820 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 3821 Builder.AddPlaceholderChunk("property"); 3822 Results.AddResult(Result(Builder.TakeString())); 3823 } 3824} 3825 3826static void AddObjCInterfaceResults(const LangOptions &LangOpts, 3827 ResultBuilder &Results, 3828 bool NeedAt) { 3829 typedef CodeCompletionResult Result; 3830 3831 // Since we have an interface or protocol, we can end it. 3832 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,end))); 3833 3834 if (LangOpts.ObjC2) { 3835 // @property 3836 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,property))); 3837 3838 // @required 3839 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,required))); 3840 3841 // @optional 3842 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,optional))); 3843 } 3844} 3845 3846static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt) { 3847 typedef CodeCompletionResult Result; 3848 CodeCompletionBuilder Builder(Results.getAllocator()); 3849 3850 // @class name ; 3851 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,class)); 3852 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 3853 Builder.AddPlaceholderChunk("name"); 3854 Results.AddResult(Result(Builder.TakeString())); 3855 3856 if (Results.includeCodePatterns()) { 3857 // @interface name 3858 // FIXME: Could introduce the whole pattern, including superclasses and 3859 // such. 3860 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,interface)); 3861 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 3862 Builder.AddPlaceholderChunk("class"); 3863 Results.AddResult(Result(Builder.TakeString())); 3864 3865 // @protocol name 3866 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,protocol)); 3867 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 3868 Builder.AddPlaceholderChunk("protocol"); 3869 Results.AddResult(Result(Builder.TakeString())); 3870 3871 // @implementation name 3872 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,implementation)); 3873 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 3874 Builder.AddPlaceholderChunk("class"); 3875 Results.AddResult(Result(Builder.TakeString())); 3876 } 3877 3878 // @compatibility_alias name 3879 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,compatibility_alias)); 3880 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 3881 Builder.AddPlaceholderChunk("alias"); 3882 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 3883 Builder.AddPlaceholderChunk("class"); 3884 Results.AddResult(Result(Builder.TakeString())); 3885} 3886 3887void Sema::CodeCompleteObjCAtDirective(Scope *S, Decl *ObjCImpDecl, 3888 bool InInterface) { 3889 typedef CodeCompletionResult Result; 3890 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 3891 CodeCompletionContext::CCC_Other); 3892 Results.EnterNewScope(); 3893 if (ObjCImpDecl) 3894 AddObjCImplementationResults(getLangOptions(), Results, false); 3895 else if (InInterface) 3896 AddObjCInterfaceResults(getLangOptions(), Results, false); 3897 else 3898 AddObjCTopLevelResults(Results, false); 3899 Results.ExitScope(); 3900 HandleCodeCompleteResults(this, CodeCompleter, 3901 CodeCompletionContext::CCC_Other, 3902 Results.data(),Results.size()); 3903} 3904 3905static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt) { 3906 typedef CodeCompletionResult Result; 3907 CodeCompletionBuilder Builder(Results.getAllocator()); 3908 3909 // @encode ( type-name ) 3910 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,encode)); 3911 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 3912 Builder.AddPlaceholderChunk("type-name"); 3913 Builder.AddChunk(CodeCompletionString::CK_RightParen); 3914 Results.AddResult(Result(Builder.TakeString())); 3915 3916 // @protocol ( protocol-name ) 3917 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,protocol)); 3918 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 3919 Builder.AddPlaceholderChunk("protocol-name"); 3920 Builder.AddChunk(CodeCompletionString::CK_RightParen); 3921 Results.AddResult(Result(Builder.TakeString())); 3922 3923 // @selector ( selector ) 3924 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,selector)); 3925 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 3926 Builder.AddPlaceholderChunk("selector"); 3927 Builder.AddChunk(CodeCompletionString::CK_RightParen); 3928 Results.AddResult(Result(Builder.TakeString())); 3929} 3930 3931static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt) { 3932 typedef CodeCompletionResult Result; 3933 CodeCompletionBuilder Builder(Results.getAllocator()); 3934 3935 if (Results.includeCodePatterns()) { 3936 // @try { statements } @catch ( declaration ) { statements } @finally 3937 // { statements } 3938 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,try)); 3939 Builder.AddChunk(CodeCompletionString::CK_LeftBrace); 3940 Builder.AddPlaceholderChunk("statements"); 3941 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 3942 Builder.AddTextChunk("@catch"); 3943 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 3944 Builder.AddPlaceholderChunk("parameter"); 3945 Builder.AddChunk(CodeCompletionString::CK_RightParen); 3946 Builder.AddChunk(CodeCompletionString::CK_LeftBrace); 3947 Builder.AddPlaceholderChunk("statements"); 3948 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 3949 Builder.AddTextChunk("@finally"); 3950 Builder.AddChunk(CodeCompletionString::CK_LeftBrace); 3951 Builder.AddPlaceholderChunk("statements"); 3952 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 3953 Results.AddResult(Result(Builder.TakeString())); 3954 } 3955 3956 // @throw 3957 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,throw)); 3958 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 3959 Builder.AddPlaceholderChunk("expression"); 3960 Results.AddResult(Result(Builder.TakeString())); 3961 3962 if (Results.includeCodePatterns()) { 3963 // @synchronized ( expression ) { statements } 3964 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,synchronized)); 3965 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 3966 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 3967 Builder.AddPlaceholderChunk("expression"); 3968 Builder.AddChunk(CodeCompletionString::CK_RightParen); 3969 Builder.AddChunk(CodeCompletionString::CK_LeftBrace); 3970 Builder.AddPlaceholderChunk("statements"); 3971 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 3972 Results.AddResult(Result(Builder.TakeString())); 3973 } 3974} 3975 3976static void AddObjCVisibilityResults(const LangOptions &LangOpts, 3977 ResultBuilder &Results, 3978 bool NeedAt) { 3979 typedef CodeCompletionResult Result; 3980 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,private))); 3981 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,protected))); 3982 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,public))); 3983 if (LangOpts.ObjC2) 3984 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,package))); 3985} 3986 3987void Sema::CodeCompleteObjCAtVisibility(Scope *S) { 3988 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 3989 CodeCompletionContext::CCC_Other); 3990 Results.EnterNewScope(); 3991 AddObjCVisibilityResults(getLangOptions(), Results, false); 3992 Results.ExitScope(); 3993 HandleCodeCompleteResults(this, CodeCompleter, 3994 CodeCompletionContext::CCC_Other, 3995 Results.data(),Results.size()); 3996} 3997 3998void Sema::CodeCompleteObjCAtStatement(Scope *S) { 3999 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 4000 CodeCompletionContext::CCC_Other); 4001 Results.EnterNewScope(); 4002 AddObjCStatementResults(Results, false); 4003 AddObjCExpressionResults(Results, false); 4004 Results.ExitScope(); 4005 HandleCodeCompleteResults(this, CodeCompleter, 4006 CodeCompletionContext::CCC_Other, 4007 Results.data(),Results.size()); 4008} 4009 4010void Sema::CodeCompleteObjCAtExpression(Scope *S) { 4011 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 4012 CodeCompletionContext::CCC_Other); 4013 Results.EnterNewScope(); 4014 AddObjCExpressionResults(Results, false); 4015 Results.ExitScope(); 4016 HandleCodeCompleteResults(this, CodeCompleter, 4017 CodeCompletionContext::CCC_Other, 4018 Results.data(),Results.size()); 4019} 4020 4021/// \brief Determine whether the addition of the given flag to an Objective-C 4022/// property's attributes will cause a conflict. 4023static bool ObjCPropertyFlagConflicts(unsigned Attributes, unsigned NewFlag) { 4024 // Check if we've already added this flag. 4025 if (Attributes & NewFlag) 4026 return true; 4027 4028 Attributes |= NewFlag; 4029 4030 // Check for collisions with "readonly". 4031 if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) && 4032 (Attributes & (ObjCDeclSpec::DQ_PR_readwrite | 4033 ObjCDeclSpec::DQ_PR_assign | 4034 ObjCDeclSpec::DQ_PR_copy | 4035 ObjCDeclSpec::DQ_PR_retain))) 4036 return true; 4037 4038 // Check for more than one of { assign, copy, retain }. 4039 unsigned AssignCopyRetMask = Attributes & (ObjCDeclSpec::DQ_PR_assign | 4040 ObjCDeclSpec::DQ_PR_copy | 4041 ObjCDeclSpec::DQ_PR_retain); 4042 if (AssignCopyRetMask && 4043 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_assign && 4044 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_copy && 4045 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_retain) 4046 return true; 4047 4048 return false; 4049} 4050 4051void Sema::CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS) { 4052 if (!CodeCompleter) 4053 return; 4054 4055 unsigned Attributes = ODS.getPropertyAttributes(); 4056 4057 typedef CodeCompletionResult Result; 4058 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 4059 CodeCompletionContext::CCC_Other); 4060 Results.EnterNewScope(); 4061 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readonly)) 4062 Results.AddResult(CodeCompletionResult("readonly")); 4063 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_assign)) 4064 Results.AddResult(CodeCompletionResult("assign")); 4065 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readwrite)) 4066 Results.AddResult(CodeCompletionResult("readwrite")); 4067 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_retain)) 4068 Results.AddResult(CodeCompletionResult("retain")); 4069 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_copy)) 4070 Results.AddResult(CodeCompletionResult("copy")); 4071 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nonatomic)) 4072 Results.AddResult(CodeCompletionResult("nonatomic")); 4073 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_setter)) { 4074 CodeCompletionBuilder Setter(Results.getAllocator()); 4075 Setter.AddTypedTextChunk("setter"); 4076 Setter.AddTextChunk(" = "); 4077 Setter.AddPlaceholderChunk("method"); 4078 Results.AddResult(CodeCompletionResult(Setter.TakeString())); 4079 } 4080 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_getter)) { 4081 CodeCompletionBuilder Getter(Results.getAllocator()); 4082 Getter.AddTypedTextChunk("getter"); 4083 Getter.AddTextChunk(" = "); 4084 Getter.AddPlaceholderChunk("method"); 4085 Results.AddResult(CodeCompletionResult(Getter.TakeString())); 4086 } 4087 Results.ExitScope(); 4088 HandleCodeCompleteResults(this, CodeCompleter, 4089 CodeCompletionContext::CCC_Other, 4090 Results.data(),Results.size()); 4091} 4092 4093/// \brief Descripts the kind of Objective-C method that we want to find 4094/// via code completion. 4095enum ObjCMethodKind { 4096 MK_Any, //< Any kind of method, provided it means other specified criteria. 4097 MK_ZeroArgSelector, //< Zero-argument (unary) selector. 4098 MK_OneArgSelector //< One-argument selector. 4099}; 4100 4101static bool isAcceptableObjCSelector(Selector Sel, 4102 ObjCMethodKind WantKind, 4103 IdentifierInfo **SelIdents, 4104 unsigned NumSelIdents, 4105 bool AllowSameLength = true) { 4106 if (NumSelIdents > Sel.getNumArgs()) 4107 return false; 4108 4109 switch (WantKind) { 4110 case MK_Any: break; 4111 case MK_ZeroArgSelector: return Sel.isUnarySelector(); 4112 case MK_OneArgSelector: return Sel.getNumArgs() == 1; 4113 } 4114 4115 if (!AllowSameLength && NumSelIdents && NumSelIdents == Sel.getNumArgs()) 4116 return false; 4117 4118 for (unsigned I = 0; I != NumSelIdents; ++I) 4119 if (SelIdents[I] != Sel.getIdentifierInfoForSlot(I)) 4120 return false; 4121 4122 return true; 4123} 4124 4125static bool isAcceptableObjCMethod(ObjCMethodDecl *Method, 4126 ObjCMethodKind WantKind, 4127 IdentifierInfo **SelIdents, 4128 unsigned NumSelIdents, 4129 bool AllowSameLength = true) { 4130 return isAcceptableObjCSelector(Method->getSelector(), WantKind, SelIdents, 4131 NumSelIdents, AllowSameLength); 4132} 4133 4134namespace { 4135 /// \brief A set of selectors, which is used to avoid introducing multiple 4136 /// completions with the same selector into the result set. 4137 typedef llvm::SmallPtrSet<Selector, 16> VisitedSelectorSet; 4138} 4139 4140/// \brief Add all of the Objective-C methods in the given Objective-C 4141/// container to the set of results. 4142/// 4143/// The container will be a class, protocol, category, or implementation of 4144/// any of the above. This mether will recurse to include methods from 4145/// the superclasses of classes along with their categories, protocols, and 4146/// implementations. 4147/// 4148/// \param Container the container in which we'll look to find methods. 4149/// 4150/// \param WantInstance whether to add instance methods (only); if false, this 4151/// routine will add factory methods (only). 4152/// 4153/// \param CurContext the context in which we're performing the lookup that 4154/// finds methods. 4155/// 4156/// \param AllowSameLength Whether we allow a method to be added to the list 4157/// when it has the same number of parameters as we have selector identifiers. 4158/// 4159/// \param Results the structure into which we'll add results. 4160static void AddObjCMethods(ObjCContainerDecl *Container, 4161 bool WantInstanceMethods, 4162 ObjCMethodKind WantKind, 4163 IdentifierInfo **SelIdents, 4164 unsigned NumSelIdents, 4165 DeclContext *CurContext, 4166 VisitedSelectorSet &Selectors, 4167 bool AllowSameLength, 4168 ResultBuilder &Results, 4169 bool InOriginalClass = true) { 4170 typedef CodeCompletionResult Result; 4171 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(), 4172 MEnd = Container->meth_end(); 4173 M != MEnd; ++M) { 4174 if ((*M)->isInstanceMethod() == WantInstanceMethods) { 4175 // Check whether the selector identifiers we've been given are a 4176 // subset of the identifiers for this particular method. 4177 if (!isAcceptableObjCMethod(*M, WantKind, SelIdents, NumSelIdents, 4178 AllowSameLength)) 4179 continue; 4180 4181 if (!Selectors.insert((*M)->getSelector())) 4182 continue; 4183 4184 Result R = Result(*M, 0); 4185 R.StartParameter = NumSelIdents; 4186 R.AllParametersAreInformative = (WantKind != MK_Any); 4187 if (!InOriginalClass) 4188 R.Priority += CCD_InBaseClass; 4189 Results.MaybeAddResult(R, CurContext); 4190 } 4191 } 4192 4193 // Visit the protocols of protocols. 4194 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) { 4195 const ObjCList<ObjCProtocolDecl> &Protocols 4196 = Protocol->getReferencedProtocols(); 4197 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(), 4198 E = Protocols.end(); 4199 I != E; ++I) 4200 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, NumSelIdents, 4201 CurContext, Selectors, AllowSameLength, Results, false); 4202 } 4203 4204 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container); 4205 if (!IFace) 4206 return; 4207 4208 // Add methods in protocols. 4209 const ObjCList<ObjCProtocolDecl> &Protocols= IFace->getReferencedProtocols(); 4210 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(), 4211 E = Protocols.end(); 4212 I != E; ++I) 4213 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, NumSelIdents, 4214 CurContext, Selectors, AllowSameLength, Results, false); 4215 4216 // Add methods in categories. 4217 for (ObjCCategoryDecl *CatDecl = IFace->getCategoryList(); CatDecl; 4218 CatDecl = CatDecl->getNextClassCategory()) { 4219 AddObjCMethods(CatDecl, WantInstanceMethods, WantKind, SelIdents, 4220 NumSelIdents, CurContext, Selectors, AllowSameLength, 4221 Results, InOriginalClass); 4222 4223 // Add a categories protocol methods. 4224 const ObjCList<ObjCProtocolDecl> &Protocols 4225 = CatDecl->getReferencedProtocols(); 4226 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(), 4227 E = Protocols.end(); 4228 I != E; ++I) 4229 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, 4230 NumSelIdents, CurContext, Selectors, AllowSameLength, 4231 Results, false); 4232 4233 // Add methods in category implementations. 4234 if (ObjCCategoryImplDecl *Impl = CatDecl->getImplementation()) 4235 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents, 4236 NumSelIdents, CurContext, Selectors, AllowSameLength, 4237 Results, InOriginalClass); 4238 } 4239 4240 // Add methods in superclass. 4241 if (IFace->getSuperClass()) 4242 AddObjCMethods(IFace->getSuperClass(), WantInstanceMethods, WantKind, 4243 SelIdents, NumSelIdents, CurContext, Selectors, 4244 AllowSameLength, Results, false); 4245 4246 // Add methods in our implementation, if any. 4247 if (ObjCImplementationDecl *Impl = IFace->getImplementation()) 4248 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents, 4249 NumSelIdents, CurContext, Selectors, AllowSameLength, 4250 Results, InOriginalClass); 4251} 4252 4253 4254void Sema::CodeCompleteObjCPropertyGetter(Scope *S, Decl *ClassDecl) { 4255 typedef CodeCompletionResult Result; 4256 4257 // Try to find the interface where getters might live. 4258 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(ClassDecl); 4259 if (!Class) { 4260 if (ObjCCategoryDecl *Category 4261 = dyn_cast_or_null<ObjCCategoryDecl>(ClassDecl)) 4262 Class = Category->getClassInterface(); 4263 4264 if (!Class) 4265 return; 4266 } 4267 4268 // Find all of the potential getters. 4269 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 4270 CodeCompletionContext::CCC_Other); 4271 Results.EnterNewScope(); 4272 4273 VisitedSelectorSet Selectors; 4274 AddObjCMethods(Class, true, MK_ZeroArgSelector, 0, 0, CurContext, Selectors, 4275 /*AllowSameLength=*/true, Results); 4276 Results.ExitScope(); 4277 HandleCodeCompleteResults(this, CodeCompleter, 4278 CodeCompletionContext::CCC_Other, 4279 Results.data(),Results.size()); 4280} 4281 4282void Sema::CodeCompleteObjCPropertySetter(Scope *S, Decl *ObjCImplDecl) { 4283 typedef CodeCompletionResult Result; 4284 4285 // Try to find the interface where setters might live. 4286 ObjCInterfaceDecl *Class 4287 = dyn_cast_or_null<ObjCInterfaceDecl>(ObjCImplDecl); 4288 if (!Class) { 4289 if (ObjCCategoryDecl *Category 4290 = dyn_cast_or_null<ObjCCategoryDecl>(ObjCImplDecl)) 4291 Class = Category->getClassInterface(); 4292 4293 if (!Class) 4294 return; 4295 } 4296 4297 // Find all of the potential getters. 4298 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 4299 CodeCompletionContext::CCC_Other); 4300 Results.EnterNewScope(); 4301 4302 VisitedSelectorSet Selectors; 4303 AddObjCMethods(Class, true, MK_OneArgSelector, 0, 0, CurContext, 4304 Selectors, /*AllowSameLength=*/true, Results); 4305 4306 Results.ExitScope(); 4307 HandleCodeCompleteResults(this, CodeCompleter, 4308 CodeCompletionContext::CCC_Other, 4309 Results.data(),Results.size()); 4310} 4311 4312void Sema::CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS, 4313 bool IsParameter) { 4314 typedef CodeCompletionResult Result; 4315 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 4316 CodeCompletionContext::CCC_Type); 4317 Results.EnterNewScope(); 4318 4319 // Add context-sensitive, Objective-C parameter-passing keywords. 4320 bool AddedInOut = false; 4321 if ((DS.getObjCDeclQualifier() & 4322 (ObjCDeclSpec::DQ_In | ObjCDeclSpec::DQ_Inout)) == 0) { 4323 Results.AddResult("in"); 4324 Results.AddResult("inout"); 4325 AddedInOut = true; 4326 } 4327 if ((DS.getObjCDeclQualifier() & 4328 (ObjCDeclSpec::DQ_Out | ObjCDeclSpec::DQ_Inout)) == 0) { 4329 Results.AddResult("out"); 4330 if (!AddedInOut) 4331 Results.AddResult("inout"); 4332 } 4333 if ((DS.getObjCDeclQualifier() & 4334 (ObjCDeclSpec::DQ_Bycopy | ObjCDeclSpec::DQ_Byref | 4335 ObjCDeclSpec::DQ_Oneway)) == 0) { 4336 Results.AddResult("bycopy"); 4337 Results.AddResult("byref"); 4338 Results.AddResult("oneway"); 4339 } 4340 4341 // If we're completing the return type of an Objective-C method and the 4342 // identifier IBAction refers to a macro, provide a completion item for 4343 // an action, e.g., 4344 // IBAction)<#selector#>:(id)sender 4345 if (DS.getObjCDeclQualifier() == 0 && !IsParameter && 4346 Context.Idents.get("IBAction").hasMacroDefinition()) { 4347 typedef CodeCompletionString::Chunk Chunk; 4348 CodeCompletionBuilder Builder(Results.getAllocator(), CCP_CodePattern, 4349 CXAvailability_Available); 4350 Builder.AddTypedTextChunk("IBAction"); 4351 Builder.AddChunk(Chunk(CodeCompletionString::CK_RightParen)); 4352 Builder.AddPlaceholderChunk("selector"); 4353 Builder.AddChunk(Chunk(CodeCompletionString::CK_Colon)); 4354 Builder.AddChunk(Chunk(CodeCompletionString::CK_LeftParen)); 4355 Builder.AddTextChunk("id"); 4356 Builder.AddChunk(Chunk(CodeCompletionString::CK_RightParen)); 4357 Builder.AddTextChunk("sender"); 4358 Results.AddResult(CodeCompletionResult(Builder.TakeString())); 4359 } 4360 4361 // Add various builtin type names and specifiers. 4362 AddOrdinaryNameResults(PCC_Type, S, *this, Results); 4363 Results.ExitScope(); 4364 4365 // Add the various type names 4366 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName); 4367 CodeCompletionDeclConsumer Consumer(Results, CurContext); 4368 LookupVisibleDecls(S, LookupOrdinaryName, Consumer, 4369 CodeCompleter->includeGlobals()); 4370 4371 if (CodeCompleter->includeMacros()) 4372 AddMacroResults(PP, Results); 4373 4374 HandleCodeCompleteResults(this, CodeCompleter, 4375 CodeCompletionContext::CCC_Type, 4376 Results.data(), Results.size()); 4377} 4378 4379/// \brief When we have an expression with type "id", we may assume 4380/// that it has some more-specific class type based on knowledge of 4381/// common uses of Objective-C. This routine returns that class type, 4382/// or NULL if no better result could be determined. 4383static ObjCInterfaceDecl *GetAssumedMessageSendExprType(Expr *E) { 4384 ObjCMessageExpr *Msg = dyn_cast_or_null<ObjCMessageExpr>(E); 4385 if (!Msg) 4386 return 0; 4387 4388 Selector Sel = Msg->getSelector(); 4389 if (Sel.isNull()) 4390 return 0; 4391 4392 IdentifierInfo *Id = Sel.getIdentifierInfoForSlot(0); 4393 if (!Id) 4394 return 0; 4395 4396 ObjCMethodDecl *Method = Msg->getMethodDecl(); 4397 if (!Method) 4398 return 0; 4399 4400 // Determine the class that we're sending the message to. 4401 ObjCInterfaceDecl *IFace = 0; 4402 switch (Msg->getReceiverKind()) { 4403 case ObjCMessageExpr::Class: 4404 if (const ObjCObjectType *ObjType 4405 = Msg->getClassReceiver()->getAs<ObjCObjectType>()) 4406 IFace = ObjType->getInterface(); 4407 break; 4408 4409 case ObjCMessageExpr::Instance: { 4410 QualType T = Msg->getInstanceReceiver()->getType(); 4411 if (const ObjCObjectPointerType *Ptr = T->getAs<ObjCObjectPointerType>()) 4412 IFace = Ptr->getInterfaceDecl(); 4413 break; 4414 } 4415 4416 case ObjCMessageExpr::SuperInstance: 4417 case ObjCMessageExpr::SuperClass: 4418 break; 4419 } 4420 4421 if (!IFace) 4422 return 0; 4423 4424 ObjCInterfaceDecl *Super = IFace->getSuperClass(); 4425 if (Method->isInstanceMethod()) 4426 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName()) 4427 .Case("retain", IFace) 4428 .Case("autorelease", IFace) 4429 .Case("copy", IFace) 4430 .Case("copyWithZone", IFace) 4431 .Case("mutableCopy", IFace) 4432 .Case("mutableCopyWithZone", IFace) 4433 .Case("awakeFromCoder", IFace) 4434 .Case("replacementObjectFromCoder", IFace) 4435 .Case("class", IFace) 4436 .Case("classForCoder", IFace) 4437 .Case("superclass", Super) 4438 .Default(0); 4439 4440 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName()) 4441 .Case("new", IFace) 4442 .Case("alloc", IFace) 4443 .Case("allocWithZone", IFace) 4444 .Case("class", IFace) 4445 .Case("superclass", Super) 4446 .Default(0); 4447} 4448 4449// Add a special completion for a message send to "super", which fills in the 4450// most likely case of forwarding all of our arguments to the superclass 4451// function. 4452/// 4453/// \param S The semantic analysis object. 4454/// 4455/// \param S NeedSuperKeyword Whether we need to prefix this completion with 4456/// the "super" keyword. Otherwise, we just need to provide the arguments. 4457/// 4458/// \param SelIdents The identifiers in the selector that have already been 4459/// provided as arguments for a send to "super". 4460/// 4461/// \param NumSelIdents The number of identifiers in \p SelIdents. 4462/// 4463/// \param Results The set of results to augment. 4464/// 4465/// \returns the Objective-C method declaration that would be invoked by 4466/// this "super" completion. If NULL, no completion was added. 4467static ObjCMethodDecl *AddSuperSendCompletion(Sema &S, bool NeedSuperKeyword, 4468 IdentifierInfo **SelIdents, 4469 unsigned NumSelIdents, 4470 ResultBuilder &Results) { 4471 ObjCMethodDecl *CurMethod = S.getCurMethodDecl(); 4472 if (!CurMethod) 4473 return 0; 4474 4475 ObjCInterfaceDecl *Class = CurMethod->getClassInterface(); 4476 if (!Class) 4477 return 0; 4478 4479 // Try to find a superclass method with the same selector. 4480 ObjCMethodDecl *SuperMethod = 0; 4481 while ((Class = Class->getSuperClass()) && !SuperMethod) 4482 SuperMethod = Class->getMethod(CurMethod->getSelector(), 4483 CurMethod->isInstanceMethod()); 4484 4485 if (!SuperMethod) 4486 return 0; 4487 4488 // Check whether the superclass method has the same signature. 4489 if (CurMethod->param_size() != SuperMethod->param_size() || 4490 CurMethod->isVariadic() != SuperMethod->isVariadic()) 4491 return 0; 4492 4493 for (ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin(), 4494 CurPEnd = CurMethod->param_end(), 4495 SuperP = SuperMethod->param_begin(); 4496 CurP != CurPEnd; ++CurP, ++SuperP) { 4497 // Make sure the parameter types are compatible. 4498 if (!S.Context.hasSameUnqualifiedType((*CurP)->getType(), 4499 (*SuperP)->getType())) 4500 return 0; 4501 4502 // Make sure we have a parameter name to forward! 4503 if (!(*CurP)->getIdentifier()) 4504 return 0; 4505 } 4506 4507 // We have a superclass method. Now, form the send-to-super completion. 4508 CodeCompletionBuilder Builder(Results.getAllocator()); 4509 4510 // Give this completion a return type. 4511 AddResultTypeChunk(S.Context, SuperMethod, Builder); 4512 4513 // If we need the "super" keyword, add it (plus some spacing). 4514 if (NeedSuperKeyword) { 4515 Builder.AddTypedTextChunk("super"); 4516 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 4517 } 4518 4519 Selector Sel = CurMethod->getSelector(); 4520 if (Sel.isUnarySelector()) { 4521 if (NeedSuperKeyword) 4522 Builder.AddTextChunk(Builder.getAllocator().CopyString( 4523 Sel.getIdentifierInfoForSlot(0)->getName())); 4524 else 4525 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString( 4526 Sel.getIdentifierInfoForSlot(0)->getName())); 4527 } else { 4528 ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin(); 4529 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I, ++CurP) { 4530 if (I > NumSelIdents) 4531 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 4532 4533 if (I < NumSelIdents) 4534 Builder.AddInformativeChunk( 4535 Builder.getAllocator().CopyString( 4536 Sel.getIdentifierInfoForSlot(I)->getName().str() + ":")); 4537 else if (NeedSuperKeyword || I > NumSelIdents) { 4538 Builder.AddTextChunk( 4539 Builder.getAllocator().CopyString( 4540 Sel.getIdentifierInfoForSlot(I)->getName().str() + ":")); 4541 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString( 4542 (*CurP)->getIdentifier()->getName())); 4543 } else { 4544 Builder.AddTypedTextChunk( 4545 Builder.getAllocator().CopyString( 4546 Sel.getIdentifierInfoForSlot(I)->getName().str() + ":")); 4547 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString( 4548 (*CurP)->getIdentifier()->getName())); 4549 } 4550 } 4551 } 4552 4553 Results.AddResult(CodeCompletionResult(Builder.TakeString(), CCP_SuperCompletion, 4554 SuperMethod->isInstanceMethod() 4555 ? CXCursor_ObjCInstanceMethodDecl 4556 : CXCursor_ObjCClassMethodDecl)); 4557 return SuperMethod; 4558} 4559 4560void Sema::CodeCompleteObjCMessageReceiver(Scope *S) { 4561 typedef CodeCompletionResult Result; 4562 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 4563 CodeCompletionContext::CCC_ObjCMessageReceiver, 4564 &ResultBuilder::IsObjCMessageReceiver); 4565 4566 CodeCompletionDeclConsumer Consumer(Results, CurContext); 4567 Results.EnterNewScope(); 4568 LookupVisibleDecls(S, LookupOrdinaryName, Consumer, 4569 CodeCompleter->includeGlobals()); 4570 4571 // If we are in an Objective-C method inside a class that has a superclass, 4572 // add "super" as an option. 4573 if (ObjCMethodDecl *Method = getCurMethodDecl()) 4574 if (ObjCInterfaceDecl *Iface = Method->getClassInterface()) 4575 if (Iface->getSuperClass()) { 4576 Results.AddResult(Result("super")); 4577 4578 AddSuperSendCompletion(*this, /*NeedSuperKeyword=*/true, 0, 0, Results); 4579 } 4580 4581 Results.ExitScope(); 4582 4583 if (CodeCompleter->includeMacros()) 4584 AddMacroResults(PP, Results); 4585 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 4586 Results.data(), Results.size()); 4587 4588} 4589 4590void Sema::CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc, 4591 IdentifierInfo **SelIdents, 4592 unsigned NumSelIdents, 4593 bool AtArgumentExpression) { 4594 ObjCInterfaceDecl *CDecl = 0; 4595 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) { 4596 // Figure out which interface we're in. 4597 CDecl = CurMethod->getClassInterface(); 4598 if (!CDecl) 4599 return; 4600 4601 // Find the superclass of this class. 4602 CDecl = CDecl->getSuperClass(); 4603 if (!CDecl) 4604 return; 4605 4606 if (CurMethod->isInstanceMethod()) { 4607 // We are inside an instance method, which means that the message 4608 // send [super ...] is actually calling an instance method on the 4609 // current object. 4610 return CodeCompleteObjCInstanceMessage(S, 0, 4611 SelIdents, NumSelIdents, 4612 AtArgumentExpression, 4613 CDecl); 4614 } 4615 4616 // Fall through to send to the superclass in CDecl. 4617 } else { 4618 // "super" may be the name of a type or variable. Figure out which 4619 // it is. 4620 IdentifierInfo *Super = &Context.Idents.get("super"); 4621 NamedDecl *ND = LookupSingleName(S, Super, SuperLoc, 4622 LookupOrdinaryName); 4623 if ((CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(ND))) { 4624 // "super" names an interface. Use it. 4625 } else if (TypeDecl *TD = dyn_cast_or_null<TypeDecl>(ND)) { 4626 if (const ObjCObjectType *Iface 4627 = Context.getTypeDeclType(TD)->getAs<ObjCObjectType>()) 4628 CDecl = Iface->getInterface(); 4629 } else if (ND && isa<UnresolvedUsingTypenameDecl>(ND)) { 4630 // "super" names an unresolved type; we can't be more specific. 4631 } else { 4632 // Assume that "super" names some kind of value and parse that way. 4633 CXXScopeSpec SS; 4634 UnqualifiedId id; 4635 id.setIdentifier(Super, SuperLoc); 4636 ExprResult SuperExpr = ActOnIdExpression(S, SS, id, false, false); 4637 return CodeCompleteObjCInstanceMessage(S, (Expr *)SuperExpr.get(), 4638 SelIdents, NumSelIdents, 4639 AtArgumentExpression); 4640 } 4641 4642 // Fall through 4643 } 4644 4645 ParsedType Receiver; 4646 if (CDecl) 4647 Receiver = ParsedType::make(Context.getObjCInterfaceType(CDecl)); 4648 return CodeCompleteObjCClassMessage(S, Receiver, SelIdents, 4649 NumSelIdents, AtArgumentExpression, 4650 /*IsSuper=*/true); 4651} 4652 4653/// \brief Given a set of code-completion results for the argument of a message 4654/// send, determine the preferred type (if any) for that argument expression. 4655static QualType getPreferredArgumentTypeForMessageSend(ResultBuilder &Results, 4656 unsigned NumSelIdents) { 4657 typedef CodeCompletionResult Result; 4658 ASTContext &Context = Results.getSema().Context; 4659 4660 QualType PreferredType; 4661 unsigned BestPriority = CCP_Unlikely * 2; 4662 Result *ResultsData = Results.data(); 4663 for (unsigned I = 0, N = Results.size(); I != N; ++I) { 4664 Result &R = ResultsData[I]; 4665 if (R.Kind == Result::RK_Declaration && 4666 isa<ObjCMethodDecl>(R.Declaration)) { 4667 if (R.Priority <= BestPriority) { 4668 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(R.Declaration); 4669 if (NumSelIdents <= Method->param_size()) { 4670 QualType MyPreferredType = Method->param_begin()[NumSelIdents - 1] 4671 ->getType(); 4672 if (R.Priority < BestPriority || PreferredType.isNull()) { 4673 BestPriority = R.Priority; 4674 PreferredType = MyPreferredType; 4675 } else if (!Context.hasSameUnqualifiedType(PreferredType, 4676 MyPreferredType)) { 4677 PreferredType = QualType(); 4678 } 4679 } 4680 } 4681 } 4682 } 4683 4684 return PreferredType; 4685} 4686 4687static void AddClassMessageCompletions(Sema &SemaRef, Scope *S, 4688 ParsedType Receiver, 4689 IdentifierInfo **SelIdents, 4690 unsigned NumSelIdents, 4691 bool AtArgumentExpression, 4692 bool IsSuper, 4693 ResultBuilder &Results) { 4694 typedef CodeCompletionResult Result; 4695 ObjCInterfaceDecl *CDecl = 0; 4696 4697 // If the given name refers to an interface type, retrieve the 4698 // corresponding declaration. 4699 if (Receiver) { 4700 QualType T = SemaRef.GetTypeFromParser(Receiver, 0); 4701 if (!T.isNull()) 4702 if (const ObjCObjectType *Interface = T->getAs<ObjCObjectType>()) 4703 CDecl = Interface->getInterface(); 4704 } 4705 4706 // Add all of the factory methods in this Objective-C class, its protocols, 4707 // superclasses, categories, implementation, etc. 4708 Results.EnterNewScope(); 4709 4710 // If this is a send-to-super, try to add the special "super" send 4711 // completion. 4712 if (IsSuper) { 4713 if (ObjCMethodDecl *SuperMethod 4714 = AddSuperSendCompletion(SemaRef, false, SelIdents, NumSelIdents, 4715 Results)) 4716 Results.Ignore(SuperMethod); 4717 } 4718 4719 // If we're inside an Objective-C method definition, prefer its selector to 4720 // others. 4721 if (ObjCMethodDecl *CurMethod = SemaRef.getCurMethodDecl()) 4722 Results.setPreferredSelector(CurMethod->getSelector()); 4723 4724 VisitedSelectorSet Selectors; 4725 if (CDecl) 4726 AddObjCMethods(CDecl, false, MK_Any, SelIdents, NumSelIdents, 4727 SemaRef.CurContext, Selectors, AtArgumentExpression, 4728 Results); 4729 else { 4730 // We're messaging "id" as a type; provide all class/factory methods. 4731 4732 // If we have an external source, load the entire class method 4733 // pool from the AST file. 4734 if (SemaRef.ExternalSource) { 4735 for (uint32_t I = 0, 4736 N = SemaRef.ExternalSource->GetNumExternalSelectors(); 4737 I != N; ++I) { 4738 Selector Sel = SemaRef.ExternalSource->GetExternalSelector(I); 4739 if (Sel.isNull() || SemaRef.MethodPool.count(Sel)) 4740 continue; 4741 4742 SemaRef.ReadMethodPool(Sel); 4743 } 4744 } 4745 4746 for (Sema::GlobalMethodPool::iterator M = SemaRef.MethodPool.begin(), 4747 MEnd = SemaRef.MethodPool.end(); 4748 M != MEnd; ++M) { 4749 for (ObjCMethodList *MethList = &M->second.second; 4750 MethList && MethList->Method; 4751 MethList = MethList->Next) { 4752 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents, 4753 NumSelIdents)) 4754 continue; 4755 4756 Result R(MethList->Method, 0); 4757 R.StartParameter = NumSelIdents; 4758 R.AllParametersAreInformative = false; 4759 Results.MaybeAddResult(R, SemaRef.CurContext); 4760 } 4761 } 4762 } 4763 4764 Results.ExitScope(); 4765} 4766 4767void Sema::CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver, 4768 IdentifierInfo **SelIdents, 4769 unsigned NumSelIdents, 4770 bool AtArgumentExpression, 4771 bool IsSuper) { 4772 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 4773 CodeCompletionContext::CCC_Other); 4774 AddClassMessageCompletions(*this, S, Receiver, SelIdents, NumSelIdents, 4775 AtArgumentExpression, IsSuper, Results); 4776 4777 // If we're actually at the argument expression (rather than prior to the 4778 // selector), we're actually performing code completion for an expression. 4779 // Determine whether we have a single, best method. If so, we can 4780 // code-complete the expression using the corresponding parameter type as 4781 // our preferred type, improving completion results. 4782 if (AtArgumentExpression) { 4783 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results, 4784 NumSelIdents); 4785 if (PreferredType.isNull()) 4786 CodeCompleteOrdinaryName(S, PCC_Expression); 4787 else 4788 CodeCompleteExpression(S, PreferredType); 4789 return; 4790 } 4791 4792 HandleCodeCompleteResults(this, CodeCompleter, 4793 CodeCompletionContext::CCC_Other, 4794 Results.data(), Results.size()); 4795} 4796 4797void Sema::CodeCompleteObjCInstanceMessage(Scope *S, ExprTy *Receiver, 4798 IdentifierInfo **SelIdents, 4799 unsigned NumSelIdents, 4800 bool AtArgumentExpression, 4801 ObjCInterfaceDecl *Super) { 4802 typedef CodeCompletionResult Result; 4803 4804 Expr *RecExpr = static_cast<Expr *>(Receiver); 4805 4806 // If necessary, apply function/array conversion to the receiver. 4807 // C99 6.7.5.3p[7,8]. 4808 if (RecExpr) 4809 DefaultFunctionArrayLvalueConversion(RecExpr); 4810 QualType ReceiverType = RecExpr? RecExpr->getType() 4811 : Super? Context.getObjCObjectPointerType( 4812 Context.getObjCInterfaceType(Super)) 4813 : Context.getObjCIdType(); 4814 4815 // If we're messaging an expression with type "id" or "Class", check 4816 // whether we know something special about the receiver that allows 4817 // us to assume a more-specific receiver type. 4818 if (ReceiverType->isObjCIdType() || ReceiverType->isObjCClassType()) 4819 if (ObjCInterfaceDecl *IFace = GetAssumedMessageSendExprType(RecExpr)) { 4820 if (ReceiverType->isObjCClassType()) 4821 return CodeCompleteObjCClassMessage(S, 4822 ParsedType::make(Context.getObjCInterfaceType(IFace)), 4823 SelIdents, NumSelIdents, 4824 AtArgumentExpression, Super); 4825 4826 ReceiverType = Context.getObjCObjectPointerType( 4827 Context.getObjCInterfaceType(IFace)); 4828 } 4829 4830 // Build the set of methods we can see. 4831 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 4832 CodeCompletionContext::CCC_Other); 4833 Results.EnterNewScope(); 4834 4835 // If this is a send-to-super, try to add the special "super" send 4836 // completion. 4837 if (Super) { 4838 if (ObjCMethodDecl *SuperMethod 4839 = AddSuperSendCompletion(*this, false, SelIdents, NumSelIdents, 4840 Results)) 4841 Results.Ignore(SuperMethod); 4842 } 4843 4844 // If we're inside an Objective-C method definition, prefer its selector to 4845 // others. 4846 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) 4847 Results.setPreferredSelector(CurMethod->getSelector()); 4848 4849 // Keep track of the selectors we've already added. 4850 VisitedSelectorSet Selectors; 4851 4852 // Handle messages to Class. This really isn't a message to an instance 4853 // method, so we treat it the same way we would treat a message send to a 4854 // class method. 4855 if (ReceiverType->isObjCClassType() || 4856 ReceiverType->isObjCQualifiedClassType()) { 4857 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) { 4858 if (ObjCInterfaceDecl *ClassDecl = CurMethod->getClassInterface()) 4859 AddObjCMethods(ClassDecl, false, MK_Any, SelIdents, NumSelIdents, 4860 CurContext, Selectors, AtArgumentExpression, Results); 4861 } 4862 } 4863 // Handle messages to a qualified ID ("id<foo>"). 4864 else if (const ObjCObjectPointerType *QualID 4865 = ReceiverType->getAsObjCQualifiedIdType()) { 4866 // Search protocols for instance methods. 4867 for (ObjCObjectPointerType::qual_iterator I = QualID->qual_begin(), 4868 E = QualID->qual_end(); 4869 I != E; ++I) 4870 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext, 4871 Selectors, AtArgumentExpression, Results); 4872 } 4873 // Handle messages to a pointer to interface type. 4874 else if (const ObjCObjectPointerType *IFacePtr 4875 = ReceiverType->getAsObjCInterfacePointerType()) { 4876 // Search the class, its superclasses, etc., for instance methods. 4877 AddObjCMethods(IFacePtr->getInterfaceDecl(), true, MK_Any, SelIdents, 4878 NumSelIdents, CurContext, Selectors, AtArgumentExpression, 4879 Results); 4880 4881 // Search protocols for instance methods. 4882 for (ObjCObjectPointerType::qual_iterator I = IFacePtr->qual_begin(), 4883 E = IFacePtr->qual_end(); 4884 I != E; ++I) 4885 AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext, 4886 Selectors, AtArgumentExpression, Results); 4887 } 4888 // Handle messages to "id". 4889 else if (ReceiverType->isObjCIdType()) { 4890 // We're messaging "id", so provide all instance methods we know 4891 // about as code-completion results. 4892 4893 // If we have an external source, load the entire class method 4894 // pool from the AST file. 4895 if (ExternalSource) { 4896 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors(); 4897 I != N; ++I) { 4898 Selector Sel = ExternalSource->GetExternalSelector(I); 4899 if (Sel.isNull() || MethodPool.count(Sel)) 4900 continue; 4901 4902 ReadMethodPool(Sel); 4903 } 4904 } 4905 4906 for (GlobalMethodPool::iterator M = MethodPool.begin(), 4907 MEnd = MethodPool.end(); 4908 M != MEnd; ++M) { 4909 for (ObjCMethodList *MethList = &M->second.first; 4910 MethList && MethList->Method; 4911 MethList = MethList->Next) { 4912 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents, 4913 NumSelIdents)) 4914 continue; 4915 4916 if (!Selectors.insert(MethList->Method->getSelector())) 4917 continue; 4918 4919 Result R(MethList->Method, 0); 4920 R.StartParameter = NumSelIdents; 4921 R.AllParametersAreInformative = false; 4922 Results.MaybeAddResult(R, CurContext); 4923 } 4924 } 4925 } 4926 Results.ExitScope(); 4927 4928 4929 // If we're actually at the argument expression (rather than prior to the 4930 // selector), we're actually performing code completion for an expression. 4931 // Determine whether we have a single, best method. If so, we can 4932 // code-complete the expression using the corresponding parameter type as 4933 // our preferred type, improving completion results. 4934 if (AtArgumentExpression) { 4935 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results, 4936 NumSelIdents); 4937 if (PreferredType.isNull()) 4938 CodeCompleteOrdinaryName(S, PCC_Expression); 4939 else 4940 CodeCompleteExpression(S, PreferredType); 4941 return; 4942 } 4943 4944 HandleCodeCompleteResults(this, CodeCompleter, 4945 CodeCompletionContext::CCC_Other, 4946 Results.data(),Results.size()); 4947} 4948 4949void Sema::CodeCompleteObjCForCollection(Scope *S, 4950 DeclGroupPtrTy IterationVar) { 4951 CodeCompleteExpressionData Data; 4952 Data.ObjCCollection = true; 4953 4954 if (IterationVar.getAsOpaquePtr()) { 4955 DeclGroupRef DG = IterationVar.getAsVal<DeclGroupRef>(); 4956 for (DeclGroupRef::iterator I = DG.begin(), End = DG.end(); I != End; ++I) { 4957 if (*I) 4958 Data.IgnoreDecls.push_back(*I); 4959 } 4960 } 4961 4962 CodeCompleteExpression(S, Data); 4963} 4964 4965void Sema::CodeCompleteObjCSelector(Scope *S, IdentifierInfo **SelIdents, 4966 unsigned NumSelIdents) { 4967 // If we have an external source, load the entire class method 4968 // pool from the AST file. 4969 if (ExternalSource) { 4970 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors(); 4971 I != N; ++I) { 4972 Selector Sel = ExternalSource->GetExternalSelector(I); 4973 if (Sel.isNull() || MethodPool.count(Sel)) 4974 continue; 4975 4976 ReadMethodPool(Sel); 4977 } 4978 } 4979 4980 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 4981 CodeCompletionContext::CCC_SelectorName); 4982 Results.EnterNewScope(); 4983 for (GlobalMethodPool::iterator M = MethodPool.begin(), 4984 MEnd = MethodPool.end(); 4985 M != MEnd; ++M) { 4986 4987 Selector Sel = M->first; 4988 if (!isAcceptableObjCSelector(Sel, MK_Any, SelIdents, NumSelIdents)) 4989 continue; 4990 4991 CodeCompletionBuilder Builder(Results.getAllocator()); 4992 if (Sel.isUnarySelector()) { 4993 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString( 4994 Sel.getIdentifierInfoForSlot(0)->getName())); 4995 Results.AddResult(Builder.TakeString()); 4996 continue; 4997 } 4998 4999 std::string Accumulator; 5000 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I) { 5001 if (I == NumSelIdents) { 5002 if (!Accumulator.empty()) { 5003 Builder.AddInformativeChunk(Builder.getAllocator().CopyString( 5004 Accumulator)); 5005 Accumulator.clear(); 5006 } 5007 } 5008 5009 Accumulator += Sel.getIdentifierInfoForSlot(I)->getName().str(); 5010 Accumulator += ':'; 5011 } 5012 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString( Accumulator)); 5013 Results.AddResult(Builder.TakeString()); 5014 } 5015 Results.ExitScope(); 5016 5017 HandleCodeCompleteResults(this, CodeCompleter, 5018 CodeCompletionContext::CCC_SelectorName, 5019 Results.data(), Results.size()); 5020} 5021 5022/// \brief Add all of the protocol declarations that we find in the given 5023/// (translation unit) context. 5024static void AddProtocolResults(DeclContext *Ctx, DeclContext *CurContext, 5025 bool OnlyForwardDeclarations, 5026 ResultBuilder &Results) { 5027 typedef CodeCompletionResult Result; 5028 5029 for (DeclContext::decl_iterator D = Ctx->decls_begin(), 5030 DEnd = Ctx->decls_end(); 5031 D != DEnd; ++D) { 5032 // Record any protocols we find. 5033 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*D)) 5034 if (!OnlyForwardDeclarations || Proto->isForwardDecl()) 5035 Results.AddResult(Result(Proto, 0), CurContext, 0, false); 5036 5037 // Record any forward-declared protocols we find. 5038 if (ObjCForwardProtocolDecl *Forward 5039 = dyn_cast<ObjCForwardProtocolDecl>(*D)) { 5040 for (ObjCForwardProtocolDecl::protocol_iterator 5041 P = Forward->protocol_begin(), 5042 PEnd = Forward->protocol_end(); 5043 P != PEnd; ++P) 5044 if (!OnlyForwardDeclarations || (*P)->isForwardDecl()) 5045 Results.AddResult(Result(*P, 0), CurContext, 0, false); 5046 } 5047 } 5048} 5049 5050void Sema::CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols, 5051 unsigned NumProtocols) { 5052 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5053 CodeCompletionContext::CCC_ObjCProtocolName); 5054 5055 if (CodeCompleter && CodeCompleter->includeGlobals()) { 5056 Results.EnterNewScope(); 5057 5058 // Tell the result set to ignore all of the protocols we have 5059 // already seen. 5060 // FIXME: This doesn't work when caching code-completion results. 5061 for (unsigned I = 0; I != NumProtocols; ++I) 5062 if (ObjCProtocolDecl *Protocol = LookupProtocol(Protocols[I].first, 5063 Protocols[I].second)) 5064 Results.Ignore(Protocol); 5065 5066 // Add all protocols. 5067 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, false, 5068 Results); 5069 5070 Results.ExitScope(); 5071 } 5072 5073 HandleCodeCompleteResults(this, CodeCompleter, 5074 CodeCompletionContext::CCC_ObjCProtocolName, 5075 Results.data(),Results.size()); 5076} 5077 5078void Sema::CodeCompleteObjCProtocolDecl(Scope *) { 5079 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5080 CodeCompletionContext::CCC_ObjCProtocolName); 5081 5082 if (CodeCompleter && CodeCompleter->includeGlobals()) { 5083 Results.EnterNewScope(); 5084 5085 // Add all protocols. 5086 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, true, 5087 Results); 5088 5089 Results.ExitScope(); 5090 } 5091 5092 HandleCodeCompleteResults(this, CodeCompleter, 5093 CodeCompletionContext::CCC_ObjCProtocolName, 5094 Results.data(),Results.size()); 5095} 5096 5097/// \brief Add all of the Objective-C interface declarations that we find in 5098/// the given (translation unit) context. 5099static void AddInterfaceResults(DeclContext *Ctx, DeclContext *CurContext, 5100 bool OnlyForwardDeclarations, 5101 bool OnlyUnimplemented, 5102 ResultBuilder &Results) { 5103 typedef CodeCompletionResult Result; 5104 5105 for (DeclContext::decl_iterator D = Ctx->decls_begin(), 5106 DEnd = Ctx->decls_end(); 5107 D != DEnd; ++D) { 5108 // Record any interfaces we find. 5109 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*D)) 5110 if ((!OnlyForwardDeclarations || Class->isForwardDecl()) && 5111 (!OnlyUnimplemented || !Class->getImplementation())) 5112 Results.AddResult(Result(Class, 0), CurContext, 0, false); 5113 5114 // Record any forward-declared interfaces we find. 5115 if (ObjCClassDecl *Forward = dyn_cast<ObjCClassDecl>(*D)) { 5116 for (ObjCClassDecl::iterator C = Forward->begin(), CEnd = Forward->end(); 5117 C != CEnd; ++C) 5118 if ((!OnlyForwardDeclarations || C->getInterface()->isForwardDecl()) && 5119 (!OnlyUnimplemented || !C->getInterface()->getImplementation())) 5120 Results.AddResult(Result(C->getInterface(), 0), CurContext, 5121 0, false); 5122 } 5123 } 5124} 5125 5126void Sema::CodeCompleteObjCInterfaceDecl(Scope *S) { 5127 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5128 CodeCompletionContext::CCC_Other); 5129 Results.EnterNewScope(); 5130 5131 // Add all classes. 5132 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, true, 5133 false, Results); 5134 5135 Results.ExitScope(); 5136 // FIXME: Add a special context for this, use cached global completion 5137 // results. 5138 HandleCodeCompleteResults(this, CodeCompleter, 5139 CodeCompletionContext::CCC_Other, 5140 Results.data(),Results.size()); 5141} 5142 5143void Sema::CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName, 5144 SourceLocation ClassNameLoc) { 5145 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5146 CodeCompletionContext::CCC_Other); 5147 Results.EnterNewScope(); 5148 5149 // Make sure that we ignore the class we're currently defining. 5150 NamedDecl *CurClass 5151 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName); 5152 if (CurClass && isa<ObjCInterfaceDecl>(CurClass)) 5153 Results.Ignore(CurClass); 5154 5155 // Add all classes. 5156 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false, 5157 false, Results); 5158 5159 Results.ExitScope(); 5160 // FIXME: Add a special context for this, use cached global completion 5161 // results. 5162 HandleCodeCompleteResults(this, CodeCompleter, 5163 CodeCompletionContext::CCC_Other, 5164 Results.data(),Results.size()); 5165} 5166 5167void Sema::CodeCompleteObjCImplementationDecl(Scope *S) { 5168 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5169 CodeCompletionContext::CCC_Other); 5170 Results.EnterNewScope(); 5171 5172 // Add all unimplemented classes. 5173 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false, 5174 true, Results); 5175 5176 Results.ExitScope(); 5177 // FIXME: Add a special context for this, use cached global completion 5178 // results. 5179 HandleCodeCompleteResults(this, CodeCompleter, 5180 CodeCompletionContext::CCC_Other, 5181 Results.data(),Results.size()); 5182} 5183 5184void Sema::CodeCompleteObjCInterfaceCategory(Scope *S, 5185 IdentifierInfo *ClassName, 5186 SourceLocation ClassNameLoc) { 5187 typedef CodeCompletionResult Result; 5188 5189 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5190 CodeCompletionContext::CCC_Other); 5191 5192 // Ignore any categories we find that have already been implemented by this 5193 // interface. 5194 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames; 5195 NamedDecl *CurClass 5196 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName); 5197 if (ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass)) 5198 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category; 5199 Category = Category->getNextClassCategory()) 5200 CategoryNames.insert(Category->getIdentifier()); 5201 5202 // Add all of the categories we know about. 5203 Results.EnterNewScope(); 5204 TranslationUnitDecl *TU = Context.getTranslationUnitDecl(); 5205 for (DeclContext::decl_iterator D = TU->decls_begin(), 5206 DEnd = TU->decls_end(); 5207 D != DEnd; ++D) 5208 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(*D)) 5209 if (CategoryNames.insert(Category->getIdentifier())) 5210 Results.AddResult(Result(Category, 0), CurContext, 0, false); 5211 Results.ExitScope(); 5212 5213 HandleCodeCompleteResults(this, CodeCompleter, 5214 CodeCompletionContext::CCC_Other, 5215 Results.data(),Results.size()); 5216} 5217 5218void Sema::CodeCompleteObjCImplementationCategory(Scope *S, 5219 IdentifierInfo *ClassName, 5220 SourceLocation ClassNameLoc) { 5221 typedef CodeCompletionResult Result; 5222 5223 // Find the corresponding interface. If we couldn't find the interface, the 5224 // program itself is ill-formed. However, we'll try to be helpful still by 5225 // providing the list of all of the categories we know about. 5226 NamedDecl *CurClass 5227 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName); 5228 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass); 5229 if (!Class) 5230 return CodeCompleteObjCInterfaceCategory(S, ClassName, ClassNameLoc); 5231 5232 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5233 CodeCompletionContext::CCC_Other); 5234 5235 // Add all of the categories that have have corresponding interface 5236 // declarations in this class and any of its superclasses, except for 5237 // already-implemented categories in the class itself. 5238 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames; 5239 Results.EnterNewScope(); 5240 bool IgnoreImplemented = true; 5241 while (Class) { 5242 for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category; 5243 Category = Category->getNextClassCategory()) 5244 if ((!IgnoreImplemented || !Category->getImplementation()) && 5245 CategoryNames.insert(Category->getIdentifier())) 5246 Results.AddResult(Result(Category, 0), CurContext, 0, false); 5247 5248 Class = Class->getSuperClass(); 5249 IgnoreImplemented = false; 5250 } 5251 Results.ExitScope(); 5252 5253 HandleCodeCompleteResults(this, CodeCompleter, 5254 CodeCompletionContext::CCC_Other, 5255 Results.data(),Results.size()); 5256} 5257 5258void Sema::CodeCompleteObjCPropertyDefinition(Scope *S, Decl *ObjCImpDecl) { 5259 typedef CodeCompletionResult Result; 5260 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5261 CodeCompletionContext::CCC_Other); 5262 5263 // Figure out where this @synthesize lives. 5264 ObjCContainerDecl *Container 5265 = dyn_cast_or_null<ObjCContainerDecl>(ObjCImpDecl); 5266 if (!Container || 5267 (!isa<ObjCImplementationDecl>(Container) && 5268 !isa<ObjCCategoryImplDecl>(Container))) 5269 return; 5270 5271 // Ignore any properties that have already been implemented. 5272 for (DeclContext::decl_iterator D = Container->decls_begin(), 5273 DEnd = Container->decls_end(); 5274 D != DEnd; ++D) 5275 if (ObjCPropertyImplDecl *PropertyImpl = dyn_cast<ObjCPropertyImplDecl>(*D)) 5276 Results.Ignore(PropertyImpl->getPropertyDecl()); 5277 5278 // Add any properties that we find. 5279 AddedPropertiesSet AddedProperties; 5280 Results.EnterNewScope(); 5281 if (ObjCImplementationDecl *ClassImpl 5282 = dyn_cast<ObjCImplementationDecl>(Container)) 5283 AddObjCProperties(ClassImpl->getClassInterface(), false, CurContext, 5284 AddedProperties, Results); 5285 else 5286 AddObjCProperties(cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl(), 5287 false, CurContext, AddedProperties, Results); 5288 Results.ExitScope(); 5289 5290 HandleCodeCompleteResults(this, CodeCompleter, 5291 CodeCompletionContext::CCC_Other, 5292 Results.data(),Results.size()); 5293} 5294 5295void Sema::CodeCompleteObjCPropertySynthesizeIvar(Scope *S, 5296 IdentifierInfo *PropertyName, 5297 Decl *ObjCImpDecl) { 5298 typedef CodeCompletionResult Result; 5299 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5300 CodeCompletionContext::CCC_Other); 5301 5302 // Figure out where this @synthesize lives. 5303 ObjCContainerDecl *Container 5304 = dyn_cast_or_null<ObjCContainerDecl>(ObjCImpDecl); 5305 if (!Container || 5306 (!isa<ObjCImplementationDecl>(Container) && 5307 !isa<ObjCCategoryImplDecl>(Container))) 5308 return; 5309 5310 // Figure out which interface we're looking into. 5311 ObjCInterfaceDecl *Class = 0; 5312 if (ObjCImplementationDecl *ClassImpl 5313 = dyn_cast<ObjCImplementationDecl>(Container)) 5314 Class = ClassImpl->getClassInterface(); 5315 else 5316 Class = cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl() 5317 ->getClassInterface(); 5318 5319 // Add all of the instance variables in this class and its superclasses. 5320 Results.EnterNewScope(); 5321 for(; Class; Class = Class->getSuperClass()) { 5322 // FIXME: We could screen the type of each ivar for compatibility with 5323 // the property, but is that being too paternal? 5324 for (ObjCInterfaceDecl::ivar_iterator IVar = Class->ivar_begin(), 5325 IVarEnd = Class->ivar_end(); 5326 IVar != IVarEnd; ++IVar) 5327 Results.AddResult(Result(*IVar, 0), CurContext, 0, false); 5328 } 5329 Results.ExitScope(); 5330 5331 HandleCodeCompleteResults(this, CodeCompleter, 5332 CodeCompletionContext::CCC_Other, 5333 Results.data(),Results.size()); 5334} 5335 5336// Mapping from selectors to the methods that implement that selector, along 5337// with the "in original class" flag. 5338typedef llvm::DenseMap<Selector, std::pair<ObjCMethodDecl *, bool> > 5339 KnownMethodsMap; 5340 5341/// \brief Find all of the methods that reside in the given container 5342/// (and its superclasses, protocols, etc.) that meet the given 5343/// criteria. Insert those methods into the map of known methods, 5344/// indexed by selector so they can be easily found. 5345static void FindImplementableMethods(ASTContext &Context, 5346 ObjCContainerDecl *Container, 5347 bool WantInstanceMethods, 5348 QualType ReturnType, 5349 KnownMethodsMap &KnownMethods, 5350 bool InOriginalClass = true) { 5351 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)) { 5352 // Recurse into protocols. 5353 const ObjCList<ObjCProtocolDecl> &Protocols 5354 = IFace->getReferencedProtocols(); 5355 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(), 5356 E = Protocols.end(); 5357 I != E; ++I) 5358 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType, 5359 KnownMethods, InOriginalClass); 5360 5361 // Add methods from any class extensions and categories. 5362 for (const ObjCCategoryDecl *Cat = IFace->getCategoryList(); Cat; 5363 Cat = Cat->getNextClassCategory()) 5364 FindImplementableMethods(Context, const_cast<ObjCCategoryDecl*>(Cat), 5365 WantInstanceMethods, ReturnType, 5366 KnownMethods, false); 5367 5368 // Visit the superclass. 5369 if (IFace->getSuperClass()) 5370 FindImplementableMethods(Context, IFace->getSuperClass(), 5371 WantInstanceMethods, ReturnType, 5372 KnownMethods, false); 5373 } 5374 5375 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) { 5376 // Recurse into protocols. 5377 const ObjCList<ObjCProtocolDecl> &Protocols 5378 = Category->getReferencedProtocols(); 5379 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(), 5380 E = Protocols.end(); 5381 I != E; ++I) 5382 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType, 5383 KnownMethods, InOriginalClass); 5384 5385 // If this category is the original class, jump to the interface. 5386 if (InOriginalClass && Category->getClassInterface()) 5387 FindImplementableMethods(Context, Category->getClassInterface(), 5388 WantInstanceMethods, ReturnType, KnownMethods, 5389 false); 5390 } 5391 5392 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) { 5393 // Recurse into protocols. 5394 const ObjCList<ObjCProtocolDecl> &Protocols 5395 = Protocol->getReferencedProtocols(); 5396 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(), 5397 E = Protocols.end(); 5398 I != E; ++I) 5399 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType, 5400 KnownMethods, false); 5401 } 5402 5403 // Add methods in this container. This operation occurs last because 5404 // we want the methods from this container to override any methods 5405 // we've previously seen with the same selector. 5406 for (ObjCContainerDecl::method_iterator M = Container->meth_begin(), 5407 MEnd = Container->meth_end(); 5408 M != MEnd; ++M) { 5409 if ((*M)->isInstanceMethod() == WantInstanceMethods) { 5410 if (!ReturnType.isNull() && 5411 !Context.hasSameUnqualifiedType(ReturnType, (*M)->getResultType())) 5412 continue; 5413 5414 KnownMethods[(*M)->getSelector()] = std::make_pair(*M, InOriginalClass); 5415 } 5416 } 5417} 5418 5419void Sema::CodeCompleteObjCMethodDecl(Scope *S, 5420 bool IsInstanceMethod, 5421 ParsedType ReturnTy, 5422 Decl *IDecl) { 5423 // Determine the return type of the method we're declaring, if 5424 // provided. 5425 QualType ReturnType = GetTypeFromParser(ReturnTy); 5426 5427 // Determine where we should start searching for methods. 5428 ObjCContainerDecl *SearchDecl = 0; 5429 bool IsInImplementation = false; 5430 if (Decl *D = IDecl) { 5431 if (ObjCImplementationDecl *Impl = dyn_cast<ObjCImplementationDecl>(D)) { 5432 SearchDecl = Impl->getClassInterface(); 5433 IsInImplementation = true; 5434 } else if (ObjCCategoryImplDecl *CatImpl 5435 = dyn_cast<ObjCCategoryImplDecl>(D)) { 5436 SearchDecl = CatImpl->getCategoryDecl(); 5437 IsInImplementation = true; 5438 } else 5439 SearchDecl = dyn_cast<ObjCContainerDecl>(D); 5440 } 5441 5442 if (!SearchDecl && S) { 5443 if (DeclContext *DC = static_cast<DeclContext *>(S->getEntity())) 5444 SearchDecl = dyn_cast<ObjCContainerDecl>(DC); 5445 } 5446 5447 if (!SearchDecl) { 5448 HandleCodeCompleteResults(this, CodeCompleter, 5449 CodeCompletionContext::CCC_Other, 5450 0, 0); 5451 return; 5452 } 5453 5454 // Find all of the methods that we could declare/implement here. 5455 KnownMethodsMap KnownMethods; 5456 FindImplementableMethods(Context, SearchDecl, IsInstanceMethod, 5457 ReturnType, KnownMethods); 5458 5459 // Add declarations or definitions for each of the known methods. 5460 typedef CodeCompletionResult Result; 5461 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5462 CodeCompletionContext::CCC_Other); 5463 Results.EnterNewScope(); 5464 PrintingPolicy Policy(Context.PrintingPolicy); 5465 Policy.AnonymousTagLocations = false; 5466 for (KnownMethodsMap::iterator M = KnownMethods.begin(), 5467 MEnd = KnownMethods.end(); 5468 M != MEnd; ++M) { 5469 ObjCMethodDecl *Method = M->second.first; 5470 CodeCompletionBuilder Builder(Results.getAllocator()); 5471 5472 // If the result type was not already provided, add it to the 5473 // pattern as (type). 5474 if (ReturnType.isNull()) { 5475 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 5476 Builder.AddTextChunk(GetCompletionTypeString(Method->getResultType(), 5477 Context, 5478 Builder.getAllocator())); 5479 Builder.AddChunk(CodeCompletionString::CK_RightParen); 5480 } 5481 5482 Selector Sel = Method->getSelector(); 5483 5484 // Add the first part of the selector to the pattern. 5485 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString( 5486 Sel.getIdentifierInfoForSlot(0)->getName())); 5487 5488 // Add parameters to the pattern. 5489 unsigned I = 0; 5490 for (ObjCMethodDecl::param_iterator P = Method->param_begin(), 5491 PEnd = Method->param_end(); 5492 P != PEnd; (void)++P, ++I) { 5493 // Add the part of the selector name. 5494 if (I == 0) 5495 Builder.AddTypedTextChunk(":"); 5496 else if (I < Sel.getNumArgs()) { 5497 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 5498 Builder.AddTypedTextChunk( 5499 Builder.getAllocator().CopyString( 5500 (Sel.getIdentifierInfoForSlot(I)->getName() 5501 + ":").str())); 5502 } else 5503 break; 5504 5505 // Add the parameter type. 5506 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 5507 Builder.AddTextChunk(GetCompletionTypeString((*P)->getOriginalType(), 5508 Context, 5509 Builder.getAllocator())); 5510 Builder.AddChunk(CodeCompletionString::CK_RightParen); 5511 5512 if (IdentifierInfo *Id = (*P)->getIdentifier()) 5513 Builder.AddTextChunk(Builder.getAllocator().CopyString( Id->getName())); 5514 } 5515 5516 if (Method->isVariadic()) { 5517 if (Method->param_size() > 0) 5518 Builder.AddChunk(CodeCompletionString::CK_Comma); 5519 Builder.AddTextChunk("..."); 5520 } 5521 5522 if (IsInImplementation && Results.includeCodePatterns()) { 5523 // We will be defining the method here, so add a compound statement. 5524 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 5525 Builder.AddChunk(CodeCompletionString::CK_LeftBrace); 5526 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); 5527 if (!Method->getResultType()->isVoidType()) { 5528 // If the result type is not void, add a return clause. 5529 Builder.AddTextChunk("return"); 5530 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 5531 Builder.AddPlaceholderChunk("expression"); 5532 Builder.AddChunk(CodeCompletionString::CK_SemiColon); 5533 } else 5534 Builder.AddPlaceholderChunk("statements"); 5535 5536 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); 5537 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 5538 } 5539 5540 unsigned Priority = CCP_CodePattern; 5541 if (!M->second.second) 5542 Priority += CCD_InBaseClass; 5543 5544 Results.AddResult(Result(Builder.TakeString(), Priority, 5545 Method->isInstanceMethod() 5546 ? CXCursor_ObjCInstanceMethodDecl 5547 : CXCursor_ObjCClassMethodDecl)); 5548 } 5549 5550 Results.ExitScope(); 5551 5552 HandleCodeCompleteResults(this, CodeCompleter, 5553 CodeCompletionContext::CCC_Other, 5554 Results.data(),Results.size()); 5555} 5556 5557void Sema::CodeCompleteObjCMethodDeclSelector(Scope *S, 5558 bool IsInstanceMethod, 5559 bool AtParameterName, 5560 ParsedType ReturnTy, 5561 IdentifierInfo **SelIdents, 5562 unsigned NumSelIdents) { 5563 // If we have an external source, load the entire class method 5564 // pool from the AST file. 5565 if (ExternalSource) { 5566 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors(); 5567 I != N; ++I) { 5568 Selector Sel = ExternalSource->GetExternalSelector(I); 5569 if (Sel.isNull() || MethodPool.count(Sel)) 5570 continue; 5571 5572 ReadMethodPool(Sel); 5573 } 5574 } 5575 5576 // Build the set of methods we can see. 5577 typedef CodeCompletionResult Result; 5578 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5579 CodeCompletionContext::CCC_Other); 5580 5581 if (ReturnTy) 5582 Results.setPreferredType(GetTypeFromParser(ReturnTy).getNonReferenceType()); 5583 5584 Results.EnterNewScope(); 5585 for (GlobalMethodPool::iterator M = MethodPool.begin(), 5586 MEnd = MethodPool.end(); 5587 M != MEnd; ++M) { 5588 for (ObjCMethodList *MethList = IsInstanceMethod ? &M->second.first : 5589 &M->second.second; 5590 MethList && MethList->Method; 5591 MethList = MethList->Next) { 5592 if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents, 5593 NumSelIdents)) 5594 continue; 5595 5596 if (AtParameterName) { 5597 // Suggest parameter names we've seen before. 5598 if (NumSelIdents && NumSelIdents <= MethList->Method->param_size()) { 5599 ParmVarDecl *Param = MethList->Method->param_begin()[NumSelIdents-1]; 5600 if (Param->getIdentifier()) { 5601 CodeCompletionBuilder Builder(Results.getAllocator()); 5602 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString( 5603 Param->getIdentifier()->getName())); 5604 Results.AddResult(Builder.TakeString()); 5605 } 5606 } 5607 5608 continue; 5609 } 5610 5611 Result R(MethList->Method, 0); 5612 R.StartParameter = NumSelIdents; 5613 R.AllParametersAreInformative = false; 5614 R.DeclaringEntity = true; 5615 Results.MaybeAddResult(R, CurContext); 5616 } 5617 } 5618 5619 Results.ExitScope(); 5620 HandleCodeCompleteResults(this, CodeCompleter, 5621 CodeCompletionContext::CCC_Other, 5622 Results.data(),Results.size()); 5623} 5624 5625void Sema::CodeCompletePreprocessorDirective(bool InConditional) { 5626 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5627 CodeCompletionContext::CCC_PreprocessorDirective); 5628 Results.EnterNewScope(); 5629 5630 // #if <condition> 5631 CodeCompletionBuilder Builder(Results.getAllocator()); 5632 Builder.AddTypedTextChunk("if"); 5633 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 5634 Builder.AddPlaceholderChunk("condition"); 5635 Results.AddResult(Builder.TakeString()); 5636 5637 // #ifdef <macro> 5638 Builder.AddTypedTextChunk("ifdef"); 5639 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 5640 Builder.AddPlaceholderChunk("macro"); 5641 Results.AddResult(Builder.TakeString()); 5642 5643 // #ifndef <macro> 5644 Builder.AddTypedTextChunk("ifndef"); 5645 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 5646 Builder.AddPlaceholderChunk("macro"); 5647 Results.AddResult(Builder.TakeString()); 5648 5649 if (InConditional) { 5650 // #elif <condition> 5651 Builder.AddTypedTextChunk("elif"); 5652 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 5653 Builder.AddPlaceholderChunk("condition"); 5654 Results.AddResult(Builder.TakeString()); 5655 5656 // #else 5657 Builder.AddTypedTextChunk("else"); 5658 Results.AddResult(Builder.TakeString()); 5659 5660 // #endif 5661 Builder.AddTypedTextChunk("endif"); 5662 Results.AddResult(Builder.TakeString()); 5663 } 5664 5665 // #include "header" 5666 Builder.AddTypedTextChunk("include"); 5667 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 5668 Builder.AddTextChunk("\""); 5669 Builder.AddPlaceholderChunk("header"); 5670 Builder.AddTextChunk("\""); 5671 Results.AddResult(Builder.TakeString()); 5672 5673 // #include <header> 5674 Builder.AddTypedTextChunk("include"); 5675 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 5676 Builder.AddTextChunk("<"); 5677 Builder.AddPlaceholderChunk("header"); 5678 Builder.AddTextChunk(">"); 5679 Results.AddResult(Builder.TakeString()); 5680 5681 // #define <macro> 5682 Builder.AddTypedTextChunk("define"); 5683 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 5684 Builder.AddPlaceholderChunk("macro"); 5685 Results.AddResult(Builder.TakeString()); 5686 5687 // #define <macro>(<args>) 5688 Builder.AddTypedTextChunk("define"); 5689 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 5690 Builder.AddPlaceholderChunk("macro"); 5691 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 5692 Builder.AddPlaceholderChunk("args"); 5693 Builder.AddChunk(CodeCompletionString::CK_RightParen); 5694 Results.AddResult(Builder.TakeString()); 5695 5696 // #undef <macro> 5697 Builder.AddTypedTextChunk("undef"); 5698 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 5699 Builder.AddPlaceholderChunk("macro"); 5700 Results.AddResult(Builder.TakeString()); 5701 5702 // #line <number> 5703 Builder.AddTypedTextChunk("line"); 5704 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 5705 Builder.AddPlaceholderChunk("number"); 5706 Results.AddResult(Builder.TakeString()); 5707 5708 // #line <number> "filename" 5709 Builder.AddTypedTextChunk("line"); 5710 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 5711 Builder.AddPlaceholderChunk("number"); 5712 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 5713 Builder.AddTextChunk("\""); 5714 Builder.AddPlaceholderChunk("filename"); 5715 Builder.AddTextChunk("\""); 5716 Results.AddResult(Builder.TakeString()); 5717 5718 // #error <message> 5719 Builder.AddTypedTextChunk("error"); 5720 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 5721 Builder.AddPlaceholderChunk("message"); 5722 Results.AddResult(Builder.TakeString()); 5723 5724 // #pragma <arguments> 5725 Builder.AddTypedTextChunk("pragma"); 5726 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 5727 Builder.AddPlaceholderChunk("arguments"); 5728 Results.AddResult(Builder.TakeString()); 5729 5730 if (getLangOptions().ObjC1) { 5731 // #import "header" 5732 Builder.AddTypedTextChunk("import"); 5733 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 5734 Builder.AddTextChunk("\""); 5735 Builder.AddPlaceholderChunk("header"); 5736 Builder.AddTextChunk("\""); 5737 Results.AddResult(Builder.TakeString()); 5738 5739 // #import <header> 5740 Builder.AddTypedTextChunk("import"); 5741 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 5742 Builder.AddTextChunk("<"); 5743 Builder.AddPlaceholderChunk("header"); 5744 Builder.AddTextChunk(">"); 5745 Results.AddResult(Builder.TakeString()); 5746 } 5747 5748 // #include_next "header" 5749 Builder.AddTypedTextChunk("include_next"); 5750 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 5751 Builder.AddTextChunk("\""); 5752 Builder.AddPlaceholderChunk("header"); 5753 Builder.AddTextChunk("\""); 5754 Results.AddResult(Builder.TakeString()); 5755 5756 // #include_next <header> 5757 Builder.AddTypedTextChunk("include_next"); 5758 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 5759 Builder.AddTextChunk("<"); 5760 Builder.AddPlaceholderChunk("header"); 5761 Builder.AddTextChunk(">"); 5762 Results.AddResult(Builder.TakeString()); 5763 5764 // #warning <message> 5765 Builder.AddTypedTextChunk("warning"); 5766 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 5767 Builder.AddPlaceholderChunk("message"); 5768 Results.AddResult(Builder.TakeString()); 5769 5770 // Note: #ident and #sccs are such crazy anachronisms that we don't provide 5771 // completions for them. And __include_macros is a Clang-internal extension 5772 // that we don't want to encourage anyone to use. 5773 5774 // FIXME: we don't support #assert or #unassert, so don't suggest them. 5775 Results.ExitScope(); 5776 5777 HandleCodeCompleteResults(this, CodeCompleter, 5778 CodeCompletionContext::CCC_PreprocessorDirective, 5779 Results.data(), Results.size()); 5780} 5781 5782void Sema::CodeCompleteInPreprocessorConditionalExclusion(Scope *S) { 5783 CodeCompleteOrdinaryName(S, 5784 S->getFnParent()? Sema::PCC_RecoveryInFunction 5785 : Sema::PCC_Namespace); 5786} 5787 5788void Sema::CodeCompletePreprocessorMacroName(bool IsDefinition) { 5789 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5790 IsDefinition? CodeCompletionContext::CCC_MacroName 5791 : CodeCompletionContext::CCC_MacroNameUse); 5792 if (!IsDefinition && (!CodeCompleter || CodeCompleter->includeMacros())) { 5793 // Add just the names of macros, not their arguments. 5794 CodeCompletionBuilder Builder(Results.getAllocator()); 5795 Results.EnterNewScope(); 5796 for (Preprocessor::macro_iterator M = PP.macro_begin(), 5797 MEnd = PP.macro_end(); 5798 M != MEnd; ++M) { 5799 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString( 5800 M->first->getName())); 5801 Results.AddResult(Builder.TakeString()); 5802 } 5803 Results.ExitScope(); 5804 } else if (IsDefinition) { 5805 // FIXME: Can we detect when the user just wrote an include guard above? 5806 } 5807 5808 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 5809 Results.data(), Results.size()); 5810} 5811 5812void Sema::CodeCompletePreprocessorExpression() { 5813 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5814 CodeCompletionContext::CCC_PreprocessorExpression); 5815 5816 if (!CodeCompleter || CodeCompleter->includeMacros()) 5817 AddMacroResults(PP, Results); 5818 5819 // defined (<macro>) 5820 Results.EnterNewScope(); 5821 CodeCompletionBuilder Builder(Results.getAllocator()); 5822 Builder.AddTypedTextChunk("defined"); 5823 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 5824 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 5825 Builder.AddPlaceholderChunk("macro"); 5826 Builder.AddChunk(CodeCompletionString::CK_RightParen); 5827 Results.AddResult(Builder.TakeString()); 5828 Results.ExitScope(); 5829 5830 HandleCodeCompleteResults(this, CodeCompleter, 5831 CodeCompletionContext::CCC_PreprocessorExpression, 5832 Results.data(), Results.size()); 5833} 5834 5835void Sema::CodeCompletePreprocessorMacroArgument(Scope *S, 5836 IdentifierInfo *Macro, 5837 MacroInfo *MacroInfo, 5838 unsigned Argument) { 5839 // FIXME: In the future, we could provide "overload" results, much like we 5840 // do for function calls. 5841 5842 CodeCompleteOrdinaryName(S, 5843 S->getFnParent()? Sema::PCC_RecoveryInFunction 5844 : Sema::PCC_Namespace); 5845} 5846 5847void Sema::CodeCompleteNaturalLanguage() { 5848 HandleCodeCompleteResults(this, CodeCompleter, 5849 CodeCompletionContext::CCC_NaturalLanguage, 5850 0, 0); 5851} 5852 5853void Sema::GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator, 5854 llvm::SmallVectorImpl<CodeCompletionResult> &Results) { 5855 ResultBuilder Builder(*this, Allocator, CodeCompletionContext::CCC_Recovery); 5856 if (!CodeCompleter || CodeCompleter->includeGlobals()) { 5857 CodeCompletionDeclConsumer Consumer(Builder, 5858 Context.getTranslationUnitDecl()); 5859 LookupVisibleDecls(Context.getTranslationUnitDecl(), LookupAnyName, 5860 Consumer); 5861 } 5862 5863 if (!CodeCompleter || CodeCompleter->includeMacros()) 5864 AddMacroResults(PP, Builder); 5865 5866 Results.clear(); 5867 Results.insert(Results.end(), 5868 Builder.data(), Builder.data() + Builder.size()); 5869} 5870