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