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