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