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