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