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