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