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