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