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 void ResultBuilder::MaybeAddConstructorResults(Result R) { 812 if (!SemaRef.getLangOpts().CPlusPlus || !R.Declaration || 813 !CompletionContext.wantConstructorResults()) 814 return; 815 816 ASTContext &Context = SemaRef.Context; 817 const NamedDecl *D = R.Declaration; 818 const CXXRecordDecl *Record = nullptr; 819 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) 820 Record = ClassTemplate->getTemplatedDecl(); 821 else if ((Record = dyn_cast<CXXRecordDecl>(D))) { 822 // Skip specializations and partial specializations. 823 if (isa<ClassTemplateSpecializationDecl>(Record)) 824 return; 825 } else { 826 // There are no constructors here. 827 return; 828 } 829 830 Record = Record->getDefinition(); 831 if (!Record) 832 return; 833 834 835 QualType RecordTy = Context.getTypeDeclType(Record); 836 DeclarationName ConstructorName 837 = Context.DeclarationNames.getCXXConstructorName( 838 Context.getCanonicalType(RecordTy)); 839 DeclContext::lookup_result Ctors = Record->lookup(ConstructorName); 840 for (DeclContext::lookup_iterator I = Ctors.begin(), 841 E = Ctors.end(); 842 I != E; ++I) { 843 R.Declaration = *I; 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().ObjC1) { 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().ObjC1) { 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.ObjC1? 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.ObjC1 || 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().ObjC1) 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().ObjC1) 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().ObjC1) { 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().ObjC1 && 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.ObjC1? 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().ObjC1) 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().ObjC1) 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 CodeCompleteExpression(S, VD->getType()); 4751 } 4752 4753 void Sema::CodeCompleteReturn(Scope *S) { 4754 QualType ResultType; 4755 if (isa<BlockDecl>(CurContext)) { 4756 if (BlockScopeInfo *BSI = getCurBlock()) 4757 ResultType = BSI->ReturnType; 4758 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(CurContext)) 4759 ResultType = Function->getReturnType(); 4760 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(CurContext)) 4761 ResultType = Method->getReturnType(); 4762 4763 if (ResultType.isNull()) 4764 CodeCompleteOrdinaryName(S, PCC_Expression); 4765 else 4766 CodeCompleteExpression(S, ResultType); 4767 } 4768 4769 void Sema::CodeCompleteAfterIf(Scope *S) { 4770 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 4771 CodeCompleter->getCodeCompletionTUInfo(), 4772 mapCodeCompletionContext(*this, PCC_Statement)); 4773 Results.setFilter(&ResultBuilder::IsOrdinaryName); 4774 Results.EnterNewScope(); 4775 4776 CodeCompletionDeclConsumer Consumer(Results, CurContext); 4777 LookupVisibleDecls(S, LookupOrdinaryName, Consumer, 4778 CodeCompleter->includeGlobals(), 4779 CodeCompleter->loadExternal()); 4780 4781 AddOrdinaryNameResults(PCC_Statement, S, *this, Results); 4782 4783 // "else" block 4784 CodeCompletionBuilder Builder(Results.getAllocator(), 4785 Results.getCodeCompletionTUInfo()); 4786 Builder.AddTypedTextChunk("else"); 4787 if (Results.includeCodePatterns()) { 4788 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 4789 Builder.AddChunk(CodeCompletionString::CK_LeftBrace); 4790 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); 4791 Builder.AddPlaceholderChunk("statements"); 4792 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); 4793 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 4794 } 4795 Results.AddResult(Builder.TakeString()); 4796 4797 // "else if" block 4798 Builder.AddTypedTextChunk("else"); 4799 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 4800 Builder.AddTextChunk("if"); 4801 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 4802 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 4803 if (getLangOpts().CPlusPlus) 4804 Builder.AddPlaceholderChunk("condition"); 4805 else 4806 Builder.AddPlaceholderChunk("expression"); 4807 Builder.AddChunk(CodeCompletionString::CK_RightParen); 4808 if (Results.includeCodePatterns()) { 4809 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 4810 Builder.AddChunk(CodeCompletionString::CK_LeftBrace); 4811 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); 4812 Builder.AddPlaceholderChunk("statements"); 4813 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); 4814 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 4815 } 4816 Results.AddResult(Builder.TakeString()); 4817 4818 Results.ExitScope(); 4819 4820 if (S->getFnParent()) 4821 AddPrettyFunctionResults(getLangOpts(), Results); 4822 4823 if (CodeCompleter->includeMacros()) 4824 AddMacroResults(PP, Results, CodeCompleter->loadExternal(), false); 4825 4826 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 4827 Results.data(),Results.size()); 4828 } 4829 4830 void Sema::CodeCompleteAssignmentRHS(Scope *S, Expr *LHS) { 4831 if (LHS) 4832 CodeCompleteExpression(S, static_cast<Expr *>(LHS)->getType()); 4833 else 4834 CodeCompleteOrdinaryName(S, PCC_Expression); 4835 } 4836 4837 void Sema::CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS, 4838 bool EnteringContext) { 4839 if (SS.isEmpty() || !CodeCompleter) 4840 return; 4841 4842 // We want to keep the scope specifier even if it's invalid (e.g. the scope 4843 // "a::b::" is not corresponding to any context/namespace in the AST), since 4844 // it can be useful for global code completion which have information about 4845 // contexts/symbols that are not in the AST. 4846 if (SS.isInvalid()) { 4847 CodeCompletionContext CC(CodeCompletionContext::CCC_Symbol); 4848 CC.setCXXScopeSpecifier(SS); 4849 HandleCodeCompleteResults(this, CodeCompleter, CC, nullptr, 0); 4850 return; 4851 } 4852 // Always pretend to enter a context to ensure that a dependent type 4853 // resolves to a dependent record. 4854 DeclContext *Ctx = computeDeclContext(SS, /*EnteringContext=*/true); 4855 if (!Ctx) 4856 return; 4857 4858 // Try to instantiate any non-dependent declaration contexts before 4859 // we look in them. 4860 if (!isDependentScopeSpecifier(SS) && RequireCompleteDeclContext(SS, Ctx)) 4861 return; 4862 4863 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 4864 CodeCompleter->getCodeCompletionTUInfo(), 4865 CodeCompletionContext::CCC_Symbol); 4866 Results.EnterNewScope(); 4867 4868 // The "template" keyword can follow "::" in the grammar, but only 4869 // put it into the grammar if the nested-name-specifier is dependent. 4870 NestedNameSpecifier *NNS = SS.getScopeRep(); 4871 if (!Results.empty() && NNS->isDependent()) 4872 Results.AddResult("template"); 4873 4874 // Add calls to overridden virtual functions, if there are any. 4875 // 4876 // FIXME: This isn't wonderful, because we don't know whether we're actually 4877 // in a context that permits expressions. This is a general issue with 4878 // qualified-id completions. 4879 if (!EnteringContext) 4880 MaybeAddOverrideCalls(*this, Ctx, Results); 4881 Results.ExitScope(); 4882 4883 if (CodeCompleter->includeNamespaceLevelDecls() || 4884 (!Ctx->isNamespace() && !Ctx->isTranslationUnit())) { 4885 CodeCompletionDeclConsumer Consumer(Results, CurContext); 4886 LookupVisibleDecls(Ctx, LookupOrdinaryName, Consumer, 4887 /*IncludeGlobalScope=*/true, 4888 /*IncludeDependentBases=*/true, 4889 CodeCompleter->loadExternal()); 4890 } 4891 4892 auto CC = Results.getCompletionContext(); 4893 CC.setCXXScopeSpecifier(SS); 4894 4895 HandleCodeCompleteResults(this, CodeCompleter, CC, Results.data(), 4896 Results.size()); 4897 } 4898 4899 void Sema::CodeCompleteUsing(Scope *S) { 4900 if (!CodeCompleter) 4901 return; 4902 4903 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 4904 CodeCompleter->getCodeCompletionTUInfo(), 4905 // This can be both a using alias or using 4906 // declaration, in the former we expect a new name and a 4907 // symbol in the latter case. 4908 CodeCompletionContext::CCC_SymbolOrNewName, 4909 &ResultBuilder::IsNestedNameSpecifier); 4910 Results.EnterNewScope(); 4911 4912 // If we aren't in class scope, we could see the "namespace" keyword. 4913 if (!S->isClassScope()) 4914 Results.AddResult(CodeCompletionResult("namespace")); 4915 4916 // After "using", we can see anything that would start a 4917 // nested-name-specifier. 4918 CodeCompletionDeclConsumer Consumer(Results, CurContext); 4919 LookupVisibleDecls(S, LookupOrdinaryName, Consumer, 4920 CodeCompleter->includeGlobals(), 4921 CodeCompleter->loadExternal()); 4922 Results.ExitScope(); 4923 4924 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 4925 Results.data(), Results.size()); 4926 } 4927 4928 void Sema::CodeCompleteUsingDirective(Scope *S) { 4929 if (!CodeCompleter) 4930 return; 4931 4932 // After "using namespace", we expect to see a namespace name or namespace 4933 // alias. 4934 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 4935 CodeCompleter->getCodeCompletionTUInfo(), 4936 CodeCompletionContext::CCC_Namespace, 4937 &ResultBuilder::IsNamespaceOrAlias); 4938 Results.EnterNewScope(); 4939 CodeCompletionDeclConsumer Consumer(Results, CurContext); 4940 LookupVisibleDecls(S, LookupOrdinaryName, Consumer, 4941 CodeCompleter->includeGlobals(), 4942 CodeCompleter->loadExternal()); 4943 Results.ExitScope(); 4944 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 4945 Results.data(), Results.size()); 4946 } 4947 4948 void Sema::CodeCompleteNamespaceDecl(Scope *S) { 4949 if (!CodeCompleter) 4950 return; 4951 4952 DeclContext *Ctx = S->getEntity(); 4953 if (!S->getParent()) 4954 Ctx = Context.getTranslationUnitDecl(); 4955 4956 bool SuppressedGlobalResults 4957 = Ctx && !CodeCompleter->includeGlobals() && isa<TranslationUnitDecl>(Ctx); 4958 4959 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 4960 CodeCompleter->getCodeCompletionTUInfo(), 4961 SuppressedGlobalResults 4962 ? CodeCompletionContext::CCC_Namespace 4963 : CodeCompletionContext::CCC_Other, 4964 &ResultBuilder::IsNamespace); 4965 4966 if (Ctx && Ctx->isFileContext() && !SuppressedGlobalResults) { 4967 // We only want to see those namespaces that have already been defined 4968 // within this scope, because its likely that the user is creating an 4969 // extended namespace declaration. Keep track of the most recent 4970 // definition of each namespace. 4971 std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest; 4972 for (DeclContext::specific_decl_iterator<NamespaceDecl> 4973 NS(Ctx->decls_begin()), NSEnd(Ctx->decls_end()); 4974 NS != NSEnd; ++NS) 4975 OrigToLatest[NS->getOriginalNamespace()] = *NS; 4976 4977 // Add the most recent definition (or extended definition) of each 4978 // namespace to the list of results. 4979 Results.EnterNewScope(); 4980 for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator 4981 NS = OrigToLatest.begin(), 4982 NSEnd = OrigToLatest.end(); 4983 NS != NSEnd; ++NS) 4984 Results.AddResult(CodeCompletionResult( 4985 NS->second, Results.getBasePriority(NS->second), 4986 nullptr), 4987 CurContext, nullptr, false); 4988 Results.ExitScope(); 4989 } 4990 4991 HandleCodeCompleteResults(this, CodeCompleter, 4992 Results.getCompletionContext(), 4993 Results.data(),Results.size()); 4994 } 4995 4996 void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) { 4997 if (!CodeCompleter) 4998 return; 4999 5000 // After "namespace", we expect to see a namespace or alias. 5001 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5002 CodeCompleter->getCodeCompletionTUInfo(), 5003 CodeCompletionContext::CCC_Namespace, 5004 &ResultBuilder::IsNamespaceOrAlias); 5005 CodeCompletionDeclConsumer Consumer(Results, CurContext); 5006 LookupVisibleDecls(S, LookupOrdinaryName, Consumer, 5007 CodeCompleter->includeGlobals(), 5008 CodeCompleter->loadExternal()); 5009 HandleCodeCompleteResults(this, CodeCompleter, 5010 Results.getCompletionContext(), 5011 Results.data(),Results.size()); 5012 } 5013 5014 void Sema::CodeCompleteOperatorName(Scope *S) { 5015 if (!CodeCompleter) 5016 return; 5017 5018 typedef CodeCompletionResult Result; 5019 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5020 CodeCompleter->getCodeCompletionTUInfo(), 5021 CodeCompletionContext::CCC_Type, 5022 &ResultBuilder::IsType); 5023 Results.EnterNewScope(); 5024 5025 // Add the names of overloadable operators. 5026 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 5027 if (std::strcmp(Spelling, "?")) \ 5028 Results.AddResult(Result(Spelling)); 5029 #include "clang/Basic/OperatorKinds.def" 5030 5031 // Add any type names visible from the current scope 5032 Results.allowNestedNameSpecifiers(); 5033 CodeCompletionDeclConsumer Consumer(Results, CurContext); 5034 LookupVisibleDecls(S, LookupOrdinaryName, Consumer, 5035 CodeCompleter->includeGlobals(), 5036 CodeCompleter->loadExternal()); 5037 5038 // Add any type specifiers 5039 AddTypeSpecifierResults(getLangOpts(), Results); 5040 Results.ExitScope(); 5041 5042 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 5043 Results.data(), Results.size()); 5044 } 5045 5046 void Sema::CodeCompleteConstructorInitializer( 5047 Decl *ConstructorD, 5048 ArrayRef <CXXCtorInitializer *> Initializers) { 5049 if (!ConstructorD) 5050 return; 5051 5052 AdjustDeclIfTemplate(ConstructorD); 5053 5054 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ConstructorD); 5055 if (!Constructor) 5056 return; 5057 5058 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5059 CodeCompleter->getCodeCompletionTUInfo(), 5060 CodeCompletionContext::CCC_Symbol); 5061 Results.EnterNewScope(); 5062 5063 // Fill in any already-initialized fields or base classes. 5064 llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields; 5065 llvm::SmallPtrSet<CanQualType, 4> InitializedBases; 5066 for (unsigned I = 0, E = Initializers.size(); I != E; ++I) { 5067 if (Initializers[I]->isBaseInitializer()) 5068 InitializedBases.insert( 5069 Context.getCanonicalType(QualType(Initializers[I]->getBaseClass(), 0))); 5070 else 5071 InitializedFields.insert(cast<FieldDecl>( 5072 Initializers[I]->getAnyMember())); 5073 } 5074 5075 // Add completions for base classes. 5076 CodeCompletionBuilder Builder(Results.getAllocator(), 5077 Results.getCodeCompletionTUInfo()); 5078 PrintingPolicy Policy = getCompletionPrintingPolicy(*this); 5079 bool SawLastInitializer = Initializers.empty(); 5080 CXXRecordDecl *ClassDecl = Constructor->getParent(); 5081 for (const auto &Base : ClassDecl->bases()) { 5082 if (!InitializedBases.insert(Context.getCanonicalType(Base.getType())) 5083 .second) { 5084 SawLastInitializer 5085 = !Initializers.empty() && 5086 Initializers.back()->isBaseInitializer() && 5087 Context.hasSameUnqualifiedType(Base.getType(), 5088 QualType(Initializers.back()->getBaseClass(), 0)); 5089 continue; 5090 } 5091 5092 Builder.AddTypedTextChunk( 5093 Results.getAllocator().CopyString( 5094 Base.getType().getAsString(Policy))); 5095 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 5096 Builder.AddPlaceholderChunk("args"); 5097 Builder.AddChunk(CodeCompletionString::CK_RightParen); 5098 Results.AddResult(CodeCompletionResult(Builder.TakeString(), 5099 SawLastInitializer? CCP_NextInitializer 5100 : CCP_MemberDeclaration)); 5101 SawLastInitializer = false; 5102 } 5103 5104 // Add completions for virtual base classes. 5105 for (const auto &Base : ClassDecl->vbases()) { 5106 if (!InitializedBases.insert(Context.getCanonicalType(Base.getType())) 5107 .second) { 5108 SawLastInitializer 5109 = !Initializers.empty() && 5110 Initializers.back()->isBaseInitializer() && 5111 Context.hasSameUnqualifiedType(Base.getType(), 5112 QualType(Initializers.back()->getBaseClass(), 0)); 5113 continue; 5114 } 5115 5116 Builder.AddTypedTextChunk( 5117 Builder.getAllocator().CopyString( 5118 Base.getType().getAsString(Policy))); 5119 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 5120 Builder.AddPlaceholderChunk("args"); 5121 Builder.AddChunk(CodeCompletionString::CK_RightParen); 5122 Results.AddResult(CodeCompletionResult(Builder.TakeString(), 5123 SawLastInitializer? CCP_NextInitializer 5124 : CCP_MemberDeclaration)); 5125 SawLastInitializer = false; 5126 } 5127 5128 // Add completions for members. 5129 for (auto *Field : ClassDecl->fields()) { 5130 if (!InitializedFields.insert(cast<FieldDecl>(Field->getCanonicalDecl())) 5131 .second) { 5132 SawLastInitializer 5133 = !Initializers.empty() && 5134 Initializers.back()->isAnyMemberInitializer() && 5135 Initializers.back()->getAnyMember() == Field; 5136 continue; 5137 } 5138 5139 if (!Field->getDeclName()) 5140 continue; 5141 5142 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString( 5143 Field->getIdentifier()->getName())); 5144 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 5145 Builder.AddPlaceholderChunk("args"); 5146 Builder.AddChunk(CodeCompletionString::CK_RightParen); 5147 Results.AddResult(CodeCompletionResult(Builder.TakeString(), 5148 SawLastInitializer? CCP_NextInitializer 5149 : CCP_MemberDeclaration, 5150 CXCursor_MemberRef, 5151 CXAvailability_Available, 5152 Field)); 5153 SawLastInitializer = false; 5154 } 5155 Results.ExitScope(); 5156 5157 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 5158 Results.data(), Results.size()); 5159 } 5160 5161 /// Determine whether this scope denotes a namespace. 5162 static bool isNamespaceScope(Scope *S) { 5163 DeclContext *DC = S->getEntity(); 5164 if (!DC) 5165 return false; 5166 5167 return DC->isFileContext(); 5168 } 5169 5170 void Sema::CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro, 5171 bool AfterAmpersand) { 5172 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5173 CodeCompleter->getCodeCompletionTUInfo(), 5174 CodeCompletionContext::CCC_Other); 5175 Results.EnterNewScope(); 5176 5177 // Note what has already been captured. 5178 llvm::SmallPtrSet<IdentifierInfo *, 4> Known; 5179 bool IncludedThis = false; 5180 for (const auto &C : Intro.Captures) { 5181 if (C.Kind == LCK_This) { 5182 IncludedThis = true; 5183 continue; 5184 } 5185 5186 Known.insert(C.Id); 5187 } 5188 5189 // Look for other capturable variables. 5190 for (; S && !isNamespaceScope(S); S = S->getParent()) { 5191 for (const auto *D : S->decls()) { 5192 const auto *Var = dyn_cast<VarDecl>(D); 5193 if (!Var || 5194 !Var->hasLocalStorage() || 5195 Var->hasAttr<BlocksAttr>()) 5196 continue; 5197 5198 if (Known.insert(Var->getIdentifier()).second) 5199 Results.AddResult(CodeCompletionResult(Var, CCP_LocalDeclaration), 5200 CurContext, nullptr, false); 5201 } 5202 } 5203 5204 // Add 'this', if it would be valid. 5205 if (!IncludedThis && !AfterAmpersand && Intro.Default != LCD_ByCopy) 5206 addThisCompletion(*this, Results); 5207 5208 Results.ExitScope(); 5209 5210 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 5211 Results.data(), Results.size()); 5212 } 5213 5214 /// Macro that optionally prepends an "@" to the string literal passed in via 5215 /// Keyword, depending on whether NeedAt is true or false. 5216 #define OBJC_AT_KEYWORD_NAME(NeedAt,Keyword) ((NeedAt)? "@" Keyword : Keyword) 5217 5218 static void AddObjCImplementationResults(const LangOptions &LangOpts, 5219 ResultBuilder &Results, 5220 bool NeedAt) { 5221 typedef CodeCompletionResult Result; 5222 // Since we have an implementation, we can end it. 5223 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"end"))); 5224 5225 CodeCompletionBuilder Builder(Results.getAllocator(), 5226 Results.getCodeCompletionTUInfo()); 5227 if (LangOpts.ObjC2) { 5228 // @dynamic 5229 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"dynamic")); 5230 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 5231 Builder.AddPlaceholderChunk("property"); 5232 Results.AddResult(Result(Builder.TakeString())); 5233 5234 // @synthesize 5235 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"synthesize")); 5236 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 5237 Builder.AddPlaceholderChunk("property"); 5238 Results.AddResult(Result(Builder.TakeString())); 5239 } 5240 } 5241 5242 static void AddObjCInterfaceResults(const LangOptions &LangOpts, 5243 ResultBuilder &Results, 5244 bool NeedAt) { 5245 typedef CodeCompletionResult Result; 5246 5247 // Since we have an interface or protocol, we can end it. 5248 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"end"))); 5249 5250 if (LangOpts.ObjC2) { 5251 // @property 5252 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"property"))); 5253 5254 // @required 5255 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"required"))); 5256 5257 // @optional 5258 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"optional"))); 5259 } 5260 } 5261 5262 static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt) { 5263 typedef CodeCompletionResult Result; 5264 CodeCompletionBuilder Builder(Results.getAllocator(), 5265 Results.getCodeCompletionTUInfo()); 5266 5267 // @class name ; 5268 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"class")); 5269 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 5270 Builder.AddPlaceholderChunk("name"); 5271 Results.AddResult(Result(Builder.TakeString())); 5272 5273 if (Results.includeCodePatterns()) { 5274 // @interface name 5275 // FIXME: Could introduce the whole pattern, including superclasses and 5276 // such. 5277 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"interface")); 5278 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 5279 Builder.AddPlaceholderChunk("class"); 5280 Results.AddResult(Result(Builder.TakeString())); 5281 5282 // @protocol name 5283 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"protocol")); 5284 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 5285 Builder.AddPlaceholderChunk("protocol"); 5286 Results.AddResult(Result(Builder.TakeString())); 5287 5288 // @implementation name 5289 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"implementation")); 5290 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 5291 Builder.AddPlaceholderChunk("class"); 5292 Results.AddResult(Result(Builder.TakeString())); 5293 } 5294 5295 // @compatibility_alias name 5296 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"compatibility_alias")); 5297 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 5298 Builder.AddPlaceholderChunk("alias"); 5299 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 5300 Builder.AddPlaceholderChunk("class"); 5301 Results.AddResult(Result(Builder.TakeString())); 5302 5303 if (Results.getSema().getLangOpts().Modules) { 5304 // @import name 5305 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "import")); 5306 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 5307 Builder.AddPlaceholderChunk("module"); 5308 Results.AddResult(Result(Builder.TakeString())); 5309 } 5310 } 5311 5312 void Sema::CodeCompleteObjCAtDirective(Scope *S) { 5313 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5314 CodeCompleter->getCodeCompletionTUInfo(), 5315 CodeCompletionContext::CCC_Other); 5316 Results.EnterNewScope(); 5317 if (isa<ObjCImplDecl>(CurContext)) 5318 AddObjCImplementationResults(getLangOpts(), Results, false); 5319 else if (CurContext->isObjCContainer()) 5320 AddObjCInterfaceResults(getLangOpts(), Results, false); 5321 else 5322 AddObjCTopLevelResults(Results, false); 5323 Results.ExitScope(); 5324 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 5325 Results.data(), Results.size()); 5326 } 5327 5328 static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt) { 5329 typedef CodeCompletionResult Result; 5330 CodeCompletionBuilder Builder(Results.getAllocator(), 5331 Results.getCodeCompletionTUInfo()); 5332 5333 // @encode ( type-name ) 5334 const char *EncodeType = "char[]"; 5335 if (Results.getSema().getLangOpts().CPlusPlus || 5336 Results.getSema().getLangOpts().ConstStrings) 5337 EncodeType = "const char[]"; 5338 Builder.AddResultTypeChunk(EncodeType); 5339 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"encode")); 5340 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 5341 Builder.AddPlaceholderChunk("type-name"); 5342 Builder.AddChunk(CodeCompletionString::CK_RightParen); 5343 Results.AddResult(Result(Builder.TakeString())); 5344 5345 // @protocol ( protocol-name ) 5346 Builder.AddResultTypeChunk("Protocol *"); 5347 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"protocol")); 5348 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 5349 Builder.AddPlaceholderChunk("protocol-name"); 5350 Builder.AddChunk(CodeCompletionString::CK_RightParen); 5351 Results.AddResult(Result(Builder.TakeString())); 5352 5353 // @selector ( selector ) 5354 Builder.AddResultTypeChunk("SEL"); 5355 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"selector")); 5356 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 5357 Builder.AddPlaceholderChunk("selector"); 5358 Builder.AddChunk(CodeCompletionString::CK_RightParen); 5359 Results.AddResult(Result(Builder.TakeString())); 5360 5361 // @"string" 5362 Builder.AddResultTypeChunk("NSString *"); 5363 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"\"")); 5364 Builder.AddPlaceholderChunk("string"); 5365 Builder.AddTextChunk("\""); 5366 Results.AddResult(Result(Builder.TakeString())); 5367 5368 // @[objects, ...] 5369 Builder.AddResultTypeChunk("NSArray *"); 5370 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"[")); 5371 Builder.AddPlaceholderChunk("objects, ..."); 5372 Builder.AddChunk(CodeCompletionString::CK_RightBracket); 5373 Results.AddResult(Result(Builder.TakeString())); 5374 5375 // @{key : object, ...} 5376 Builder.AddResultTypeChunk("NSDictionary *"); 5377 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"{")); 5378 Builder.AddPlaceholderChunk("key"); 5379 Builder.AddChunk(CodeCompletionString::CK_Colon); 5380 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 5381 Builder.AddPlaceholderChunk("object, ..."); 5382 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 5383 Results.AddResult(Result(Builder.TakeString())); 5384 5385 // @(expression) 5386 Builder.AddResultTypeChunk("id"); 5387 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "(")); 5388 Builder.AddPlaceholderChunk("expression"); 5389 Builder.AddChunk(CodeCompletionString::CK_RightParen); 5390 Results.AddResult(Result(Builder.TakeString())); 5391 } 5392 5393 static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt) { 5394 typedef CodeCompletionResult Result; 5395 CodeCompletionBuilder Builder(Results.getAllocator(), 5396 Results.getCodeCompletionTUInfo()); 5397 5398 if (Results.includeCodePatterns()) { 5399 // @try { statements } @catch ( declaration ) { statements } @finally 5400 // { statements } 5401 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"try")); 5402 Builder.AddChunk(CodeCompletionString::CK_LeftBrace); 5403 Builder.AddPlaceholderChunk("statements"); 5404 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 5405 Builder.AddTextChunk("@catch"); 5406 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 5407 Builder.AddPlaceholderChunk("parameter"); 5408 Builder.AddChunk(CodeCompletionString::CK_RightParen); 5409 Builder.AddChunk(CodeCompletionString::CK_LeftBrace); 5410 Builder.AddPlaceholderChunk("statements"); 5411 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 5412 Builder.AddTextChunk("@finally"); 5413 Builder.AddChunk(CodeCompletionString::CK_LeftBrace); 5414 Builder.AddPlaceholderChunk("statements"); 5415 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 5416 Results.AddResult(Result(Builder.TakeString())); 5417 } 5418 5419 // @throw 5420 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"throw")); 5421 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 5422 Builder.AddPlaceholderChunk("expression"); 5423 Results.AddResult(Result(Builder.TakeString())); 5424 5425 if (Results.includeCodePatterns()) { 5426 // @synchronized ( expression ) { statements } 5427 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"synchronized")); 5428 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 5429 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 5430 Builder.AddPlaceholderChunk("expression"); 5431 Builder.AddChunk(CodeCompletionString::CK_RightParen); 5432 Builder.AddChunk(CodeCompletionString::CK_LeftBrace); 5433 Builder.AddPlaceholderChunk("statements"); 5434 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 5435 Results.AddResult(Result(Builder.TakeString())); 5436 } 5437 } 5438 5439 static void AddObjCVisibilityResults(const LangOptions &LangOpts, 5440 ResultBuilder &Results, 5441 bool NeedAt) { 5442 typedef CodeCompletionResult Result; 5443 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"private"))); 5444 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"protected"))); 5445 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"public"))); 5446 if (LangOpts.ObjC2) 5447 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"package"))); 5448 } 5449 5450 void Sema::CodeCompleteObjCAtVisibility(Scope *S) { 5451 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5452 CodeCompleter->getCodeCompletionTUInfo(), 5453 CodeCompletionContext::CCC_Other); 5454 Results.EnterNewScope(); 5455 AddObjCVisibilityResults(getLangOpts(), Results, false); 5456 Results.ExitScope(); 5457 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 5458 Results.data(), Results.size()); 5459 } 5460 5461 void Sema::CodeCompleteObjCAtStatement(Scope *S) { 5462 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5463 CodeCompleter->getCodeCompletionTUInfo(), 5464 CodeCompletionContext::CCC_Other); 5465 Results.EnterNewScope(); 5466 AddObjCStatementResults(Results, false); 5467 AddObjCExpressionResults(Results, false); 5468 Results.ExitScope(); 5469 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 5470 Results.data(), Results.size()); 5471 } 5472 5473 void Sema::CodeCompleteObjCAtExpression(Scope *S) { 5474 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5475 CodeCompleter->getCodeCompletionTUInfo(), 5476 CodeCompletionContext::CCC_Other); 5477 Results.EnterNewScope(); 5478 AddObjCExpressionResults(Results, false); 5479 Results.ExitScope(); 5480 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 5481 Results.data(), Results.size()); 5482 } 5483 5484 /// Determine whether the addition of the given flag to an Objective-C 5485 /// property's attributes will cause a conflict. 5486 static bool ObjCPropertyFlagConflicts(unsigned Attributes, unsigned NewFlag) { 5487 // Check if we've already added this flag. 5488 if (Attributes & NewFlag) 5489 return true; 5490 5491 Attributes |= NewFlag; 5492 5493 // Check for collisions with "readonly". 5494 if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) && 5495 (Attributes & ObjCDeclSpec::DQ_PR_readwrite)) 5496 return true; 5497 5498 // Check for more than one of { assign, copy, retain, strong, weak }. 5499 unsigned AssignCopyRetMask = Attributes & (ObjCDeclSpec::DQ_PR_assign | 5500 ObjCDeclSpec::DQ_PR_unsafe_unretained | 5501 ObjCDeclSpec::DQ_PR_copy | 5502 ObjCDeclSpec::DQ_PR_retain | 5503 ObjCDeclSpec::DQ_PR_strong | 5504 ObjCDeclSpec::DQ_PR_weak); 5505 if (AssignCopyRetMask && 5506 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_assign && 5507 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_unsafe_unretained && 5508 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_copy && 5509 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_retain && 5510 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_strong && 5511 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_weak) 5512 return true; 5513 5514 return false; 5515 } 5516 5517 void Sema::CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS) { 5518 if (!CodeCompleter) 5519 return; 5520 5521 unsigned Attributes = ODS.getPropertyAttributes(); 5522 5523 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5524 CodeCompleter->getCodeCompletionTUInfo(), 5525 CodeCompletionContext::CCC_Other); 5526 Results.EnterNewScope(); 5527 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readonly)) 5528 Results.AddResult(CodeCompletionResult("readonly")); 5529 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_assign)) 5530 Results.AddResult(CodeCompletionResult("assign")); 5531 if (!ObjCPropertyFlagConflicts(Attributes, 5532 ObjCDeclSpec::DQ_PR_unsafe_unretained)) 5533 Results.AddResult(CodeCompletionResult("unsafe_unretained")); 5534 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readwrite)) 5535 Results.AddResult(CodeCompletionResult("readwrite")); 5536 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_retain)) 5537 Results.AddResult(CodeCompletionResult("retain")); 5538 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_strong)) 5539 Results.AddResult(CodeCompletionResult("strong")); 5540 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_copy)) 5541 Results.AddResult(CodeCompletionResult("copy")); 5542 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nonatomic)) 5543 Results.AddResult(CodeCompletionResult("nonatomic")); 5544 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_atomic)) 5545 Results.AddResult(CodeCompletionResult("atomic")); 5546 5547 // Only suggest "weak" if we're compiling for ARC-with-weak-references or GC. 5548 if (getLangOpts().ObjCWeak || getLangOpts().getGC() != LangOptions::NonGC) 5549 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_weak)) 5550 Results.AddResult(CodeCompletionResult("weak")); 5551 5552 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_setter)) { 5553 CodeCompletionBuilder Setter(Results.getAllocator(), 5554 Results.getCodeCompletionTUInfo()); 5555 Setter.AddTypedTextChunk("setter"); 5556 Setter.AddTextChunk("="); 5557 Setter.AddPlaceholderChunk("method"); 5558 Results.AddResult(CodeCompletionResult(Setter.TakeString())); 5559 } 5560 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_getter)) { 5561 CodeCompletionBuilder Getter(Results.getAllocator(), 5562 Results.getCodeCompletionTUInfo()); 5563 Getter.AddTypedTextChunk("getter"); 5564 Getter.AddTextChunk("="); 5565 Getter.AddPlaceholderChunk("method"); 5566 Results.AddResult(CodeCompletionResult(Getter.TakeString())); 5567 } 5568 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nullability)) { 5569 Results.AddResult(CodeCompletionResult("nonnull")); 5570 Results.AddResult(CodeCompletionResult("nullable")); 5571 Results.AddResult(CodeCompletionResult("null_unspecified")); 5572 Results.AddResult(CodeCompletionResult("null_resettable")); 5573 } 5574 Results.ExitScope(); 5575 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 5576 Results.data(), Results.size()); 5577 } 5578 5579 /// Describes the kind of Objective-C method that we want to find 5580 /// via code completion. 5581 enum ObjCMethodKind { 5582 MK_Any, ///< Any kind of method, provided it means other specified criteria. 5583 MK_ZeroArgSelector, ///< Zero-argument (unary) selector. 5584 MK_OneArgSelector ///< One-argument selector. 5585 }; 5586 5587 static bool isAcceptableObjCSelector(Selector Sel, 5588 ObjCMethodKind WantKind, 5589 ArrayRef<IdentifierInfo *> SelIdents, 5590 bool AllowSameLength = true) { 5591 unsigned NumSelIdents = SelIdents.size(); 5592 if (NumSelIdents > Sel.getNumArgs()) 5593 return false; 5594 5595 switch (WantKind) { 5596 case MK_Any: break; 5597 case MK_ZeroArgSelector: return Sel.isUnarySelector(); 5598 case MK_OneArgSelector: return Sel.getNumArgs() == 1; 5599 } 5600 5601 if (!AllowSameLength && NumSelIdents && NumSelIdents == Sel.getNumArgs()) 5602 return false; 5603 5604 for (unsigned I = 0; I != NumSelIdents; ++I) 5605 if (SelIdents[I] != Sel.getIdentifierInfoForSlot(I)) 5606 return false; 5607 5608 return true; 5609 } 5610 5611 static bool isAcceptableObjCMethod(ObjCMethodDecl *Method, 5612 ObjCMethodKind WantKind, 5613 ArrayRef<IdentifierInfo *> SelIdents, 5614 bool AllowSameLength = true) { 5615 return isAcceptableObjCSelector(Method->getSelector(), WantKind, SelIdents, 5616 AllowSameLength); 5617 } 5618 5619 namespace { 5620 /// A set of selectors, which is used to avoid introducing multiple 5621 /// completions with the same selector into the result set. 5622 typedef llvm::SmallPtrSet<Selector, 16> VisitedSelectorSet; 5623 } 5624 5625 /// Add all of the Objective-C methods in the given Objective-C 5626 /// container to the set of results. 5627 /// 5628 /// The container will be a class, protocol, category, or implementation of 5629 /// any of the above. This mether will recurse to include methods from 5630 /// the superclasses of classes along with their categories, protocols, and 5631 /// implementations. 5632 /// 5633 /// \param Container the container in which we'll look to find methods. 5634 /// 5635 /// \param WantInstanceMethods Whether to add instance methods (only); if 5636 /// false, this routine will add factory methods (only). 5637 /// 5638 /// \param CurContext the context in which we're performing the lookup that 5639 /// finds methods. 5640 /// 5641 /// \param AllowSameLength Whether we allow a method to be added to the list 5642 /// when it has the same number of parameters as we have selector identifiers. 5643 /// 5644 /// \param Results the structure into which we'll add results. 5645 static void AddObjCMethods(ObjCContainerDecl *Container, 5646 bool WantInstanceMethods, ObjCMethodKind WantKind, 5647 ArrayRef<IdentifierInfo *> SelIdents, 5648 DeclContext *CurContext, 5649 VisitedSelectorSet &Selectors, bool AllowSameLength, 5650 ResultBuilder &Results, bool InOriginalClass = true, 5651 bool IsRootClass = false) { 5652 typedef CodeCompletionResult Result; 5653 Container = getContainerDef(Container); 5654 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container); 5655 IsRootClass = IsRootClass || (IFace && !IFace->getSuperClass()); 5656 for (auto *M : Container->methods()) { 5657 // The instance methods on the root class can be messaged via the 5658 // metaclass. 5659 if (M->isInstanceMethod() == WantInstanceMethods || 5660 (IsRootClass && !WantInstanceMethods)) { 5661 // Check whether the selector identifiers we've been given are a 5662 // subset of the identifiers for this particular method. 5663 if (!isAcceptableObjCMethod(M, WantKind, SelIdents, AllowSameLength)) 5664 continue; 5665 5666 if (!Selectors.insert(M->getSelector()).second) 5667 continue; 5668 5669 Result R = Result(M, Results.getBasePriority(M), nullptr); 5670 R.StartParameter = SelIdents.size(); 5671 R.AllParametersAreInformative = (WantKind != MK_Any); 5672 if (!InOriginalClass) 5673 setInBaseClass(R); 5674 Results.MaybeAddResult(R, CurContext); 5675 } 5676 } 5677 5678 // Visit the protocols of protocols. 5679 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) { 5680 if (Protocol->hasDefinition()) { 5681 const ObjCList<ObjCProtocolDecl> &Protocols 5682 = Protocol->getReferencedProtocols(); 5683 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(), 5684 E = Protocols.end(); 5685 I != E; ++I) 5686 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, CurContext, 5687 Selectors, AllowSameLength, Results, false, IsRootClass); 5688 } 5689 } 5690 5691 if (!IFace || !IFace->hasDefinition()) 5692 return; 5693 5694 // Add methods in protocols. 5695 for (auto *I : IFace->protocols()) 5696 AddObjCMethods(I, WantInstanceMethods, WantKind, SelIdents, CurContext, 5697 Selectors, AllowSameLength, Results, false, IsRootClass); 5698 5699 // Add methods in categories. 5700 for (auto *CatDecl : IFace->known_categories()) { 5701 AddObjCMethods(CatDecl, WantInstanceMethods, WantKind, SelIdents, 5702 CurContext, Selectors, AllowSameLength, Results, 5703 InOriginalClass, IsRootClass); 5704 5705 // Add a categories protocol methods. 5706 const ObjCList<ObjCProtocolDecl> &Protocols 5707 = CatDecl->getReferencedProtocols(); 5708 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(), 5709 E = Protocols.end(); 5710 I != E; ++I) 5711 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, CurContext, 5712 Selectors, AllowSameLength, Results, false, IsRootClass); 5713 5714 // Add methods in category implementations. 5715 if (ObjCCategoryImplDecl *Impl = CatDecl->getImplementation()) 5716 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents, CurContext, 5717 Selectors, AllowSameLength, Results, InOriginalClass, 5718 IsRootClass); 5719 } 5720 5721 // Add methods in superclass. 5722 // Avoid passing in IsRootClass since root classes won't have super classes. 5723 if (IFace->getSuperClass()) 5724 AddObjCMethods(IFace->getSuperClass(), WantInstanceMethods, WantKind, 5725 SelIdents, CurContext, Selectors, AllowSameLength, Results, 5726 /*IsRootClass=*/false); 5727 5728 // Add methods in our implementation, if any. 5729 if (ObjCImplementationDecl *Impl = IFace->getImplementation()) 5730 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents, CurContext, 5731 Selectors, AllowSameLength, Results, InOriginalClass, 5732 IsRootClass); 5733 } 5734 5735 5736 void Sema::CodeCompleteObjCPropertyGetter(Scope *S) { 5737 // Try to find the interface where getters might live. 5738 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext); 5739 if (!Class) { 5740 if (ObjCCategoryDecl *Category 5741 = dyn_cast_or_null<ObjCCategoryDecl>(CurContext)) 5742 Class = Category->getClassInterface(); 5743 5744 if (!Class) 5745 return; 5746 } 5747 5748 // Find all of the potential getters. 5749 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5750 CodeCompleter->getCodeCompletionTUInfo(), 5751 CodeCompletionContext::CCC_Other); 5752 Results.EnterNewScope(); 5753 5754 VisitedSelectorSet Selectors; 5755 AddObjCMethods(Class, true, MK_ZeroArgSelector, None, CurContext, Selectors, 5756 /*AllowSameLength=*/true, Results); 5757 Results.ExitScope(); 5758 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 5759 Results.data(), Results.size()); 5760 } 5761 5762 void Sema::CodeCompleteObjCPropertySetter(Scope *S) { 5763 // Try to find the interface where setters might live. 5764 ObjCInterfaceDecl *Class 5765 = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext); 5766 if (!Class) { 5767 if (ObjCCategoryDecl *Category 5768 = dyn_cast_or_null<ObjCCategoryDecl>(CurContext)) 5769 Class = Category->getClassInterface(); 5770 5771 if (!Class) 5772 return; 5773 } 5774 5775 // Find all of the potential getters. 5776 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5777 CodeCompleter->getCodeCompletionTUInfo(), 5778 CodeCompletionContext::CCC_Other); 5779 Results.EnterNewScope(); 5780 5781 VisitedSelectorSet Selectors; 5782 AddObjCMethods(Class, true, MK_OneArgSelector, None, CurContext, 5783 Selectors, /*AllowSameLength=*/true, Results); 5784 5785 Results.ExitScope(); 5786 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 5787 Results.data(), Results.size()); 5788 } 5789 5790 void Sema::CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS, 5791 bool IsParameter) { 5792 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5793 CodeCompleter->getCodeCompletionTUInfo(), 5794 CodeCompletionContext::CCC_Type); 5795 Results.EnterNewScope(); 5796 5797 // Add context-sensitive, Objective-C parameter-passing keywords. 5798 bool AddedInOut = false; 5799 if ((DS.getObjCDeclQualifier() & 5800 (ObjCDeclSpec::DQ_In | ObjCDeclSpec::DQ_Inout)) == 0) { 5801 Results.AddResult("in"); 5802 Results.AddResult("inout"); 5803 AddedInOut = true; 5804 } 5805 if ((DS.getObjCDeclQualifier() & 5806 (ObjCDeclSpec::DQ_Out | ObjCDeclSpec::DQ_Inout)) == 0) { 5807 Results.AddResult("out"); 5808 if (!AddedInOut) 5809 Results.AddResult("inout"); 5810 } 5811 if ((DS.getObjCDeclQualifier() & 5812 (ObjCDeclSpec::DQ_Bycopy | ObjCDeclSpec::DQ_Byref | 5813 ObjCDeclSpec::DQ_Oneway)) == 0) { 5814 Results.AddResult("bycopy"); 5815 Results.AddResult("byref"); 5816 Results.AddResult("oneway"); 5817 } 5818 if ((DS.getObjCDeclQualifier() & ObjCDeclSpec::DQ_CSNullability) == 0) { 5819 Results.AddResult("nonnull"); 5820 Results.AddResult("nullable"); 5821 Results.AddResult("null_unspecified"); 5822 } 5823 5824 // If we're completing the return type of an Objective-C method and the 5825 // identifier IBAction refers to a macro, provide a completion item for 5826 // an action, e.g., 5827 // IBAction)<#selector#>:(id)sender 5828 if (DS.getObjCDeclQualifier() == 0 && !IsParameter && 5829 PP.isMacroDefined("IBAction")) { 5830 CodeCompletionBuilder Builder(Results.getAllocator(), 5831 Results.getCodeCompletionTUInfo(), 5832 CCP_CodePattern, CXAvailability_Available); 5833 Builder.AddTypedTextChunk("IBAction"); 5834 Builder.AddChunk(CodeCompletionString::CK_RightParen); 5835 Builder.AddPlaceholderChunk("selector"); 5836 Builder.AddChunk(CodeCompletionString::CK_Colon); 5837 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 5838 Builder.AddTextChunk("id"); 5839 Builder.AddChunk(CodeCompletionString::CK_RightParen); 5840 Builder.AddTextChunk("sender"); 5841 Results.AddResult(CodeCompletionResult(Builder.TakeString())); 5842 } 5843 5844 // If we're completing the return type, provide 'instancetype'. 5845 if (!IsParameter) { 5846 Results.AddResult(CodeCompletionResult("instancetype")); 5847 } 5848 5849 // Add various builtin type names and specifiers. 5850 AddOrdinaryNameResults(PCC_Type, S, *this, Results); 5851 Results.ExitScope(); 5852 5853 // Add the various type names 5854 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName); 5855 CodeCompletionDeclConsumer Consumer(Results, CurContext); 5856 LookupVisibleDecls(S, LookupOrdinaryName, Consumer, 5857 CodeCompleter->includeGlobals(), 5858 CodeCompleter->loadExternal()); 5859 5860 if (CodeCompleter->includeMacros()) 5861 AddMacroResults(PP, Results, CodeCompleter->loadExternal(), false); 5862 5863 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 5864 Results.data(), Results.size()); 5865 } 5866 5867 /// When we have an expression with type "id", we may assume 5868 /// that it has some more-specific class type based on knowledge of 5869 /// common uses of Objective-C. This routine returns that class type, 5870 /// or NULL if no better result could be determined. 5871 static ObjCInterfaceDecl *GetAssumedMessageSendExprType(Expr *E) { 5872 ObjCMessageExpr *Msg = dyn_cast_or_null<ObjCMessageExpr>(E); 5873 if (!Msg) 5874 return nullptr; 5875 5876 Selector Sel = Msg->getSelector(); 5877 if (Sel.isNull()) 5878 return nullptr; 5879 5880 IdentifierInfo *Id = Sel.getIdentifierInfoForSlot(0); 5881 if (!Id) 5882 return nullptr; 5883 5884 ObjCMethodDecl *Method = Msg->getMethodDecl(); 5885 if (!Method) 5886 return nullptr; 5887 5888 // Determine the class that we're sending the message to. 5889 ObjCInterfaceDecl *IFace = nullptr; 5890 switch (Msg->getReceiverKind()) { 5891 case ObjCMessageExpr::Class: 5892 if (const ObjCObjectType *ObjType 5893 = Msg->getClassReceiver()->getAs<ObjCObjectType>()) 5894 IFace = ObjType->getInterface(); 5895 break; 5896 5897 case ObjCMessageExpr::Instance: { 5898 QualType T = Msg->getInstanceReceiver()->getType(); 5899 if (const ObjCObjectPointerType *Ptr = T->getAs<ObjCObjectPointerType>()) 5900 IFace = Ptr->getInterfaceDecl(); 5901 break; 5902 } 5903 5904 case ObjCMessageExpr::SuperInstance: 5905 case ObjCMessageExpr::SuperClass: 5906 break; 5907 } 5908 5909 if (!IFace) 5910 return nullptr; 5911 5912 ObjCInterfaceDecl *Super = IFace->getSuperClass(); 5913 if (Method->isInstanceMethod()) 5914 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName()) 5915 .Case("retain", IFace) 5916 .Case("strong", IFace) 5917 .Case("autorelease", IFace) 5918 .Case("copy", IFace) 5919 .Case("copyWithZone", IFace) 5920 .Case("mutableCopy", IFace) 5921 .Case("mutableCopyWithZone", IFace) 5922 .Case("awakeFromCoder", IFace) 5923 .Case("replacementObjectFromCoder", IFace) 5924 .Case("class", IFace) 5925 .Case("classForCoder", IFace) 5926 .Case("superclass", Super) 5927 .Default(nullptr); 5928 5929 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName()) 5930 .Case("new", IFace) 5931 .Case("alloc", IFace) 5932 .Case("allocWithZone", IFace) 5933 .Case("class", IFace) 5934 .Case("superclass", Super) 5935 .Default(nullptr); 5936 } 5937 5938 // Add a special completion for a message send to "super", which fills in the 5939 // most likely case of forwarding all of our arguments to the superclass 5940 // function. 5941 /// 5942 /// \param S The semantic analysis object. 5943 /// 5944 /// \param NeedSuperKeyword Whether we need to prefix this completion with 5945 /// the "super" keyword. Otherwise, we just need to provide the arguments. 5946 /// 5947 /// \param SelIdents The identifiers in the selector that have already been 5948 /// provided as arguments for a send to "super". 5949 /// 5950 /// \param Results The set of results to augment. 5951 /// 5952 /// \returns the Objective-C method declaration that would be invoked by 5953 /// this "super" completion. If NULL, no completion was added. 5954 static ObjCMethodDecl *AddSuperSendCompletion( 5955 Sema &S, bool NeedSuperKeyword, 5956 ArrayRef<IdentifierInfo *> SelIdents, 5957 ResultBuilder &Results) { 5958 ObjCMethodDecl *CurMethod = S.getCurMethodDecl(); 5959 if (!CurMethod) 5960 return nullptr; 5961 5962 ObjCInterfaceDecl *Class = CurMethod->getClassInterface(); 5963 if (!Class) 5964 return nullptr; 5965 5966 // Try to find a superclass method with the same selector. 5967 ObjCMethodDecl *SuperMethod = nullptr; 5968 while ((Class = Class->getSuperClass()) && !SuperMethod) { 5969 // Check in the class 5970 SuperMethod = Class->getMethod(CurMethod->getSelector(), 5971 CurMethod->isInstanceMethod()); 5972 5973 // Check in categories or class extensions. 5974 if (!SuperMethod) { 5975 for (const auto *Cat : Class->known_categories()) { 5976 if ((SuperMethod = Cat->getMethod(CurMethod->getSelector(), 5977 CurMethod->isInstanceMethod()))) 5978 break; 5979 } 5980 } 5981 } 5982 5983 if (!SuperMethod) 5984 return nullptr; 5985 5986 // Check whether the superclass method has the same signature. 5987 if (CurMethod->param_size() != SuperMethod->param_size() || 5988 CurMethod->isVariadic() != SuperMethod->isVariadic()) 5989 return nullptr; 5990 5991 for (ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin(), 5992 CurPEnd = CurMethod->param_end(), 5993 SuperP = SuperMethod->param_begin(); 5994 CurP != CurPEnd; ++CurP, ++SuperP) { 5995 // Make sure the parameter types are compatible. 5996 if (!S.Context.hasSameUnqualifiedType((*CurP)->getType(), 5997 (*SuperP)->getType())) 5998 return nullptr; 5999 6000 // Make sure we have a parameter name to forward! 6001 if (!(*CurP)->getIdentifier()) 6002 return nullptr; 6003 } 6004 6005 // We have a superclass method. Now, form the send-to-super completion. 6006 CodeCompletionBuilder Builder(Results.getAllocator(), 6007 Results.getCodeCompletionTUInfo()); 6008 6009 // Give this completion a return type. 6010 AddResultTypeChunk(S.Context, getCompletionPrintingPolicy(S), SuperMethod, 6011 Results.getCompletionContext().getBaseType(), 6012 Builder); 6013 6014 // If we need the "super" keyword, add it (plus some spacing). 6015 if (NeedSuperKeyword) { 6016 Builder.AddTypedTextChunk("super"); 6017 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 6018 } 6019 6020 Selector Sel = CurMethod->getSelector(); 6021 if (Sel.isUnarySelector()) { 6022 if (NeedSuperKeyword) 6023 Builder.AddTextChunk(Builder.getAllocator().CopyString( 6024 Sel.getNameForSlot(0))); 6025 else 6026 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString( 6027 Sel.getNameForSlot(0))); 6028 } else { 6029 ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin(); 6030 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I, ++CurP) { 6031 if (I > SelIdents.size()) 6032 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 6033 6034 if (I < SelIdents.size()) 6035 Builder.AddInformativeChunk( 6036 Builder.getAllocator().CopyString( 6037 Sel.getNameForSlot(I) + ":")); 6038 else if (NeedSuperKeyword || I > SelIdents.size()) { 6039 Builder.AddTextChunk( 6040 Builder.getAllocator().CopyString( 6041 Sel.getNameForSlot(I) + ":")); 6042 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString( 6043 (*CurP)->getIdentifier()->getName())); 6044 } else { 6045 Builder.AddTypedTextChunk( 6046 Builder.getAllocator().CopyString( 6047 Sel.getNameForSlot(I) + ":")); 6048 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString( 6049 (*CurP)->getIdentifier()->getName())); 6050 } 6051 } 6052 } 6053 6054 Results.AddResult(CodeCompletionResult(Builder.TakeString(), SuperMethod, 6055 CCP_SuperCompletion)); 6056 return SuperMethod; 6057 } 6058 6059 void Sema::CodeCompleteObjCMessageReceiver(Scope *S) { 6060 typedef CodeCompletionResult Result; 6061 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 6062 CodeCompleter->getCodeCompletionTUInfo(), 6063 CodeCompletionContext::CCC_ObjCMessageReceiver, 6064 getLangOpts().CPlusPlus11 6065 ? &ResultBuilder::IsObjCMessageReceiverOrLambdaCapture 6066 : &ResultBuilder::IsObjCMessageReceiver); 6067 6068 CodeCompletionDeclConsumer Consumer(Results, CurContext); 6069 Results.EnterNewScope(); 6070 LookupVisibleDecls(S, LookupOrdinaryName, Consumer, 6071 CodeCompleter->includeGlobals(), 6072 CodeCompleter->loadExternal()); 6073 6074 // If we are in an Objective-C method inside a class that has a superclass, 6075 // add "super" as an option. 6076 if (ObjCMethodDecl *Method = getCurMethodDecl()) 6077 if (ObjCInterfaceDecl *Iface = Method->getClassInterface()) 6078 if (Iface->getSuperClass()) { 6079 Results.AddResult(Result("super")); 6080 6081 AddSuperSendCompletion(*this, /*NeedSuperKeyword=*/true, None, Results); 6082 } 6083 6084 if (getLangOpts().CPlusPlus11) 6085 addThisCompletion(*this, Results); 6086 6087 Results.ExitScope(); 6088 6089 if (CodeCompleter->includeMacros()) 6090 AddMacroResults(PP, Results, CodeCompleter->loadExternal(), false); 6091 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 6092 Results.data(), Results.size()); 6093 } 6094 6095 void Sema::CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc, 6096 ArrayRef<IdentifierInfo *> SelIdents, 6097 bool AtArgumentExpression) { 6098 ObjCInterfaceDecl *CDecl = nullptr; 6099 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) { 6100 // Figure out which interface we're in. 6101 CDecl = CurMethod->getClassInterface(); 6102 if (!CDecl) 6103 return; 6104 6105 // Find the superclass of this class. 6106 CDecl = CDecl->getSuperClass(); 6107 if (!CDecl) 6108 return; 6109 6110 if (CurMethod->isInstanceMethod()) { 6111 // We are inside an instance method, which means that the message 6112 // send [super ...] is actually calling an instance method on the 6113 // current object. 6114 return CodeCompleteObjCInstanceMessage(S, nullptr, SelIdents, 6115 AtArgumentExpression, 6116 CDecl); 6117 } 6118 6119 // Fall through to send to the superclass in CDecl. 6120 } else { 6121 // "super" may be the name of a type or variable. Figure out which 6122 // it is. 6123 IdentifierInfo *Super = getSuperIdentifier(); 6124 NamedDecl *ND = LookupSingleName(S, Super, SuperLoc, 6125 LookupOrdinaryName); 6126 if ((CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(ND))) { 6127 // "super" names an interface. Use it. 6128 } else if (TypeDecl *TD = dyn_cast_or_null<TypeDecl>(ND)) { 6129 if (const ObjCObjectType *Iface 6130 = Context.getTypeDeclType(TD)->getAs<ObjCObjectType>()) 6131 CDecl = Iface->getInterface(); 6132 } else if (ND && isa<UnresolvedUsingTypenameDecl>(ND)) { 6133 // "super" names an unresolved type; we can't be more specific. 6134 } else { 6135 // Assume that "super" names some kind of value and parse that way. 6136 CXXScopeSpec SS; 6137 SourceLocation TemplateKWLoc; 6138 UnqualifiedId id; 6139 id.setIdentifier(Super, SuperLoc); 6140 ExprResult SuperExpr = ActOnIdExpression(S, SS, TemplateKWLoc, id, 6141 false, false); 6142 return CodeCompleteObjCInstanceMessage(S, (Expr *)SuperExpr.get(), 6143 SelIdents, 6144 AtArgumentExpression); 6145 } 6146 6147 // Fall through 6148 } 6149 6150 ParsedType Receiver; 6151 if (CDecl) 6152 Receiver = ParsedType::make(Context.getObjCInterfaceType(CDecl)); 6153 return CodeCompleteObjCClassMessage(S, Receiver, SelIdents, 6154 AtArgumentExpression, 6155 /*IsSuper=*/true); 6156 } 6157 6158 /// Given a set of code-completion results for the argument of a message 6159 /// send, determine the preferred type (if any) for that argument expression. 6160 static QualType getPreferredArgumentTypeForMessageSend(ResultBuilder &Results, 6161 unsigned NumSelIdents) { 6162 typedef CodeCompletionResult Result; 6163 ASTContext &Context = Results.getSema().Context; 6164 6165 QualType PreferredType; 6166 unsigned BestPriority = CCP_Unlikely * 2; 6167 Result *ResultsData = Results.data(); 6168 for (unsigned I = 0, N = Results.size(); I != N; ++I) { 6169 Result &R = ResultsData[I]; 6170 if (R.Kind == Result::RK_Declaration && 6171 isa<ObjCMethodDecl>(R.Declaration)) { 6172 if (R.Priority <= BestPriority) { 6173 const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(R.Declaration); 6174 if (NumSelIdents <= Method->param_size()) { 6175 QualType MyPreferredType = Method->parameters()[NumSelIdents - 1] 6176 ->getType(); 6177 if (R.Priority < BestPriority || PreferredType.isNull()) { 6178 BestPriority = R.Priority; 6179 PreferredType = MyPreferredType; 6180 } else if (!Context.hasSameUnqualifiedType(PreferredType, 6181 MyPreferredType)) { 6182 PreferredType = QualType(); 6183 } 6184 } 6185 } 6186 } 6187 } 6188 6189 return PreferredType; 6190 } 6191 6192 static void AddClassMessageCompletions(Sema &SemaRef, Scope *S, 6193 ParsedType Receiver, 6194 ArrayRef<IdentifierInfo *> SelIdents, 6195 bool AtArgumentExpression, 6196 bool IsSuper, 6197 ResultBuilder &Results) { 6198 typedef CodeCompletionResult Result; 6199 ObjCInterfaceDecl *CDecl = nullptr; 6200 6201 // If the given name refers to an interface type, retrieve the 6202 // corresponding declaration. 6203 if (Receiver) { 6204 QualType T = SemaRef.GetTypeFromParser(Receiver, nullptr); 6205 if (!T.isNull()) 6206 if (const ObjCObjectType *Interface = T->getAs<ObjCObjectType>()) 6207 CDecl = Interface->getInterface(); 6208 } 6209 6210 // Add all of the factory methods in this Objective-C class, its protocols, 6211 // superclasses, categories, implementation, etc. 6212 Results.EnterNewScope(); 6213 6214 // If this is a send-to-super, try to add the special "super" send 6215 // completion. 6216 if (IsSuper) { 6217 if (ObjCMethodDecl *SuperMethod 6218 = AddSuperSendCompletion(SemaRef, false, SelIdents, Results)) 6219 Results.Ignore(SuperMethod); 6220 } 6221 6222 // If we're inside an Objective-C method definition, prefer its selector to 6223 // others. 6224 if (ObjCMethodDecl *CurMethod = SemaRef.getCurMethodDecl()) 6225 Results.setPreferredSelector(CurMethod->getSelector()); 6226 6227 VisitedSelectorSet Selectors; 6228 if (CDecl) 6229 AddObjCMethods(CDecl, false, MK_Any, SelIdents, 6230 SemaRef.CurContext, Selectors, AtArgumentExpression, 6231 Results); 6232 else { 6233 // We're messaging "id" as a type; provide all class/factory methods. 6234 6235 // If we have an external source, load the entire class method 6236 // pool from the AST file. 6237 if (SemaRef.getExternalSource()) { 6238 for (uint32_t I = 0, 6239 N = SemaRef.getExternalSource()->GetNumExternalSelectors(); 6240 I != N; ++I) { 6241 Selector Sel = SemaRef.getExternalSource()->GetExternalSelector(I); 6242 if (Sel.isNull() || SemaRef.MethodPool.count(Sel)) 6243 continue; 6244 6245 SemaRef.ReadMethodPool(Sel); 6246 } 6247 } 6248 6249 for (Sema::GlobalMethodPool::iterator M = SemaRef.MethodPool.begin(), 6250 MEnd = SemaRef.MethodPool.end(); 6251 M != MEnd; ++M) { 6252 for (ObjCMethodList *MethList = &M->second.second; 6253 MethList && MethList->getMethod(); 6254 MethList = MethList->getNext()) { 6255 if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents)) 6256 continue; 6257 6258 Result R(MethList->getMethod(), 6259 Results.getBasePriority(MethList->getMethod()), nullptr); 6260 R.StartParameter = SelIdents.size(); 6261 R.AllParametersAreInformative = false; 6262 Results.MaybeAddResult(R, SemaRef.CurContext); 6263 } 6264 } 6265 } 6266 6267 Results.ExitScope(); 6268 } 6269 6270 void Sema::CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver, 6271 ArrayRef<IdentifierInfo *> SelIdents, 6272 bool AtArgumentExpression, 6273 bool IsSuper) { 6274 6275 QualType T = this->GetTypeFromParser(Receiver); 6276 6277 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 6278 CodeCompleter->getCodeCompletionTUInfo(), 6279 CodeCompletionContext(CodeCompletionContext::CCC_ObjCClassMessage, 6280 T, SelIdents)); 6281 6282 AddClassMessageCompletions(*this, S, Receiver, SelIdents, 6283 AtArgumentExpression, IsSuper, Results); 6284 6285 // If we're actually at the argument expression (rather than prior to the 6286 // selector), we're actually performing code completion for an expression. 6287 // Determine whether we have a single, best method. If so, we can 6288 // code-complete the expression using the corresponding parameter type as 6289 // our preferred type, improving completion results. 6290 if (AtArgumentExpression) { 6291 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results, 6292 SelIdents.size()); 6293 if (PreferredType.isNull()) 6294 CodeCompleteOrdinaryName(S, PCC_Expression); 6295 else 6296 CodeCompleteExpression(S, PreferredType); 6297 return; 6298 } 6299 6300 HandleCodeCompleteResults(this, CodeCompleter, 6301 Results.getCompletionContext(), 6302 Results.data(), Results.size()); 6303 } 6304 6305 void Sema::CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver, 6306 ArrayRef<IdentifierInfo *> SelIdents, 6307 bool AtArgumentExpression, 6308 ObjCInterfaceDecl *Super) { 6309 typedef CodeCompletionResult Result; 6310 6311 Expr *RecExpr = static_cast<Expr *>(Receiver); 6312 6313 // If necessary, apply function/array conversion to the receiver. 6314 // C99 6.7.5.3p[7,8]. 6315 if (RecExpr) { 6316 ExprResult Conv = DefaultFunctionArrayLvalueConversion(RecExpr); 6317 if (Conv.isInvalid()) // conversion failed. bail. 6318 return; 6319 RecExpr = Conv.get(); 6320 } 6321 QualType ReceiverType = RecExpr? RecExpr->getType() 6322 : Super? Context.getObjCObjectPointerType( 6323 Context.getObjCInterfaceType(Super)) 6324 : Context.getObjCIdType(); 6325 6326 // If we're messaging an expression with type "id" or "Class", check 6327 // whether we know something special about the receiver that allows 6328 // us to assume a more-specific receiver type. 6329 if (ReceiverType->isObjCIdType() || ReceiverType->isObjCClassType()) { 6330 if (ObjCInterfaceDecl *IFace = GetAssumedMessageSendExprType(RecExpr)) { 6331 if (ReceiverType->isObjCClassType()) 6332 return CodeCompleteObjCClassMessage(S, 6333 ParsedType::make(Context.getObjCInterfaceType(IFace)), 6334 SelIdents, 6335 AtArgumentExpression, Super); 6336 6337 ReceiverType = Context.getObjCObjectPointerType( 6338 Context.getObjCInterfaceType(IFace)); 6339 } 6340 } else if (RecExpr && getLangOpts().CPlusPlus) { 6341 ExprResult Conv = PerformContextuallyConvertToObjCPointer(RecExpr); 6342 if (Conv.isUsable()) { 6343 RecExpr = Conv.get(); 6344 ReceiverType = RecExpr->getType(); 6345 } 6346 } 6347 6348 // Build the set of methods we can see. 6349 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 6350 CodeCompleter->getCodeCompletionTUInfo(), 6351 CodeCompletionContext(CodeCompletionContext::CCC_ObjCInstanceMessage, 6352 ReceiverType, SelIdents)); 6353 6354 Results.EnterNewScope(); 6355 6356 // If this is a send-to-super, try to add the special "super" send 6357 // completion. 6358 if (Super) { 6359 if (ObjCMethodDecl *SuperMethod 6360 = AddSuperSendCompletion(*this, false, SelIdents, Results)) 6361 Results.Ignore(SuperMethod); 6362 } 6363 6364 // If we're inside an Objective-C method definition, prefer its selector to 6365 // others. 6366 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) 6367 Results.setPreferredSelector(CurMethod->getSelector()); 6368 6369 // Keep track of the selectors we've already added. 6370 VisitedSelectorSet Selectors; 6371 6372 // Handle messages to Class. This really isn't a message to an instance 6373 // method, so we treat it the same way we would treat a message send to a 6374 // class method. 6375 if (ReceiverType->isObjCClassType() || 6376 ReceiverType->isObjCQualifiedClassType()) { 6377 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) { 6378 if (ObjCInterfaceDecl *ClassDecl = CurMethod->getClassInterface()) 6379 AddObjCMethods(ClassDecl, false, MK_Any, SelIdents, 6380 CurContext, Selectors, AtArgumentExpression, Results); 6381 } 6382 } 6383 // Handle messages to a qualified ID ("id<foo>"). 6384 else if (const ObjCObjectPointerType *QualID 6385 = ReceiverType->getAsObjCQualifiedIdType()) { 6386 // Search protocols for instance methods. 6387 for (auto *I : QualID->quals()) 6388 AddObjCMethods(I, true, MK_Any, SelIdents, CurContext, 6389 Selectors, AtArgumentExpression, Results); 6390 } 6391 // Handle messages to a pointer to interface type. 6392 else if (const ObjCObjectPointerType *IFacePtr 6393 = ReceiverType->getAsObjCInterfacePointerType()) { 6394 // Search the class, its superclasses, etc., for instance methods. 6395 AddObjCMethods(IFacePtr->getInterfaceDecl(), true, MK_Any, SelIdents, 6396 CurContext, Selectors, AtArgumentExpression, 6397 Results); 6398 6399 // Search protocols for instance methods. 6400 for (auto *I : IFacePtr->quals()) 6401 AddObjCMethods(I, true, MK_Any, SelIdents, CurContext, 6402 Selectors, AtArgumentExpression, Results); 6403 } 6404 // Handle messages to "id". 6405 else if (ReceiverType->isObjCIdType()) { 6406 // We're messaging "id", so provide all instance methods we know 6407 // about as code-completion results. 6408 6409 // If we have an external source, load the entire class method 6410 // pool from the AST file. 6411 if (ExternalSource) { 6412 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors(); 6413 I != N; ++I) { 6414 Selector Sel = ExternalSource->GetExternalSelector(I); 6415 if (Sel.isNull() || MethodPool.count(Sel)) 6416 continue; 6417 6418 ReadMethodPool(Sel); 6419 } 6420 } 6421 6422 for (GlobalMethodPool::iterator M = MethodPool.begin(), 6423 MEnd = MethodPool.end(); 6424 M != MEnd; ++M) { 6425 for (ObjCMethodList *MethList = &M->second.first; 6426 MethList && MethList->getMethod(); 6427 MethList = MethList->getNext()) { 6428 if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents)) 6429 continue; 6430 6431 if (!Selectors.insert(MethList->getMethod()->getSelector()).second) 6432 continue; 6433 6434 Result R(MethList->getMethod(), 6435 Results.getBasePriority(MethList->getMethod()), nullptr); 6436 R.StartParameter = SelIdents.size(); 6437 R.AllParametersAreInformative = false; 6438 Results.MaybeAddResult(R, CurContext); 6439 } 6440 } 6441 } 6442 Results.ExitScope(); 6443 6444 6445 // If we're actually at the argument expression (rather than prior to the 6446 // selector), we're actually performing code completion for an expression. 6447 // Determine whether we have a single, best method. If so, we can 6448 // code-complete the expression using the corresponding parameter type as 6449 // our preferred type, improving completion results. 6450 if (AtArgumentExpression) { 6451 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results, 6452 SelIdents.size()); 6453 if (PreferredType.isNull()) 6454 CodeCompleteOrdinaryName(S, PCC_Expression); 6455 else 6456 CodeCompleteExpression(S, PreferredType); 6457 return; 6458 } 6459 6460 HandleCodeCompleteResults(this, CodeCompleter, 6461 Results.getCompletionContext(), 6462 Results.data(),Results.size()); 6463 } 6464 6465 void Sema::CodeCompleteObjCForCollection(Scope *S, 6466 DeclGroupPtrTy IterationVar) { 6467 CodeCompleteExpressionData Data; 6468 Data.ObjCCollection = true; 6469 6470 if (IterationVar.getAsOpaquePtr()) { 6471 DeclGroupRef DG = IterationVar.get(); 6472 for (DeclGroupRef::iterator I = DG.begin(), End = DG.end(); I != End; ++I) { 6473 if (*I) 6474 Data.IgnoreDecls.push_back(*I); 6475 } 6476 } 6477 6478 CodeCompleteExpression(S, Data); 6479 } 6480 6481 void Sema::CodeCompleteObjCSelector(Scope *S, 6482 ArrayRef<IdentifierInfo *> SelIdents) { 6483 // If we have an external source, load the entire class method 6484 // pool from the AST file. 6485 if (ExternalSource) { 6486 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors(); 6487 I != N; ++I) { 6488 Selector Sel = ExternalSource->GetExternalSelector(I); 6489 if (Sel.isNull() || MethodPool.count(Sel)) 6490 continue; 6491 6492 ReadMethodPool(Sel); 6493 } 6494 } 6495 6496 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 6497 CodeCompleter->getCodeCompletionTUInfo(), 6498 CodeCompletionContext::CCC_SelectorName); 6499 Results.EnterNewScope(); 6500 for (GlobalMethodPool::iterator M = MethodPool.begin(), 6501 MEnd = MethodPool.end(); 6502 M != MEnd; ++M) { 6503 6504 Selector Sel = M->first; 6505 if (!isAcceptableObjCSelector(Sel, MK_Any, SelIdents)) 6506 continue; 6507 6508 CodeCompletionBuilder Builder(Results.getAllocator(), 6509 Results.getCodeCompletionTUInfo()); 6510 if (Sel.isUnarySelector()) { 6511 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString( 6512 Sel.getNameForSlot(0))); 6513 Results.AddResult(Builder.TakeString()); 6514 continue; 6515 } 6516 6517 std::string Accumulator; 6518 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I) { 6519 if (I == SelIdents.size()) { 6520 if (!Accumulator.empty()) { 6521 Builder.AddInformativeChunk(Builder.getAllocator().CopyString( 6522 Accumulator)); 6523 Accumulator.clear(); 6524 } 6525 } 6526 6527 Accumulator += Sel.getNameForSlot(I); 6528 Accumulator += ':'; 6529 } 6530 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString( Accumulator)); 6531 Results.AddResult(Builder.TakeString()); 6532 } 6533 Results.ExitScope(); 6534 6535 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 6536 Results.data(), Results.size()); 6537 } 6538 6539 /// Add all of the protocol declarations that we find in the given 6540 /// (translation unit) context. 6541 static void AddProtocolResults(DeclContext *Ctx, DeclContext *CurContext, 6542 bool OnlyForwardDeclarations, 6543 ResultBuilder &Results) { 6544 typedef CodeCompletionResult Result; 6545 6546 for (const auto *D : Ctx->decls()) { 6547 // Record any protocols we find. 6548 if (const auto *Proto = dyn_cast<ObjCProtocolDecl>(D)) 6549 if (!OnlyForwardDeclarations || !Proto->hasDefinition()) 6550 Results.AddResult(Result(Proto, Results.getBasePriority(Proto),nullptr), 6551 CurContext, nullptr, false); 6552 } 6553 } 6554 6555 void Sema::CodeCompleteObjCProtocolReferences( 6556 ArrayRef<IdentifierLocPair> Protocols) { 6557 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 6558 CodeCompleter->getCodeCompletionTUInfo(), 6559 CodeCompletionContext::CCC_ObjCProtocolName); 6560 6561 if (CodeCompleter->includeGlobals()) { 6562 Results.EnterNewScope(); 6563 6564 // Tell the result set to ignore all of the protocols we have 6565 // already seen. 6566 // FIXME: This doesn't work when caching code-completion results. 6567 for (const IdentifierLocPair &Pair : Protocols) 6568 if (ObjCProtocolDecl *Protocol = LookupProtocol(Pair.first, 6569 Pair.second)) 6570 Results.Ignore(Protocol); 6571 6572 // Add all protocols. 6573 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, false, 6574 Results); 6575 6576 Results.ExitScope(); 6577 } 6578 6579 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 6580 Results.data(), Results.size()); 6581 } 6582 6583 void Sema::CodeCompleteObjCProtocolDecl(Scope *) { 6584 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 6585 CodeCompleter->getCodeCompletionTUInfo(), 6586 CodeCompletionContext::CCC_ObjCProtocolName); 6587 6588 if (CodeCompleter->includeGlobals()) { 6589 Results.EnterNewScope(); 6590 6591 // Add all protocols. 6592 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, true, 6593 Results); 6594 6595 Results.ExitScope(); 6596 } 6597 6598 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 6599 Results.data(), Results.size()); 6600 } 6601 6602 /// Add all of the Objective-C interface declarations that we find in 6603 /// the given (translation unit) context. 6604 static void AddInterfaceResults(DeclContext *Ctx, DeclContext *CurContext, 6605 bool OnlyForwardDeclarations, 6606 bool OnlyUnimplemented, 6607 ResultBuilder &Results) { 6608 typedef CodeCompletionResult Result; 6609 6610 for (const auto *D : Ctx->decls()) { 6611 // Record any interfaces we find. 6612 if (const auto *Class = dyn_cast<ObjCInterfaceDecl>(D)) 6613 if ((!OnlyForwardDeclarations || !Class->hasDefinition()) && 6614 (!OnlyUnimplemented || !Class->getImplementation())) 6615 Results.AddResult(Result(Class, Results.getBasePriority(Class),nullptr), 6616 CurContext, nullptr, false); 6617 } 6618 } 6619 6620 void Sema::CodeCompleteObjCInterfaceDecl(Scope *S) { 6621 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 6622 CodeCompleter->getCodeCompletionTUInfo(), 6623 CodeCompletionContext::CCC_ObjCInterfaceName); 6624 Results.EnterNewScope(); 6625 6626 if (CodeCompleter->includeGlobals()) { 6627 // Add all classes. 6628 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false, 6629 false, Results); 6630 } 6631 6632 Results.ExitScope(); 6633 6634 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 6635 Results.data(), Results.size()); 6636 } 6637 6638 void Sema::CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName, 6639 SourceLocation ClassNameLoc) { 6640 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 6641 CodeCompleter->getCodeCompletionTUInfo(), 6642 CodeCompletionContext::CCC_ObjCInterfaceName); 6643 Results.EnterNewScope(); 6644 6645 // Make sure that we ignore the class we're currently defining. 6646 NamedDecl *CurClass 6647 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName); 6648 if (CurClass && isa<ObjCInterfaceDecl>(CurClass)) 6649 Results.Ignore(CurClass); 6650 6651 if (CodeCompleter->includeGlobals()) { 6652 // Add all classes. 6653 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false, 6654 false, Results); 6655 } 6656 6657 Results.ExitScope(); 6658 6659 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 6660 Results.data(), Results.size()); 6661 } 6662 6663 void Sema::CodeCompleteObjCImplementationDecl(Scope *S) { 6664 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 6665 CodeCompleter->getCodeCompletionTUInfo(), 6666 CodeCompletionContext::CCC_ObjCImplementation); 6667 Results.EnterNewScope(); 6668 6669 if (CodeCompleter->includeGlobals()) { 6670 // Add all unimplemented classes. 6671 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false, 6672 true, Results); 6673 } 6674 6675 Results.ExitScope(); 6676 6677 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 6678 Results.data(), Results.size()); 6679 } 6680 6681 void Sema::CodeCompleteObjCInterfaceCategory(Scope *S, 6682 IdentifierInfo *ClassName, 6683 SourceLocation ClassNameLoc) { 6684 typedef CodeCompletionResult Result; 6685 6686 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 6687 CodeCompleter->getCodeCompletionTUInfo(), 6688 CodeCompletionContext::CCC_ObjCCategoryName); 6689 6690 // Ignore any categories we find that have already been implemented by this 6691 // interface. 6692 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames; 6693 NamedDecl *CurClass 6694 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName); 6695 if (ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass)){ 6696 for (const auto *Cat : Class->visible_categories()) 6697 CategoryNames.insert(Cat->getIdentifier()); 6698 } 6699 6700 // Add all of the categories we know about. 6701 Results.EnterNewScope(); 6702 TranslationUnitDecl *TU = Context.getTranslationUnitDecl(); 6703 for (const auto *D : TU->decls()) 6704 if (const auto *Category = dyn_cast<ObjCCategoryDecl>(D)) 6705 if (CategoryNames.insert(Category->getIdentifier()).second) 6706 Results.AddResult(Result(Category, Results.getBasePriority(Category), 6707 nullptr), 6708 CurContext, nullptr, false); 6709 Results.ExitScope(); 6710 6711 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 6712 Results.data(), Results.size()); 6713 } 6714 6715 void Sema::CodeCompleteObjCImplementationCategory(Scope *S, 6716 IdentifierInfo *ClassName, 6717 SourceLocation ClassNameLoc) { 6718 typedef CodeCompletionResult Result; 6719 6720 // Find the corresponding interface. If we couldn't find the interface, the 6721 // program itself is ill-formed. However, we'll try to be helpful still by 6722 // providing the list of all of the categories we know about. 6723 NamedDecl *CurClass 6724 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName); 6725 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass); 6726 if (!Class) 6727 return CodeCompleteObjCInterfaceCategory(S, ClassName, ClassNameLoc); 6728 6729 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 6730 CodeCompleter->getCodeCompletionTUInfo(), 6731 CodeCompletionContext::CCC_ObjCCategoryName); 6732 6733 // Add all of the categories that have have corresponding interface 6734 // declarations in this class and any of its superclasses, except for 6735 // already-implemented categories in the class itself. 6736 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames; 6737 Results.EnterNewScope(); 6738 bool IgnoreImplemented = true; 6739 while (Class) { 6740 for (const auto *Cat : Class->visible_categories()) { 6741 if ((!IgnoreImplemented || !Cat->getImplementation()) && 6742 CategoryNames.insert(Cat->getIdentifier()).second) 6743 Results.AddResult(Result(Cat, Results.getBasePriority(Cat), nullptr), 6744 CurContext, nullptr, false); 6745 } 6746 6747 Class = Class->getSuperClass(); 6748 IgnoreImplemented = false; 6749 } 6750 Results.ExitScope(); 6751 6752 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 6753 Results.data(), Results.size()); 6754 } 6755 6756 void Sema::CodeCompleteObjCPropertyDefinition(Scope *S) { 6757 CodeCompletionContext CCContext(CodeCompletionContext::CCC_Other); 6758 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 6759 CodeCompleter->getCodeCompletionTUInfo(), 6760 CCContext); 6761 6762 // Figure out where this @synthesize lives. 6763 ObjCContainerDecl *Container 6764 = dyn_cast_or_null<ObjCContainerDecl>(CurContext); 6765 if (!Container || 6766 (!isa<ObjCImplementationDecl>(Container) && 6767 !isa<ObjCCategoryImplDecl>(Container))) 6768 return; 6769 6770 // Ignore any properties that have already been implemented. 6771 Container = getContainerDef(Container); 6772 for (const auto *D : Container->decls()) 6773 if (const auto *PropertyImpl = dyn_cast<ObjCPropertyImplDecl>(D)) 6774 Results.Ignore(PropertyImpl->getPropertyDecl()); 6775 6776 // Add any properties that we find. 6777 AddedPropertiesSet AddedProperties; 6778 Results.EnterNewScope(); 6779 if (ObjCImplementationDecl *ClassImpl 6780 = dyn_cast<ObjCImplementationDecl>(Container)) 6781 AddObjCProperties(CCContext, ClassImpl->getClassInterface(), false, 6782 /*AllowNullaryMethods=*/false, CurContext, 6783 AddedProperties, Results); 6784 else 6785 AddObjCProperties(CCContext, 6786 cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl(), 6787 false, /*AllowNullaryMethods=*/false, CurContext, 6788 AddedProperties, Results); 6789 Results.ExitScope(); 6790 6791 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 6792 Results.data(), Results.size()); 6793 } 6794 6795 void Sema::CodeCompleteObjCPropertySynthesizeIvar(Scope *S, 6796 IdentifierInfo *PropertyName) { 6797 typedef CodeCompletionResult Result; 6798 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 6799 CodeCompleter->getCodeCompletionTUInfo(), 6800 CodeCompletionContext::CCC_Other); 6801 6802 // Figure out where this @synthesize lives. 6803 ObjCContainerDecl *Container 6804 = dyn_cast_or_null<ObjCContainerDecl>(CurContext); 6805 if (!Container || 6806 (!isa<ObjCImplementationDecl>(Container) && 6807 !isa<ObjCCategoryImplDecl>(Container))) 6808 return; 6809 6810 // Figure out which interface we're looking into. 6811 ObjCInterfaceDecl *Class = nullptr; 6812 if (ObjCImplementationDecl *ClassImpl 6813 = dyn_cast<ObjCImplementationDecl>(Container)) 6814 Class = ClassImpl->getClassInterface(); 6815 else 6816 Class = cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl() 6817 ->getClassInterface(); 6818 6819 // Determine the type of the property we're synthesizing. 6820 QualType PropertyType = Context.getObjCIdType(); 6821 if (Class) { 6822 if (ObjCPropertyDecl *Property = Class->FindPropertyDeclaration( 6823 PropertyName, ObjCPropertyQueryKind::OBJC_PR_query_instance)) { 6824 PropertyType 6825 = Property->getType().getNonReferenceType().getUnqualifiedType(); 6826 6827 // Give preference to ivars 6828 Results.setPreferredType(PropertyType); 6829 } 6830 } 6831 6832 // Add all of the instance variables in this class and its superclasses. 6833 Results.EnterNewScope(); 6834 bool SawSimilarlyNamedIvar = false; 6835 std::string NameWithPrefix; 6836 NameWithPrefix += '_'; 6837 NameWithPrefix += PropertyName->getName(); 6838 std::string NameWithSuffix = PropertyName->getName().str(); 6839 NameWithSuffix += '_'; 6840 for(; Class; Class = Class->getSuperClass()) { 6841 for (ObjCIvarDecl *Ivar = Class->all_declared_ivar_begin(); Ivar; 6842 Ivar = Ivar->getNextIvar()) { 6843 Results.AddResult(Result(Ivar, Results.getBasePriority(Ivar), nullptr), 6844 CurContext, nullptr, false); 6845 6846 // Determine whether we've seen an ivar with a name similar to the 6847 // property. 6848 if ((PropertyName == Ivar->getIdentifier() || 6849 NameWithPrefix == Ivar->getName() || 6850 NameWithSuffix == Ivar->getName())) { 6851 SawSimilarlyNamedIvar = true; 6852 6853 // Reduce the priority of this result by one, to give it a slight 6854 // advantage over other results whose names don't match so closely. 6855 if (Results.size() && 6856 Results.data()[Results.size() - 1].Kind 6857 == CodeCompletionResult::RK_Declaration && 6858 Results.data()[Results.size() - 1].Declaration == Ivar) 6859 Results.data()[Results.size() - 1].Priority--; 6860 } 6861 } 6862 } 6863 6864 if (!SawSimilarlyNamedIvar) { 6865 // Create ivar result _propName, that the user can use to synthesize 6866 // an ivar of the appropriate type. 6867 unsigned Priority = CCP_MemberDeclaration + 1; 6868 typedef CodeCompletionResult Result; 6869 CodeCompletionAllocator &Allocator = Results.getAllocator(); 6870 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo(), 6871 Priority,CXAvailability_Available); 6872 6873 PrintingPolicy Policy = getCompletionPrintingPolicy(*this); 6874 Builder.AddResultTypeChunk(GetCompletionTypeString(PropertyType, Context, 6875 Policy, Allocator)); 6876 Builder.AddTypedTextChunk(Allocator.CopyString(NameWithPrefix)); 6877 Results.AddResult(Result(Builder.TakeString(), Priority, 6878 CXCursor_ObjCIvarDecl)); 6879 } 6880 6881 Results.ExitScope(); 6882 6883 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 6884 Results.data(), Results.size()); 6885 } 6886 6887 // Mapping from selectors to the methods that implement that selector, along 6888 // with the "in original class" flag. 6889 typedef llvm::DenseMap< 6890 Selector, llvm::PointerIntPair<ObjCMethodDecl *, 1, bool> > KnownMethodsMap; 6891 6892 /// Find all of the methods that reside in the given container 6893 /// (and its superclasses, protocols, etc.) that meet the given 6894 /// criteria. Insert those methods into the map of known methods, 6895 /// indexed by selector so they can be easily found. 6896 static void FindImplementableMethods(ASTContext &Context, 6897 ObjCContainerDecl *Container, 6898 Optional<bool> WantInstanceMethods, 6899 QualType ReturnType, 6900 KnownMethodsMap &KnownMethods, 6901 bool InOriginalClass = true) { 6902 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)) { 6903 // Make sure we have a definition; that's what we'll walk. 6904 if (!IFace->hasDefinition()) 6905 return; 6906 6907 IFace = IFace->getDefinition(); 6908 Container = IFace; 6909 6910 const ObjCList<ObjCProtocolDecl> &Protocols 6911 = IFace->getReferencedProtocols(); 6912 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(), 6913 E = Protocols.end(); 6914 I != E; ++I) 6915 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType, 6916 KnownMethods, InOriginalClass); 6917 6918 // Add methods from any class extensions and categories. 6919 for (auto *Cat : IFace->visible_categories()) { 6920 FindImplementableMethods(Context, Cat, WantInstanceMethods, ReturnType, 6921 KnownMethods, false); 6922 } 6923 6924 // Visit the superclass. 6925 if (IFace->getSuperClass()) 6926 FindImplementableMethods(Context, IFace->getSuperClass(), 6927 WantInstanceMethods, ReturnType, 6928 KnownMethods, false); 6929 } 6930 6931 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) { 6932 // Recurse into protocols. 6933 const ObjCList<ObjCProtocolDecl> &Protocols 6934 = Category->getReferencedProtocols(); 6935 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(), 6936 E = Protocols.end(); 6937 I != E; ++I) 6938 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType, 6939 KnownMethods, InOriginalClass); 6940 6941 // If this category is the original class, jump to the interface. 6942 if (InOriginalClass && Category->getClassInterface()) 6943 FindImplementableMethods(Context, Category->getClassInterface(), 6944 WantInstanceMethods, ReturnType, KnownMethods, 6945 false); 6946 } 6947 6948 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) { 6949 // Make sure we have a definition; that's what we'll walk. 6950 if (!Protocol->hasDefinition()) 6951 return; 6952 Protocol = Protocol->getDefinition(); 6953 Container = Protocol; 6954 6955 // Recurse into protocols. 6956 const ObjCList<ObjCProtocolDecl> &Protocols 6957 = Protocol->getReferencedProtocols(); 6958 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(), 6959 E = Protocols.end(); 6960 I != E; ++I) 6961 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType, 6962 KnownMethods, false); 6963 } 6964 6965 // Add methods in this container. This operation occurs last because 6966 // we want the methods from this container to override any methods 6967 // we've previously seen with the same selector. 6968 for (auto *M : Container->methods()) { 6969 if (!WantInstanceMethods || M->isInstanceMethod() == *WantInstanceMethods) { 6970 if (!ReturnType.isNull() && 6971 !Context.hasSameUnqualifiedType(ReturnType, M->getReturnType())) 6972 continue; 6973 6974 KnownMethods[M->getSelector()] = 6975 KnownMethodsMap::mapped_type(M, InOriginalClass); 6976 } 6977 } 6978 } 6979 6980 /// Add the parenthesized return or parameter type chunk to a code 6981 /// completion string. 6982 static void AddObjCPassingTypeChunk(QualType Type, 6983 unsigned ObjCDeclQuals, 6984 ASTContext &Context, 6985 const PrintingPolicy &Policy, 6986 CodeCompletionBuilder &Builder) { 6987 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 6988 std::string Quals = formatObjCParamQualifiers(ObjCDeclQuals, Type); 6989 if (!Quals.empty()) 6990 Builder.AddTextChunk(Builder.getAllocator().CopyString(Quals)); 6991 Builder.AddTextChunk(GetCompletionTypeString(Type, Context, Policy, 6992 Builder.getAllocator())); 6993 Builder.AddChunk(CodeCompletionString::CK_RightParen); 6994 } 6995 6996 /// Determine whether the given class is or inherits from a class by 6997 /// the given name. 6998 static bool InheritsFromClassNamed(ObjCInterfaceDecl *Class, 6999 StringRef Name) { 7000 if (!Class) 7001 return false; 7002 7003 if (Class->getIdentifier() && Class->getIdentifier()->getName() == Name) 7004 return true; 7005 7006 return InheritsFromClassNamed(Class->getSuperClass(), Name); 7007 } 7008 7009 /// Add code completions for Objective-C Key-Value Coding (KVC) and 7010 /// Key-Value Observing (KVO). 7011 static void AddObjCKeyValueCompletions(ObjCPropertyDecl *Property, 7012 bool IsInstanceMethod, 7013 QualType ReturnType, 7014 ASTContext &Context, 7015 VisitedSelectorSet &KnownSelectors, 7016 ResultBuilder &Results) { 7017 IdentifierInfo *PropName = Property->getIdentifier(); 7018 if (!PropName || PropName->getLength() == 0) 7019 return; 7020 7021 PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema()); 7022 7023 // Builder that will create each code completion. 7024 typedef CodeCompletionResult Result; 7025 CodeCompletionAllocator &Allocator = Results.getAllocator(); 7026 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo()); 7027 7028 // The selector table. 7029 SelectorTable &Selectors = Context.Selectors; 7030 7031 // The property name, copied into the code completion allocation region 7032 // on demand. 7033 struct KeyHolder { 7034 CodeCompletionAllocator &Allocator; 7035 StringRef Key; 7036 const char *CopiedKey; 7037 7038 KeyHolder(CodeCompletionAllocator &Allocator, StringRef Key) 7039 : Allocator(Allocator), Key(Key), CopiedKey(nullptr) {} 7040 7041 operator const char *() { 7042 if (CopiedKey) 7043 return CopiedKey; 7044 7045 return CopiedKey = Allocator.CopyString(Key); 7046 } 7047 } Key(Allocator, PropName->getName()); 7048 7049 // The uppercased name of the property name. 7050 std::string UpperKey = PropName->getName(); 7051 if (!UpperKey.empty()) 7052 UpperKey[0] = toUppercase(UpperKey[0]); 7053 7054 bool ReturnTypeMatchesProperty = ReturnType.isNull() || 7055 Context.hasSameUnqualifiedType(ReturnType.getNonReferenceType(), 7056 Property->getType()); 7057 bool ReturnTypeMatchesVoid 7058 = ReturnType.isNull() || ReturnType->isVoidType(); 7059 7060 // Add the normal accessor -(type)key. 7061 if (IsInstanceMethod && 7062 KnownSelectors.insert(Selectors.getNullarySelector(PropName)).second && 7063 ReturnTypeMatchesProperty && !Property->getGetterMethodDecl()) { 7064 if (ReturnType.isNull()) 7065 AddObjCPassingTypeChunk(Property->getType(), /*Quals=*/0, 7066 Context, Policy, Builder); 7067 7068 Builder.AddTypedTextChunk(Key); 7069 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern, 7070 CXCursor_ObjCInstanceMethodDecl)); 7071 } 7072 7073 // If we have an integral or boolean property (or the user has provided 7074 // an integral or boolean return type), add the accessor -(type)isKey. 7075 if (IsInstanceMethod && 7076 ((!ReturnType.isNull() && 7077 (ReturnType->isIntegerType() || ReturnType->isBooleanType())) || 7078 (ReturnType.isNull() && 7079 (Property->getType()->isIntegerType() || 7080 Property->getType()->isBooleanType())))) { 7081 std::string SelectorName = (Twine("is") + UpperKey).str(); 7082 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 7083 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId)) 7084 .second) { 7085 if (ReturnType.isNull()) { 7086 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7087 Builder.AddTextChunk("BOOL"); 7088 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7089 } 7090 7091 Builder.AddTypedTextChunk( 7092 Allocator.CopyString(SelectorId->getName())); 7093 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern, 7094 CXCursor_ObjCInstanceMethodDecl)); 7095 } 7096 } 7097 7098 // Add the normal mutator. 7099 if (IsInstanceMethod && ReturnTypeMatchesVoid && 7100 !Property->getSetterMethodDecl()) { 7101 std::string SelectorName = (Twine("set") + UpperKey).str(); 7102 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 7103 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 7104 if (ReturnType.isNull()) { 7105 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7106 Builder.AddTextChunk("void"); 7107 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7108 } 7109 7110 Builder.AddTypedTextChunk( 7111 Allocator.CopyString(SelectorId->getName())); 7112 Builder.AddTypedTextChunk(":"); 7113 AddObjCPassingTypeChunk(Property->getType(), /*Quals=*/0, 7114 Context, Policy, Builder); 7115 Builder.AddTextChunk(Key); 7116 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern, 7117 CXCursor_ObjCInstanceMethodDecl)); 7118 } 7119 } 7120 7121 // Indexed and unordered accessors 7122 unsigned IndexedGetterPriority = CCP_CodePattern; 7123 unsigned IndexedSetterPriority = CCP_CodePattern; 7124 unsigned UnorderedGetterPriority = CCP_CodePattern; 7125 unsigned UnorderedSetterPriority = CCP_CodePattern; 7126 if (const ObjCObjectPointerType *ObjCPointer 7127 = Property->getType()->getAs<ObjCObjectPointerType>()) { 7128 if (ObjCInterfaceDecl *IFace = ObjCPointer->getInterfaceDecl()) { 7129 // If this interface type is not provably derived from a known 7130 // collection, penalize the corresponding completions. 7131 if (!InheritsFromClassNamed(IFace, "NSMutableArray")) { 7132 IndexedSetterPriority += CCD_ProbablyNotObjCCollection; 7133 if (!InheritsFromClassNamed(IFace, "NSArray")) 7134 IndexedGetterPriority += CCD_ProbablyNotObjCCollection; 7135 } 7136 7137 if (!InheritsFromClassNamed(IFace, "NSMutableSet")) { 7138 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection; 7139 if (!InheritsFromClassNamed(IFace, "NSSet")) 7140 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection; 7141 } 7142 } 7143 } else { 7144 IndexedGetterPriority += CCD_ProbablyNotObjCCollection; 7145 IndexedSetterPriority += CCD_ProbablyNotObjCCollection; 7146 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection; 7147 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection; 7148 } 7149 7150 // Add -(NSUInteger)countOf<key> 7151 if (IsInstanceMethod && 7152 (ReturnType.isNull() || ReturnType->isIntegerType())) { 7153 std::string SelectorName = (Twine("countOf") + UpperKey).str(); 7154 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 7155 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId)) 7156 .second) { 7157 if (ReturnType.isNull()) { 7158 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7159 Builder.AddTextChunk("NSUInteger"); 7160 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7161 } 7162 7163 Builder.AddTypedTextChunk( 7164 Allocator.CopyString(SelectorId->getName())); 7165 Results.AddResult(Result(Builder.TakeString(), 7166 std::min(IndexedGetterPriority, 7167 UnorderedGetterPriority), 7168 CXCursor_ObjCInstanceMethodDecl)); 7169 } 7170 } 7171 7172 // Indexed getters 7173 // Add -(id)objectInKeyAtIndex:(NSUInteger)index 7174 if (IsInstanceMethod && 7175 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) { 7176 std::string SelectorName 7177 = (Twine("objectIn") + UpperKey + "AtIndex").str(); 7178 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 7179 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 7180 if (ReturnType.isNull()) { 7181 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7182 Builder.AddTextChunk("id"); 7183 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7184 } 7185 7186 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 7187 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7188 Builder.AddTextChunk("NSUInteger"); 7189 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7190 Builder.AddTextChunk("index"); 7191 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority, 7192 CXCursor_ObjCInstanceMethodDecl)); 7193 } 7194 } 7195 7196 // Add -(NSArray *)keyAtIndexes:(NSIndexSet *)indexes 7197 if (IsInstanceMethod && 7198 (ReturnType.isNull() || 7199 (ReturnType->isObjCObjectPointerType() && 7200 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() && 7201 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() 7202 ->getName() == "NSArray"))) { 7203 std::string SelectorName 7204 = (Twine(Property->getName()) + "AtIndexes").str(); 7205 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 7206 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 7207 if (ReturnType.isNull()) { 7208 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7209 Builder.AddTextChunk("NSArray *"); 7210 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7211 } 7212 7213 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 7214 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7215 Builder.AddTextChunk("NSIndexSet *"); 7216 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7217 Builder.AddTextChunk("indexes"); 7218 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority, 7219 CXCursor_ObjCInstanceMethodDecl)); 7220 } 7221 } 7222 7223 // Add -(void)getKey:(type **)buffer range:(NSRange)inRange 7224 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 7225 std::string SelectorName = (Twine("get") + UpperKey).str(); 7226 IdentifierInfo *SelectorIds[2] = { 7227 &Context.Idents.get(SelectorName), 7228 &Context.Idents.get("range") 7229 }; 7230 7231 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) { 7232 if (ReturnType.isNull()) { 7233 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7234 Builder.AddTextChunk("void"); 7235 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7236 } 7237 7238 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 7239 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7240 Builder.AddPlaceholderChunk("object-type"); 7241 Builder.AddTextChunk(" **"); 7242 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7243 Builder.AddTextChunk("buffer"); 7244 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7245 Builder.AddTypedTextChunk("range:"); 7246 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7247 Builder.AddTextChunk("NSRange"); 7248 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7249 Builder.AddTextChunk("inRange"); 7250 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority, 7251 CXCursor_ObjCInstanceMethodDecl)); 7252 } 7253 } 7254 7255 // Mutable indexed accessors 7256 7257 // - (void)insertObject:(type *)object inKeyAtIndex:(NSUInteger)index 7258 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 7259 std::string SelectorName = (Twine("in") + UpperKey + "AtIndex").str(); 7260 IdentifierInfo *SelectorIds[2] = { 7261 &Context.Idents.get("insertObject"), 7262 &Context.Idents.get(SelectorName) 7263 }; 7264 7265 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) { 7266 if (ReturnType.isNull()) { 7267 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7268 Builder.AddTextChunk("void"); 7269 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7270 } 7271 7272 Builder.AddTypedTextChunk("insertObject:"); 7273 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7274 Builder.AddPlaceholderChunk("object-type"); 7275 Builder.AddTextChunk(" *"); 7276 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7277 Builder.AddTextChunk("object"); 7278 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7279 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 7280 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7281 Builder.AddPlaceholderChunk("NSUInteger"); 7282 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7283 Builder.AddTextChunk("index"); 7284 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority, 7285 CXCursor_ObjCInstanceMethodDecl)); 7286 } 7287 } 7288 7289 // - (void)insertKey:(NSArray *)array atIndexes:(NSIndexSet *)indexes 7290 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 7291 std::string SelectorName = (Twine("insert") + UpperKey).str(); 7292 IdentifierInfo *SelectorIds[2] = { 7293 &Context.Idents.get(SelectorName), 7294 &Context.Idents.get("atIndexes") 7295 }; 7296 7297 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) { 7298 if (ReturnType.isNull()) { 7299 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7300 Builder.AddTextChunk("void"); 7301 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7302 } 7303 7304 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 7305 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7306 Builder.AddTextChunk("NSArray *"); 7307 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7308 Builder.AddTextChunk("array"); 7309 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7310 Builder.AddTypedTextChunk("atIndexes:"); 7311 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7312 Builder.AddPlaceholderChunk("NSIndexSet *"); 7313 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7314 Builder.AddTextChunk("indexes"); 7315 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority, 7316 CXCursor_ObjCInstanceMethodDecl)); 7317 } 7318 } 7319 7320 // -(void)removeObjectFromKeyAtIndex:(NSUInteger)index 7321 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 7322 std::string SelectorName 7323 = (Twine("removeObjectFrom") + UpperKey + "AtIndex").str(); 7324 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 7325 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 7326 if (ReturnType.isNull()) { 7327 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7328 Builder.AddTextChunk("void"); 7329 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7330 } 7331 7332 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 7333 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7334 Builder.AddTextChunk("NSUInteger"); 7335 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7336 Builder.AddTextChunk("index"); 7337 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority, 7338 CXCursor_ObjCInstanceMethodDecl)); 7339 } 7340 } 7341 7342 // -(void)removeKeyAtIndexes:(NSIndexSet *)indexes 7343 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 7344 std::string SelectorName 7345 = (Twine("remove") + UpperKey + "AtIndexes").str(); 7346 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 7347 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 7348 if (ReturnType.isNull()) { 7349 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7350 Builder.AddTextChunk("void"); 7351 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7352 } 7353 7354 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 7355 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7356 Builder.AddTextChunk("NSIndexSet *"); 7357 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7358 Builder.AddTextChunk("indexes"); 7359 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority, 7360 CXCursor_ObjCInstanceMethodDecl)); 7361 } 7362 } 7363 7364 // - (void)replaceObjectInKeyAtIndex:(NSUInteger)index withObject:(id)object 7365 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 7366 std::string SelectorName 7367 = (Twine("replaceObjectIn") + UpperKey + "AtIndex").str(); 7368 IdentifierInfo *SelectorIds[2] = { 7369 &Context.Idents.get(SelectorName), 7370 &Context.Idents.get("withObject") 7371 }; 7372 7373 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) { 7374 if (ReturnType.isNull()) { 7375 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7376 Builder.AddTextChunk("void"); 7377 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7378 } 7379 7380 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 7381 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7382 Builder.AddPlaceholderChunk("NSUInteger"); 7383 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7384 Builder.AddTextChunk("index"); 7385 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7386 Builder.AddTypedTextChunk("withObject:"); 7387 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7388 Builder.AddTextChunk("id"); 7389 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7390 Builder.AddTextChunk("object"); 7391 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority, 7392 CXCursor_ObjCInstanceMethodDecl)); 7393 } 7394 } 7395 7396 // - (void)replaceKeyAtIndexes:(NSIndexSet *)indexes withKey:(NSArray *)array 7397 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 7398 std::string SelectorName1 7399 = (Twine("replace") + UpperKey + "AtIndexes").str(); 7400 std::string SelectorName2 = (Twine("with") + UpperKey).str(); 7401 IdentifierInfo *SelectorIds[2] = { 7402 &Context.Idents.get(SelectorName1), 7403 &Context.Idents.get(SelectorName2) 7404 }; 7405 7406 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) { 7407 if (ReturnType.isNull()) { 7408 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7409 Builder.AddTextChunk("void"); 7410 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7411 } 7412 7413 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName1 + ":")); 7414 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7415 Builder.AddPlaceholderChunk("NSIndexSet *"); 7416 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7417 Builder.AddTextChunk("indexes"); 7418 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7419 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName2 + ":")); 7420 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7421 Builder.AddTextChunk("NSArray *"); 7422 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7423 Builder.AddTextChunk("array"); 7424 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority, 7425 CXCursor_ObjCInstanceMethodDecl)); 7426 } 7427 } 7428 7429 // Unordered getters 7430 // - (NSEnumerator *)enumeratorOfKey 7431 if (IsInstanceMethod && 7432 (ReturnType.isNull() || 7433 (ReturnType->isObjCObjectPointerType() && 7434 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() && 7435 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() 7436 ->getName() == "NSEnumerator"))) { 7437 std::string SelectorName = (Twine("enumeratorOf") + UpperKey).str(); 7438 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 7439 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId)) 7440 .second) { 7441 if (ReturnType.isNull()) { 7442 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7443 Builder.AddTextChunk("NSEnumerator *"); 7444 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7445 } 7446 7447 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName)); 7448 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority, 7449 CXCursor_ObjCInstanceMethodDecl)); 7450 } 7451 } 7452 7453 // - (type *)memberOfKey:(type *)object 7454 if (IsInstanceMethod && 7455 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) { 7456 std::string SelectorName = (Twine("memberOf") + UpperKey).str(); 7457 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 7458 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 7459 if (ReturnType.isNull()) { 7460 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7461 Builder.AddPlaceholderChunk("object-type"); 7462 Builder.AddTextChunk(" *"); 7463 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7464 } 7465 7466 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 7467 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7468 if (ReturnType.isNull()) { 7469 Builder.AddPlaceholderChunk("object-type"); 7470 Builder.AddTextChunk(" *"); 7471 } else { 7472 Builder.AddTextChunk(GetCompletionTypeString(ReturnType, Context, 7473 Policy, 7474 Builder.getAllocator())); 7475 } 7476 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7477 Builder.AddTextChunk("object"); 7478 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority, 7479 CXCursor_ObjCInstanceMethodDecl)); 7480 } 7481 } 7482 7483 // Mutable unordered accessors 7484 // - (void)addKeyObject:(type *)object 7485 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 7486 std::string SelectorName 7487 = (Twine("add") + UpperKey + Twine("Object")).str(); 7488 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 7489 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 7490 if (ReturnType.isNull()) { 7491 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7492 Builder.AddTextChunk("void"); 7493 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7494 } 7495 7496 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 7497 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7498 Builder.AddPlaceholderChunk("object-type"); 7499 Builder.AddTextChunk(" *"); 7500 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7501 Builder.AddTextChunk("object"); 7502 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority, 7503 CXCursor_ObjCInstanceMethodDecl)); 7504 } 7505 } 7506 7507 // - (void)addKey:(NSSet *)objects 7508 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 7509 std::string SelectorName = (Twine("add") + UpperKey).str(); 7510 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 7511 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 7512 if (ReturnType.isNull()) { 7513 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7514 Builder.AddTextChunk("void"); 7515 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7516 } 7517 7518 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 7519 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7520 Builder.AddTextChunk("NSSet *"); 7521 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7522 Builder.AddTextChunk("objects"); 7523 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority, 7524 CXCursor_ObjCInstanceMethodDecl)); 7525 } 7526 } 7527 7528 // - (void)removeKeyObject:(type *)object 7529 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 7530 std::string SelectorName 7531 = (Twine("remove") + UpperKey + Twine("Object")).str(); 7532 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 7533 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 7534 if (ReturnType.isNull()) { 7535 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7536 Builder.AddTextChunk("void"); 7537 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7538 } 7539 7540 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 7541 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7542 Builder.AddPlaceholderChunk("object-type"); 7543 Builder.AddTextChunk(" *"); 7544 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7545 Builder.AddTextChunk("object"); 7546 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority, 7547 CXCursor_ObjCInstanceMethodDecl)); 7548 } 7549 } 7550 7551 // - (void)removeKey:(NSSet *)objects 7552 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 7553 std::string SelectorName = (Twine("remove") + UpperKey).str(); 7554 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 7555 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 7556 if (ReturnType.isNull()) { 7557 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7558 Builder.AddTextChunk("void"); 7559 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7560 } 7561 7562 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 7563 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7564 Builder.AddTextChunk("NSSet *"); 7565 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7566 Builder.AddTextChunk("objects"); 7567 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority, 7568 CXCursor_ObjCInstanceMethodDecl)); 7569 } 7570 } 7571 7572 // - (void)intersectKey:(NSSet *)objects 7573 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 7574 std::string SelectorName = (Twine("intersect") + UpperKey).str(); 7575 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 7576 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 7577 if (ReturnType.isNull()) { 7578 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7579 Builder.AddTextChunk("void"); 7580 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7581 } 7582 7583 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 7584 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7585 Builder.AddTextChunk("NSSet *"); 7586 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7587 Builder.AddTextChunk("objects"); 7588 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority, 7589 CXCursor_ObjCInstanceMethodDecl)); 7590 } 7591 } 7592 7593 // Key-Value Observing 7594 // + (NSSet *)keyPathsForValuesAffectingKey 7595 if (!IsInstanceMethod && 7596 (ReturnType.isNull() || 7597 (ReturnType->isObjCObjectPointerType() && 7598 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() && 7599 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() 7600 ->getName() == "NSSet"))) { 7601 std::string SelectorName 7602 = (Twine("keyPathsForValuesAffecting") + UpperKey).str(); 7603 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 7604 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId)) 7605 .second) { 7606 if (ReturnType.isNull()) { 7607 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7608 Builder.AddTextChunk("NSSet<NSString *> *"); 7609 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7610 } 7611 7612 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName)); 7613 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern, 7614 CXCursor_ObjCClassMethodDecl)); 7615 } 7616 } 7617 7618 // + (BOOL)automaticallyNotifiesObserversForKey 7619 if (!IsInstanceMethod && 7620 (ReturnType.isNull() || 7621 ReturnType->isIntegerType() || 7622 ReturnType->isBooleanType())) { 7623 std::string SelectorName 7624 = (Twine("automaticallyNotifiesObserversOf") + UpperKey).str(); 7625 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 7626 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId)) 7627 .second) { 7628 if (ReturnType.isNull()) { 7629 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7630 Builder.AddTextChunk("BOOL"); 7631 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7632 } 7633 7634 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName)); 7635 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern, 7636 CXCursor_ObjCClassMethodDecl)); 7637 } 7638 } 7639 } 7640 7641 void Sema::CodeCompleteObjCMethodDecl(Scope *S, Optional<bool> IsInstanceMethod, 7642 ParsedType ReturnTy) { 7643 // Determine the return type of the method we're declaring, if 7644 // provided. 7645 QualType ReturnType = GetTypeFromParser(ReturnTy); 7646 Decl *IDecl = nullptr; 7647 if (CurContext->isObjCContainer()) { 7648 ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext); 7649 IDecl = OCD; 7650 } 7651 // Determine where we should start searching for methods. 7652 ObjCContainerDecl *SearchDecl = nullptr; 7653 bool IsInImplementation = false; 7654 if (Decl *D = IDecl) { 7655 if (ObjCImplementationDecl *Impl = dyn_cast<ObjCImplementationDecl>(D)) { 7656 SearchDecl = Impl->getClassInterface(); 7657 IsInImplementation = true; 7658 } else if (ObjCCategoryImplDecl *CatImpl 7659 = dyn_cast<ObjCCategoryImplDecl>(D)) { 7660 SearchDecl = CatImpl->getCategoryDecl(); 7661 IsInImplementation = true; 7662 } else 7663 SearchDecl = dyn_cast<ObjCContainerDecl>(D); 7664 } 7665 7666 if (!SearchDecl && S) { 7667 if (DeclContext *DC = S->getEntity()) 7668 SearchDecl = dyn_cast<ObjCContainerDecl>(DC); 7669 } 7670 7671 if (!SearchDecl) { 7672 HandleCodeCompleteResults(this, CodeCompleter, 7673 CodeCompletionContext::CCC_Other, 7674 nullptr, 0); 7675 return; 7676 } 7677 7678 // Find all of the methods that we could declare/implement here. 7679 KnownMethodsMap KnownMethods; 7680 FindImplementableMethods(Context, SearchDecl, IsInstanceMethod, 7681 ReturnType, KnownMethods); 7682 7683 // Add declarations or definitions for each of the known methods. 7684 typedef CodeCompletionResult Result; 7685 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 7686 CodeCompleter->getCodeCompletionTUInfo(), 7687 CodeCompletionContext::CCC_Other); 7688 Results.EnterNewScope(); 7689 PrintingPolicy Policy = getCompletionPrintingPolicy(*this); 7690 for (KnownMethodsMap::iterator M = KnownMethods.begin(), 7691 MEnd = KnownMethods.end(); 7692 M != MEnd; ++M) { 7693 ObjCMethodDecl *Method = M->second.getPointer(); 7694 CodeCompletionBuilder Builder(Results.getAllocator(), 7695 Results.getCodeCompletionTUInfo()); 7696 7697 // Add the '-'/'+' prefix if it wasn't provided yet. 7698 if (!IsInstanceMethod) { 7699 Builder.AddTextChunk(Method->isInstanceMethod() ? "-" : "+"); 7700 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7701 } 7702 7703 // If the result type was not already provided, add it to the 7704 // pattern as (type). 7705 if (ReturnType.isNull()) { 7706 QualType ResTy = Method->getSendResultType().stripObjCKindOfType(Context); 7707 AttributedType::stripOuterNullability(ResTy); 7708 AddObjCPassingTypeChunk(ResTy, 7709 Method->getObjCDeclQualifier(), Context, Policy, 7710 Builder); 7711 } 7712 7713 Selector Sel = Method->getSelector(); 7714 7715 // Add the first part of the selector to the pattern. 7716 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString( 7717 Sel.getNameForSlot(0))); 7718 7719 // Add parameters to the pattern. 7720 unsigned I = 0; 7721 for (ObjCMethodDecl::param_iterator P = Method->param_begin(), 7722 PEnd = Method->param_end(); 7723 P != PEnd; (void)++P, ++I) { 7724 // Add the part of the selector name. 7725 if (I == 0) 7726 Builder.AddTypedTextChunk(":"); 7727 else if (I < Sel.getNumArgs()) { 7728 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7729 Builder.AddTypedTextChunk( 7730 Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":")); 7731 } else 7732 break; 7733 7734 // Add the parameter type. 7735 QualType ParamType; 7736 if ((*P)->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 7737 ParamType = (*P)->getType(); 7738 else 7739 ParamType = (*P)->getOriginalType(); 7740 ParamType = ParamType.substObjCTypeArgs(Context, {}, 7741 ObjCSubstitutionContext::Parameter); 7742 AttributedType::stripOuterNullability(ParamType); 7743 AddObjCPassingTypeChunk(ParamType, 7744 (*P)->getObjCDeclQualifier(), 7745 Context, Policy, 7746 Builder); 7747 7748 if (IdentifierInfo *Id = (*P)->getIdentifier()) 7749 Builder.AddTextChunk(Builder.getAllocator().CopyString( Id->getName())); 7750 } 7751 7752 if (Method->isVariadic()) { 7753 if (Method->param_size() > 0) 7754 Builder.AddChunk(CodeCompletionString::CK_Comma); 7755 Builder.AddTextChunk("..."); 7756 } 7757 7758 if (IsInImplementation && Results.includeCodePatterns()) { 7759 // We will be defining the method here, so add a compound statement. 7760 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7761 Builder.AddChunk(CodeCompletionString::CK_LeftBrace); 7762 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); 7763 if (!Method->getReturnType()->isVoidType()) { 7764 // If the result type is not void, add a return clause. 7765 Builder.AddTextChunk("return"); 7766 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7767 Builder.AddPlaceholderChunk("expression"); 7768 Builder.AddChunk(CodeCompletionString::CK_SemiColon); 7769 } else 7770 Builder.AddPlaceholderChunk("statements"); 7771 7772 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); 7773 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 7774 } 7775 7776 unsigned Priority = CCP_CodePattern; 7777 auto R = Result(Builder.TakeString(), Method, Priority); 7778 if (!M->second.getInt()) 7779 setInBaseClass(R); 7780 Results.AddResult(std::move(R)); 7781 } 7782 7783 // Add Key-Value-Coding and Key-Value-Observing accessor methods for all of 7784 // the properties in this class and its categories. 7785 if (Context.getLangOpts().ObjC2) { 7786 SmallVector<ObjCContainerDecl *, 4> Containers; 7787 Containers.push_back(SearchDecl); 7788 7789 VisitedSelectorSet KnownSelectors; 7790 for (KnownMethodsMap::iterator M = KnownMethods.begin(), 7791 MEnd = KnownMethods.end(); 7792 M != MEnd; ++M) 7793 KnownSelectors.insert(M->first); 7794 7795 7796 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(SearchDecl); 7797 if (!IFace) 7798 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(SearchDecl)) 7799 IFace = Category->getClassInterface(); 7800 7801 if (IFace) 7802 for (auto *Cat : IFace->visible_categories()) 7803 Containers.push_back(Cat); 7804 7805 if (IsInstanceMethod) { 7806 for (unsigned I = 0, N = Containers.size(); I != N; ++I) 7807 for (auto *P : Containers[I]->instance_properties()) 7808 AddObjCKeyValueCompletions(P, *IsInstanceMethod, ReturnType, Context, 7809 KnownSelectors, Results); 7810 } 7811 } 7812 7813 Results.ExitScope(); 7814 7815 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 7816 Results.data(), Results.size()); 7817 } 7818 7819 void Sema::CodeCompleteObjCMethodDeclSelector(Scope *S, 7820 bool IsInstanceMethod, 7821 bool AtParameterName, 7822 ParsedType ReturnTy, 7823 ArrayRef<IdentifierInfo *> SelIdents) { 7824 // If we have an external source, load the entire class method 7825 // pool from the AST file. 7826 if (ExternalSource) { 7827 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors(); 7828 I != N; ++I) { 7829 Selector Sel = ExternalSource->GetExternalSelector(I); 7830 if (Sel.isNull() || MethodPool.count(Sel)) 7831 continue; 7832 7833 ReadMethodPool(Sel); 7834 } 7835 } 7836 7837 // Build the set of methods we can see. 7838 typedef CodeCompletionResult Result; 7839 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 7840 CodeCompleter->getCodeCompletionTUInfo(), 7841 CodeCompletionContext::CCC_Other); 7842 7843 if (ReturnTy) 7844 Results.setPreferredType(GetTypeFromParser(ReturnTy).getNonReferenceType()); 7845 7846 Results.EnterNewScope(); 7847 for (GlobalMethodPool::iterator M = MethodPool.begin(), 7848 MEnd = MethodPool.end(); 7849 M != MEnd; ++M) { 7850 for (ObjCMethodList *MethList = IsInstanceMethod ? &M->second.first : 7851 &M->second.second; 7852 MethList && MethList->getMethod(); 7853 MethList = MethList->getNext()) { 7854 if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents)) 7855 continue; 7856 7857 if (AtParameterName) { 7858 // Suggest parameter names we've seen before. 7859 unsigned NumSelIdents = SelIdents.size(); 7860 if (NumSelIdents && 7861 NumSelIdents <= MethList->getMethod()->param_size()) { 7862 ParmVarDecl *Param = 7863 MethList->getMethod()->parameters()[NumSelIdents - 1]; 7864 if (Param->getIdentifier()) { 7865 CodeCompletionBuilder Builder(Results.getAllocator(), 7866 Results.getCodeCompletionTUInfo()); 7867 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString( 7868 Param->getIdentifier()->getName())); 7869 Results.AddResult(Builder.TakeString()); 7870 } 7871 } 7872 7873 continue; 7874 } 7875 7876 Result R(MethList->getMethod(), 7877 Results.getBasePriority(MethList->getMethod()), nullptr); 7878 R.StartParameter = SelIdents.size(); 7879 R.AllParametersAreInformative = false; 7880 R.DeclaringEntity = true; 7881 Results.MaybeAddResult(R, CurContext); 7882 } 7883 } 7884 7885 Results.ExitScope(); 7886 7887 if (!AtParameterName && !SelIdents.empty() && 7888 SelIdents.front()->getName().startswith("init")) { 7889 for (const auto &M : PP.macros()) { 7890 if (M.first->getName() != "NS_DESIGNATED_INITIALIZER") 7891 continue; 7892 Results.EnterNewScope(); 7893 CodeCompletionBuilder Builder(Results.getAllocator(), 7894 Results.getCodeCompletionTUInfo()); 7895 Builder.AddTypedTextChunk( 7896 Builder.getAllocator().CopyString(M.first->getName())); 7897 Results.AddResult(CodeCompletionResult(Builder.TakeString(), CCP_Macro, 7898 CXCursor_MacroDefinition)); 7899 Results.ExitScope(); 7900 } 7901 } 7902 7903 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 7904 Results.data(), Results.size()); 7905 } 7906 7907 void Sema::CodeCompletePreprocessorDirective(bool InConditional) { 7908 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 7909 CodeCompleter->getCodeCompletionTUInfo(), 7910 CodeCompletionContext::CCC_PreprocessorDirective); 7911 Results.EnterNewScope(); 7912 7913 // #if <condition> 7914 CodeCompletionBuilder Builder(Results.getAllocator(), 7915 Results.getCodeCompletionTUInfo()); 7916 Builder.AddTypedTextChunk("if"); 7917 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7918 Builder.AddPlaceholderChunk("condition"); 7919 Results.AddResult(Builder.TakeString()); 7920 7921 // #ifdef <macro> 7922 Builder.AddTypedTextChunk("ifdef"); 7923 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7924 Builder.AddPlaceholderChunk("macro"); 7925 Results.AddResult(Builder.TakeString()); 7926 7927 // #ifndef <macro> 7928 Builder.AddTypedTextChunk("ifndef"); 7929 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7930 Builder.AddPlaceholderChunk("macro"); 7931 Results.AddResult(Builder.TakeString()); 7932 7933 if (InConditional) { 7934 // #elif <condition> 7935 Builder.AddTypedTextChunk("elif"); 7936 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7937 Builder.AddPlaceholderChunk("condition"); 7938 Results.AddResult(Builder.TakeString()); 7939 7940 // #else 7941 Builder.AddTypedTextChunk("else"); 7942 Results.AddResult(Builder.TakeString()); 7943 7944 // #endif 7945 Builder.AddTypedTextChunk("endif"); 7946 Results.AddResult(Builder.TakeString()); 7947 } 7948 7949 // #include "header" 7950 Builder.AddTypedTextChunk("include"); 7951 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7952 Builder.AddTextChunk("\""); 7953 Builder.AddPlaceholderChunk("header"); 7954 Builder.AddTextChunk("\""); 7955 Results.AddResult(Builder.TakeString()); 7956 7957 // #include <header> 7958 Builder.AddTypedTextChunk("include"); 7959 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7960 Builder.AddTextChunk("<"); 7961 Builder.AddPlaceholderChunk("header"); 7962 Builder.AddTextChunk(">"); 7963 Results.AddResult(Builder.TakeString()); 7964 7965 // #define <macro> 7966 Builder.AddTypedTextChunk("define"); 7967 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7968 Builder.AddPlaceholderChunk("macro"); 7969 Results.AddResult(Builder.TakeString()); 7970 7971 // #define <macro>(<args>) 7972 Builder.AddTypedTextChunk("define"); 7973 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7974 Builder.AddPlaceholderChunk("macro"); 7975 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7976 Builder.AddPlaceholderChunk("args"); 7977 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7978 Results.AddResult(Builder.TakeString()); 7979 7980 // #undef <macro> 7981 Builder.AddTypedTextChunk("undef"); 7982 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7983 Builder.AddPlaceholderChunk("macro"); 7984 Results.AddResult(Builder.TakeString()); 7985 7986 // #line <number> 7987 Builder.AddTypedTextChunk("line"); 7988 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7989 Builder.AddPlaceholderChunk("number"); 7990 Results.AddResult(Builder.TakeString()); 7991 7992 // #line <number> "filename" 7993 Builder.AddTypedTextChunk("line"); 7994 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7995 Builder.AddPlaceholderChunk("number"); 7996 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7997 Builder.AddTextChunk("\""); 7998 Builder.AddPlaceholderChunk("filename"); 7999 Builder.AddTextChunk("\""); 8000 Results.AddResult(Builder.TakeString()); 8001 8002 // #error <message> 8003 Builder.AddTypedTextChunk("error"); 8004 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 8005 Builder.AddPlaceholderChunk("message"); 8006 Results.AddResult(Builder.TakeString()); 8007 8008 // #pragma <arguments> 8009 Builder.AddTypedTextChunk("pragma"); 8010 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 8011 Builder.AddPlaceholderChunk("arguments"); 8012 Results.AddResult(Builder.TakeString()); 8013 8014 if (getLangOpts().ObjC1) { 8015 // #import "header" 8016 Builder.AddTypedTextChunk("import"); 8017 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 8018 Builder.AddTextChunk("\""); 8019 Builder.AddPlaceholderChunk("header"); 8020 Builder.AddTextChunk("\""); 8021 Results.AddResult(Builder.TakeString()); 8022 8023 // #import <header> 8024 Builder.AddTypedTextChunk("import"); 8025 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 8026 Builder.AddTextChunk("<"); 8027 Builder.AddPlaceholderChunk("header"); 8028 Builder.AddTextChunk(">"); 8029 Results.AddResult(Builder.TakeString()); 8030 } 8031 8032 // #include_next "header" 8033 Builder.AddTypedTextChunk("include_next"); 8034 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 8035 Builder.AddTextChunk("\""); 8036 Builder.AddPlaceholderChunk("header"); 8037 Builder.AddTextChunk("\""); 8038 Results.AddResult(Builder.TakeString()); 8039 8040 // #include_next <header> 8041 Builder.AddTypedTextChunk("include_next"); 8042 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 8043 Builder.AddTextChunk("<"); 8044 Builder.AddPlaceholderChunk("header"); 8045 Builder.AddTextChunk(">"); 8046 Results.AddResult(Builder.TakeString()); 8047 8048 // #warning <message> 8049 Builder.AddTypedTextChunk("warning"); 8050 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 8051 Builder.AddPlaceholderChunk("message"); 8052 Results.AddResult(Builder.TakeString()); 8053 8054 // Note: #ident and #sccs are such crazy anachronisms that we don't provide 8055 // completions for them. And __include_macros is a Clang-internal extension 8056 // that we don't want to encourage anyone to use. 8057 8058 // FIXME: we don't support #assert or #unassert, so don't suggest them. 8059 Results.ExitScope(); 8060 8061 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 8062 Results.data(), Results.size()); 8063 } 8064 8065 void Sema::CodeCompleteInPreprocessorConditionalExclusion(Scope *S) { 8066 CodeCompleteOrdinaryName(S, 8067 S->getFnParent()? Sema::PCC_RecoveryInFunction 8068 : Sema::PCC_Namespace); 8069 } 8070 8071 void Sema::CodeCompletePreprocessorMacroName(bool IsDefinition) { 8072 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 8073 CodeCompleter->getCodeCompletionTUInfo(), 8074 IsDefinition? CodeCompletionContext::CCC_MacroName 8075 : CodeCompletionContext::CCC_MacroNameUse); 8076 if (!IsDefinition && (!CodeCompleter || CodeCompleter->includeMacros())) { 8077 // Add just the names of macros, not their arguments. 8078 CodeCompletionBuilder Builder(Results.getAllocator(), 8079 Results.getCodeCompletionTUInfo()); 8080 Results.EnterNewScope(); 8081 for (Preprocessor::macro_iterator M = PP.macro_begin(), 8082 MEnd = PP.macro_end(); 8083 M != MEnd; ++M) { 8084 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString( 8085 M->first->getName())); 8086 Results.AddResult(CodeCompletionResult(Builder.TakeString(), 8087 CCP_CodePattern, 8088 CXCursor_MacroDefinition)); 8089 } 8090 Results.ExitScope(); 8091 } else if (IsDefinition) { 8092 // FIXME: Can we detect when the user just wrote an include guard above? 8093 } 8094 8095 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 8096 Results.data(), Results.size()); 8097 } 8098 8099 void Sema::CodeCompletePreprocessorExpression() { 8100 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 8101 CodeCompleter->getCodeCompletionTUInfo(), 8102 CodeCompletionContext::CCC_PreprocessorExpression); 8103 8104 if (!CodeCompleter || CodeCompleter->includeMacros()) 8105 AddMacroResults(PP, Results, 8106 CodeCompleter ? CodeCompleter->loadExternal() : false, 8107 true); 8108 8109 // defined (<macro>) 8110 Results.EnterNewScope(); 8111 CodeCompletionBuilder Builder(Results.getAllocator(), 8112 Results.getCodeCompletionTUInfo()); 8113 Builder.AddTypedTextChunk("defined"); 8114 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 8115 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 8116 Builder.AddPlaceholderChunk("macro"); 8117 Builder.AddChunk(CodeCompletionString::CK_RightParen); 8118 Results.AddResult(Builder.TakeString()); 8119 Results.ExitScope(); 8120 8121 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 8122 Results.data(), Results.size()); 8123 } 8124 8125 void Sema::CodeCompletePreprocessorMacroArgument(Scope *S, 8126 IdentifierInfo *Macro, 8127 MacroInfo *MacroInfo, 8128 unsigned Argument) { 8129 // FIXME: In the future, we could provide "overload" results, much like we 8130 // do for function calls. 8131 8132 // Now just ignore this. There will be another code-completion callback 8133 // for the expanded tokens. 8134 } 8135 8136 // This handles completion inside an #include filename, e.g. #include <foo/ba 8137 // We look for the directory "foo" under each directory on the include path, 8138 // list its files, and reassemble the appropriate #include. 8139 void Sema::CodeCompleteIncludedFile(llvm::StringRef Dir, bool Angled) { 8140 // RelDir should use /, but unescaped \ is possible on windows! 8141 // Our completions will normalize to / for simplicity, this case is rare. 8142 std::string RelDir = llvm::sys::path::convert_to_slash(Dir); 8143 // We need the native slashes for the actual file system interactions. 8144 SmallString<128> NativeRelDir = StringRef(RelDir); 8145 llvm::sys::path::native(NativeRelDir); 8146 auto FS = getSourceManager().getFileManager().getVirtualFileSystem(); 8147 8148 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 8149 CodeCompleter->getCodeCompletionTUInfo(), 8150 CodeCompletionContext::CCC_IncludedFile); 8151 llvm::DenseSet<StringRef> SeenResults; // To deduplicate results. 8152 8153 // Helper: adds one file or directory completion result. 8154 auto AddCompletion = [&](StringRef Filename, bool IsDirectory) { 8155 SmallString<64> TypedChunk = Filename; 8156 // Directory completion is up to the slash, e.g. <sys/ 8157 TypedChunk.push_back(IsDirectory ? '/' : Angled ? '>' : '"'); 8158 auto R = SeenResults.insert(TypedChunk); 8159 if (R.second) { // New completion 8160 const char *InternedTyped = Results.getAllocator().CopyString(TypedChunk); 8161 *R.first = InternedTyped; // Avoid dangling StringRef. 8162 CodeCompletionBuilder Builder(CodeCompleter->getAllocator(), 8163 CodeCompleter->getCodeCompletionTUInfo()); 8164 Builder.AddTypedTextChunk(InternedTyped); 8165 // The result is a "Pattern", which is pretty opaque. 8166 // We may want to include the real filename to allow smart ranking. 8167 Results.AddResult(CodeCompletionResult(Builder.TakeString())); 8168 } 8169 }; 8170 8171 // Helper: scans IncludeDir for nice files, and adds results for each. 8172 auto AddFilesFromIncludeDir = [&](StringRef IncludeDir, bool IsSystem) { 8173 llvm::SmallString<128> Dir = IncludeDir; 8174 if (!NativeRelDir.empty()) 8175 llvm::sys::path::append(Dir, NativeRelDir); 8176 8177 std::error_code EC; 8178 unsigned Count = 0; 8179 for (auto It = FS->dir_begin(Dir, EC); 8180 !EC && It != llvm::vfs::directory_iterator(); It.increment(EC)) { 8181 if (++Count == 2500) // If we happen to hit a huge directory, 8182 break; // bail out early so we're not too slow. 8183 StringRef Filename = llvm::sys::path::filename(It->path()); 8184 switch (It->type()) { 8185 case llvm::sys::fs::file_type::directory_file: 8186 AddCompletion(Filename, /*IsDirectory=*/true); 8187 break; 8188 case llvm::sys::fs::file_type::regular_file: 8189 // Only files that really look like headers. (Except in system dirs). 8190 if (!IsSystem) { 8191 // Header extensions from Types.def, which we can't depend on here. 8192 if (!(Filename.endswith_lower(".h") || 8193 Filename.endswith_lower(".hh") || 8194 Filename.endswith_lower(".hpp") || 8195 Filename.endswith_lower(".inc"))) 8196 break; 8197 } 8198 AddCompletion(Filename, /*IsDirectory=*/false); 8199 break; 8200 default: 8201 break; 8202 } 8203 } 8204 }; 8205 8206 // Helper: adds results relative to IncludeDir, if possible. 8207 auto AddFilesFromDirLookup = [&](const DirectoryLookup &IncludeDir, 8208 bool IsSystem) { 8209 llvm::SmallString<128> Dir; 8210 switch (IncludeDir.getLookupType()) { 8211 case DirectoryLookup::LT_HeaderMap: 8212 // header maps are not (currently) enumerable. 8213 break; 8214 case DirectoryLookup::LT_NormalDir: 8215 AddFilesFromIncludeDir(IncludeDir.getDir()->getName(), IsSystem); 8216 break; 8217 case DirectoryLookup::LT_Framework: 8218 AddFilesFromIncludeDir(IncludeDir.getFrameworkDir()->getName(), IsSystem); 8219 break; 8220 } 8221 }; 8222 8223 // Finally with all our helpers, we can scan the include path. 8224 // Do this in standard order so deduplication keeps the right file. 8225 // (In case we decide to add more details to the results later). 8226 const auto &S = PP.getHeaderSearchInfo(); 8227 using llvm::make_range; 8228 if (!Angled) { 8229 // The current directory is on the include path for "quoted" includes. 8230 auto *CurFile = PP.getCurrentFileLexer()->getFileEntry(); 8231 if (CurFile && CurFile->getDir()) 8232 AddFilesFromIncludeDir(CurFile->getDir()->getName(), false); 8233 for (const auto &D : make_range(S.quoted_dir_begin(), S.quoted_dir_end())) 8234 AddFilesFromDirLookup(D, false); 8235 } 8236 for (const auto &D : make_range(S.angled_dir_begin(), S.angled_dir_end())) 8237 AddFilesFromDirLookup(D, false); 8238 for (const auto &D : make_range(S.system_dir_begin(), S.system_dir_end())) 8239 AddFilesFromDirLookup(D, true); 8240 8241 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 8242 Results.data(), Results.size()); 8243 } 8244 8245 void Sema::CodeCompleteNaturalLanguage() { 8246 HandleCodeCompleteResults(this, CodeCompleter, 8247 CodeCompletionContext::CCC_NaturalLanguage, 8248 nullptr, 0); 8249 } 8250 8251 void Sema::CodeCompleteAvailabilityPlatformName() { 8252 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 8253 CodeCompleter->getCodeCompletionTUInfo(), 8254 CodeCompletionContext::CCC_Other); 8255 Results.EnterNewScope(); 8256 static const char *Platforms[] = {"macOS", "iOS", "watchOS", "tvOS"}; 8257 for (const char *Platform : llvm::makeArrayRef(Platforms)) { 8258 Results.AddResult(CodeCompletionResult(Platform)); 8259 Results.AddResult(CodeCompletionResult(Results.getAllocator().CopyString( 8260 Twine(Platform) + "ApplicationExtension"))); 8261 } 8262 Results.ExitScope(); 8263 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 8264 Results.data(), Results.size()); 8265 } 8266 8267 void Sema::GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator, 8268 CodeCompletionTUInfo &CCTUInfo, 8269 SmallVectorImpl<CodeCompletionResult> &Results) { 8270 ResultBuilder Builder(*this, Allocator, CCTUInfo, 8271 CodeCompletionContext::CCC_Recovery); 8272 if (!CodeCompleter || CodeCompleter->includeGlobals()) { 8273 CodeCompletionDeclConsumer Consumer(Builder, 8274 Context.getTranslationUnitDecl()); 8275 LookupVisibleDecls(Context.getTranslationUnitDecl(), LookupAnyName, 8276 Consumer, 8277 !CodeCompleter || CodeCompleter->loadExternal()); 8278 } 8279 8280 if (!CodeCompleter || CodeCompleter->includeMacros()) 8281 AddMacroResults(PP, Builder, 8282 CodeCompleter ? CodeCompleter->loadExternal() : false, 8283 true); 8284 8285 Results.clear(); 8286 Results.insert(Results.end(), 8287 Builder.data(), Builder.data() + Builder.size()); 8288 } 8289