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. 3690 if (CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext)) 3691 if (CurMethod->isInstance()) 3692 Results.setObjectTypeQualifiers( 3693 Qualifiers::fromCVRMask(CurMethod->getTypeQualifiers())); 3694 3695 CodeCompletionDeclConsumer Consumer(Results, CurContext); 3696 LookupVisibleDecls(S, LookupOrdinaryName, Consumer, 3697 CodeCompleter->includeGlobals(), 3698 CodeCompleter->loadExternal()); 3699 3700 AddOrdinaryNameResults(CompletionContext, S, *this, Results); 3701 Results.ExitScope(); 3702 3703 switch (CompletionContext) { 3704 case PCC_ParenthesizedExpression: 3705 case PCC_Expression: 3706 case PCC_Statement: 3707 case PCC_RecoveryInFunction: 3708 if (S->getFnParent()) 3709 AddPrettyFunctionResults(getLangOpts(), Results); 3710 break; 3711 3712 case PCC_Namespace: 3713 case PCC_Class: 3714 case PCC_ObjCInterface: 3715 case PCC_ObjCImplementation: 3716 case PCC_ObjCInstanceVariableList: 3717 case PCC_Template: 3718 case PCC_MemberTemplate: 3719 case PCC_ForInit: 3720 case PCC_Condition: 3721 case PCC_Type: 3722 case PCC_LocalDeclarationSpecifiers: 3723 break; 3724 } 3725 3726 if (CodeCompleter->includeMacros()) 3727 AddMacroResults(PP, Results, CodeCompleter->loadExternal(), false); 3728 3729 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 3730 Results.data(),Results.size()); 3731 } 3732 3733 static void AddClassMessageCompletions(Sema &SemaRef, Scope *S, 3734 ParsedType Receiver, 3735 ArrayRef<IdentifierInfo *> SelIdents, 3736 bool AtArgumentExpression, 3737 bool IsSuper, 3738 ResultBuilder &Results); 3739 3740 void Sema::CodeCompleteDeclSpec(Scope *S, DeclSpec &DS, 3741 bool AllowNonIdentifiers, 3742 bool AllowNestedNameSpecifiers) { 3743 typedef CodeCompletionResult Result; 3744 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 3745 CodeCompleter->getCodeCompletionTUInfo(), 3746 AllowNestedNameSpecifiers 3747 ? CodeCompletionContext::CCC_PotentiallyQualifiedName 3748 : CodeCompletionContext::CCC_Name); 3749 Results.EnterNewScope(); 3750 3751 // Type qualifiers can come after names. 3752 Results.AddResult(Result("const")); 3753 Results.AddResult(Result("volatile")); 3754 if (getLangOpts().C99) 3755 Results.AddResult(Result("restrict")); 3756 3757 if (getLangOpts().CPlusPlus) { 3758 if (getLangOpts().CPlusPlus11 && 3759 (DS.getTypeSpecType() == DeclSpec::TST_class || 3760 DS.getTypeSpecType() == DeclSpec::TST_struct)) 3761 Results.AddResult("final"); 3762 3763 if (AllowNonIdentifiers) { 3764 Results.AddResult(Result("operator")); 3765 } 3766 3767 // Add nested-name-specifiers. 3768 if (AllowNestedNameSpecifiers) { 3769 Results.allowNestedNameSpecifiers(); 3770 Results.setFilter(&ResultBuilder::IsImpossibleToSatisfy); 3771 CodeCompletionDeclConsumer Consumer(Results, CurContext); 3772 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer, 3773 CodeCompleter->includeGlobals(), 3774 CodeCompleter->loadExternal()); 3775 Results.setFilter(nullptr); 3776 } 3777 } 3778 Results.ExitScope(); 3779 3780 // If we're in a context where we might have an expression (rather than a 3781 // declaration), and what we've seen so far is an Objective-C type that could 3782 // be a receiver of a class message, this may be a class message send with 3783 // the initial opening bracket '[' missing. Add appropriate completions. 3784 if (AllowNonIdentifiers && !AllowNestedNameSpecifiers && 3785 DS.getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier && 3786 DS.getTypeSpecType() == DeclSpec::TST_typename && 3787 DS.getTypeSpecComplex() == DeclSpec::TSC_unspecified && 3788 DS.getTypeSpecSign() == DeclSpec::TSS_unspecified && 3789 !DS.isTypeAltiVecVector() && 3790 S && 3791 (S->getFlags() & Scope::DeclScope) != 0 && 3792 (S->getFlags() & (Scope::ClassScope | Scope::TemplateParamScope | 3793 Scope::FunctionPrototypeScope | 3794 Scope::AtCatchScope)) == 0) { 3795 ParsedType T = DS.getRepAsType(); 3796 if (!T.get().isNull() && T.get()->isObjCObjectOrInterfaceType()) 3797 AddClassMessageCompletions(*this, S, T, None, false, false, Results); 3798 } 3799 3800 // Note that we intentionally suppress macro results here, since we do not 3801 // encourage using macros to produce the names of entities. 3802 3803 HandleCodeCompleteResults(this, CodeCompleter, 3804 Results.getCompletionContext(), 3805 Results.data(), Results.size()); 3806 } 3807 3808 struct Sema::CodeCompleteExpressionData { 3809 CodeCompleteExpressionData(QualType PreferredType = QualType()) 3810 : PreferredType(PreferredType), IntegralConstantExpression(false), 3811 ObjCCollection(false) { } 3812 3813 QualType PreferredType; 3814 bool IntegralConstantExpression; 3815 bool ObjCCollection; 3816 SmallVector<Decl *, 4> IgnoreDecls; 3817 }; 3818 3819 /// Perform code-completion in an expression context when we know what 3820 /// type we're looking for. 3821 void Sema::CodeCompleteExpression(Scope *S, 3822 const CodeCompleteExpressionData &Data) { 3823 ResultBuilder Results( 3824 *this, CodeCompleter->getAllocator(), 3825 CodeCompleter->getCodeCompletionTUInfo(), 3826 CodeCompletionContext(CodeCompletionContext::CCC_Expression, 3827 Data.PreferredType)); 3828 if (Data.ObjCCollection) 3829 Results.setFilter(&ResultBuilder::IsObjCCollection); 3830 else if (Data.IntegralConstantExpression) 3831 Results.setFilter(&ResultBuilder::IsIntegralConstantValue); 3832 else if (WantTypesInContext(PCC_Expression, getLangOpts())) 3833 Results.setFilter(&ResultBuilder::IsOrdinaryName); 3834 else 3835 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName); 3836 3837 if (!Data.PreferredType.isNull()) 3838 Results.setPreferredType(Data.PreferredType.getNonReferenceType()); 3839 3840 // Ignore any declarations that we were told that we don't care about. 3841 for (unsigned I = 0, N = Data.IgnoreDecls.size(); I != N; ++I) 3842 Results.Ignore(Data.IgnoreDecls[I]); 3843 3844 CodeCompletionDeclConsumer Consumer(Results, CurContext); 3845 LookupVisibleDecls(S, LookupOrdinaryName, Consumer, 3846 CodeCompleter->includeGlobals(), 3847 CodeCompleter->loadExternal()); 3848 3849 Results.EnterNewScope(); 3850 AddOrdinaryNameResults(PCC_Expression, S, *this, Results); 3851 Results.ExitScope(); 3852 3853 bool PreferredTypeIsPointer = false; 3854 if (!Data.PreferredType.isNull()) 3855 PreferredTypeIsPointer = Data.PreferredType->isAnyPointerType() 3856 || Data.PreferredType->isMemberPointerType() 3857 || Data.PreferredType->isBlockPointerType(); 3858 3859 if (S->getFnParent() && 3860 !Data.ObjCCollection && 3861 !Data.IntegralConstantExpression) 3862 AddPrettyFunctionResults(getLangOpts(), Results); 3863 3864 if (CodeCompleter->includeMacros()) 3865 AddMacroResults(PP, Results, CodeCompleter->loadExternal(), false, 3866 PreferredTypeIsPointer); 3867 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 3868 Results.data(), Results.size()); 3869 } 3870 3871 void Sema::CodeCompleteExpression(Scope *S, QualType PreferredType) { 3872 return CodeCompleteExpression(S, CodeCompleteExpressionData(PreferredType)); 3873 } 3874 3875 void Sema::CodeCompletePostfixExpression(Scope *S, ExprResult E) { 3876 if (E.isInvalid()) 3877 CodeCompleteOrdinaryName(S, PCC_RecoveryInFunction); 3878 else if (getLangOpts().ObjC1) 3879 CodeCompleteObjCInstanceMessage(S, E.get(), None, false); 3880 } 3881 3882 /// The set of properties that have already been added, referenced by 3883 /// property name. 3884 typedef llvm::SmallPtrSet<IdentifierInfo*, 16> AddedPropertiesSet; 3885 3886 /// Retrieve the container definition, if any? 3887 static ObjCContainerDecl *getContainerDef(ObjCContainerDecl *Container) { 3888 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) { 3889 if (Interface->hasDefinition()) 3890 return Interface->getDefinition(); 3891 3892 return Interface; 3893 } 3894 3895 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) { 3896 if (Protocol->hasDefinition()) 3897 return Protocol->getDefinition(); 3898 3899 return Protocol; 3900 } 3901 return Container; 3902 } 3903 3904 /// Adds a block invocation code completion result for the given block 3905 /// declaration \p BD. 3906 static void AddObjCBlockCall(ASTContext &Context, const PrintingPolicy &Policy, 3907 CodeCompletionBuilder &Builder, 3908 const NamedDecl *BD, 3909 const FunctionTypeLoc &BlockLoc, 3910 const FunctionProtoTypeLoc &BlockProtoLoc) { 3911 Builder.AddResultTypeChunk( 3912 GetCompletionTypeString(BlockLoc.getReturnLoc().getType(), Context, 3913 Policy, Builder.getAllocator())); 3914 3915 AddTypedNameChunk(Context, Policy, BD, Builder); 3916 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 3917 3918 if (BlockProtoLoc && BlockProtoLoc.getTypePtr()->isVariadic()) { 3919 Builder.AddPlaceholderChunk("..."); 3920 } else { 3921 for (unsigned I = 0, N = BlockLoc.getNumParams(); I != N; ++I) { 3922 if (I) 3923 Builder.AddChunk(CodeCompletionString::CK_Comma); 3924 3925 // Format the placeholder string. 3926 std::string PlaceholderStr = 3927 FormatFunctionParameter(Policy, BlockLoc.getParam(I)); 3928 3929 if (I == N - 1 && BlockProtoLoc && 3930 BlockProtoLoc.getTypePtr()->isVariadic()) 3931 PlaceholderStr += ", ..."; 3932 3933 // Add the placeholder string. 3934 Builder.AddPlaceholderChunk( 3935 Builder.getAllocator().CopyString(PlaceholderStr)); 3936 } 3937 } 3938 3939 Builder.AddChunk(CodeCompletionString::CK_RightParen); 3940 } 3941 3942 static void AddObjCProperties( 3943 const CodeCompletionContext &CCContext, ObjCContainerDecl *Container, 3944 bool AllowCategories, bool AllowNullaryMethods, DeclContext *CurContext, 3945 AddedPropertiesSet &AddedProperties, ResultBuilder &Results, 3946 bool IsBaseExprStatement = false, bool IsClassProperty = false) { 3947 typedef CodeCompletionResult Result; 3948 3949 // Retrieve the definition. 3950 Container = getContainerDef(Container); 3951 3952 // Add properties in this container. 3953 const auto AddProperty = [&](const ObjCPropertyDecl *P) { 3954 if (!AddedProperties.insert(P->getIdentifier()).second) 3955 return; 3956 3957 // FIXME: Provide block invocation completion for non-statement 3958 // expressions. 3959 if (!P->getType().getTypePtr()->isBlockPointerType() || 3960 !IsBaseExprStatement) { 3961 Results.MaybeAddResult(Result(P, Results.getBasePriority(P), nullptr), 3962 CurContext); 3963 return; 3964 } 3965 3966 // Block setter and invocation completion is provided only when we are able 3967 // to find the FunctionProtoTypeLoc with parameter names for the block. 3968 FunctionTypeLoc BlockLoc; 3969 FunctionProtoTypeLoc BlockProtoLoc; 3970 findTypeLocationForBlockDecl(P->getTypeSourceInfo(), BlockLoc, 3971 BlockProtoLoc); 3972 if (!BlockLoc) { 3973 Results.MaybeAddResult(Result(P, Results.getBasePriority(P), nullptr), 3974 CurContext); 3975 return; 3976 } 3977 3978 // The default completion result for block properties should be the block 3979 // invocation completion when the base expression is a statement. 3980 CodeCompletionBuilder Builder(Results.getAllocator(), 3981 Results.getCodeCompletionTUInfo()); 3982 AddObjCBlockCall(Container->getASTContext(), 3983 getCompletionPrintingPolicy(Results.getSema()), Builder, P, 3984 BlockLoc, BlockProtoLoc); 3985 Results.MaybeAddResult( 3986 Result(Builder.TakeString(), P, Results.getBasePriority(P)), 3987 CurContext); 3988 3989 // Provide additional block setter completion iff the base expression is a 3990 // statement and the block property is mutable. 3991 if (!P->isReadOnly()) { 3992 CodeCompletionBuilder Builder(Results.getAllocator(), 3993 Results.getCodeCompletionTUInfo()); 3994 AddResultTypeChunk(Container->getASTContext(), 3995 getCompletionPrintingPolicy(Results.getSema()), P, 3996 CCContext.getBaseType(), Builder); 3997 Builder.AddTypedTextChunk( 3998 Results.getAllocator().CopyString(P->getName())); 3999 Builder.AddChunk(CodeCompletionString::CK_Equal); 4000 4001 std::string PlaceholderStr = formatBlockPlaceholder( 4002 getCompletionPrintingPolicy(Results.getSema()), P, BlockLoc, 4003 BlockProtoLoc, /*SuppressBlockName=*/true); 4004 // Add the placeholder string. 4005 Builder.AddPlaceholderChunk( 4006 Builder.getAllocator().CopyString(PlaceholderStr)); 4007 4008 // When completing blocks properties that return void the default 4009 // property completion result should show up before the setter, 4010 // otherwise the setter completion should show up before the default 4011 // property completion, as we normally want to use the result of the 4012 // call. 4013 Results.MaybeAddResult( 4014 Result(Builder.TakeString(), P, 4015 Results.getBasePriority(P) + 4016 (BlockLoc.getTypePtr()->getReturnType()->isVoidType() 4017 ? CCD_BlockPropertySetter 4018 : -CCD_BlockPropertySetter)), 4019 CurContext); 4020 } 4021 }; 4022 4023 if (IsClassProperty) { 4024 for (const auto *P : Container->class_properties()) 4025 AddProperty(P); 4026 } else { 4027 for (const auto *P : Container->instance_properties()) 4028 AddProperty(P); 4029 } 4030 4031 // Add nullary methods or implicit class properties 4032 if (AllowNullaryMethods) { 4033 ASTContext &Context = Container->getASTContext(); 4034 PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema()); 4035 // Adds a method result 4036 const auto AddMethod = [&](const ObjCMethodDecl *M) { 4037 IdentifierInfo *Name = M->getSelector().getIdentifierInfoForSlot(0); 4038 if (!Name) 4039 return; 4040 if (!AddedProperties.insert(Name).second) 4041 return; 4042 CodeCompletionBuilder Builder(Results.getAllocator(), 4043 Results.getCodeCompletionTUInfo()); 4044 AddResultTypeChunk(Context, Policy, M, CCContext.getBaseType(), Builder); 4045 Builder.AddTypedTextChunk( 4046 Results.getAllocator().CopyString(Name->getName())); 4047 Results.MaybeAddResult( 4048 Result(Builder.TakeString(), M, 4049 CCP_MemberDeclaration + CCD_MethodAsProperty), 4050 CurContext); 4051 }; 4052 4053 if (IsClassProperty) { 4054 for (const auto *M : Container->methods()) { 4055 // Gather the class method that can be used as implicit property 4056 // getters. Methods with arguments or methods that return void aren't 4057 // added to the results as they can't be used as a getter. 4058 if (!M->getSelector().isUnarySelector() || 4059 M->getReturnType()->isVoidType() || M->isInstanceMethod()) 4060 continue; 4061 AddMethod(M); 4062 } 4063 } else { 4064 for (auto *M : Container->methods()) { 4065 if (M->getSelector().isUnarySelector()) 4066 AddMethod(M); 4067 } 4068 } 4069 } 4070 4071 // Add properties in referenced protocols. 4072 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) { 4073 for (auto *P : Protocol->protocols()) 4074 AddObjCProperties(CCContext, P, AllowCategories, AllowNullaryMethods, 4075 CurContext, AddedProperties, Results, 4076 IsBaseExprStatement, IsClassProperty); 4077 } else if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)){ 4078 if (AllowCategories) { 4079 // Look through categories. 4080 for (auto *Cat : IFace->known_categories()) 4081 AddObjCProperties(CCContext, Cat, AllowCategories, AllowNullaryMethods, 4082 CurContext, AddedProperties, Results, 4083 IsBaseExprStatement, IsClassProperty); 4084 } 4085 4086 // Look through protocols. 4087 for (auto *I : IFace->all_referenced_protocols()) 4088 AddObjCProperties(CCContext, I, AllowCategories, AllowNullaryMethods, 4089 CurContext, AddedProperties, Results, 4090 IsBaseExprStatement, IsClassProperty); 4091 4092 // Look in the superclass. 4093 if (IFace->getSuperClass()) 4094 AddObjCProperties(CCContext, IFace->getSuperClass(), AllowCategories, 4095 AllowNullaryMethods, CurContext, AddedProperties, 4096 Results, IsBaseExprStatement, IsClassProperty); 4097 } else if (const ObjCCategoryDecl *Category 4098 = dyn_cast<ObjCCategoryDecl>(Container)) { 4099 // Look through protocols. 4100 for (auto *P : Category->protocols()) 4101 AddObjCProperties(CCContext, P, AllowCategories, AllowNullaryMethods, 4102 CurContext, AddedProperties, Results, 4103 IsBaseExprStatement, IsClassProperty); 4104 } 4105 } 4106 4107 static void AddRecordMembersCompletionResults(Sema &SemaRef, 4108 ResultBuilder &Results, Scope *S, 4109 QualType BaseType, 4110 RecordDecl *RD, 4111 Optional<FixItHint> AccessOpFixIt) { 4112 // Indicate that we are performing a member access, and the cv-qualifiers 4113 // for the base object type. 4114 Results.setObjectTypeQualifiers(BaseType.getQualifiers()); 4115 4116 // Access to a C/C++ class, struct, or union. 4117 Results.allowNestedNameSpecifiers(); 4118 std::vector<FixItHint> FixIts; 4119 if (AccessOpFixIt) 4120 FixIts.emplace_back(AccessOpFixIt.getValue()); 4121 CodeCompletionDeclConsumer Consumer(Results, SemaRef.CurContext, 4122 std::move(FixIts), RD); 4123 SemaRef.LookupVisibleDecls(RD, Sema::LookupMemberName, Consumer, 4124 SemaRef.CodeCompleter->includeGlobals(), 4125 /*IncludeDependentBases=*/true, 4126 SemaRef.CodeCompleter->loadExternal()); 4127 4128 if (SemaRef.getLangOpts().CPlusPlus) { 4129 if (!Results.empty()) { 4130 // The "template" keyword can follow "->" or "." in the grammar. 4131 // However, we only want to suggest the template keyword if something 4132 // is dependent. 4133 bool IsDependent = BaseType->isDependentType(); 4134 if (!IsDependent) { 4135 for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent()) 4136 if (DeclContext *Ctx = DepScope->getEntity()) { 4137 IsDependent = Ctx->isDependentContext(); 4138 break; 4139 } 4140 } 4141 4142 if (IsDependent) 4143 Results.AddResult(CodeCompletionResult("template")); 4144 } 4145 } 4146 } 4147 4148 void Sema::CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base, 4149 Expr *OtherOpBase, 4150 SourceLocation OpLoc, bool IsArrow, 4151 bool IsBaseExprStatement) { 4152 if (!Base || !CodeCompleter) 4153 return; 4154 4155 ExprResult ConvertedBase = PerformMemberExprBaseConversion(Base, IsArrow); 4156 if (ConvertedBase.isInvalid()) 4157 return; 4158 QualType ConvertedBaseType = ConvertedBase.get()->getType(); 4159 4160 enum CodeCompletionContext::Kind contextKind; 4161 4162 if (IsArrow) { 4163 if (const PointerType *Ptr = ConvertedBaseType->getAs<PointerType>()) 4164 ConvertedBaseType = Ptr->getPointeeType(); 4165 } 4166 4167 if (IsArrow) { 4168 contextKind = CodeCompletionContext::CCC_ArrowMemberAccess; 4169 } else { 4170 if (ConvertedBaseType->isObjCObjectPointerType() || 4171 ConvertedBaseType->isObjCObjectOrInterfaceType()) { 4172 contextKind = CodeCompletionContext::CCC_ObjCPropertyAccess; 4173 } else { 4174 contextKind = CodeCompletionContext::CCC_DotMemberAccess; 4175 } 4176 } 4177 4178 CodeCompletionContext CCContext(contextKind, ConvertedBaseType); 4179 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 4180 CodeCompleter->getCodeCompletionTUInfo(), CCContext, 4181 &ResultBuilder::IsMember); 4182 4183 auto DoCompletion = [&](Expr *Base, bool IsArrow, Optional<FixItHint> AccessOpFixIt) -> bool { 4184 if (!Base) 4185 return false; 4186 4187 ExprResult ConvertedBase = PerformMemberExprBaseConversion(Base, IsArrow); 4188 if (ConvertedBase.isInvalid()) 4189 return false; 4190 Base = ConvertedBase.get(); 4191 4192 QualType BaseType = Base->getType(); 4193 4194 if (IsArrow) { 4195 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) 4196 BaseType = Ptr->getPointeeType(); 4197 else if (BaseType->isObjCObjectPointerType()) 4198 /*Do nothing*/; 4199 else 4200 return false; 4201 } 4202 4203 if (const RecordType *Record = BaseType->getAs<RecordType>()) { 4204 AddRecordMembersCompletionResults(*this, Results, S, BaseType, 4205 Record->getDecl(), 4206 std::move(AccessOpFixIt)); 4207 } else if (const auto *TST = 4208 BaseType->getAs<TemplateSpecializationType>()) { 4209 TemplateName TN = TST->getTemplateName(); 4210 if (const auto *TD = 4211 dyn_cast_or_null<ClassTemplateDecl>(TN.getAsTemplateDecl())) { 4212 CXXRecordDecl *RD = TD->getTemplatedDecl(); 4213 AddRecordMembersCompletionResults(*this, Results, S, BaseType, RD, 4214 std::move(AccessOpFixIt)); 4215 } 4216 } else if (const auto *ICNT = BaseType->getAs<InjectedClassNameType>()) { 4217 if (auto *RD = ICNT->getDecl()) 4218 AddRecordMembersCompletionResults(*this, Results, S, BaseType, RD, 4219 std::move(AccessOpFixIt)); 4220 } else if (!IsArrow && BaseType->isObjCObjectPointerType()) { 4221 // Objective-C property reference. 4222 AddedPropertiesSet AddedProperties; 4223 4224 if (const ObjCObjectPointerType *ObjCPtr = 4225 BaseType->getAsObjCInterfacePointerType()) { 4226 // Add property results based on our interface. 4227 assert(ObjCPtr && "Non-NULL pointer guaranteed above!"); 4228 AddObjCProperties(CCContext, ObjCPtr->getInterfaceDecl(), true, 4229 /*AllowNullaryMethods=*/true, CurContext, 4230 AddedProperties, Results, IsBaseExprStatement); 4231 } 4232 4233 // Add properties from the protocols in a qualified interface. 4234 for (auto *I : BaseType->getAs<ObjCObjectPointerType>()->quals()) 4235 AddObjCProperties(CCContext, I, true, /*AllowNullaryMethods=*/true, 4236 CurContext, AddedProperties, Results, 4237 IsBaseExprStatement); 4238 } else if ((IsArrow && BaseType->isObjCObjectPointerType()) || 4239 (!IsArrow && BaseType->isObjCObjectType())) { 4240 // Objective-C instance variable access. 4241 ObjCInterfaceDecl *Class = nullptr; 4242 if (const ObjCObjectPointerType *ObjCPtr = 4243 BaseType->getAs<ObjCObjectPointerType>()) 4244 Class = ObjCPtr->getInterfaceDecl(); 4245 else 4246 Class = BaseType->getAs<ObjCObjectType>()->getInterface(); 4247 4248 // Add all ivars from this class and its superclasses. 4249 if (Class) { 4250 CodeCompletionDeclConsumer Consumer(Results, CurContext); 4251 Results.setFilter(&ResultBuilder::IsObjCIvar); 4252 LookupVisibleDecls( 4253 Class, LookupMemberName, Consumer, CodeCompleter->includeGlobals(), 4254 /*IncludeDependentBases=*/false, CodeCompleter->loadExternal()); 4255 } 4256 } 4257 4258 // FIXME: How do we cope with isa? 4259 return true; 4260 }; 4261 4262 Results.EnterNewScope(); 4263 4264 bool CompletionSucceded = DoCompletion(Base, IsArrow, None); 4265 if (CodeCompleter->includeFixIts()) { 4266 const CharSourceRange OpRange = 4267 CharSourceRange::getTokenRange(OpLoc, OpLoc); 4268 CompletionSucceded |= DoCompletion( 4269 OtherOpBase, !IsArrow, 4270 FixItHint::CreateReplacement(OpRange, IsArrow ? "." : "->")); 4271 } 4272 4273 Results.ExitScope(); 4274 4275 if (!CompletionSucceded) 4276 return; 4277 4278 // Hand off the results found for code completion. 4279 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 4280 Results.data(), Results.size()); 4281 } 4282 4283 void Sema::CodeCompleteObjCClassPropertyRefExpr(Scope *S, 4284 IdentifierInfo &ClassName, 4285 SourceLocation ClassNameLoc, 4286 bool IsBaseExprStatement) { 4287 IdentifierInfo *ClassNamePtr = &ClassName; 4288 ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(ClassNamePtr, ClassNameLoc); 4289 if (!IFace) 4290 return; 4291 CodeCompletionContext CCContext( 4292 CodeCompletionContext::CCC_ObjCPropertyAccess); 4293 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 4294 CodeCompleter->getCodeCompletionTUInfo(), CCContext, 4295 &ResultBuilder::IsMember); 4296 Results.EnterNewScope(); 4297 AddedPropertiesSet AddedProperties; 4298 AddObjCProperties(CCContext, IFace, true, 4299 /*AllowNullaryMethods=*/true, CurContext, AddedProperties, 4300 Results, IsBaseExprStatement, 4301 /*IsClassProperty=*/true); 4302 Results.ExitScope(); 4303 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 4304 Results.data(), Results.size()); 4305 } 4306 4307 void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) { 4308 if (!CodeCompleter) 4309 return; 4310 4311 ResultBuilder::LookupFilter Filter = nullptr; 4312 enum CodeCompletionContext::Kind ContextKind 4313 = CodeCompletionContext::CCC_Other; 4314 switch ((DeclSpec::TST)TagSpec) { 4315 case DeclSpec::TST_enum: 4316 Filter = &ResultBuilder::IsEnum; 4317 ContextKind = CodeCompletionContext::CCC_EnumTag; 4318 break; 4319 4320 case DeclSpec::TST_union: 4321 Filter = &ResultBuilder::IsUnion; 4322 ContextKind = CodeCompletionContext::CCC_UnionTag; 4323 break; 4324 4325 case DeclSpec::TST_struct: 4326 case DeclSpec::TST_class: 4327 case DeclSpec::TST_interface: 4328 Filter = &ResultBuilder::IsClassOrStruct; 4329 ContextKind = CodeCompletionContext::CCC_ClassOrStructTag; 4330 break; 4331 4332 default: 4333 llvm_unreachable("Unknown type specifier kind in CodeCompleteTag"); 4334 } 4335 4336 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 4337 CodeCompleter->getCodeCompletionTUInfo(), ContextKind); 4338 CodeCompletionDeclConsumer Consumer(Results, CurContext); 4339 4340 // First pass: look for tags. 4341 Results.setFilter(Filter); 4342 LookupVisibleDecls(S, LookupTagName, Consumer, 4343 CodeCompleter->includeGlobals(), 4344 CodeCompleter->loadExternal()); 4345 4346 if (CodeCompleter->includeGlobals()) { 4347 // Second pass: look for nested name specifiers. 4348 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier); 4349 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer, 4350 CodeCompleter->includeGlobals(), 4351 CodeCompleter->loadExternal()); 4352 } 4353 4354 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 4355 Results.data(),Results.size()); 4356 } 4357 4358 static void AddTypeQualifierResults(DeclSpec &DS, ResultBuilder &Results, 4359 const LangOptions &LangOpts) { 4360 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_const)) 4361 Results.AddResult("const"); 4362 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_volatile)) 4363 Results.AddResult("volatile"); 4364 if (LangOpts.C99 && !(DS.getTypeQualifiers() & DeclSpec::TQ_restrict)) 4365 Results.AddResult("restrict"); 4366 if (LangOpts.C11 && !(DS.getTypeQualifiers() & DeclSpec::TQ_atomic)) 4367 Results.AddResult("_Atomic"); 4368 if (LangOpts.MSVCCompat && !(DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)) 4369 Results.AddResult("__unaligned"); 4370 } 4371 4372 void Sema::CodeCompleteTypeQualifiers(DeclSpec &DS) { 4373 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 4374 CodeCompleter->getCodeCompletionTUInfo(), 4375 CodeCompletionContext::CCC_TypeQualifiers); 4376 Results.EnterNewScope(); 4377 AddTypeQualifierResults(DS, Results, LangOpts); 4378 Results.ExitScope(); 4379 HandleCodeCompleteResults(this, CodeCompleter, 4380 Results.getCompletionContext(), 4381 Results.data(), Results.size()); 4382 } 4383 4384 void Sema::CodeCompleteFunctionQualifiers(DeclSpec &DS, Declarator &D, 4385 const VirtSpecifiers *VS) { 4386 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 4387 CodeCompleter->getCodeCompletionTUInfo(), 4388 CodeCompletionContext::CCC_TypeQualifiers); 4389 Results.EnterNewScope(); 4390 AddTypeQualifierResults(DS, Results, LangOpts); 4391 if (LangOpts.CPlusPlus11) { 4392 Results.AddResult("noexcept"); 4393 if (D.getContext() == DeclaratorContext::MemberContext && 4394 !D.isCtorOrDtor() && !D.isStaticMember()) { 4395 if (!VS || !VS->isFinalSpecified()) 4396 Results.AddResult("final"); 4397 if (!VS || !VS->isOverrideSpecified()) 4398 Results.AddResult("override"); 4399 } 4400 } 4401 Results.ExitScope(); 4402 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 4403 Results.data(), Results.size()); 4404 } 4405 4406 void Sema::CodeCompleteBracketDeclarator(Scope *S) { 4407 CodeCompleteExpression(S, QualType(getASTContext().getSizeType())); 4408 } 4409 4410 void Sema::CodeCompleteCase(Scope *S) { 4411 if (getCurFunction()->SwitchStack.empty() || !CodeCompleter) 4412 return; 4413 4414 SwitchStmt *Switch = getCurFunction()->SwitchStack.back().getPointer(); 4415 QualType type = Switch->getCond()->IgnoreImplicit()->getType(); 4416 if (!type->isEnumeralType()) { 4417 CodeCompleteExpressionData Data(type); 4418 Data.IntegralConstantExpression = true; 4419 CodeCompleteExpression(S, Data); 4420 return; 4421 } 4422 4423 // Code-complete the cases of a switch statement over an enumeration type 4424 // by providing the list of 4425 EnumDecl *Enum = type->castAs<EnumType>()->getDecl(); 4426 if (EnumDecl *Def = Enum->getDefinition()) 4427 Enum = Def; 4428 4429 // Determine which enumerators we have already seen in the switch statement. 4430 // FIXME: Ideally, we would also be able to look *past* the code-completion 4431 // token, in case we are code-completing in the middle of the switch and not 4432 // at the end. However, we aren't able to do so at the moment. 4433 llvm::SmallPtrSet<EnumConstantDecl *, 8> EnumeratorsSeen; 4434 NestedNameSpecifier *Qualifier = nullptr; 4435 for (SwitchCase *SC = Switch->getSwitchCaseList(); SC; 4436 SC = SC->getNextSwitchCase()) { 4437 CaseStmt *Case = dyn_cast<CaseStmt>(SC); 4438 if (!Case) 4439 continue; 4440 4441 Expr *CaseVal = Case->getLHS()->IgnoreParenCasts(); 4442 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseVal)) 4443 if (EnumConstantDecl *Enumerator 4444 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 4445 // We look into the AST of the case statement to determine which 4446 // enumerator was named. Alternatively, we could compute the value of 4447 // the integral constant expression, then compare it against the 4448 // values of each enumerator. However, value-based approach would not 4449 // work as well with C++ templates where enumerators declared within a 4450 // template are type- and value-dependent. 4451 EnumeratorsSeen.insert(Enumerator); 4452 4453 // If this is a qualified-id, keep track of the nested-name-specifier 4454 // so that we can reproduce it as part of code completion, e.g., 4455 // 4456 // switch (TagD.getKind()) { 4457 // case TagDecl::TK_enum: 4458 // break; 4459 // case XXX 4460 // 4461 // At the XXX, our completions are TagDecl::TK_union, 4462 // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union, 4463 // TK_struct, and TK_class. 4464 Qualifier = DRE->getQualifier(); 4465 } 4466 } 4467 4468 if (getLangOpts().CPlusPlus && !Qualifier && EnumeratorsSeen.empty()) { 4469 // If there are no prior enumerators in C++, check whether we have to 4470 // qualify the names of the enumerators that we suggest, because they 4471 // may not be visible in this scope. 4472 Qualifier = getRequiredQualification(Context, CurContext, Enum); 4473 } 4474 4475 // Add any enumerators that have not yet been mentioned. 4476 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 4477 CodeCompleter->getCodeCompletionTUInfo(), 4478 CodeCompletionContext::CCC_Expression); 4479 Results.EnterNewScope(); 4480 for (auto *E : Enum->enumerators()) { 4481 if (EnumeratorsSeen.count(E)) 4482 continue; 4483 4484 CodeCompletionResult R(E, CCP_EnumInCase, Qualifier); 4485 Results.AddResult(R, CurContext, nullptr, false); 4486 } 4487 Results.ExitScope(); 4488 4489 if (CodeCompleter->includeMacros()) { 4490 AddMacroResults(PP, Results, CodeCompleter->loadExternal(), false); 4491 } 4492 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 4493 Results.data(), Results.size()); 4494 } 4495 4496 static bool anyNullArguments(ArrayRef<Expr *> Args) { 4497 if (Args.size() && !Args.data()) 4498 return true; 4499 4500 for (unsigned I = 0; I != Args.size(); ++I) 4501 if (!Args[I]) 4502 return true; 4503 4504 return false; 4505 } 4506 4507 typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate; 4508 4509 static void mergeCandidatesWithResults(Sema &SemaRef, 4510 SmallVectorImpl<ResultCandidate> &Results, 4511 OverloadCandidateSet &CandidateSet, 4512 SourceLocation Loc) { 4513 if (!CandidateSet.empty()) { 4514 // Sort the overload candidate set by placing the best overloads first. 4515 std::stable_sort( 4516 CandidateSet.begin(), CandidateSet.end(), 4517 [&](const OverloadCandidate &X, const OverloadCandidate &Y) { 4518 return isBetterOverloadCandidate(SemaRef, X, Y, Loc, 4519 CandidateSet.getKind()); 4520 }); 4521 4522 // Add the remaining viable overload candidates as code-completion results. 4523 for (auto &Candidate : CandidateSet) { 4524 if (Candidate.Function && Candidate.Function->isDeleted()) 4525 continue; 4526 if (Candidate.Viable) 4527 Results.push_back(ResultCandidate(Candidate.Function)); 4528 } 4529 } 4530 } 4531 4532 /// Get the type of the Nth parameter from a given set of overload 4533 /// candidates. 4534 static QualType getParamType(Sema &SemaRef, 4535 ArrayRef<ResultCandidate> Candidates, 4536 unsigned N) { 4537 4538 // Given the overloads 'Candidates' for a function call matching all arguments 4539 // up to N, return the type of the Nth parameter if it is the same for all 4540 // overload candidates. 4541 QualType ParamType; 4542 for (auto &Candidate : Candidates) { 4543 if (auto FType = Candidate.getFunctionType()) 4544 if (auto Proto = dyn_cast<FunctionProtoType>(FType)) 4545 if (N < Proto->getNumParams()) { 4546 if (ParamType.isNull()) 4547 ParamType = Proto->getParamType(N); 4548 else if (!SemaRef.Context.hasSameUnqualifiedType( 4549 ParamType.getNonReferenceType(), 4550 Proto->getParamType(N).getNonReferenceType())) 4551 // Otherwise return a default-constructed QualType. 4552 return QualType(); 4553 } 4554 } 4555 4556 return ParamType; 4557 } 4558 4559 static QualType 4560 ProduceSignatureHelp(Sema &SemaRef, Scope *S, 4561 MutableArrayRef<ResultCandidate> Candidates, 4562 unsigned CurrentArg, SourceLocation OpenParLoc) { 4563 if (Candidates.empty()) 4564 return QualType(); 4565 SemaRef.CodeCompleter->ProcessOverloadCandidates( 4566 SemaRef, CurrentArg, Candidates.data(), Candidates.size(), OpenParLoc); 4567 return getParamType(SemaRef, Candidates, CurrentArg); 4568 } 4569 4570 QualType Sema::ProduceCallSignatureHelp(Scope *S, Expr *Fn, 4571 ArrayRef<Expr *> Args, 4572 SourceLocation OpenParLoc) { 4573 if (!CodeCompleter) 4574 return QualType(); 4575 4576 // FIXME: Provide support for variadic template functions. 4577 // Ignore type-dependent call expressions entirely. 4578 if (!Fn || Fn->isTypeDependent() || anyNullArguments(Args) || 4579 Expr::hasAnyTypeDependentArguments(Args)) { 4580 return QualType(); 4581 } 4582 4583 // Build an overload candidate set based on the functions we find. 4584 SourceLocation Loc = Fn->getExprLoc(); 4585 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); 4586 4587 SmallVector<ResultCandidate, 8> Results; 4588 4589 Expr *NakedFn = Fn->IgnoreParenCasts(); 4590 if (auto ULE = dyn_cast<UnresolvedLookupExpr>(NakedFn)) 4591 AddOverloadedCallCandidates(ULE, Args, CandidateSet, 4592 /*PartialOverloading=*/true); 4593 else if (auto UME = dyn_cast<UnresolvedMemberExpr>(NakedFn)) { 4594 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 4595 if (UME->hasExplicitTemplateArgs()) { 4596 UME->copyTemplateArgumentsInto(TemplateArgsBuffer); 4597 TemplateArgs = &TemplateArgsBuffer; 4598 } 4599 4600 // Add the base as first argument (use a nullptr if the base is implicit). 4601 SmallVector<Expr *, 12> ArgExprs( 4602 1, UME->isImplicitAccess() ? nullptr : UME->getBase()); 4603 ArgExprs.append(Args.begin(), Args.end()); 4604 UnresolvedSet<8> Decls; 4605 Decls.append(UME->decls_begin(), UME->decls_end()); 4606 const bool FirstArgumentIsBase = !UME->isImplicitAccess() && UME->getBase(); 4607 AddFunctionCandidates(Decls, ArgExprs, CandidateSet, TemplateArgs, 4608 /*SuppressUsedConversions=*/false, 4609 /*PartialOverloading=*/true, 4610 FirstArgumentIsBase); 4611 } else { 4612 FunctionDecl *FD = nullptr; 4613 if (auto MCE = dyn_cast<MemberExpr>(NakedFn)) 4614 FD = dyn_cast<FunctionDecl>(MCE->getMemberDecl()); 4615 else if (auto DRE = dyn_cast<DeclRefExpr>(NakedFn)) 4616 FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 4617 if (FD) { // We check whether it's a resolved function declaration. 4618 if (!getLangOpts().CPlusPlus || 4619 !FD->getType()->getAs<FunctionProtoType>()) 4620 Results.push_back(ResultCandidate(FD)); 4621 else 4622 AddOverloadCandidate(FD, DeclAccessPair::make(FD, FD->getAccess()), 4623 Args, CandidateSet, 4624 /*SuppressUsedConversions=*/false, 4625 /*PartialOverloading=*/true); 4626 4627 } else if (auto DC = NakedFn->getType()->getAsCXXRecordDecl()) { 4628 // If expression's type is CXXRecordDecl, it may overload the function 4629 // call operator, so we check if it does and add them as candidates. 4630 // A complete type is needed to lookup for member function call operators. 4631 if (isCompleteType(Loc, NakedFn->getType())) { 4632 DeclarationName OpName = Context.DeclarationNames 4633 .getCXXOperatorName(OO_Call); 4634 LookupResult R(*this, OpName, Loc, LookupOrdinaryName); 4635 LookupQualifiedName(R, DC); 4636 R.suppressDiagnostics(); 4637 SmallVector<Expr *, 12> ArgExprs(1, NakedFn); 4638 ArgExprs.append(Args.begin(), Args.end()); 4639 AddFunctionCandidates(R.asUnresolvedSet(), ArgExprs, CandidateSet, 4640 /*ExplicitArgs=*/nullptr, 4641 /*SuppressUsedConversions=*/false, 4642 /*PartialOverloading=*/true); 4643 } 4644 } else { 4645 // Lastly we check whether expression's type is function pointer or 4646 // function. 4647 QualType T = NakedFn->getType(); 4648 if (!T->getPointeeType().isNull()) 4649 T = T->getPointeeType(); 4650 4651 if (auto FP = T->getAs<FunctionProtoType>()) { 4652 if (!TooManyArguments(FP->getNumParams(), Args.size(), 4653 /*PartialOverloading=*/true) || 4654 FP->isVariadic()) 4655 Results.push_back(ResultCandidate(FP)); 4656 } else if (auto FT = T->getAs<FunctionType>()) 4657 // No prototype and declaration, it may be a K & R style function. 4658 Results.push_back(ResultCandidate(FT)); 4659 } 4660 } 4661 mergeCandidatesWithResults(*this, Results, CandidateSet, Loc); 4662 QualType ParamType = 4663 ProduceSignatureHelp(*this, S, Results, Args.size(), OpenParLoc); 4664 return !CandidateSet.empty() ? ParamType : QualType(); 4665 } 4666 4667 QualType Sema::ProduceConstructorSignatureHelp(Scope *S, QualType Type, 4668 SourceLocation Loc, 4669 ArrayRef<Expr *> Args, 4670 SourceLocation OpenParLoc) { 4671 if (!CodeCompleter) 4672 return QualType(); 4673 4674 // A complete type is needed to lookup for constructors. 4675 CXXRecordDecl *RD = 4676 isCompleteType(Loc, Type) ? Type->getAsCXXRecordDecl() : nullptr; 4677 if (!RD) 4678 return Type; 4679 4680 // FIXME: Provide support for member initializers. 4681 // FIXME: Provide support for variadic template constructors. 4682 4683 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); 4684 4685 for (auto C : LookupConstructors(RD)) { 4686 if (auto FD = dyn_cast<FunctionDecl>(C)) { 4687 AddOverloadCandidate(FD, DeclAccessPair::make(FD, C->getAccess()), 4688 Args, CandidateSet, 4689 /*SuppressUsedConversions=*/false, 4690 /*PartialOverloading=*/true); 4691 } else if (auto FTD = dyn_cast<FunctionTemplateDecl>(C)) { 4692 AddTemplateOverloadCandidate(FTD, 4693 DeclAccessPair::make(FTD, C->getAccess()), 4694 /*ExplicitTemplateArgs=*/nullptr, 4695 Args, CandidateSet, 4696 /*SuppressUsedConversions=*/false, 4697 /*PartialOverloading=*/true); 4698 } 4699 } 4700 4701 SmallVector<ResultCandidate, 8> Results; 4702 mergeCandidatesWithResults(*this, Results, CandidateSet, Loc); 4703 return ProduceSignatureHelp(*this, S, Results, Args.size(), OpenParLoc); 4704 } 4705 4706 QualType Sema::ProduceCtorInitMemberSignatureHelp( 4707 Scope *S, Decl *ConstructorDecl, CXXScopeSpec SS, ParsedType TemplateTypeTy, 4708 ArrayRef<Expr *> ArgExprs, IdentifierInfo *II, SourceLocation OpenParLoc) { 4709 if (!CodeCompleter) 4710 return QualType(); 4711 4712 CXXConstructorDecl *Constructor = 4713 dyn_cast<CXXConstructorDecl>(ConstructorDecl); 4714 if (!Constructor) 4715 return QualType(); 4716 // FIXME: Add support for Base class constructors as well. 4717 if (ValueDecl *MemberDecl = tryLookupCtorInitMemberDecl( 4718 Constructor->getParent(), SS, TemplateTypeTy, II)) 4719 return ProduceConstructorSignatureHelp(getCurScope(), MemberDecl->getType(), 4720 MemberDecl->getLocation(), ArgExprs, 4721 OpenParLoc); 4722 return QualType(); 4723 } 4724 4725 void Sema::CodeCompleteInitializer(Scope *S, Decl *D) { 4726 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D); 4727 if (!VD) { 4728 CodeCompleteOrdinaryName(S, PCC_Expression); 4729 return; 4730 } 4731 4732 CodeCompleteExpression(S, VD->getType()); 4733 } 4734 4735 void Sema::CodeCompleteReturn(Scope *S) { 4736 QualType ResultType; 4737 if (isa<BlockDecl>(CurContext)) { 4738 if (BlockScopeInfo *BSI = getCurBlock()) 4739 ResultType = BSI->ReturnType; 4740 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(CurContext)) 4741 ResultType = Function->getReturnType(); 4742 else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(CurContext)) 4743 ResultType = Method->getReturnType(); 4744 4745 if (ResultType.isNull()) 4746 CodeCompleteOrdinaryName(S, PCC_Expression); 4747 else 4748 CodeCompleteExpression(S, ResultType); 4749 } 4750 4751 void Sema::CodeCompleteAfterIf(Scope *S) { 4752 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 4753 CodeCompleter->getCodeCompletionTUInfo(), 4754 mapCodeCompletionContext(*this, PCC_Statement)); 4755 Results.setFilter(&ResultBuilder::IsOrdinaryName); 4756 Results.EnterNewScope(); 4757 4758 CodeCompletionDeclConsumer Consumer(Results, CurContext); 4759 LookupVisibleDecls(S, LookupOrdinaryName, Consumer, 4760 CodeCompleter->includeGlobals(), 4761 CodeCompleter->loadExternal()); 4762 4763 AddOrdinaryNameResults(PCC_Statement, S, *this, Results); 4764 4765 // "else" block 4766 CodeCompletionBuilder Builder(Results.getAllocator(), 4767 Results.getCodeCompletionTUInfo()); 4768 Builder.AddTypedTextChunk("else"); 4769 if (Results.includeCodePatterns()) { 4770 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 4771 Builder.AddChunk(CodeCompletionString::CK_LeftBrace); 4772 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); 4773 Builder.AddPlaceholderChunk("statements"); 4774 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); 4775 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 4776 } 4777 Results.AddResult(Builder.TakeString()); 4778 4779 // "else if" block 4780 Builder.AddTypedTextChunk("else"); 4781 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 4782 Builder.AddTextChunk("if"); 4783 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 4784 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 4785 if (getLangOpts().CPlusPlus) 4786 Builder.AddPlaceholderChunk("condition"); 4787 else 4788 Builder.AddPlaceholderChunk("expression"); 4789 Builder.AddChunk(CodeCompletionString::CK_RightParen); 4790 if (Results.includeCodePatterns()) { 4791 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 4792 Builder.AddChunk(CodeCompletionString::CK_LeftBrace); 4793 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); 4794 Builder.AddPlaceholderChunk("statements"); 4795 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); 4796 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 4797 } 4798 Results.AddResult(Builder.TakeString()); 4799 4800 Results.ExitScope(); 4801 4802 if (S->getFnParent()) 4803 AddPrettyFunctionResults(getLangOpts(), Results); 4804 4805 if (CodeCompleter->includeMacros()) 4806 AddMacroResults(PP, Results, CodeCompleter->loadExternal(), false); 4807 4808 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 4809 Results.data(),Results.size()); 4810 } 4811 4812 void Sema::CodeCompleteAssignmentRHS(Scope *S, Expr *LHS) { 4813 if (LHS) 4814 CodeCompleteExpression(S, static_cast<Expr *>(LHS)->getType()); 4815 else 4816 CodeCompleteOrdinaryName(S, PCC_Expression); 4817 } 4818 4819 void Sema::CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS, 4820 bool EnteringContext) { 4821 if (SS.isEmpty() || !CodeCompleter) 4822 return; 4823 4824 // We want to keep the scope specifier even if it's invalid (e.g. the scope 4825 // "a::b::" is not corresponding to any context/namespace in the AST), since 4826 // it can be useful for global code completion which have information about 4827 // contexts/symbols that are not in the AST. 4828 if (SS.isInvalid()) { 4829 CodeCompletionContext CC(CodeCompletionContext::CCC_Name); 4830 CC.setCXXScopeSpecifier(SS); 4831 HandleCodeCompleteResults(this, CodeCompleter, CC, nullptr, 0); 4832 return; 4833 } 4834 // Always pretend to enter a context to ensure that a dependent type 4835 // resolves to a dependent record. 4836 DeclContext *Ctx = computeDeclContext(SS, /*EnteringContext=*/true); 4837 if (!Ctx) 4838 return; 4839 4840 // Try to instantiate any non-dependent declaration contexts before 4841 // we look in them. 4842 if (!isDependentScopeSpecifier(SS) && RequireCompleteDeclContext(SS, Ctx)) 4843 return; 4844 4845 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 4846 CodeCompleter->getCodeCompletionTUInfo(), 4847 CodeCompletionContext::CCC_Name); 4848 Results.EnterNewScope(); 4849 4850 // The "template" keyword can follow "::" in the grammar, but only 4851 // put it into the grammar if the nested-name-specifier is dependent. 4852 NestedNameSpecifier *NNS = SS.getScopeRep(); 4853 if (!Results.empty() && NNS->isDependent()) 4854 Results.AddResult("template"); 4855 4856 // Add calls to overridden virtual functions, if there are any. 4857 // 4858 // FIXME: This isn't wonderful, because we don't know whether we're actually 4859 // in a context that permits expressions. This is a general issue with 4860 // qualified-id completions. 4861 if (!EnteringContext) 4862 MaybeAddOverrideCalls(*this, Ctx, Results); 4863 Results.ExitScope(); 4864 4865 if (CodeCompleter->includeNamespaceLevelDecls() || 4866 (!Ctx->isNamespace() && !Ctx->isTranslationUnit())) { 4867 CodeCompletionDeclConsumer Consumer(Results, CurContext); 4868 LookupVisibleDecls(Ctx, LookupOrdinaryName, Consumer, 4869 /*IncludeGlobalScope=*/true, 4870 /*IncludeDependentBases=*/true, 4871 CodeCompleter->loadExternal()); 4872 } 4873 4874 auto CC = Results.getCompletionContext(); 4875 CC.setCXXScopeSpecifier(SS); 4876 4877 HandleCodeCompleteResults(this, CodeCompleter, CC, Results.data(), 4878 Results.size()); 4879 } 4880 4881 void Sema::CodeCompleteUsing(Scope *S) { 4882 if (!CodeCompleter) 4883 return; 4884 4885 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 4886 CodeCompleter->getCodeCompletionTUInfo(), 4887 CodeCompletionContext::CCC_PotentiallyQualifiedName, 4888 &ResultBuilder::IsNestedNameSpecifier); 4889 Results.EnterNewScope(); 4890 4891 // If we aren't in class scope, we could see the "namespace" keyword. 4892 if (!S->isClassScope()) 4893 Results.AddResult(CodeCompletionResult("namespace")); 4894 4895 // After "using", we can see anything that would start a 4896 // nested-name-specifier. 4897 CodeCompletionDeclConsumer Consumer(Results, CurContext); 4898 LookupVisibleDecls(S, LookupOrdinaryName, Consumer, 4899 CodeCompleter->includeGlobals(), 4900 CodeCompleter->loadExternal()); 4901 Results.ExitScope(); 4902 4903 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 4904 Results.data(), Results.size()); 4905 } 4906 4907 void Sema::CodeCompleteUsingDirective(Scope *S) { 4908 if (!CodeCompleter) 4909 return; 4910 4911 // After "using namespace", we expect to see a namespace name or namespace 4912 // alias. 4913 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 4914 CodeCompleter->getCodeCompletionTUInfo(), 4915 CodeCompletionContext::CCC_Namespace, 4916 &ResultBuilder::IsNamespaceOrAlias); 4917 Results.EnterNewScope(); 4918 CodeCompletionDeclConsumer Consumer(Results, CurContext); 4919 LookupVisibleDecls(S, LookupOrdinaryName, Consumer, 4920 CodeCompleter->includeGlobals(), 4921 CodeCompleter->loadExternal()); 4922 Results.ExitScope(); 4923 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 4924 Results.data(), Results.size()); 4925 } 4926 4927 void Sema::CodeCompleteNamespaceDecl(Scope *S) { 4928 if (!CodeCompleter) 4929 return; 4930 4931 DeclContext *Ctx = S->getEntity(); 4932 if (!S->getParent()) 4933 Ctx = Context.getTranslationUnitDecl(); 4934 4935 bool SuppressedGlobalResults 4936 = Ctx && !CodeCompleter->includeGlobals() && isa<TranslationUnitDecl>(Ctx); 4937 4938 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 4939 CodeCompleter->getCodeCompletionTUInfo(), 4940 SuppressedGlobalResults 4941 ? CodeCompletionContext::CCC_Namespace 4942 : CodeCompletionContext::CCC_Other, 4943 &ResultBuilder::IsNamespace); 4944 4945 if (Ctx && Ctx->isFileContext() && !SuppressedGlobalResults) { 4946 // We only want to see those namespaces that have already been defined 4947 // within this scope, because its likely that the user is creating an 4948 // extended namespace declaration. Keep track of the most recent 4949 // definition of each namespace. 4950 std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest; 4951 for (DeclContext::specific_decl_iterator<NamespaceDecl> 4952 NS(Ctx->decls_begin()), NSEnd(Ctx->decls_end()); 4953 NS != NSEnd; ++NS) 4954 OrigToLatest[NS->getOriginalNamespace()] = *NS; 4955 4956 // Add the most recent definition (or extended definition) of each 4957 // namespace to the list of results. 4958 Results.EnterNewScope(); 4959 for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator 4960 NS = OrigToLatest.begin(), 4961 NSEnd = OrigToLatest.end(); 4962 NS != NSEnd; ++NS) 4963 Results.AddResult(CodeCompletionResult( 4964 NS->second, Results.getBasePriority(NS->second), 4965 nullptr), 4966 CurContext, nullptr, false); 4967 Results.ExitScope(); 4968 } 4969 4970 HandleCodeCompleteResults(this, CodeCompleter, 4971 Results.getCompletionContext(), 4972 Results.data(),Results.size()); 4973 } 4974 4975 void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) { 4976 if (!CodeCompleter) 4977 return; 4978 4979 // After "namespace", we expect to see a namespace or alias. 4980 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 4981 CodeCompleter->getCodeCompletionTUInfo(), 4982 CodeCompletionContext::CCC_Namespace, 4983 &ResultBuilder::IsNamespaceOrAlias); 4984 CodeCompletionDeclConsumer Consumer(Results, CurContext); 4985 LookupVisibleDecls(S, LookupOrdinaryName, Consumer, 4986 CodeCompleter->includeGlobals(), 4987 CodeCompleter->loadExternal()); 4988 HandleCodeCompleteResults(this, CodeCompleter, 4989 Results.getCompletionContext(), 4990 Results.data(),Results.size()); 4991 } 4992 4993 void Sema::CodeCompleteOperatorName(Scope *S) { 4994 if (!CodeCompleter) 4995 return; 4996 4997 typedef CodeCompletionResult Result; 4998 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 4999 CodeCompleter->getCodeCompletionTUInfo(), 5000 CodeCompletionContext::CCC_Type, 5001 &ResultBuilder::IsType); 5002 Results.EnterNewScope(); 5003 5004 // Add the names of overloadable operators. 5005 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 5006 if (std::strcmp(Spelling, "?")) \ 5007 Results.AddResult(Result(Spelling)); 5008 #include "clang/Basic/OperatorKinds.def" 5009 5010 // Add any type names visible from the current scope 5011 Results.allowNestedNameSpecifiers(); 5012 CodeCompletionDeclConsumer Consumer(Results, CurContext); 5013 LookupVisibleDecls(S, LookupOrdinaryName, Consumer, 5014 CodeCompleter->includeGlobals(), 5015 CodeCompleter->loadExternal()); 5016 5017 // Add any type specifiers 5018 AddTypeSpecifierResults(getLangOpts(), Results); 5019 Results.ExitScope(); 5020 5021 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 5022 Results.data(), Results.size()); 5023 } 5024 5025 void Sema::CodeCompleteConstructorInitializer( 5026 Decl *ConstructorD, 5027 ArrayRef <CXXCtorInitializer *> Initializers) { 5028 if (!ConstructorD) 5029 return; 5030 5031 AdjustDeclIfTemplate(ConstructorD); 5032 5033 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ConstructorD); 5034 if (!Constructor) 5035 return; 5036 5037 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5038 CodeCompleter->getCodeCompletionTUInfo(), 5039 CodeCompletionContext::CCC_PotentiallyQualifiedName); 5040 Results.EnterNewScope(); 5041 5042 // Fill in any already-initialized fields or base classes. 5043 llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields; 5044 llvm::SmallPtrSet<CanQualType, 4> InitializedBases; 5045 for (unsigned I = 0, E = Initializers.size(); I != E; ++I) { 5046 if (Initializers[I]->isBaseInitializer()) 5047 InitializedBases.insert( 5048 Context.getCanonicalType(QualType(Initializers[I]->getBaseClass(), 0))); 5049 else 5050 InitializedFields.insert(cast<FieldDecl>( 5051 Initializers[I]->getAnyMember())); 5052 } 5053 5054 // Add completions for base classes. 5055 CodeCompletionBuilder Builder(Results.getAllocator(), 5056 Results.getCodeCompletionTUInfo()); 5057 PrintingPolicy Policy = getCompletionPrintingPolicy(*this); 5058 bool SawLastInitializer = Initializers.empty(); 5059 CXXRecordDecl *ClassDecl = Constructor->getParent(); 5060 for (const auto &Base : ClassDecl->bases()) { 5061 if (!InitializedBases.insert(Context.getCanonicalType(Base.getType())) 5062 .second) { 5063 SawLastInitializer 5064 = !Initializers.empty() && 5065 Initializers.back()->isBaseInitializer() && 5066 Context.hasSameUnqualifiedType(Base.getType(), 5067 QualType(Initializers.back()->getBaseClass(), 0)); 5068 continue; 5069 } 5070 5071 Builder.AddTypedTextChunk( 5072 Results.getAllocator().CopyString( 5073 Base.getType().getAsString(Policy))); 5074 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 5075 Builder.AddPlaceholderChunk("args"); 5076 Builder.AddChunk(CodeCompletionString::CK_RightParen); 5077 Results.AddResult(CodeCompletionResult(Builder.TakeString(), 5078 SawLastInitializer? CCP_NextInitializer 5079 : CCP_MemberDeclaration)); 5080 SawLastInitializer = false; 5081 } 5082 5083 // Add completions for virtual base classes. 5084 for (const auto &Base : ClassDecl->vbases()) { 5085 if (!InitializedBases.insert(Context.getCanonicalType(Base.getType())) 5086 .second) { 5087 SawLastInitializer 5088 = !Initializers.empty() && 5089 Initializers.back()->isBaseInitializer() && 5090 Context.hasSameUnqualifiedType(Base.getType(), 5091 QualType(Initializers.back()->getBaseClass(), 0)); 5092 continue; 5093 } 5094 5095 Builder.AddTypedTextChunk( 5096 Builder.getAllocator().CopyString( 5097 Base.getType().getAsString(Policy))); 5098 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 5099 Builder.AddPlaceholderChunk("args"); 5100 Builder.AddChunk(CodeCompletionString::CK_RightParen); 5101 Results.AddResult(CodeCompletionResult(Builder.TakeString(), 5102 SawLastInitializer? CCP_NextInitializer 5103 : CCP_MemberDeclaration)); 5104 SawLastInitializer = false; 5105 } 5106 5107 // Add completions for members. 5108 for (auto *Field : ClassDecl->fields()) { 5109 if (!InitializedFields.insert(cast<FieldDecl>(Field->getCanonicalDecl())) 5110 .second) { 5111 SawLastInitializer 5112 = !Initializers.empty() && 5113 Initializers.back()->isAnyMemberInitializer() && 5114 Initializers.back()->getAnyMember() == Field; 5115 continue; 5116 } 5117 5118 if (!Field->getDeclName()) 5119 continue; 5120 5121 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString( 5122 Field->getIdentifier()->getName())); 5123 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 5124 Builder.AddPlaceholderChunk("args"); 5125 Builder.AddChunk(CodeCompletionString::CK_RightParen); 5126 Results.AddResult(CodeCompletionResult(Builder.TakeString(), 5127 SawLastInitializer? CCP_NextInitializer 5128 : CCP_MemberDeclaration, 5129 CXCursor_MemberRef, 5130 CXAvailability_Available, 5131 Field)); 5132 SawLastInitializer = false; 5133 } 5134 Results.ExitScope(); 5135 5136 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 5137 Results.data(), Results.size()); 5138 } 5139 5140 /// Determine whether this scope denotes a namespace. 5141 static bool isNamespaceScope(Scope *S) { 5142 DeclContext *DC = S->getEntity(); 5143 if (!DC) 5144 return false; 5145 5146 return DC->isFileContext(); 5147 } 5148 5149 void Sema::CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro, 5150 bool AfterAmpersand) { 5151 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5152 CodeCompleter->getCodeCompletionTUInfo(), 5153 CodeCompletionContext::CCC_Other); 5154 Results.EnterNewScope(); 5155 5156 // Note what has already been captured. 5157 llvm::SmallPtrSet<IdentifierInfo *, 4> Known; 5158 bool IncludedThis = false; 5159 for (const auto &C : Intro.Captures) { 5160 if (C.Kind == LCK_This) { 5161 IncludedThis = true; 5162 continue; 5163 } 5164 5165 Known.insert(C.Id); 5166 } 5167 5168 // Look for other capturable variables. 5169 for (; S && !isNamespaceScope(S); S = S->getParent()) { 5170 for (const auto *D : S->decls()) { 5171 const auto *Var = dyn_cast<VarDecl>(D); 5172 if (!Var || 5173 !Var->hasLocalStorage() || 5174 Var->hasAttr<BlocksAttr>()) 5175 continue; 5176 5177 if (Known.insert(Var->getIdentifier()).second) 5178 Results.AddResult(CodeCompletionResult(Var, CCP_LocalDeclaration), 5179 CurContext, nullptr, false); 5180 } 5181 } 5182 5183 // Add 'this', if it would be valid. 5184 if (!IncludedThis && !AfterAmpersand && Intro.Default != LCD_ByCopy) 5185 addThisCompletion(*this, Results); 5186 5187 Results.ExitScope(); 5188 5189 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 5190 Results.data(), Results.size()); 5191 } 5192 5193 /// Macro that optionally prepends an "@" to the string literal passed in via 5194 /// Keyword, depending on whether NeedAt is true or false. 5195 #define OBJC_AT_KEYWORD_NAME(NeedAt,Keyword) ((NeedAt)? "@" Keyword : Keyword) 5196 5197 static void AddObjCImplementationResults(const LangOptions &LangOpts, 5198 ResultBuilder &Results, 5199 bool NeedAt) { 5200 typedef CodeCompletionResult Result; 5201 // Since we have an implementation, we can end it. 5202 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"end"))); 5203 5204 CodeCompletionBuilder Builder(Results.getAllocator(), 5205 Results.getCodeCompletionTUInfo()); 5206 if (LangOpts.ObjC2) { 5207 // @dynamic 5208 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"dynamic")); 5209 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 5210 Builder.AddPlaceholderChunk("property"); 5211 Results.AddResult(Result(Builder.TakeString())); 5212 5213 // @synthesize 5214 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"synthesize")); 5215 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 5216 Builder.AddPlaceholderChunk("property"); 5217 Results.AddResult(Result(Builder.TakeString())); 5218 } 5219 } 5220 5221 static void AddObjCInterfaceResults(const LangOptions &LangOpts, 5222 ResultBuilder &Results, 5223 bool NeedAt) { 5224 typedef CodeCompletionResult Result; 5225 5226 // Since we have an interface or protocol, we can end it. 5227 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"end"))); 5228 5229 if (LangOpts.ObjC2) { 5230 // @property 5231 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"property"))); 5232 5233 // @required 5234 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"required"))); 5235 5236 // @optional 5237 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"optional"))); 5238 } 5239 } 5240 5241 static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt) { 5242 typedef CodeCompletionResult Result; 5243 CodeCompletionBuilder Builder(Results.getAllocator(), 5244 Results.getCodeCompletionTUInfo()); 5245 5246 // @class name ; 5247 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"class")); 5248 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 5249 Builder.AddPlaceholderChunk("name"); 5250 Results.AddResult(Result(Builder.TakeString())); 5251 5252 if (Results.includeCodePatterns()) { 5253 // @interface name 5254 // FIXME: Could introduce the whole pattern, including superclasses and 5255 // such. 5256 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"interface")); 5257 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 5258 Builder.AddPlaceholderChunk("class"); 5259 Results.AddResult(Result(Builder.TakeString())); 5260 5261 // @protocol name 5262 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"protocol")); 5263 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 5264 Builder.AddPlaceholderChunk("protocol"); 5265 Results.AddResult(Result(Builder.TakeString())); 5266 5267 // @implementation name 5268 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"implementation")); 5269 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 5270 Builder.AddPlaceholderChunk("class"); 5271 Results.AddResult(Result(Builder.TakeString())); 5272 } 5273 5274 // @compatibility_alias name 5275 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"compatibility_alias")); 5276 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 5277 Builder.AddPlaceholderChunk("alias"); 5278 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 5279 Builder.AddPlaceholderChunk("class"); 5280 Results.AddResult(Result(Builder.TakeString())); 5281 5282 if (Results.getSema().getLangOpts().Modules) { 5283 // @import name 5284 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "import")); 5285 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 5286 Builder.AddPlaceholderChunk("module"); 5287 Results.AddResult(Result(Builder.TakeString())); 5288 } 5289 } 5290 5291 void Sema::CodeCompleteObjCAtDirective(Scope *S) { 5292 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5293 CodeCompleter->getCodeCompletionTUInfo(), 5294 CodeCompletionContext::CCC_Other); 5295 Results.EnterNewScope(); 5296 if (isa<ObjCImplDecl>(CurContext)) 5297 AddObjCImplementationResults(getLangOpts(), Results, false); 5298 else if (CurContext->isObjCContainer()) 5299 AddObjCInterfaceResults(getLangOpts(), Results, false); 5300 else 5301 AddObjCTopLevelResults(Results, false); 5302 Results.ExitScope(); 5303 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 5304 Results.data(), Results.size()); 5305 } 5306 5307 static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt) { 5308 typedef CodeCompletionResult Result; 5309 CodeCompletionBuilder Builder(Results.getAllocator(), 5310 Results.getCodeCompletionTUInfo()); 5311 5312 // @encode ( type-name ) 5313 const char *EncodeType = "char[]"; 5314 if (Results.getSema().getLangOpts().CPlusPlus || 5315 Results.getSema().getLangOpts().ConstStrings) 5316 EncodeType = "const char[]"; 5317 Builder.AddResultTypeChunk(EncodeType); 5318 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"encode")); 5319 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 5320 Builder.AddPlaceholderChunk("type-name"); 5321 Builder.AddChunk(CodeCompletionString::CK_RightParen); 5322 Results.AddResult(Result(Builder.TakeString())); 5323 5324 // @protocol ( protocol-name ) 5325 Builder.AddResultTypeChunk("Protocol *"); 5326 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"protocol")); 5327 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 5328 Builder.AddPlaceholderChunk("protocol-name"); 5329 Builder.AddChunk(CodeCompletionString::CK_RightParen); 5330 Results.AddResult(Result(Builder.TakeString())); 5331 5332 // @selector ( selector ) 5333 Builder.AddResultTypeChunk("SEL"); 5334 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"selector")); 5335 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 5336 Builder.AddPlaceholderChunk("selector"); 5337 Builder.AddChunk(CodeCompletionString::CK_RightParen); 5338 Results.AddResult(Result(Builder.TakeString())); 5339 5340 // @"string" 5341 Builder.AddResultTypeChunk("NSString *"); 5342 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"\"")); 5343 Builder.AddPlaceholderChunk("string"); 5344 Builder.AddTextChunk("\""); 5345 Results.AddResult(Result(Builder.TakeString())); 5346 5347 // @[objects, ...] 5348 Builder.AddResultTypeChunk("NSArray *"); 5349 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"[")); 5350 Builder.AddPlaceholderChunk("objects, ..."); 5351 Builder.AddChunk(CodeCompletionString::CK_RightBracket); 5352 Results.AddResult(Result(Builder.TakeString())); 5353 5354 // @{key : object, ...} 5355 Builder.AddResultTypeChunk("NSDictionary *"); 5356 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"{")); 5357 Builder.AddPlaceholderChunk("key"); 5358 Builder.AddChunk(CodeCompletionString::CK_Colon); 5359 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 5360 Builder.AddPlaceholderChunk("object, ..."); 5361 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 5362 Results.AddResult(Result(Builder.TakeString())); 5363 5364 // @(expression) 5365 Builder.AddResultTypeChunk("id"); 5366 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "(")); 5367 Builder.AddPlaceholderChunk("expression"); 5368 Builder.AddChunk(CodeCompletionString::CK_RightParen); 5369 Results.AddResult(Result(Builder.TakeString())); 5370 } 5371 5372 static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt) { 5373 typedef CodeCompletionResult Result; 5374 CodeCompletionBuilder Builder(Results.getAllocator(), 5375 Results.getCodeCompletionTUInfo()); 5376 5377 if (Results.includeCodePatterns()) { 5378 // @try { statements } @catch ( declaration ) { statements } @finally 5379 // { statements } 5380 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"try")); 5381 Builder.AddChunk(CodeCompletionString::CK_LeftBrace); 5382 Builder.AddPlaceholderChunk("statements"); 5383 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 5384 Builder.AddTextChunk("@catch"); 5385 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 5386 Builder.AddPlaceholderChunk("parameter"); 5387 Builder.AddChunk(CodeCompletionString::CK_RightParen); 5388 Builder.AddChunk(CodeCompletionString::CK_LeftBrace); 5389 Builder.AddPlaceholderChunk("statements"); 5390 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 5391 Builder.AddTextChunk("@finally"); 5392 Builder.AddChunk(CodeCompletionString::CK_LeftBrace); 5393 Builder.AddPlaceholderChunk("statements"); 5394 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 5395 Results.AddResult(Result(Builder.TakeString())); 5396 } 5397 5398 // @throw 5399 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"throw")); 5400 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 5401 Builder.AddPlaceholderChunk("expression"); 5402 Results.AddResult(Result(Builder.TakeString())); 5403 5404 if (Results.includeCodePatterns()) { 5405 // @synchronized ( expression ) { statements } 5406 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,"synchronized")); 5407 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 5408 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 5409 Builder.AddPlaceholderChunk("expression"); 5410 Builder.AddChunk(CodeCompletionString::CK_RightParen); 5411 Builder.AddChunk(CodeCompletionString::CK_LeftBrace); 5412 Builder.AddPlaceholderChunk("statements"); 5413 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 5414 Results.AddResult(Result(Builder.TakeString())); 5415 } 5416 } 5417 5418 static void AddObjCVisibilityResults(const LangOptions &LangOpts, 5419 ResultBuilder &Results, 5420 bool NeedAt) { 5421 typedef CodeCompletionResult Result; 5422 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"private"))); 5423 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"protected"))); 5424 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"public"))); 5425 if (LangOpts.ObjC2) 5426 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,"package"))); 5427 } 5428 5429 void Sema::CodeCompleteObjCAtVisibility(Scope *S) { 5430 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5431 CodeCompleter->getCodeCompletionTUInfo(), 5432 CodeCompletionContext::CCC_Other); 5433 Results.EnterNewScope(); 5434 AddObjCVisibilityResults(getLangOpts(), Results, false); 5435 Results.ExitScope(); 5436 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 5437 Results.data(), Results.size()); 5438 } 5439 5440 void Sema::CodeCompleteObjCAtStatement(Scope *S) { 5441 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5442 CodeCompleter->getCodeCompletionTUInfo(), 5443 CodeCompletionContext::CCC_Other); 5444 Results.EnterNewScope(); 5445 AddObjCStatementResults(Results, false); 5446 AddObjCExpressionResults(Results, false); 5447 Results.ExitScope(); 5448 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 5449 Results.data(), Results.size()); 5450 } 5451 5452 void Sema::CodeCompleteObjCAtExpression(Scope *S) { 5453 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5454 CodeCompleter->getCodeCompletionTUInfo(), 5455 CodeCompletionContext::CCC_Other); 5456 Results.EnterNewScope(); 5457 AddObjCExpressionResults(Results, false); 5458 Results.ExitScope(); 5459 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 5460 Results.data(), Results.size()); 5461 } 5462 5463 /// Determine whether the addition of the given flag to an Objective-C 5464 /// property's attributes will cause a conflict. 5465 static bool ObjCPropertyFlagConflicts(unsigned Attributes, unsigned NewFlag) { 5466 // Check if we've already added this flag. 5467 if (Attributes & NewFlag) 5468 return true; 5469 5470 Attributes |= NewFlag; 5471 5472 // Check for collisions with "readonly". 5473 if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) && 5474 (Attributes & ObjCDeclSpec::DQ_PR_readwrite)) 5475 return true; 5476 5477 // Check for more than one of { assign, copy, retain, strong, weak }. 5478 unsigned AssignCopyRetMask = Attributes & (ObjCDeclSpec::DQ_PR_assign | 5479 ObjCDeclSpec::DQ_PR_unsafe_unretained | 5480 ObjCDeclSpec::DQ_PR_copy | 5481 ObjCDeclSpec::DQ_PR_retain | 5482 ObjCDeclSpec::DQ_PR_strong | 5483 ObjCDeclSpec::DQ_PR_weak); 5484 if (AssignCopyRetMask && 5485 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_assign && 5486 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_unsafe_unretained && 5487 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_copy && 5488 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_retain && 5489 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_strong && 5490 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_weak) 5491 return true; 5492 5493 return false; 5494 } 5495 5496 void Sema::CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS) { 5497 if (!CodeCompleter) 5498 return; 5499 5500 unsigned Attributes = ODS.getPropertyAttributes(); 5501 5502 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5503 CodeCompleter->getCodeCompletionTUInfo(), 5504 CodeCompletionContext::CCC_Other); 5505 Results.EnterNewScope(); 5506 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readonly)) 5507 Results.AddResult(CodeCompletionResult("readonly")); 5508 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_assign)) 5509 Results.AddResult(CodeCompletionResult("assign")); 5510 if (!ObjCPropertyFlagConflicts(Attributes, 5511 ObjCDeclSpec::DQ_PR_unsafe_unretained)) 5512 Results.AddResult(CodeCompletionResult("unsafe_unretained")); 5513 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readwrite)) 5514 Results.AddResult(CodeCompletionResult("readwrite")); 5515 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_retain)) 5516 Results.AddResult(CodeCompletionResult("retain")); 5517 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_strong)) 5518 Results.AddResult(CodeCompletionResult("strong")); 5519 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_copy)) 5520 Results.AddResult(CodeCompletionResult("copy")); 5521 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nonatomic)) 5522 Results.AddResult(CodeCompletionResult("nonatomic")); 5523 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_atomic)) 5524 Results.AddResult(CodeCompletionResult("atomic")); 5525 5526 // Only suggest "weak" if we're compiling for ARC-with-weak-references or GC. 5527 if (getLangOpts().ObjCWeak || getLangOpts().getGC() != LangOptions::NonGC) 5528 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_weak)) 5529 Results.AddResult(CodeCompletionResult("weak")); 5530 5531 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_setter)) { 5532 CodeCompletionBuilder Setter(Results.getAllocator(), 5533 Results.getCodeCompletionTUInfo()); 5534 Setter.AddTypedTextChunk("setter"); 5535 Setter.AddTextChunk("="); 5536 Setter.AddPlaceholderChunk("method"); 5537 Results.AddResult(CodeCompletionResult(Setter.TakeString())); 5538 } 5539 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_getter)) { 5540 CodeCompletionBuilder Getter(Results.getAllocator(), 5541 Results.getCodeCompletionTUInfo()); 5542 Getter.AddTypedTextChunk("getter"); 5543 Getter.AddTextChunk("="); 5544 Getter.AddPlaceholderChunk("method"); 5545 Results.AddResult(CodeCompletionResult(Getter.TakeString())); 5546 } 5547 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nullability)) { 5548 Results.AddResult(CodeCompletionResult("nonnull")); 5549 Results.AddResult(CodeCompletionResult("nullable")); 5550 Results.AddResult(CodeCompletionResult("null_unspecified")); 5551 Results.AddResult(CodeCompletionResult("null_resettable")); 5552 } 5553 Results.ExitScope(); 5554 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 5555 Results.data(), Results.size()); 5556 } 5557 5558 /// Describes the kind of Objective-C method that we want to find 5559 /// via code completion. 5560 enum ObjCMethodKind { 5561 MK_Any, ///< Any kind of method, provided it means other specified criteria. 5562 MK_ZeroArgSelector, ///< Zero-argument (unary) selector. 5563 MK_OneArgSelector ///< One-argument selector. 5564 }; 5565 5566 static bool isAcceptableObjCSelector(Selector Sel, 5567 ObjCMethodKind WantKind, 5568 ArrayRef<IdentifierInfo *> SelIdents, 5569 bool AllowSameLength = true) { 5570 unsigned NumSelIdents = SelIdents.size(); 5571 if (NumSelIdents > Sel.getNumArgs()) 5572 return false; 5573 5574 switch (WantKind) { 5575 case MK_Any: break; 5576 case MK_ZeroArgSelector: return Sel.isUnarySelector(); 5577 case MK_OneArgSelector: return Sel.getNumArgs() == 1; 5578 } 5579 5580 if (!AllowSameLength && NumSelIdents && NumSelIdents == Sel.getNumArgs()) 5581 return false; 5582 5583 for (unsigned I = 0; I != NumSelIdents; ++I) 5584 if (SelIdents[I] != Sel.getIdentifierInfoForSlot(I)) 5585 return false; 5586 5587 return true; 5588 } 5589 5590 static bool isAcceptableObjCMethod(ObjCMethodDecl *Method, 5591 ObjCMethodKind WantKind, 5592 ArrayRef<IdentifierInfo *> SelIdents, 5593 bool AllowSameLength = true) { 5594 return isAcceptableObjCSelector(Method->getSelector(), WantKind, SelIdents, 5595 AllowSameLength); 5596 } 5597 5598 namespace { 5599 /// A set of selectors, which is used to avoid introducing multiple 5600 /// completions with the same selector into the result set. 5601 typedef llvm::SmallPtrSet<Selector, 16> VisitedSelectorSet; 5602 } 5603 5604 /// Add all of the Objective-C methods in the given Objective-C 5605 /// container to the set of results. 5606 /// 5607 /// The container will be a class, protocol, category, or implementation of 5608 /// any of the above. This mether will recurse to include methods from 5609 /// the superclasses of classes along with their categories, protocols, and 5610 /// implementations. 5611 /// 5612 /// \param Container the container in which we'll look to find methods. 5613 /// 5614 /// \param WantInstanceMethods Whether to add instance methods (only); if 5615 /// false, this routine will add factory methods (only). 5616 /// 5617 /// \param CurContext the context in which we're performing the lookup that 5618 /// finds methods. 5619 /// 5620 /// \param AllowSameLength Whether we allow a method to be added to the list 5621 /// when it has the same number of parameters as we have selector identifiers. 5622 /// 5623 /// \param Results the structure into which we'll add results. 5624 static void AddObjCMethods(ObjCContainerDecl *Container, 5625 bool WantInstanceMethods, ObjCMethodKind WantKind, 5626 ArrayRef<IdentifierInfo *> SelIdents, 5627 DeclContext *CurContext, 5628 VisitedSelectorSet &Selectors, bool AllowSameLength, 5629 ResultBuilder &Results, bool InOriginalClass = true, 5630 bool IsRootClass = false) { 5631 typedef CodeCompletionResult Result; 5632 Container = getContainerDef(Container); 5633 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container); 5634 IsRootClass = IsRootClass || (IFace && !IFace->getSuperClass()); 5635 for (auto *M : Container->methods()) { 5636 // The instance methods on the root class can be messaged via the 5637 // metaclass. 5638 if (M->isInstanceMethod() == WantInstanceMethods || 5639 (IsRootClass && !WantInstanceMethods)) { 5640 // Check whether the selector identifiers we've been given are a 5641 // subset of the identifiers for this particular method. 5642 if (!isAcceptableObjCMethod(M, WantKind, SelIdents, AllowSameLength)) 5643 continue; 5644 5645 if (!Selectors.insert(M->getSelector()).second) 5646 continue; 5647 5648 Result R = Result(M, Results.getBasePriority(M), nullptr); 5649 R.StartParameter = SelIdents.size(); 5650 R.AllParametersAreInformative = (WantKind != MK_Any); 5651 if (!InOriginalClass) 5652 R.Priority += CCD_InBaseClass; 5653 Results.MaybeAddResult(R, CurContext); 5654 } 5655 } 5656 5657 // Visit the protocols of protocols. 5658 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) { 5659 if (Protocol->hasDefinition()) { 5660 const ObjCList<ObjCProtocolDecl> &Protocols 5661 = Protocol->getReferencedProtocols(); 5662 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(), 5663 E = Protocols.end(); 5664 I != E; ++I) 5665 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, CurContext, 5666 Selectors, AllowSameLength, Results, false, IsRootClass); 5667 } 5668 } 5669 5670 if (!IFace || !IFace->hasDefinition()) 5671 return; 5672 5673 // Add methods in protocols. 5674 for (auto *I : IFace->protocols()) 5675 AddObjCMethods(I, WantInstanceMethods, WantKind, SelIdents, CurContext, 5676 Selectors, AllowSameLength, Results, false, IsRootClass); 5677 5678 // Add methods in categories. 5679 for (auto *CatDecl : IFace->known_categories()) { 5680 AddObjCMethods(CatDecl, WantInstanceMethods, WantKind, SelIdents, 5681 CurContext, Selectors, AllowSameLength, Results, 5682 InOriginalClass, IsRootClass); 5683 5684 // Add a categories protocol methods. 5685 const ObjCList<ObjCProtocolDecl> &Protocols 5686 = CatDecl->getReferencedProtocols(); 5687 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(), 5688 E = Protocols.end(); 5689 I != E; ++I) 5690 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, CurContext, 5691 Selectors, AllowSameLength, Results, false, IsRootClass); 5692 5693 // Add methods in category implementations. 5694 if (ObjCCategoryImplDecl *Impl = CatDecl->getImplementation()) 5695 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents, CurContext, 5696 Selectors, AllowSameLength, Results, InOriginalClass, 5697 IsRootClass); 5698 } 5699 5700 // Add methods in superclass. 5701 // Avoid passing in IsRootClass since root classes won't have super classes. 5702 if (IFace->getSuperClass()) 5703 AddObjCMethods(IFace->getSuperClass(), WantInstanceMethods, WantKind, 5704 SelIdents, CurContext, Selectors, AllowSameLength, Results, 5705 /*IsRootClass=*/false); 5706 5707 // Add methods in our implementation, if any. 5708 if (ObjCImplementationDecl *Impl = IFace->getImplementation()) 5709 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents, CurContext, 5710 Selectors, AllowSameLength, Results, InOriginalClass, 5711 IsRootClass); 5712 } 5713 5714 5715 void Sema::CodeCompleteObjCPropertyGetter(Scope *S) { 5716 // Try to find the interface where getters might live. 5717 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext); 5718 if (!Class) { 5719 if (ObjCCategoryDecl *Category 5720 = dyn_cast_or_null<ObjCCategoryDecl>(CurContext)) 5721 Class = Category->getClassInterface(); 5722 5723 if (!Class) 5724 return; 5725 } 5726 5727 // Find all of the potential getters. 5728 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5729 CodeCompleter->getCodeCompletionTUInfo(), 5730 CodeCompletionContext::CCC_Other); 5731 Results.EnterNewScope(); 5732 5733 VisitedSelectorSet Selectors; 5734 AddObjCMethods(Class, true, MK_ZeroArgSelector, None, CurContext, Selectors, 5735 /*AllowSameLength=*/true, Results); 5736 Results.ExitScope(); 5737 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 5738 Results.data(), Results.size()); 5739 } 5740 5741 void Sema::CodeCompleteObjCPropertySetter(Scope *S) { 5742 // Try to find the interface where setters might live. 5743 ObjCInterfaceDecl *Class 5744 = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext); 5745 if (!Class) { 5746 if (ObjCCategoryDecl *Category 5747 = dyn_cast_or_null<ObjCCategoryDecl>(CurContext)) 5748 Class = Category->getClassInterface(); 5749 5750 if (!Class) 5751 return; 5752 } 5753 5754 // Find all of the potential getters. 5755 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5756 CodeCompleter->getCodeCompletionTUInfo(), 5757 CodeCompletionContext::CCC_Other); 5758 Results.EnterNewScope(); 5759 5760 VisitedSelectorSet Selectors; 5761 AddObjCMethods(Class, true, MK_OneArgSelector, None, CurContext, 5762 Selectors, /*AllowSameLength=*/true, Results); 5763 5764 Results.ExitScope(); 5765 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 5766 Results.data(), Results.size()); 5767 } 5768 5769 void Sema::CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS, 5770 bool IsParameter) { 5771 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5772 CodeCompleter->getCodeCompletionTUInfo(), 5773 CodeCompletionContext::CCC_Type); 5774 Results.EnterNewScope(); 5775 5776 // Add context-sensitive, Objective-C parameter-passing keywords. 5777 bool AddedInOut = false; 5778 if ((DS.getObjCDeclQualifier() & 5779 (ObjCDeclSpec::DQ_In | ObjCDeclSpec::DQ_Inout)) == 0) { 5780 Results.AddResult("in"); 5781 Results.AddResult("inout"); 5782 AddedInOut = true; 5783 } 5784 if ((DS.getObjCDeclQualifier() & 5785 (ObjCDeclSpec::DQ_Out | ObjCDeclSpec::DQ_Inout)) == 0) { 5786 Results.AddResult("out"); 5787 if (!AddedInOut) 5788 Results.AddResult("inout"); 5789 } 5790 if ((DS.getObjCDeclQualifier() & 5791 (ObjCDeclSpec::DQ_Bycopy | ObjCDeclSpec::DQ_Byref | 5792 ObjCDeclSpec::DQ_Oneway)) == 0) { 5793 Results.AddResult("bycopy"); 5794 Results.AddResult("byref"); 5795 Results.AddResult("oneway"); 5796 } 5797 if ((DS.getObjCDeclQualifier() & ObjCDeclSpec::DQ_CSNullability) == 0) { 5798 Results.AddResult("nonnull"); 5799 Results.AddResult("nullable"); 5800 Results.AddResult("null_unspecified"); 5801 } 5802 5803 // If we're completing the return type of an Objective-C method and the 5804 // identifier IBAction refers to a macro, provide a completion item for 5805 // an action, e.g., 5806 // IBAction)<#selector#>:(id)sender 5807 if (DS.getObjCDeclQualifier() == 0 && !IsParameter && 5808 PP.isMacroDefined("IBAction")) { 5809 CodeCompletionBuilder Builder(Results.getAllocator(), 5810 Results.getCodeCompletionTUInfo(), 5811 CCP_CodePattern, CXAvailability_Available); 5812 Builder.AddTypedTextChunk("IBAction"); 5813 Builder.AddChunk(CodeCompletionString::CK_RightParen); 5814 Builder.AddPlaceholderChunk("selector"); 5815 Builder.AddChunk(CodeCompletionString::CK_Colon); 5816 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 5817 Builder.AddTextChunk("id"); 5818 Builder.AddChunk(CodeCompletionString::CK_RightParen); 5819 Builder.AddTextChunk("sender"); 5820 Results.AddResult(CodeCompletionResult(Builder.TakeString())); 5821 } 5822 5823 // If we're completing the return type, provide 'instancetype'. 5824 if (!IsParameter) { 5825 Results.AddResult(CodeCompletionResult("instancetype")); 5826 } 5827 5828 // Add various builtin type names and specifiers. 5829 AddOrdinaryNameResults(PCC_Type, S, *this, Results); 5830 Results.ExitScope(); 5831 5832 // Add the various type names 5833 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName); 5834 CodeCompletionDeclConsumer Consumer(Results, CurContext); 5835 LookupVisibleDecls(S, LookupOrdinaryName, Consumer, 5836 CodeCompleter->includeGlobals(), 5837 CodeCompleter->loadExternal()); 5838 5839 if (CodeCompleter->includeMacros()) 5840 AddMacroResults(PP, Results, CodeCompleter->loadExternal(), false); 5841 5842 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 5843 Results.data(), Results.size()); 5844 } 5845 5846 /// When we have an expression with type "id", we may assume 5847 /// that it has some more-specific class type based on knowledge of 5848 /// common uses of Objective-C. This routine returns that class type, 5849 /// or NULL if no better result could be determined. 5850 static ObjCInterfaceDecl *GetAssumedMessageSendExprType(Expr *E) { 5851 ObjCMessageExpr *Msg = dyn_cast_or_null<ObjCMessageExpr>(E); 5852 if (!Msg) 5853 return nullptr; 5854 5855 Selector Sel = Msg->getSelector(); 5856 if (Sel.isNull()) 5857 return nullptr; 5858 5859 IdentifierInfo *Id = Sel.getIdentifierInfoForSlot(0); 5860 if (!Id) 5861 return nullptr; 5862 5863 ObjCMethodDecl *Method = Msg->getMethodDecl(); 5864 if (!Method) 5865 return nullptr; 5866 5867 // Determine the class that we're sending the message to. 5868 ObjCInterfaceDecl *IFace = nullptr; 5869 switch (Msg->getReceiverKind()) { 5870 case ObjCMessageExpr::Class: 5871 if (const ObjCObjectType *ObjType 5872 = Msg->getClassReceiver()->getAs<ObjCObjectType>()) 5873 IFace = ObjType->getInterface(); 5874 break; 5875 5876 case ObjCMessageExpr::Instance: { 5877 QualType T = Msg->getInstanceReceiver()->getType(); 5878 if (const ObjCObjectPointerType *Ptr = T->getAs<ObjCObjectPointerType>()) 5879 IFace = Ptr->getInterfaceDecl(); 5880 break; 5881 } 5882 5883 case ObjCMessageExpr::SuperInstance: 5884 case ObjCMessageExpr::SuperClass: 5885 break; 5886 } 5887 5888 if (!IFace) 5889 return nullptr; 5890 5891 ObjCInterfaceDecl *Super = IFace->getSuperClass(); 5892 if (Method->isInstanceMethod()) 5893 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName()) 5894 .Case("retain", IFace) 5895 .Case("strong", IFace) 5896 .Case("autorelease", IFace) 5897 .Case("copy", IFace) 5898 .Case("copyWithZone", IFace) 5899 .Case("mutableCopy", IFace) 5900 .Case("mutableCopyWithZone", IFace) 5901 .Case("awakeFromCoder", IFace) 5902 .Case("replacementObjectFromCoder", IFace) 5903 .Case("class", IFace) 5904 .Case("classForCoder", IFace) 5905 .Case("superclass", Super) 5906 .Default(nullptr); 5907 5908 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName()) 5909 .Case("new", IFace) 5910 .Case("alloc", IFace) 5911 .Case("allocWithZone", IFace) 5912 .Case("class", IFace) 5913 .Case("superclass", Super) 5914 .Default(nullptr); 5915 } 5916 5917 // Add a special completion for a message send to "super", which fills in the 5918 // most likely case of forwarding all of our arguments to the superclass 5919 // function. 5920 /// 5921 /// \param S The semantic analysis object. 5922 /// 5923 /// \param NeedSuperKeyword Whether we need to prefix this completion with 5924 /// the "super" keyword. Otherwise, we just need to provide the arguments. 5925 /// 5926 /// \param SelIdents The identifiers in the selector that have already been 5927 /// provided as arguments for a send to "super". 5928 /// 5929 /// \param Results The set of results to augment. 5930 /// 5931 /// \returns the Objective-C method declaration that would be invoked by 5932 /// this "super" completion. If NULL, no completion was added. 5933 static ObjCMethodDecl *AddSuperSendCompletion( 5934 Sema &S, bool NeedSuperKeyword, 5935 ArrayRef<IdentifierInfo *> SelIdents, 5936 ResultBuilder &Results) { 5937 ObjCMethodDecl *CurMethod = S.getCurMethodDecl(); 5938 if (!CurMethod) 5939 return nullptr; 5940 5941 ObjCInterfaceDecl *Class = CurMethod->getClassInterface(); 5942 if (!Class) 5943 return nullptr; 5944 5945 // Try to find a superclass method with the same selector. 5946 ObjCMethodDecl *SuperMethod = nullptr; 5947 while ((Class = Class->getSuperClass()) && !SuperMethod) { 5948 // Check in the class 5949 SuperMethod = Class->getMethod(CurMethod->getSelector(), 5950 CurMethod->isInstanceMethod()); 5951 5952 // Check in categories or class extensions. 5953 if (!SuperMethod) { 5954 for (const auto *Cat : Class->known_categories()) { 5955 if ((SuperMethod = Cat->getMethod(CurMethod->getSelector(), 5956 CurMethod->isInstanceMethod()))) 5957 break; 5958 } 5959 } 5960 } 5961 5962 if (!SuperMethod) 5963 return nullptr; 5964 5965 // Check whether the superclass method has the same signature. 5966 if (CurMethod->param_size() != SuperMethod->param_size() || 5967 CurMethod->isVariadic() != SuperMethod->isVariadic()) 5968 return nullptr; 5969 5970 for (ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin(), 5971 CurPEnd = CurMethod->param_end(), 5972 SuperP = SuperMethod->param_begin(); 5973 CurP != CurPEnd; ++CurP, ++SuperP) { 5974 // Make sure the parameter types are compatible. 5975 if (!S.Context.hasSameUnqualifiedType((*CurP)->getType(), 5976 (*SuperP)->getType())) 5977 return nullptr; 5978 5979 // Make sure we have a parameter name to forward! 5980 if (!(*CurP)->getIdentifier()) 5981 return nullptr; 5982 } 5983 5984 // We have a superclass method. Now, form the send-to-super completion. 5985 CodeCompletionBuilder Builder(Results.getAllocator(), 5986 Results.getCodeCompletionTUInfo()); 5987 5988 // Give this completion a return type. 5989 AddResultTypeChunk(S.Context, getCompletionPrintingPolicy(S), SuperMethod, 5990 Results.getCompletionContext().getBaseType(), 5991 Builder); 5992 5993 // If we need the "super" keyword, add it (plus some spacing). 5994 if (NeedSuperKeyword) { 5995 Builder.AddTypedTextChunk("super"); 5996 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 5997 } 5998 5999 Selector Sel = CurMethod->getSelector(); 6000 if (Sel.isUnarySelector()) { 6001 if (NeedSuperKeyword) 6002 Builder.AddTextChunk(Builder.getAllocator().CopyString( 6003 Sel.getNameForSlot(0))); 6004 else 6005 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString( 6006 Sel.getNameForSlot(0))); 6007 } else { 6008 ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin(); 6009 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I, ++CurP) { 6010 if (I > SelIdents.size()) 6011 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 6012 6013 if (I < SelIdents.size()) 6014 Builder.AddInformativeChunk( 6015 Builder.getAllocator().CopyString( 6016 Sel.getNameForSlot(I) + ":")); 6017 else if (NeedSuperKeyword || I > SelIdents.size()) { 6018 Builder.AddTextChunk( 6019 Builder.getAllocator().CopyString( 6020 Sel.getNameForSlot(I) + ":")); 6021 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString( 6022 (*CurP)->getIdentifier()->getName())); 6023 } else { 6024 Builder.AddTypedTextChunk( 6025 Builder.getAllocator().CopyString( 6026 Sel.getNameForSlot(I) + ":")); 6027 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString( 6028 (*CurP)->getIdentifier()->getName())); 6029 } 6030 } 6031 } 6032 6033 Results.AddResult(CodeCompletionResult(Builder.TakeString(), SuperMethod, 6034 CCP_SuperCompletion)); 6035 return SuperMethod; 6036 } 6037 6038 void Sema::CodeCompleteObjCMessageReceiver(Scope *S) { 6039 typedef CodeCompletionResult Result; 6040 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 6041 CodeCompleter->getCodeCompletionTUInfo(), 6042 CodeCompletionContext::CCC_ObjCMessageReceiver, 6043 getLangOpts().CPlusPlus11 6044 ? &ResultBuilder::IsObjCMessageReceiverOrLambdaCapture 6045 : &ResultBuilder::IsObjCMessageReceiver); 6046 6047 CodeCompletionDeclConsumer Consumer(Results, CurContext); 6048 Results.EnterNewScope(); 6049 LookupVisibleDecls(S, LookupOrdinaryName, Consumer, 6050 CodeCompleter->includeGlobals(), 6051 CodeCompleter->loadExternal()); 6052 6053 // If we are in an Objective-C method inside a class that has a superclass, 6054 // add "super" as an option. 6055 if (ObjCMethodDecl *Method = getCurMethodDecl()) 6056 if (ObjCInterfaceDecl *Iface = Method->getClassInterface()) 6057 if (Iface->getSuperClass()) { 6058 Results.AddResult(Result("super")); 6059 6060 AddSuperSendCompletion(*this, /*NeedSuperKeyword=*/true, None, Results); 6061 } 6062 6063 if (getLangOpts().CPlusPlus11) 6064 addThisCompletion(*this, Results); 6065 6066 Results.ExitScope(); 6067 6068 if (CodeCompleter->includeMacros()) 6069 AddMacroResults(PP, Results, CodeCompleter->loadExternal(), false); 6070 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 6071 Results.data(), Results.size()); 6072 } 6073 6074 void Sema::CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc, 6075 ArrayRef<IdentifierInfo *> SelIdents, 6076 bool AtArgumentExpression) { 6077 ObjCInterfaceDecl *CDecl = nullptr; 6078 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) { 6079 // Figure out which interface we're in. 6080 CDecl = CurMethod->getClassInterface(); 6081 if (!CDecl) 6082 return; 6083 6084 // Find the superclass of this class. 6085 CDecl = CDecl->getSuperClass(); 6086 if (!CDecl) 6087 return; 6088 6089 if (CurMethod->isInstanceMethod()) { 6090 // We are inside an instance method, which means that the message 6091 // send [super ...] is actually calling an instance method on the 6092 // current object. 6093 return CodeCompleteObjCInstanceMessage(S, nullptr, SelIdents, 6094 AtArgumentExpression, 6095 CDecl); 6096 } 6097 6098 // Fall through to send to the superclass in CDecl. 6099 } else { 6100 // "super" may be the name of a type or variable. Figure out which 6101 // it is. 6102 IdentifierInfo *Super = getSuperIdentifier(); 6103 NamedDecl *ND = LookupSingleName(S, Super, SuperLoc, 6104 LookupOrdinaryName); 6105 if ((CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(ND))) { 6106 // "super" names an interface. Use it. 6107 } else if (TypeDecl *TD = dyn_cast_or_null<TypeDecl>(ND)) { 6108 if (const ObjCObjectType *Iface 6109 = Context.getTypeDeclType(TD)->getAs<ObjCObjectType>()) 6110 CDecl = Iface->getInterface(); 6111 } else if (ND && isa<UnresolvedUsingTypenameDecl>(ND)) { 6112 // "super" names an unresolved type; we can't be more specific. 6113 } else { 6114 // Assume that "super" names some kind of value and parse that way. 6115 CXXScopeSpec SS; 6116 SourceLocation TemplateKWLoc; 6117 UnqualifiedId id; 6118 id.setIdentifier(Super, SuperLoc); 6119 ExprResult SuperExpr = ActOnIdExpression(S, SS, TemplateKWLoc, id, 6120 false, false); 6121 return CodeCompleteObjCInstanceMessage(S, (Expr *)SuperExpr.get(), 6122 SelIdents, 6123 AtArgumentExpression); 6124 } 6125 6126 // Fall through 6127 } 6128 6129 ParsedType Receiver; 6130 if (CDecl) 6131 Receiver = ParsedType::make(Context.getObjCInterfaceType(CDecl)); 6132 return CodeCompleteObjCClassMessage(S, Receiver, SelIdents, 6133 AtArgumentExpression, 6134 /*IsSuper=*/true); 6135 } 6136 6137 /// Given a set of code-completion results for the argument of a message 6138 /// send, determine the preferred type (if any) for that argument expression. 6139 static QualType getPreferredArgumentTypeForMessageSend(ResultBuilder &Results, 6140 unsigned NumSelIdents) { 6141 typedef CodeCompletionResult Result; 6142 ASTContext &Context = Results.getSema().Context; 6143 6144 QualType PreferredType; 6145 unsigned BestPriority = CCP_Unlikely * 2; 6146 Result *ResultsData = Results.data(); 6147 for (unsigned I = 0, N = Results.size(); I != N; ++I) { 6148 Result &R = ResultsData[I]; 6149 if (R.Kind == Result::RK_Declaration && 6150 isa<ObjCMethodDecl>(R.Declaration)) { 6151 if (R.Priority <= BestPriority) { 6152 const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(R.Declaration); 6153 if (NumSelIdents <= Method->param_size()) { 6154 QualType MyPreferredType = Method->parameters()[NumSelIdents - 1] 6155 ->getType(); 6156 if (R.Priority < BestPriority || PreferredType.isNull()) { 6157 BestPriority = R.Priority; 6158 PreferredType = MyPreferredType; 6159 } else if (!Context.hasSameUnqualifiedType(PreferredType, 6160 MyPreferredType)) { 6161 PreferredType = QualType(); 6162 } 6163 } 6164 } 6165 } 6166 } 6167 6168 return PreferredType; 6169 } 6170 6171 static void AddClassMessageCompletions(Sema &SemaRef, Scope *S, 6172 ParsedType Receiver, 6173 ArrayRef<IdentifierInfo *> SelIdents, 6174 bool AtArgumentExpression, 6175 bool IsSuper, 6176 ResultBuilder &Results) { 6177 typedef CodeCompletionResult Result; 6178 ObjCInterfaceDecl *CDecl = nullptr; 6179 6180 // If the given name refers to an interface type, retrieve the 6181 // corresponding declaration. 6182 if (Receiver) { 6183 QualType T = SemaRef.GetTypeFromParser(Receiver, nullptr); 6184 if (!T.isNull()) 6185 if (const ObjCObjectType *Interface = T->getAs<ObjCObjectType>()) 6186 CDecl = Interface->getInterface(); 6187 } 6188 6189 // Add all of the factory methods in this Objective-C class, its protocols, 6190 // superclasses, categories, implementation, etc. 6191 Results.EnterNewScope(); 6192 6193 // If this is a send-to-super, try to add the special "super" send 6194 // completion. 6195 if (IsSuper) { 6196 if (ObjCMethodDecl *SuperMethod 6197 = AddSuperSendCompletion(SemaRef, false, SelIdents, Results)) 6198 Results.Ignore(SuperMethod); 6199 } 6200 6201 // If we're inside an Objective-C method definition, prefer its selector to 6202 // others. 6203 if (ObjCMethodDecl *CurMethod = SemaRef.getCurMethodDecl()) 6204 Results.setPreferredSelector(CurMethod->getSelector()); 6205 6206 VisitedSelectorSet Selectors; 6207 if (CDecl) 6208 AddObjCMethods(CDecl, false, MK_Any, SelIdents, 6209 SemaRef.CurContext, Selectors, AtArgumentExpression, 6210 Results); 6211 else { 6212 // We're messaging "id" as a type; provide all class/factory methods. 6213 6214 // If we have an external source, load the entire class method 6215 // pool from the AST file. 6216 if (SemaRef.getExternalSource()) { 6217 for (uint32_t I = 0, 6218 N = SemaRef.getExternalSource()->GetNumExternalSelectors(); 6219 I != N; ++I) { 6220 Selector Sel = SemaRef.getExternalSource()->GetExternalSelector(I); 6221 if (Sel.isNull() || SemaRef.MethodPool.count(Sel)) 6222 continue; 6223 6224 SemaRef.ReadMethodPool(Sel); 6225 } 6226 } 6227 6228 for (Sema::GlobalMethodPool::iterator M = SemaRef.MethodPool.begin(), 6229 MEnd = SemaRef.MethodPool.end(); 6230 M != MEnd; ++M) { 6231 for (ObjCMethodList *MethList = &M->second.second; 6232 MethList && MethList->getMethod(); 6233 MethList = MethList->getNext()) { 6234 if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents)) 6235 continue; 6236 6237 Result R(MethList->getMethod(), 6238 Results.getBasePriority(MethList->getMethod()), nullptr); 6239 R.StartParameter = SelIdents.size(); 6240 R.AllParametersAreInformative = false; 6241 Results.MaybeAddResult(R, SemaRef.CurContext); 6242 } 6243 } 6244 } 6245 6246 Results.ExitScope(); 6247 } 6248 6249 void Sema::CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver, 6250 ArrayRef<IdentifierInfo *> SelIdents, 6251 bool AtArgumentExpression, 6252 bool IsSuper) { 6253 6254 QualType T = this->GetTypeFromParser(Receiver); 6255 6256 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 6257 CodeCompleter->getCodeCompletionTUInfo(), 6258 CodeCompletionContext(CodeCompletionContext::CCC_ObjCClassMessage, 6259 T, SelIdents)); 6260 6261 AddClassMessageCompletions(*this, S, Receiver, SelIdents, 6262 AtArgumentExpression, IsSuper, Results); 6263 6264 // If we're actually at the argument expression (rather than prior to the 6265 // selector), we're actually performing code completion for an expression. 6266 // Determine whether we have a single, best method. If so, we can 6267 // code-complete the expression using the corresponding parameter type as 6268 // our preferred type, improving completion results. 6269 if (AtArgumentExpression) { 6270 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results, 6271 SelIdents.size()); 6272 if (PreferredType.isNull()) 6273 CodeCompleteOrdinaryName(S, PCC_Expression); 6274 else 6275 CodeCompleteExpression(S, PreferredType); 6276 return; 6277 } 6278 6279 HandleCodeCompleteResults(this, CodeCompleter, 6280 Results.getCompletionContext(), 6281 Results.data(), Results.size()); 6282 } 6283 6284 void Sema::CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver, 6285 ArrayRef<IdentifierInfo *> SelIdents, 6286 bool AtArgumentExpression, 6287 ObjCInterfaceDecl *Super) { 6288 typedef CodeCompletionResult Result; 6289 6290 Expr *RecExpr = static_cast<Expr *>(Receiver); 6291 6292 // If necessary, apply function/array conversion to the receiver. 6293 // C99 6.7.5.3p[7,8]. 6294 if (RecExpr) { 6295 ExprResult Conv = DefaultFunctionArrayLvalueConversion(RecExpr); 6296 if (Conv.isInvalid()) // conversion failed. bail. 6297 return; 6298 RecExpr = Conv.get(); 6299 } 6300 QualType ReceiverType = RecExpr? RecExpr->getType() 6301 : Super? Context.getObjCObjectPointerType( 6302 Context.getObjCInterfaceType(Super)) 6303 : Context.getObjCIdType(); 6304 6305 // If we're messaging an expression with type "id" or "Class", check 6306 // whether we know something special about the receiver that allows 6307 // us to assume a more-specific receiver type. 6308 if (ReceiverType->isObjCIdType() || ReceiverType->isObjCClassType()) { 6309 if (ObjCInterfaceDecl *IFace = GetAssumedMessageSendExprType(RecExpr)) { 6310 if (ReceiverType->isObjCClassType()) 6311 return CodeCompleteObjCClassMessage(S, 6312 ParsedType::make(Context.getObjCInterfaceType(IFace)), 6313 SelIdents, 6314 AtArgumentExpression, Super); 6315 6316 ReceiverType = Context.getObjCObjectPointerType( 6317 Context.getObjCInterfaceType(IFace)); 6318 } 6319 } else if (RecExpr && getLangOpts().CPlusPlus) { 6320 ExprResult Conv = PerformContextuallyConvertToObjCPointer(RecExpr); 6321 if (Conv.isUsable()) { 6322 RecExpr = Conv.get(); 6323 ReceiverType = RecExpr->getType(); 6324 } 6325 } 6326 6327 // Build the set of methods we can see. 6328 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 6329 CodeCompleter->getCodeCompletionTUInfo(), 6330 CodeCompletionContext(CodeCompletionContext::CCC_ObjCInstanceMessage, 6331 ReceiverType, SelIdents)); 6332 6333 Results.EnterNewScope(); 6334 6335 // If this is a send-to-super, try to add the special "super" send 6336 // completion. 6337 if (Super) { 6338 if (ObjCMethodDecl *SuperMethod 6339 = AddSuperSendCompletion(*this, false, SelIdents, Results)) 6340 Results.Ignore(SuperMethod); 6341 } 6342 6343 // If we're inside an Objective-C method definition, prefer its selector to 6344 // others. 6345 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) 6346 Results.setPreferredSelector(CurMethod->getSelector()); 6347 6348 // Keep track of the selectors we've already added. 6349 VisitedSelectorSet Selectors; 6350 6351 // Handle messages to Class. This really isn't a message to an instance 6352 // method, so we treat it the same way we would treat a message send to a 6353 // class method. 6354 if (ReceiverType->isObjCClassType() || 6355 ReceiverType->isObjCQualifiedClassType()) { 6356 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) { 6357 if (ObjCInterfaceDecl *ClassDecl = CurMethod->getClassInterface()) 6358 AddObjCMethods(ClassDecl, false, MK_Any, SelIdents, 6359 CurContext, Selectors, AtArgumentExpression, Results); 6360 } 6361 } 6362 // Handle messages to a qualified ID ("id<foo>"). 6363 else if (const ObjCObjectPointerType *QualID 6364 = ReceiverType->getAsObjCQualifiedIdType()) { 6365 // Search protocols for instance methods. 6366 for (auto *I : QualID->quals()) 6367 AddObjCMethods(I, true, MK_Any, SelIdents, CurContext, 6368 Selectors, AtArgumentExpression, Results); 6369 } 6370 // Handle messages to a pointer to interface type. 6371 else if (const ObjCObjectPointerType *IFacePtr 6372 = ReceiverType->getAsObjCInterfacePointerType()) { 6373 // Search the class, its superclasses, etc., for instance methods. 6374 AddObjCMethods(IFacePtr->getInterfaceDecl(), true, MK_Any, SelIdents, 6375 CurContext, Selectors, AtArgumentExpression, 6376 Results); 6377 6378 // Search protocols for instance methods. 6379 for (auto *I : IFacePtr->quals()) 6380 AddObjCMethods(I, true, MK_Any, SelIdents, CurContext, 6381 Selectors, AtArgumentExpression, Results); 6382 } 6383 // Handle messages to "id". 6384 else if (ReceiverType->isObjCIdType()) { 6385 // We're messaging "id", so provide all instance methods we know 6386 // about as code-completion results. 6387 6388 // If we have an external source, load the entire class method 6389 // pool from the AST file. 6390 if (ExternalSource) { 6391 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors(); 6392 I != N; ++I) { 6393 Selector Sel = ExternalSource->GetExternalSelector(I); 6394 if (Sel.isNull() || MethodPool.count(Sel)) 6395 continue; 6396 6397 ReadMethodPool(Sel); 6398 } 6399 } 6400 6401 for (GlobalMethodPool::iterator M = MethodPool.begin(), 6402 MEnd = MethodPool.end(); 6403 M != MEnd; ++M) { 6404 for (ObjCMethodList *MethList = &M->second.first; 6405 MethList && MethList->getMethod(); 6406 MethList = MethList->getNext()) { 6407 if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents)) 6408 continue; 6409 6410 if (!Selectors.insert(MethList->getMethod()->getSelector()).second) 6411 continue; 6412 6413 Result R(MethList->getMethod(), 6414 Results.getBasePriority(MethList->getMethod()), nullptr); 6415 R.StartParameter = SelIdents.size(); 6416 R.AllParametersAreInformative = false; 6417 Results.MaybeAddResult(R, CurContext); 6418 } 6419 } 6420 } 6421 Results.ExitScope(); 6422 6423 6424 // If we're actually at the argument expression (rather than prior to the 6425 // selector), we're actually performing code completion for an expression. 6426 // Determine whether we have a single, best method. If so, we can 6427 // code-complete the expression using the corresponding parameter type as 6428 // our preferred type, improving completion results. 6429 if (AtArgumentExpression) { 6430 QualType PreferredType = getPreferredArgumentTypeForMessageSend(Results, 6431 SelIdents.size()); 6432 if (PreferredType.isNull()) 6433 CodeCompleteOrdinaryName(S, PCC_Expression); 6434 else 6435 CodeCompleteExpression(S, PreferredType); 6436 return; 6437 } 6438 6439 HandleCodeCompleteResults(this, CodeCompleter, 6440 Results.getCompletionContext(), 6441 Results.data(),Results.size()); 6442 } 6443 6444 void Sema::CodeCompleteObjCForCollection(Scope *S, 6445 DeclGroupPtrTy IterationVar) { 6446 CodeCompleteExpressionData Data; 6447 Data.ObjCCollection = true; 6448 6449 if (IterationVar.getAsOpaquePtr()) { 6450 DeclGroupRef DG = IterationVar.get(); 6451 for (DeclGroupRef::iterator I = DG.begin(), End = DG.end(); I != End; ++I) { 6452 if (*I) 6453 Data.IgnoreDecls.push_back(*I); 6454 } 6455 } 6456 6457 CodeCompleteExpression(S, Data); 6458 } 6459 6460 void Sema::CodeCompleteObjCSelector(Scope *S, 6461 ArrayRef<IdentifierInfo *> SelIdents) { 6462 // If we have an external source, load the entire class method 6463 // pool from the AST file. 6464 if (ExternalSource) { 6465 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors(); 6466 I != N; ++I) { 6467 Selector Sel = ExternalSource->GetExternalSelector(I); 6468 if (Sel.isNull() || MethodPool.count(Sel)) 6469 continue; 6470 6471 ReadMethodPool(Sel); 6472 } 6473 } 6474 6475 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 6476 CodeCompleter->getCodeCompletionTUInfo(), 6477 CodeCompletionContext::CCC_SelectorName); 6478 Results.EnterNewScope(); 6479 for (GlobalMethodPool::iterator M = MethodPool.begin(), 6480 MEnd = MethodPool.end(); 6481 M != MEnd; ++M) { 6482 6483 Selector Sel = M->first; 6484 if (!isAcceptableObjCSelector(Sel, MK_Any, SelIdents)) 6485 continue; 6486 6487 CodeCompletionBuilder Builder(Results.getAllocator(), 6488 Results.getCodeCompletionTUInfo()); 6489 if (Sel.isUnarySelector()) { 6490 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString( 6491 Sel.getNameForSlot(0))); 6492 Results.AddResult(Builder.TakeString()); 6493 continue; 6494 } 6495 6496 std::string Accumulator; 6497 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I) { 6498 if (I == SelIdents.size()) { 6499 if (!Accumulator.empty()) { 6500 Builder.AddInformativeChunk(Builder.getAllocator().CopyString( 6501 Accumulator)); 6502 Accumulator.clear(); 6503 } 6504 } 6505 6506 Accumulator += Sel.getNameForSlot(I); 6507 Accumulator += ':'; 6508 } 6509 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString( Accumulator)); 6510 Results.AddResult(Builder.TakeString()); 6511 } 6512 Results.ExitScope(); 6513 6514 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 6515 Results.data(), Results.size()); 6516 } 6517 6518 /// Add all of the protocol declarations that we find in the given 6519 /// (translation unit) context. 6520 static void AddProtocolResults(DeclContext *Ctx, DeclContext *CurContext, 6521 bool OnlyForwardDeclarations, 6522 ResultBuilder &Results) { 6523 typedef CodeCompletionResult Result; 6524 6525 for (const auto *D : Ctx->decls()) { 6526 // Record any protocols we find. 6527 if (const auto *Proto = dyn_cast<ObjCProtocolDecl>(D)) 6528 if (!OnlyForwardDeclarations || !Proto->hasDefinition()) 6529 Results.AddResult(Result(Proto, Results.getBasePriority(Proto),nullptr), 6530 CurContext, nullptr, false); 6531 } 6532 } 6533 6534 void Sema::CodeCompleteObjCProtocolReferences( 6535 ArrayRef<IdentifierLocPair> Protocols) { 6536 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 6537 CodeCompleter->getCodeCompletionTUInfo(), 6538 CodeCompletionContext::CCC_ObjCProtocolName); 6539 6540 if (CodeCompleter->includeGlobals()) { 6541 Results.EnterNewScope(); 6542 6543 // Tell the result set to ignore all of the protocols we have 6544 // already seen. 6545 // FIXME: This doesn't work when caching code-completion results. 6546 for (const IdentifierLocPair &Pair : Protocols) 6547 if (ObjCProtocolDecl *Protocol = LookupProtocol(Pair.first, 6548 Pair.second)) 6549 Results.Ignore(Protocol); 6550 6551 // Add all protocols. 6552 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, false, 6553 Results); 6554 6555 Results.ExitScope(); 6556 } 6557 6558 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 6559 Results.data(), Results.size()); 6560 } 6561 6562 void Sema::CodeCompleteObjCProtocolDecl(Scope *) { 6563 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 6564 CodeCompleter->getCodeCompletionTUInfo(), 6565 CodeCompletionContext::CCC_ObjCProtocolName); 6566 6567 if (CodeCompleter->includeGlobals()) { 6568 Results.EnterNewScope(); 6569 6570 // Add all protocols. 6571 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, true, 6572 Results); 6573 6574 Results.ExitScope(); 6575 } 6576 6577 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 6578 Results.data(), Results.size()); 6579 } 6580 6581 /// Add all of the Objective-C interface declarations that we find in 6582 /// the given (translation unit) context. 6583 static void AddInterfaceResults(DeclContext *Ctx, DeclContext *CurContext, 6584 bool OnlyForwardDeclarations, 6585 bool OnlyUnimplemented, 6586 ResultBuilder &Results) { 6587 typedef CodeCompletionResult Result; 6588 6589 for (const auto *D : Ctx->decls()) { 6590 // Record any interfaces we find. 6591 if (const auto *Class = dyn_cast<ObjCInterfaceDecl>(D)) 6592 if ((!OnlyForwardDeclarations || !Class->hasDefinition()) && 6593 (!OnlyUnimplemented || !Class->getImplementation())) 6594 Results.AddResult(Result(Class, Results.getBasePriority(Class),nullptr), 6595 CurContext, nullptr, false); 6596 } 6597 } 6598 6599 void Sema::CodeCompleteObjCInterfaceDecl(Scope *S) { 6600 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 6601 CodeCompleter->getCodeCompletionTUInfo(), 6602 CodeCompletionContext::CCC_ObjCInterfaceName); 6603 Results.EnterNewScope(); 6604 6605 if (CodeCompleter->includeGlobals()) { 6606 // Add all classes. 6607 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false, 6608 false, Results); 6609 } 6610 6611 Results.ExitScope(); 6612 6613 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 6614 Results.data(), Results.size()); 6615 } 6616 6617 void Sema::CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName, 6618 SourceLocation ClassNameLoc) { 6619 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 6620 CodeCompleter->getCodeCompletionTUInfo(), 6621 CodeCompletionContext::CCC_ObjCInterfaceName); 6622 Results.EnterNewScope(); 6623 6624 // Make sure that we ignore the class we're currently defining. 6625 NamedDecl *CurClass 6626 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName); 6627 if (CurClass && isa<ObjCInterfaceDecl>(CurClass)) 6628 Results.Ignore(CurClass); 6629 6630 if (CodeCompleter->includeGlobals()) { 6631 // Add all classes. 6632 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false, 6633 false, Results); 6634 } 6635 6636 Results.ExitScope(); 6637 6638 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 6639 Results.data(), Results.size()); 6640 } 6641 6642 void Sema::CodeCompleteObjCImplementationDecl(Scope *S) { 6643 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 6644 CodeCompleter->getCodeCompletionTUInfo(), 6645 CodeCompletionContext::CCC_ObjCImplementation); 6646 Results.EnterNewScope(); 6647 6648 if (CodeCompleter->includeGlobals()) { 6649 // Add all unimplemented classes. 6650 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false, 6651 true, Results); 6652 } 6653 6654 Results.ExitScope(); 6655 6656 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 6657 Results.data(), Results.size()); 6658 } 6659 6660 void Sema::CodeCompleteObjCInterfaceCategory(Scope *S, 6661 IdentifierInfo *ClassName, 6662 SourceLocation ClassNameLoc) { 6663 typedef CodeCompletionResult Result; 6664 6665 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 6666 CodeCompleter->getCodeCompletionTUInfo(), 6667 CodeCompletionContext::CCC_ObjCCategoryName); 6668 6669 // Ignore any categories we find that have already been implemented by this 6670 // interface. 6671 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames; 6672 NamedDecl *CurClass 6673 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName); 6674 if (ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass)){ 6675 for (const auto *Cat : Class->visible_categories()) 6676 CategoryNames.insert(Cat->getIdentifier()); 6677 } 6678 6679 // Add all of the categories we know about. 6680 Results.EnterNewScope(); 6681 TranslationUnitDecl *TU = Context.getTranslationUnitDecl(); 6682 for (const auto *D : TU->decls()) 6683 if (const auto *Category = dyn_cast<ObjCCategoryDecl>(D)) 6684 if (CategoryNames.insert(Category->getIdentifier()).second) 6685 Results.AddResult(Result(Category, Results.getBasePriority(Category), 6686 nullptr), 6687 CurContext, nullptr, false); 6688 Results.ExitScope(); 6689 6690 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 6691 Results.data(), Results.size()); 6692 } 6693 6694 void Sema::CodeCompleteObjCImplementationCategory(Scope *S, 6695 IdentifierInfo *ClassName, 6696 SourceLocation ClassNameLoc) { 6697 typedef CodeCompletionResult Result; 6698 6699 // Find the corresponding interface. If we couldn't find the interface, the 6700 // program itself is ill-formed. However, we'll try to be helpful still by 6701 // providing the list of all of the categories we know about. 6702 NamedDecl *CurClass 6703 = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName); 6704 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass); 6705 if (!Class) 6706 return CodeCompleteObjCInterfaceCategory(S, ClassName, ClassNameLoc); 6707 6708 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 6709 CodeCompleter->getCodeCompletionTUInfo(), 6710 CodeCompletionContext::CCC_ObjCCategoryName); 6711 6712 // Add all of the categories that have have corresponding interface 6713 // declarations in this class and any of its superclasses, except for 6714 // already-implemented categories in the class itself. 6715 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames; 6716 Results.EnterNewScope(); 6717 bool IgnoreImplemented = true; 6718 while (Class) { 6719 for (const auto *Cat : Class->visible_categories()) { 6720 if ((!IgnoreImplemented || !Cat->getImplementation()) && 6721 CategoryNames.insert(Cat->getIdentifier()).second) 6722 Results.AddResult(Result(Cat, Results.getBasePriority(Cat), nullptr), 6723 CurContext, nullptr, false); 6724 } 6725 6726 Class = Class->getSuperClass(); 6727 IgnoreImplemented = false; 6728 } 6729 Results.ExitScope(); 6730 6731 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 6732 Results.data(), Results.size()); 6733 } 6734 6735 void Sema::CodeCompleteObjCPropertyDefinition(Scope *S) { 6736 CodeCompletionContext CCContext(CodeCompletionContext::CCC_Other); 6737 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 6738 CodeCompleter->getCodeCompletionTUInfo(), 6739 CCContext); 6740 6741 // Figure out where this @synthesize lives. 6742 ObjCContainerDecl *Container 6743 = dyn_cast_or_null<ObjCContainerDecl>(CurContext); 6744 if (!Container || 6745 (!isa<ObjCImplementationDecl>(Container) && 6746 !isa<ObjCCategoryImplDecl>(Container))) 6747 return; 6748 6749 // Ignore any properties that have already been implemented. 6750 Container = getContainerDef(Container); 6751 for (const auto *D : Container->decls()) 6752 if (const auto *PropertyImpl = dyn_cast<ObjCPropertyImplDecl>(D)) 6753 Results.Ignore(PropertyImpl->getPropertyDecl()); 6754 6755 // Add any properties that we find. 6756 AddedPropertiesSet AddedProperties; 6757 Results.EnterNewScope(); 6758 if (ObjCImplementationDecl *ClassImpl 6759 = dyn_cast<ObjCImplementationDecl>(Container)) 6760 AddObjCProperties(CCContext, ClassImpl->getClassInterface(), false, 6761 /*AllowNullaryMethods=*/false, CurContext, 6762 AddedProperties, Results); 6763 else 6764 AddObjCProperties(CCContext, 6765 cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl(), 6766 false, /*AllowNullaryMethods=*/false, CurContext, 6767 AddedProperties, Results); 6768 Results.ExitScope(); 6769 6770 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 6771 Results.data(), Results.size()); 6772 } 6773 6774 void Sema::CodeCompleteObjCPropertySynthesizeIvar(Scope *S, 6775 IdentifierInfo *PropertyName) { 6776 typedef CodeCompletionResult Result; 6777 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 6778 CodeCompleter->getCodeCompletionTUInfo(), 6779 CodeCompletionContext::CCC_Other); 6780 6781 // Figure out where this @synthesize lives. 6782 ObjCContainerDecl *Container 6783 = dyn_cast_or_null<ObjCContainerDecl>(CurContext); 6784 if (!Container || 6785 (!isa<ObjCImplementationDecl>(Container) && 6786 !isa<ObjCCategoryImplDecl>(Container))) 6787 return; 6788 6789 // Figure out which interface we're looking into. 6790 ObjCInterfaceDecl *Class = nullptr; 6791 if (ObjCImplementationDecl *ClassImpl 6792 = dyn_cast<ObjCImplementationDecl>(Container)) 6793 Class = ClassImpl->getClassInterface(); 6794 else 6795 Class = cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl() 6796 ->getClassInterface(); 6797 6798 // Determine the type of the property we're synthesizing. 6799 QualType PropertyType = Context.getObjCIdType(); 6800 if (Class) { 6801 if (ObjCPropertyDecl *Property = Class->FindPropertyDeclaration( 6802 PropertyName, ObjCPropertyQueryKind::OBJC_PR_query_instance)) { 6803 PropertyType 6804 = Property->getType().getNonReferenceType().getUnqualifiedType(); 6805 6806 // Give preference to ivars 6807 Results.setPreferredType(PropertyType); 6808 } 6809 } 6810 6811 // Add all of the instance variables in this class and its superclasses. 6812 Results.EnterNewScope(); 6813 bool SawSimilarlyNamedIvar = false; 6814 std::string NameWithPrefix; 6815 NameWithPrefix += '_'; 6816 NameWithPrefix += PropertyName->getName(); 6817 std::string NameWithSuffix = PropertyName->getName().str(); 6818 NameWithSuffix += '_'; 6819 for(; Class; Class = Class->getSuperClass()) { 6820 for (ObjCIvarDecl *Ivar = Class->all_declared_ivar_begin(); Ivar; 6821 Ivar = Ivar->getNextIvar()) { 6822 Results.AddResult(Result(Ivar, Results.getBasePriority(Ivar), nullptr), 6823 CurContext, nullptr, false); 6824 6825 // Determine whether we've seen an ivar with a name similar to the 6826 // property. 6827 if ((PropertyName == Ivar->getIdentifier() || 6828 NameWithPrefix == Ivar->getName() || 6829 NameWithSuffix == Ivar->getName())) { 6830 SawSimilarlyNamedIvar = true; 6831 6832 // Reduce the priority of this result by one, to give it a slight 6833 // advantage over other results whose names don't match so closely. 6834 if (Results.size() && 6835 Results.data()[Results.size() - 1].Kind 6836 == CodeCompletionResult::RK_Declaration && 6837 Results.data()[Results.size() - 1].Declaration == Ivar) 6838 Results.data()[Results.size() - 1].Priority--; 6839 } 6840 } 6841 } 6842 6843 if (!SawSimilarlyNamedIvar) { 6844 // Create ivar result _propName, that the user can use to synthesize 6845 // an ivar of the appropriate type. 6846 unsigned Priority = CCP_MemberDeclaration + 1; 6847 typedef CodeCompletionResult Result; 6848 CodeCompletionAllocator &Allocator = Results.getAllocator(); 6849 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo(), 6850 Priority,CXAvailability_Available); 6851 6852 PrintingPolicy Policy = getCompletionPrintingPolicy(*this); 6853 Builder.AddResultTypeChunk(GetCompletionTypeString(PropertyType, Context, 6854 Policy, Allocator)); 6855 Builder.AddTypedTextChunk(Allocator.CopyString(NameWithPrefix)); 6856 Results.AddResult(Result(Builder.TakeString(), Priority, 6857 CXCursor_ObjCIvarDecl)); 6858 } 6859 6860 Results.ExitScope(); 6861 6862 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 6863 Results.data(), Results.size()); 6864 } 6865 6866 // Mapping from selectors to the methods that implement that selector, along 6867 // with the "in original class" flag. 6868 typedef llvm::DenseMap< 6869 Selector, llvm::PointerIntPair<ObjCMethodDecl *, 1, bool> > KnownMethodsMap; 6870 6871 /// Find all of the methods that reside in the given container 6872 /// (and its superclasses, protocols, etc.) that meet the given 6873 /// criteria. Insert those methods into the map of known methods, 6874 /// indexed by selector so they can be easily found. 6875 static void FindImplementableMethods(ASTContext &Context, 6876 ObjCContainerDecl *Container, 6877 Optional<bool> WantInstanceMethods, 6878 QualType ReturnType, 6879 KnownMethodsMap &KnownMethods, 6880 bool InOriginalClass = true) { 6881 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)) { 6882 // Make sure we have a definition; that's what we'll walk. 6883 if (!IFace->hasDefinition()) 6884 return; 6885 6886 IFace = IFace->getDefinition(); 6887 Container = IFace; 6888 6889 const ObjCList<ObjCProtocolDecl> &Protocols 6890 = IFace->getReferencedProtocols(); 6891 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(), 6892 E = Protocols.end(); 6893 I != E; ++I) 6894 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType, 6895 KnownMethods, InOriginalClass); 6896 6897 // Add methods from any class extensions and categories. 6898 for (auto *Cat : IFace->visible_categories()) { 6899 FindImplementableMethods(Context, Cat, WantInstanceMethods, ReturnType, 6900 KnownMethods, false); 6901 } 6902 6903 // Visit the superclass. 6904 if (IFace->getSuperClass()) 6905 FindImplementableMethods(Context, IFace->getSuperClass(), 6906 WantInstanceMethods, ReturnType, 6907 KnownMethods, false); 6908 } 6909 6910 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) { 6911 // Recurse into protocols. 6912 const ObjCList<ObjCProtocolDecl> &Protocols 6913 = Category->getReferencedProtocols(); 6914 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(), 6915 E = Protocols.end(); 6916 I != E; ++I) 6917 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType, 6918 KnownMethods, InOriginalClass); 6919 6920 // If this category is the original class, jump to the interface. 6921 if (InOriginalClass && Category->getClassInterface()) 6922 FindImplementableMethods(Context, Category->getClassInterface(), 6923 WantInstanceMethods, ReturnType, KnownMethods, 6924 false); 6925 } 6926 6927 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) { 6928 // Make sure we have a definition; that's what we'll walk. 6929 if (!Protocol->hasDefinition()) 6930 return; 6931 Protocol = Protocol->getDefinition(); 6932 Container = Protocol; 6933 6934 // Recurse into protocols. 6935 const ObjCList<ObjCProtocolDecl> &Protocols 6936 = Protocol->getReferencedProtocols(); 6937 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(), 6938 E = Protocols.end(); 6939 I != E; ++I) 6940 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType, 6941 KnownMethods, false); 6942 } 6943 6944 // Add methods in this container. This operation occurs last because 6945 // we want the methods from this container to override any methods 6946 // we've previously seen with the same selector. 6947 for (auto *M : Container->methods()) { 6948 if (!WantInstanceMethods || M->isInstanceMethod() == *WantInstanceMethods) { 6949 if (!ReturnType.isNull() && 6950 !Context.hasSameUnqualifiedType(ReturnType, M->getReturnType())) 6951 continue; 6952 6953 KnownMethods[M->getSelector()] = 6954 KnownMethodsMap::mapped_type(M, InOriginalClass); 6955 } 6956 } 6957 } 6958 6959 /// Add the parenthesized return or parameter type chunk to a code 6960 /// completion string. 6961 static void AddObjCPassingTypeChunk(QualType Type, 6962 unsigned ObjCDeclQuals, 6963 ASTContext &Context, 6964 const PrintingPolicy &Policy, 6965 CodeCompletionBuilder &Builder) { 6966 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 6967 std::string Quals = formatObjCParamQualifiers(ObjCDeclQuals, Type); 6968 if (!Quals.empty()) 6969 Builder.AddTextChunk(Builder.getAllocator().CopyString(Quals)); 6970 Builder.AddTextChunk(GetCompletionTypeString(Type, Context, Policy, 6971 Builder.getAllocator())); 6972 Builder.AddChunk(CodeCompletionString::CK_RightParen); 6973 } 6974 6975 /// Determine whether the given class is or inherits from a class by 6976 /// the given name. 6977 static bool InheritsFromClassNamed(ObjCInterfaceDecl *Class, 6978 StringRef Name) { 6979 if (!Class) 6980 return false; 6981 6982 if (Class->getIdentifier() && Class->getIdentifier()->getName() == Name) 6983 return true; 6984 6985 return InheritsFromClassNamed(Class->getSuperClass(), Name); 6986 } 6987 6988 /// Add code completions for Objective-C Key-Value Coding (KVC) and 6989 /// Key-Value Observing (KVO). 6990 static void AddObjCKeyValueCompletions(ObjCPropertyDecl *Property, 6991 bool IsInstanceMethod, 6992 QualType ReturnType, 6993 ASTContext &Context, 6994 VisitedSelectorSet &KnownSelectors, 6995 ResultBuilder &Results) { 6996 IdentifierInfo *PropName = Property->getIdentifier(); 6997 if (!PropName || PropName->getLength() == 0) 6998 return; 6999 7000 PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema()); 7001 7002 // Builder that will create each code completion. 7003 typedef CodeCompletionResult Result; 7004 CodeCompletionAllocator &Allocator = Results.getAllocator(); 7005 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo()); 7006 7007 // The selector table. 7008 SelectorTable &Selectors = Context.Selectors; 7009 7010 // The property name, copied into the code completion allocation region 7011 // on demand. 7012 struct KeyHolder { 7013 CodeCompletionAllocator &Allocator; 7014 StringRef Key; 7015 const char *CopiedKey; 7016 7017 KeyHolder(CodeCompletionAllocator &Allocator, StringRef Key) 7018 : Allocator(Allocator), Key(Key), CopiedKey(nullptr) {} 7019 7020 operator const char *() { 7021 if (CopiedKey) 7022 return CopiedKey; 7023 7024 return CopiedKey = Allocator.CopyString(Key); 7025 } 7026 } Key(Allocator, PropName->getName()); 7027 7028 // The uppercased name of the property name. 7029 std::string UpperKey = PropName->getName(); 7030 if (!UpperKey.empty()) 7031 UpperKey[0] = toUppercase(UpperKey[0]); 7032 7033 bool ReturnTypeMatchesProperty = ReturnType.isNull() || 7034 Context.hasSameUnqualifiedType(ReturnType.getNonReferenceType(), 7035 Property->getType()); 7036 bool ReturnTypeMatchesVoid 7037 = ReturnType.isNull() || ReturnType->isVoidType(); 7038 7039 // Add the normal accessor -(type)key. 7040 if (IsInstanceMethod && 7041 KnownSelectors.insert(Selectors.getNullarySelector(PropName)).second && 7042 ReturnTypeMatchesProperty && !Property->getGetterMethodDecl()) { 7043 if (ReturnType.isNull()) 7044 AddObjCPassingTypeChunk(Property->getType(), /*Quals=*/0, 7045 Context, Policy, Builder); 7046 7047 Builder.AddTypedTextChunk(Key); 7048 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern, 7049 CXCursor_ObjCInstanceMethodDecl)); 7050 } 7051 7052 // If we have an integral or boolean property (or the user has provided 7053 // an integral or boolean return type), add the accessor -(type)isKey. 7054 if (IsInstanceMethod && 7055 ((!ReturnType.isNull() && 7056 (ReturnType->isIntegerType() || ReturnType->isBooleanType())) || 7057 (ReturnType.isNull() && 7058 (Property->getType()->isIntegerType() || 7059 Property->getType()->isBooleanType())))) { 7060 std::string SelectorName = (Twine("is") + UpperKey).str(); 7061 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 7062 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId)) 7063 .second) { 7064 if (ReturnType.isNull()) { 7065 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7066 Builder.AddTextChunk("BOOL"); 7067 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7068 } 7069 7070 Builder.AddTypedTextChunk( 7071 Allocator.CopyString(SelectorId->getName())); 7072 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern, 7073 CXCursor_ObjCInstanceMethodDecl)); 7074 } 7075 } 7076 7077 // Add the normal mutator. 7078 if (IsInstanceMethod && ReturnTypeMatchesVoid && 7079 !Property->getSetterMethodDecl()) { 7080 std::string SelectorName = (Twine("set") + UpperKey).str(); 7081 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 7082 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 7083 if (ReturnType.isNull()) { 7084 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7085 Builder.AddTextChunk("void"); 7086 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7087 } 7088 7089 Builder.AddTypedTextChunk( 7090 Allocator.CopyString(SelectorId->getName())); 7091 Builder.AddTypedTextChunk(":"); 7092 AddObjCPassingTypeChunk(Property->getType(), /*Quals=*/0, 7093 Context, Policy, Builder); 7094 Builder.AddTextChunk(Key); 7095 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern, 7096 CXCursor_ObjCInstanceMethodDecl)); 7097 } 7098 } 7099 7100 // Indexed and unordered accessors 7101 unsigned IndexedGetterPriority = CCP_CodePattern; 7102 unsigned IndexedSetterPriority = CCP_CodePattern; 7103 unsigned UnorderedGetterPriority = CCP_CodePattern; 7104 unsigned UnorderedSetterPriority = CCP_CodePattern; 7105 if (const ObjCObjectPointerType *ObjCPointer 7106 = Property->getType()->getAs<ObjCObjectPointerType>()) { 7107 if (ObjCInterfaceDecl *IFace = ObjCPointer->getInterfaceDecl()) { 7108 // If this interface type is not provably derived from a known 7109 // collection, penalize the corresponding completions. 7110 if (!InheritsFromClassNamed(IFace, "NSMutableArray")) { 7111 IndexedSetterPriority += CCD_ProbablyNotObjCCollection; 7112 if (!InheritsFromClassNamed(IFace, "NSArray")) 7113 IndexedGetterPriority += CCD_ProbablyNotObjCCollection; 7114 } 7115 7116 if (!InheritsFromClassNamed(IFace, "NSMutableSet")) { 7117 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection; 7118 if (!InheritsFromClassNamed(IFace, "NSSet")) 7119 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection; 7120 } 7121 } 7122 } else { 7123 IndexedGetterPriority += CCD_ProbablyNotObjCCollection; 7124 IndexedSetterPriority += CCD_ProbablyNotObjCCollection; 7125 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection; 7126 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection; 7127 } 7128 7129 // Add -(NSUInteger)countOf<key> 7130 if (IsInstanceMethod && 7131 (ReturnType.isNull() || ReturnType->isIntegerType())) { 7132 std::string SelectorName = (Twine("countOf") + UpperKey).str(); 7133 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 7134 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId)) 7135 .second) { 7136 if (ReturnType.isNull()) { 7137 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7138 Builder.AddTextChunk("NSUInteger"); 7139 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7140 } 7141 7142 Builder.AddTypedTextChunk( 7143 Allocator.CopyString(SelectorId->getName())); 7144 Results.AddResult(Result(Builder.TakeString(), 7145 std::min(IndexedGetterPriority, 7146 UnorderedGetterPriority), 7147 CXCursor_ObjCInstanceMethodDecl)); 7148 } 7149 } 7150 7151 // Indexed getters 7152 // Add -(id)objectInKeyAtIndex:(NSUInteger)index 7153 if (IsInstanceMethod && 7154 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) { 7155 std::string SelectorName 7156 = (Twine("objectIn") + UpperKey + "AtIndex").str(); 7157 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 7158 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 7159 if (ReturnType.isNull()) { 7160 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7161 Builder.AddTextChunk("id"); 7162 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7163 } 7164 7165 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 7166 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7167 Builder.AddTextChunk("NSUInteger"); 7168 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7169 Builder.AddTextChunk("index"); 7170 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority, 7171 CXCursor_ObjCInstanceMethodDecl)); 7172 } 7173 } 7174 7175 // Add -(NSArray *)keyAtIndexes:(NSIndexSet *)indexes 7176 if (IsInstanceMethod && 7177 (ReturnType.isNull() || 7178 (ReturnType->isObjCObjectPointerType() && 7179 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() && 7180 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() 7181 ->getName() == "NSArray"))) { 7182 std::string SelectorName 7183 = (Twine(Property->getName()) + "AtIndexes").str(); 7184 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 7185 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 7186 if (ReturnType.isNull()) { 7187 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7188 Builder.AddTextChunk("NSArray *"); 7189 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7190 } 7191 7192 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 7193 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7194 Builder.AddTextChunk("NSIndexSet *"); 7195 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7196 Builder.AddTextChunk("indexes"); 7197 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority, 7198 CXCursor_ObjCInstanceMethodDecl)); 7199 } 7200 } 7201 7202 // Add -(void)getKey:(type **)buffer range:(NSRange)inRange 7203 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 7204 std::string SelectorName = (Twine("get") + UpperKey).str(); 7205 IdentifierInfo *SelectorIds[2] = { 7206 &Context.Idents.get(SelectorName), 7207 &Context.Idents.get("range") 7208 }; 7209 7210 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) { 7211 if (ReturnType.isNull()) { 7212 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7213 Builder.AddTextChunk("void"); 7214 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7215 } 7216 7217 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 7218 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7219 Builder.AddPlaceholderChunk("object-type"); 7220 Builder.AddTextChunk(" **"); 7221 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7222 Builder.AddTextChunk("buffer"); 7223 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7224 Builder.AddTypedTextChunk("range:"); 7225 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7226 Builder.AddTextChunk("NSRange"); 7227 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7228 Builder.AddTextChunk("inRange"); 7229 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority, 7230 CXCursor_ObjCInstanceMethodDecl)); 7231 } 7232 } 7233 7234 // Mutable indexed accessors 7235 7236 // - (void)insertObject:(type *)object inKeyAtIndex:(NSUInteger)index 7237 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 7238 std::string SelectorName = (Twine("in") + UpperKey + "AtIndex").str(); 7239 IdentifierInfo *SelectorIds[2] = { 7240 &Context.Idents.get("insertObject"), 7241 &Context.Idents.get(SelectorName) 7242 }; 7243 7244 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) { 7245 if (ReturnType.isNull()) { 7246 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7247 Builder.AddTextChunk("void"); 7248 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7249 } 7250 7251 Builder.AddTypedTextChunk("insertObject:"); 7252 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7253 Builder.AddPlaceholderChunk("object-type"); 7254 Builder.AddTextChunk(" *"); 7255 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7256 Builder.AddTextChunk("object"); 7257 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7258 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 7259 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7260 Builder.AddPlaceholderChunk("NSUInteger"); 7261 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7262 Builder.AddTextChunk("index"); 7263 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority, 7264 CXCursor_ObjCInstanceMethodDecl)); 7265 } 7266 } 7267 7268 // - (void)insertKey:(NSArray *)array atIndexes:(NSIndexSet *)indexes 7269 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 7270 std::string SelectorName = (Twine("insert") + UpperKey).str(); 7271 IdentifierInfo *SelectorIds[2] = { 7272 &Context.Idents.get(SelectorName), 7273 &Context.Idents.get("atIndexes") 7274 }; 7275 7276 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) { 7277 if (ReturnType.isNull()) { 7278 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7279 Builder.AddTextChunk("void"); 7280 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7281 } 7282 7283 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 7284 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7285 Builder.AddTextChunk("NSArray *"); 7286 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7287 Builder.AddTextChunk("array"); 7288 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7289 Builder.AddTypedTextChunk("atIndexes:"); 7290 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7291 Builder.AddPlaceholderChunk("NSIndexSet *"); 7292 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7293 Builder.AddTextChunk("indexes"); 7294 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority, 7295 CXCursor_ObjCInstanceMethodDecl)); 7296 } 7297 } 7298 7299 // -(void)removeObjectFromKeyAtIndex:(NSUInteger)index 7300 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 7301 std::string SelectorName 7302 = (Twine("removeObjectFrom") + UpperKey + "AtIndex").str(); 7303 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 7304 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 7305 if (ReturnType.isNull()) { 7306 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7307 Builder.AddTextChunk("void"); 7308 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7309 } 7310 7311 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 7312 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7313 Builder.AddTextChunk("NSUInteger"); 7314 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7315 Builder.AddTextChunk("index"); 7316 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority, 7317 CXCursor_ObjCInstanceMethodDecl)); 7318 } 7319 } 7320 7321 // -(void)removeKeyAtIndexes:(NSIndexSet *)indexes 7322 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 7323 std::string SelectorName 7324 = (Twine("remove") + UpperKey + "AtIndexes").str(); 7325 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 7326 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 7327 if (ReturnType.isNull()) { 7328 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7329 Builder.AddTextChunk("void"); 7330 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7331 } 7332 7333 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 7334 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7335 Builder.AddTextChunk("NSIndexSet *"); 7336 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7337 Builder.AddTextChunk("indexes"); 7338 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority, 7339 CXCursor_ObjCInstanceMethodDecl)); 7340 } 7341 } 7342 7343 // - (void)replaceObjectInKeyAtIndex:(NSUInteger)index withObject:(id)object 7344 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 7345 std::string SelectorName 7346 = (Twine("replaceObjectIn") + UpperKey + "AtIndex").str(); 7347 IdentifierInfo *SelectorIds[2] = { 7348 &Context.Idents.get(SelectorName), 7349 &Context.Idents.get("withObject") 7350 }; 7351 7352 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) { 7353 if (ReturnType.isNull()) { 7354 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7355 Builder.AddTextChunk("void"); 7356 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7357 } 7358 7359 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 7360 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7361 Builder.AddPlaceholderChunk("NSUInteger"); 7362 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7363 Builder.AddTextChunk("index"); 7364 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7365 Builder.AddTypedTextChunk("withObject:"); 7366 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7367 Builder.AddTextChunk("id"); 7368 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7369 Builder.AddTextChunk("object"); 7370 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority, 7371 CXCursor_ObjCInstanceMethodDecl)); 7372 } 7373 } 7374 7375 // - (void)replaceKeyAtIndexes:(NSIndexSet *)indexes withKey:(NSArray *)array 7376 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 7377 std::string SelectorName1 7378 = (Twine("replace") + UpperKey + "AtIndexes").str(); 7379 std::string SelectorName2 = (Twine("with") + UpperKey).str(); 7380 IdentifierInfo *SelectorIds[2] = { 7381 &Context.Idents.get(SelectorName1), 7382 &Context.Idents.get(SelectorName2) 7383 }; 7384 7385 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) { 7386 if (ReturnType.isNull()) { 7387 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7388 Builder.AddTextChunk("void"); 7389 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7390 } 7391 7392 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName1 + ":")); 7393 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7394 Builder.AddPlaceholderChunk("NSIndexSet *"); 7395 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7396 Builder.AddTextChunk("indexes"); 7397 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7398 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName2 + ":")); 7399 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7400 Builder.AddTextChunk("NSArray *"); 7401 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7402 Builder.AddTextChunk("array"); 7403 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority, 7404 CXCursor_ObjCInstanceMethodDecl)); 7405 } 7406 } 7407 7408 // Unordered getters 7409 // - (NSEnumerator *)enumeratorOfKey 7410 if (IsInstanceMethod && 7411 (ReturnType.isNull() || 7412 (ReturnType->isObjCObjectPointerType() && 7413 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() && 7414 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() 7415 ->getName() == "NSEnumerator"))) { 7416 std::string SelectorName = (Twine("enumeratorOf") + UpperKey).str(); 7417 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 7418 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId)) 7419 .second) { 7420 if (ReturnType.isNull()) { 7421 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7422 Builder.AddTextChunk("NSEnumerator *"); 7423 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7424 } 7425 7426 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName)); 7427 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority, 7428 CXCursor_ObjCInstanceMethodDecl)); 7429 } 7430 } 7431 7432 // - (type *)memberOfKey:(type *)object 7433 if (IsInstanceMethod && 7434 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) { 7435 std::string SelectorName = (Twine("memberOf") + UpperKey).str(); 7436 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 7437 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 7438 if (ReturnType.isNull()) { 7439 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7440 Builder.AddPlaceholderChunk("object-type"); 7441 Builder.AddTextChunk(" *"); 7442 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7443 } 7444 7445 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 7446 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7447 if (ReturnType.isNull()) { 7448 Builder.AddPlaceholderChunk("object-type"); 7449 Builder.AddTextChunk(" *"); 7450 } else { 7451 Builder.AddTextChunk(GetCompletionTypeString(ReturnType, Context, 7452 Policy, 7453 Builder.getAllocator())); 7454 } 7455 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7456 Builder.AddTextChunk("object"); 7457 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority, 7458 CXCursor_ObjCInstanceMethodDecl)); 7459 } 7460 } 7461 7462 // Mutable unordered accessors 7463 // - (void)addKeyObject:(type *)object 7464 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 7465 std::string SelectorName 7466 = (Twine("add") + UpperKey + Twine("Object")).str(); 7467 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 7468 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 7469 if (ReturnType.isNull()) { 7470 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7471 Builder.AddTextChunk("void"); 7472 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7473 } 7474 7475 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 7476 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7477 Builder.AddPlaceholderChunk("object-type"); 7478 Builder.AddTextChunk(" *"); 7479 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7480 Builder.AddTextChunk("object"); 7481 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority, 7482 CXCursor_ObjCInstanceMethodDecl)); 7483 } 7484 } 7485 7486 // - (void)addKey:(NSSet *)objects 7487 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 7488 std::string SelectorName = (Twine("add") + UpperKey).str(); 7489 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 7490 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 7491 if (ReturnType.isNull()) { 7492 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7493 Builder.AddTextChunk("void"); 7494 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7495 } 7496 7497 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 7498 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7499 Builder.AddTextChunk("NSSet *"); 7500 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7501 Builder.AddTextChunk("objects"); 7502 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority, 7503 CXCursor_ObjCInstanceMethodDecl)); 7504 } 7505 } 7506 7507 // - (void)removeKeyObject:(type *)object 7508 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 7509 std::string SelectorName 7510 = (Twine("remove") + UpperKey + Twine("Object")).str(); 7511 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 7512 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 7513 if (ReturnType.isNull()) { 7514 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7515 Builder.AddTextChunk("void"); 7516 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7517 } 7518 7519 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 7520 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7521 Builder.AddPlaceholderChunk("object-type"); 7522 Builder.AddTextChunk(" *"); 7523 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7524 Builder.AddTextChunk("object"); 7525 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority, 7526 CXCursor_ObjCInstanceMethodDecl)); 7527 } 7528 } 7529 7530 // - (void)removeKey:(NSSet *)objects 7531 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 7532 std::string SelectorName = (Twine("remove") + UpperKey).str(); 7533 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 7534 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 7535 if (ReturnType.isNull()) { 7536 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7537 Builder.AddTextChunk("void"); 7538 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7539 } 7540 7541 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 7542 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7543 Builder.AddTextChunk("NSSet *"); 7544 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7545 Builder.AddTextChunk("objects"); 7546 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority, 7547 CXCursor_ObjCInstanceMethodDecl)); 7548 } 7549 } 7550 7551 // - (void)intersectKey:(NSSet *)objects 7552 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 7553 std::string SelectorName = (Twine("intersect") + UpperKey).str(); 7554 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 7555 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 7556 if (ReturnType.isNull()) { 7557 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7558 Builder.AddTextChunk("void"); 7559 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7560 } 7561 7562 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 7563 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7564 Builder.AddTextChunk("NSSet *"); 7565 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7566 Builder.AddTextChunk("objects"); 7567 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority, 7568 CXCursor_ObjCInstanceMethodDecl)); 7569 } 7570 } 7571 7572 // Key-Value Observing 7573 // + (NSSet *)keyPathsForValuesAffectingKey 7574 if (!IsInstanceMethod && 7575 (ReturnType.isNull() || 7576 (ReturnType->isObjCObjectPointerType() && 7577 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() && 7578 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() 7579 ->getName() == "NSSet"))) { 7580 std::string SelectorName 7581 = (Twine("keyPathsForValuesAffecting") + UpperKey).str(); 7582 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 7583 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId)) 7584 .second) { 7585 if (ReturnType.isNull()) { 7586 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7587 Builder.AddTextChunk("NSSet<NSString *> *"); 7588 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7589 } 7590 7591 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName)); 7592 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern, 7593 CXCursor_ObjCClassMethodDecl)); 7594 } 7595 } 7596 7597 // + (BOOL)automaticallyNotifiesObserversForKey 7598 if (!IsInstanceMethod && 7599 (ReturnType.isNull() || 7600 ReturnType->isIntegerType() || 7601 ReturnType->isBooleanType())) { 7602 std::string SelectorName 7603 = (Twine("automaticallyNotifiesObserversOf") + UpperKey).str(); 7604 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 7605 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId)) 7606 .second) { 7607 if (ReturnType.isNull()) { 7608 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7609 Builder.AddTextChunk("BOOL"); 7610 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7611 } 7612 7613 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName)); 7614 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern, 7615 CXCursor_ObjCClassMethodDecl)); 7616 } 7617 } 7618 } 7619 7620 void Sema::CodeCompleteObjCMethodDecl(Scope *S, Optional<bool> IsInstanceMethod, 7621 ParsedType ReturnTy) { 7622 // Determine the return type of the method we're declaring, if 7623 // provided. 7624 QualType ReturnType = GetTypeFromParser(ReturnTy); 7625 Decl *IDecl = nullptr; 7626 if (CurContext->isObjCContainer()) { 7627 ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext); 7628 IDecl = OCD; 7629 } 7630 // Determine where we should start searching for methods. 7631 ObjCContainerDecl *SearchDecl = nullptr; 7632 bool IsInImplementation = false; 7633 if (Decl *D = IDecl) { 7634 if (ObjCImplementationDecl *Impl = dyn_cast<ObjCImplementationDecl>(D)) { 7635 SearchDecl = Impl->getClassInterface(); 7636 IsInImplementation = true; 7637 } else if (ObjCCategoryImplDecl *CatImpl 7638 = dyn_cast<ObjCCategoryImplDecl>(D)) { 7639 SearchDecl = CatImpl->getCategoryDecl(); 7640 IsInImplementation = true; 7641 } else 7642 SearchDecl = dyn_cast<ObjCContainerDecl>(D); 7643 } 7644 7645 if (!SearchDecl && S) { 7646 if (DeclContext *DC = S->getEntity()) 7647 SearchDecl = dyn_cast<ObjCContainerDecl>(DC); 7648 } 7649 7650 if (!SearchDecl) { 7651 HandleCodeCompleteResults(this, CodeCompleter, 7652 CodeCompletionContext::CCC_Other, 7653 nullptr, 0); 7654 return; 7655 } 7656 7657 // Find all of the methods that we could declare/implement here. 7658 KnownMethodsMap KnownMethods; 7659 FindImplementableMethods(Context, SearchDecl, IsInstanceMethod, 7660 ReturnType, KnownMethods); 7661 7662 // Add declarations or definitions for each of the known methods. 7663 typedef CodeCompletionResult Result; 7664 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 7665 CodeCompleter->getCodeCompletionTUInfo(), 7666 CodeCompletionContext::CCC_Other); 7667 Results.EnterNewScope(); 7668 PrintingPolicy Policy = getCompletionPrintingPolicy(*this); 7669 for (KnownMethodsMap::iterator M = KnownMethods.begin(), 7670 MEnd = KnownMethods.end(); 7671 M != MEnd; ++M) { 7672 ObjCMethodDecl *Method = M->second.getPointer(); 7673 CodeCompletionBuilder Builder(Results.getAllocator(), 7674 Results.getCodeCompletionTUInfo()); 7675 7676 // Add the '-'/'+' prefix if it wasn't provided yet. 7677 if (!IsInstanceMethod) { 7678 Builder.AddTextChunk(Method->isInstanceMethod() ? "-" : "+"); 7679 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7680 } 7681 7682 // If the result type was not already provided, add it to the 7683 // pattern as (type). 7684 if (ReturnType.isNull()) { 7685 QualType ResTy = Method->getSendResultType().stripObjCKindOfType(Context); 7686 AttributedType::stripOuterNullability(ResTy); 7687 AddObjCPassingTypeChunk(ResTy, 7688 Method->getObjCDeclQualifier(), Context, Policy, 7689 Builder); 7690 } 7691 7692 Selector Sel = Method->getSelector(); 7693 7694 // Add the first part of the selector to the pattern. 7695 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString( 7696 Sel.getNameForSlot(0))); 7697 7698 // Add parameters to the pattern. 7699 unsigned I = 0; 7700 for (ObjCMethodDecl::param_iterator P = Method->param_begin(), 7701 PEnd = Method->param_end(); 7702 P != PEnd; (void)++P, ++I) { 7703 // Add the part of the selector name. 7704 if (I == 0) 7705 Builder.AddTypedTextChunk(":"); 7706 else if (I < Sel.getNumArgs()) { 7707 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7708 Builder.AddTypedTextChunk( 7709 Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":")); 7710 } else 7711 break; 7712 7713 // Add the parameter type. 7714 QualType ParamType; 7715 if ((*P)->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 7716 ParamType = (*P)->getType(); 7717 else 7718 ParamType = (*P)->getOriginalType(); 7719 ParamType = ParamType.substObjCTypeArgs(Context, {}, 7720 ObjCSubstitutionContext::Parameter); 7721 AttributedType::stripOuterNullability(ParamType); 7722 AddObjCPassingTypeChunk(ParamType, 7723 (*P)->getObjCDeclQualifier(), 7724 Context, Policy, 7725 Builder); 7726 7727 if (IdentifierInfo *Id = (*P)->getIdentifier()) 7728 Builder.AddTextChunk(Builder.getAllocator().CopyString( Id->getName())); 7729 } 7730 7731 if (Method->isVariadic()) { 7732 if (Method->param_size() > 0) 7733 Builder.AddChunk(CodeCompletionString::CK_Comma); 7734 Builder.AddTextChunk("..."); 7735 } 7736 7737 if (IsInImplementation && Results.includeCodePatterns()) { 7738 // We will be defining the method here, so add a compound statement. 7739 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7740 Builder.AddChunk(CodeCompletionString::CK_LeftBrace); 7741 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); 7742 if (!Method->getReturnType()->isVoidType()) { 7743 // If the result type is not void, add a return clause. 7744 Builder.AddTextChunk("return"); 7745 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7746 Builder.AddPlaceholderChunk("expression"); 7747 Builder.AddChunk(CodeCompletionString::CK_SemiColon); 7748 } else 7749 Builder.AddPlaceholderChunk("statements"); 7750 7751 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); 7752 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 7753 } 7754 7755 unsigned Priority = CCP_CodePattern; 7756 if (!M->second.getInt()) 7757 Priority += CCD_InBaseClass; 7758 7759 Results.AddResult(Result(Builder.TakeString(), Method, Priority)); 7760 } 7761 7762 // Add Key-Value-Coding and Key-Value-Observing accessor methods for all of 7763 // the properties in this class and its categories. 7764 if (Context.getLangOpts().ObjC2) { 7765 SmallVector<ObjCContainerDecl *, 4> Containers; 7766 Containers.push_back(SearchDecl); 7767 7768 VisitedSelectorSet KnownSelectors; 7769 for (KnownMethodsMap::iterator M = KnownMethods.begin(), 7770 MEnd = KnownMethods.end(); 7771 M != MEnd; ++M) 7772 KnownSelectors.insert(M->first); 7773 7774 7775 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(SearchDecl); 7776 if (!IFace) 7777 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(SearchDecl)) 7778 IFace = Category->getClassInterface(); 7779 7780 if (IFace) 7781 for (auto *Cat : IFace->visible_categories()) 7782 Containers.push_back(Cat); 7783 7784 if (IsInstanceMethod) { 7785 for (unsigned I = 0, N = Containers.size(); I != N; ++I) 7786 for (auto *P : Containers[I]->instance_properties()) 7787 AddObjCKeyValueCompletions(P, *IsInstanceMethod, ReturnType, Context, 7788 KnownSelectors, Results); 7789 } 7790 } 7791 7792 Results.ExitScope(); 7793 7794 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 7795 Results.data(), Results.size()); 7796 } 7797 7798 void Sema::CodeCompleteObjCMethodDeclSelector(Scope *S, 7799 bool IsInstanceMethod, 7800 bool AtParameterName, 7801 ParsedType ReturnTy, 7802 ArrayRef<IdentifierInfo *> SelIdents) { 7803 // If we have an external source, load the entire class method 7804 // pool from the AST file. 7805 if (ExternalSource) { 7806 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors(); 7807 I != N; ++I) { 7808 Selector Sel = ExternalSource->GetExternalSelector(I); 7809 if (Sel.isNull() || MethodPool.count(Sel)) 7810 continue; 7811 7812 ReadMethodPool(Sel); 7813 } 7814 } 7815 7816 // Build the set of methods we can see. 7817 typedef CodeCompletionResult Result; 7818 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 7819 CodeCompleter->getCodeCompletionTUInfo(), 7820 CodeCompletionContext::CCC_Other); 7821 7822 if (ReturnTy) 7823 Results.setPreferredType(GetTypeFromParser(ReturnTy).getNonReferenceType()); 7824 7825 Results.EnterNewScope(); 7826 for (GlobalMethodPool::iterator M = MethodPool.begin(), 7827 MEnd = MethodPool.end(); 7828 M != MEnd; ++M) { 7829 for (ObjCMethodList *MethList = IsInstanceMethod ? &M->second.first : 7830 &M->second.second; 7831 MethList && MethList->getMethod(); 7832 MethList = MethList->getNext()) { 7833 if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents)) 7834 continue; 7835 7836 if (AtParameterName) { 7837 // Suggest parameter names we've seen before. 7838 unsigned NumSelIdents = SelIdents.size(); 7839 if (NumSelIdents && 7840 NumSelIdents <= MethList->getMethod()->param_size()) { 7841 ParmVarDecl *Param = 7842 MethList->getMethod()->parameters()[NumSelIdents - 1]; 7843 if (Param->getIdentifier()) { 7844 CodeCompletionBuilder Builder(Results.getAllocator(), 7845 Results.getCodeCompletionTUInfo()); 7846 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString( 7847 Param->getIdentifier()->getName())); 7848 Results.AddResult(Builder.TakeString()); 7849 } 7850 } 7851 7852 continue; 7853 } 7854 7855 Result R(MethList->getMethod(), 7856 Results.getBasePriority(MethList->getMethod()), nullptr); 7857 R.StartParameter = SelIdents.size(); 7858 R.AllParametersAreInformative = false; 7859 R.DeclaringEntity = true; 7860 Results.MaybeAddResult(R, CurContext); 7861 } 7862 } 7863 7864 Results.ExitScope(); 7865 7866 if (!AtParameterName && !SelIdents.empty() && 7867 SelIdents.front()->getName().startswith("init")) { 7868 for (const auto &M : PP.macros()) { 7869 if (M.first->getName() != "NS_DESIGNATED_INITIALIZER") 7870 continue; 7871 Results.EnterNewScope(); 7872 CodeCompletionBuilder Builder(Results.getAllocator(), 7873 Results.getCodeCompletionTUInfo()); 7874 Builder.AddTypedTextChunk( 7875 Builder.getAllocator().CopyString(M.first->getName())); 7876 Results.AddResult(CodeCompletionResult(Builder.TakeString(), CCP_Macro, 7877 CXCursor_MacroDefinition)); 7878 Results.ExitScope(); 7879 } 7880 } 7881 7882 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 7883 Results.data(), Results.size()); 7884 } 7885 7886 void Sema::CodeCompletePreprocessorDirective(bool InConditional) { 7887 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 7888 CodeCompleter->getCodeCompletionTUInfo(), 7889 CodeCompletionContext::CCC_PreprocessorDirective); 7890 Results.EnterNewScope(); 7891 7892 // #if <condition> 7893 CodeCompletionBuilder Builder(Results.getAllocator(), 7894 Results.getCodeCompletionTUInfo()); 7895 Builder.AddTypedTextChunk("if"); 7896 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7897 Builder.AddPlaceholderChunk("condition"); 7898 Results.AddResult(Builder.TakeString()); 7899 7900 // #ifdef <macro> 7901 Builder.AddTypedTextChunk("ifdef"); 7902 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7903 Builder.AddPlaceholderChunk("macro"); 7904 Results.AddResult(Builder.TakeString()); 7905 7906 // #ifndef <macro> 7907 Builder.AddTypedTextChunk("ifndef"); 7908 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7909 Builder.AddPlaceholderChunk("macro"); 7910 Results.AddResult(Builder.TakeString()); 7911 7912 if (InConditional) { 7913 // #elif <condition> 7914 Builder.AddTypedTextChunk("elif"); 7915 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7916 Builder.AddPlaceholderChunk("condition"); 7917 Results.AddResult(Builder.TakeString()); 7918 7919 // #else 7920 Builder.AddTypedTextChunk("else"); 7921 Results.AddResult(Builder.TakeString()); 7922 7923 // #endif 7924 Builder.AddTypedTextChunk("endif"); 7925 Results.AddResult(Builder.TakeString()); 7926 } 7927 7928 // #include "header" 7929 Builder.AddTypedTextChunk("include"); 7930 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7931 Builder.AddTextChunk("\""); 7932 Builder.AddPlaceholderChunk("header"); 7933 Builder.AddTextChunk("\""); 7934 Results.AddResult(Builder.TakeString()); 7935 7936 // #include <header> 7937 Builder.AddTypedTextChunk("include"); 7938 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7939 Builder.AddTextChunk("<"); 7940 Builder.AddPlaceholderChunk("header"); 7941 Builder.AddTextChunk(">"); 7942 Results.AddResult(Builder.TakeString()); 7943 7944 // #define <macro> 7945 Builder.AddTypedTextChunk("define"); 7946 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7947 Builder.AddPlaceholderChunk("macro"); 7948 Results.AddResult(Builder.TakeString()); 7949 7950 // #define <macro>(<args>) 7951 Builder.AddTypedTextChunk("define"); 7952 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7953 Builder.AddPlaceholderChunk("macro"); 7954 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7955 Builder.AddPlaceholderChunk("args"); 7956 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7957 Results.AddResult(Builder.TakeString()); 7958 7959 // #undef <macro> 7960 Builder.AddTypedTextChunk("undef"); 7961 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7962 Builder.AddPlaceholderChunk("macro"); 7963 Results.AddResult(Builder.TakeString()); 7964 7965 // #line <number> 7966 Builder.AddTypedTextChunk("line"); 7967 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7968 Builder.AddPlaceholderChunk("number"); 7969 Results.AddResult(Builder.TakeString()); 7970 7971 // #line <number> "filename" 7972 Builder.AddTypedTextChunk("line"); 7973 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7974 Builder.AddPlaceholderChunk("number"); 7975 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7976 Builder.AddTextChunk("\""); 7977 Builder.AddPlaceholderChunk("filename"); 7978 Builder.AddTextChunk("\""); 7979 Results.AddResult(Builder.TakeString()); 7980 7981 // #error <message> 7982 Builder.AddTypedTextChunk("error"); 7983 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7984 Builder.AddPlaceholderChunk("message"); 7985 Results.AddResult(Builder.TakeString()); 7986 7987 // #pragma <arguments> 7988 Builder.AddTypedTextChunk("pragma"); 7989 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7990 Builder.AddPlaceholderChunk("arguments"); 7991 Results.AddResult(Builder.TakeString()); 7992 7993 if (getLangOpts().ObjC1) { 7994 // #import "header" 7995 Builder.AddTypedTextChunk("import"); 7996 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7997 Builder.AddTextChunk("\""); 7998 Builder.AddPlaceholderChunk("header"); 7999 Builder.AddTextChunk("\""); 8000 Results.AddResult(Builder.TakeString()); 8001 8002 // #import <header> 8003 Builder.AddTypedTextChunk("import"); 8004 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 8005 Builder.AddTextChunk("<"); 8006 Builder.AddPlaceholderChunk("header"); 8007 Builder.AddTextChunk(">"); 8008 Results.AddResult(Builder.TakeString()); 8009 } 8010 8011 // #include_next "header" 8012 Builder.AddTypedTextChunk("include_next"); 8013 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 8014 Builder.AddTextChunk("\""); 8015 Builder.AddPlaceholderChunk("header"); 8016 Builder.AddTextChunk("\""); 8017 Results.AddResult(Builder.TakeString()); 8018 8019 // #include_next <header> 8020 Builder.AddTypedTextChunk("include_next"); 8021 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 8022 Builder.AddTextChunk("<"); 8023 Builder.AddPlaceholderChunk("header"); 8024 Builder.AddTextChunk(">"); 8025 Results.AddResult(Builder.TakeString()); 8026 8027 // #warning <message> 8028 Builder.AddTypedTextChunk("warning"); 8029 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 8030 Builder.AddPlaceholderChunk("message"); 8031 Results.AddResult(Builder.TakeString()); 8032 8033 // Note: #ident and #sccs are such crazy anachronisms that we don't provide 8034 // completions for them. And __include_macros is a Clang-internal extension 8035 // that we don't want to encourage anyone to use. 8036 8037 // FIXME: we don't support #assert or #unassert, so don't suggest them. 8038 Results.ExitScope(); 8039 8040 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 8041 Results.data(), Results.size()); 8042 } 8043 8044 void Sema::CodeCompleteInPreprocessorConditionalExclusion(Scope *S) { 8045 CodeCompleteOrdinaryName(S, 8046 S->getFnParent()? Sema::PCC_RecoveryInFunction 8047 : Sema::PCC_Namespace); 8048 } 8049 8050 void Sema::CodeCompletePreprocessorMacroName(bool IsDefinition) { 8051 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 8052 CodeCompleter->getCodeCompletionTUInfo(), 8053 IsDefinition? CodeCompletionContext::CCC_MacroName 8054 : CodeCompletionContext::CCC_MacroNameUse); 8055 if (!IsDefinition && (!CodeCompleter || CodeCompleter->includeMacros())) { 8056 // Add just the names of macros, not their arguments. 8057 CodeCompletionBuilder Builder(Results.getAllocator(), 8058 Results.getCodeCompletionTUInfo()); 8059 Results.EnterNewScope(); 8060 for (Preprocessor::macro_iterator M = PP.macro_begin(), 8061 MEnd = PP.macro_end(); 8062 M != MEnd; ++M) { 8063 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString( 8064 M->first->getName())); 8065 Results.AddResult(CodeCompletionResult(Builder.TakeString(), 8066 CCP_CodePattern, 8067 CXCursor_MacroDefinition)); 8068 } 8069 Results.ExitScope(); 8070 } else if (IsDefinition) { 8071 // FIXME: Can we detect when the user just wrote an include guard above? 8072 } 8073 8074 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 8075 Results.data(), Results.size()); 8076 } 8077 8078 void Sema::CodeCompletePreprocessorExpression() { 8079 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 8080 CodeCompleter->getCodeCompletionTUInfo(), 8081 CodeCompletionContext::CCC_PreprocessorExpression); 8082 8083 if (!CodeCompleter || CodeCompleter->includeMacros()) 8084 AddMacroResults(PP, Results, 8085 CodeCompleter ? CodeCompleter->loadExternal() : false, 8086 true); 8087 8088 // defined (<macro>) 8089 Results.EnterNewScope(); 8090 CodeCompletionBuilder Builder(Results.getAllocator(), 8091 Results.getCodeCompletionTUInfo()); 8092 Builder.AddTypedTextChunk("defined"); 8093 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 8094 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 8095 Builder.AddPlaceholderChunk("macro"); 8096 Builder.AddChunk(CodeCompletionString::CK_RightParen); 8097 Results.AddResult(Builder.TakeString()); 8098 Results.ExitScope(); 8099 8100 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 8101 Results.data(), Results.size()); 8102 } 8103 8104 void Sema::CodeCompletePreprocessorMacroArgument(Scope *S, 8105 IdentifierInfo *Macro, 8106 MacroInfo *MacroInfo, 8107 unsigned Argument) { 8108 // FIXME: In the future, we could provide "overload" results, much like we 8109 // do for function calls. 8110 8111 // Now just ignore this. There will be another code-completion callback 8112 // for the expanded tokens. 8113 } 8114 8115 // This handles completion inside an #include filename, e.g. #include <foo/ba 8116 // We look for the directory "foo" under each directory on the include path, 8117 // list its files, and reassemble the appropriate #include. 8118 void Sema::CodeCompleteIncludedFile(llvm::StringRef Dir, bool Angled) { 8119 // RelDir should use /, but unescaped \ is possible on windows! 8120 // Our completions will normalize to / for simplicity, this case is rare. 8121 std::string RelDir = llvm::sys::path::convert_to_slash(Dir); 8122 // We need the native slashes for the actual file system interactions. 8123 SmallString<128> NativeRelDir = StringRef(RelDir); 8124 llvm::sys::path::native(NativeRelDir); 8125 auto FS = getSourceManager().getFileManager().getVirtualFileSystem(); 8126 8127 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 8128 CodeCompleter->getCodeCompletionTUInfo(), 8129 CodeCompletionContext::CCC_IncludedFile); 8130 llvm::DenseSet<StringRef> SeenResults; // To deduplicate results. 8131 8132 // Helper: adds one file or directory completion result. 8133 auto AddCompletion = [&](StringRef Filename, bool IsDirectory) { 8134 SmallString<64> TypedChunk = Filename; 8135 // Directory completion is up to the slash, e.g. <sys/ 8136 TypedChunk.push_back(IsDirectory ? '/' : Angled ? '>' : '"'); 8137 auto R = SeenResults.insert(TypedChunk); 8138 if (R.second) { // New completion 8139 const char *InternedTyped = Results.getAllocator().CopyString(TypedChunk); 8140 *R.first = InternedTyped; // Avoid dangling StringRef. 8141 CodeCompletionBuilder Builder(CodeCompleter->getAllocator(), 8142 CodeCompleter->getCodeCompletionTUInfo()); 8143 Builder.AddTypedTextChunk(InternedTyped); 8144 // The result is a "Pattern", which is pretty opaque. 8145 // We may want to include the real filename to allow smart ranking. 8146 Results.AddResult(CodeCompletionResult(Builder.TakeString())); 8147 } 8148 }; 8149 8150 // Helper: scans IncludeDir for nice files, and adds results for each. 8151 auto AddFilesFromIncludeDir = [&](StringRef IncludeDir, bool IsSystem) { 8152 llvm::SmallString<128> Dir = IncludeDir; 8153 if (!NativeRelDir.empty()) 8154 llvm::sys::path::append(Dir, NativeRelDir); 8155 8156 std::error_code EC; 8157 unsigned Count = 0; 8158 for (auto It = FS->dir_begin(Dir, EC); 8159 !EC && It != llvm::vfs::directory_iterator(); It.increment(EC)) { 8160 if (++Count == 2500) // If we happen to hit a huge directory, 8161 break; // bail out early so we're not too slow. 8162 StringRef Filename = llvm::sys::path::filename(It->path()); 8163 switch (It->type()) { 8164 case llvm::sys::fs::file_type::directory_file: 8165 AddCompletion(Filename, /*IsDirectory=*/true); 8166 break; 8167 case llvm::sys::fs::file_type::regular_file: 8168 // Only files that really look like headers. (Except in system dirs). 8169 if (!IsSystem) { 8170 // Header extensions from Types.def, which we can't depend on here. 8171 if (!(Filename.endswith_lower(".h") || 8172 Filename.endswith_lower(".hh") || 8173 Filename.endswith_lower(".hpp") || 8174 Filename.endswith_lower(".inc"))) 8175 break; 8176 } 8177 AddCompletion(Filename, /*IsDirectory=*/false); 8178 break; 8179 default: 8180 break; 8181 } 8182 } 8183 }; 8184 8185 // Helper: adds results relative to IncludeDir, if possible. 8186 auto AddFilesFromDirLookup = [&](const DirectoryLookup &IncludeDir, 8187 bool IsSystem) { 8188 llvm::SmallString<128> Dir; 8189 switch (IncludeDir.getLookupType()) { 8190 case DirectoryLookup::LT_HeaderMap: 8191 // header maps are not (currently) enumerable. 8192 break; 8193 case DirectoryLookup::LT_NormalDir: 8194 AddFilesFromIncludeDir(IncludeDir.getDir()->getName(), IsSystem); 8195 break; 8196 case DirectoryLookup::LT_Framework: 8197 AddFilesFromIncludeDir(IncludeDir.getFrameworkDir()->getName(), IsSystem); 8198 break; 8199 } 8200 }; 8201 8202 // Finally with all our helpers, we can scan the include path. 8203 // Do this in standard order so deduplication keeps the right file. 8204 // (In case we decide to add more details to the results later). 8205 const auto &S = PP.getHeaderSearchInfo(); 8206 using llvm::make_range; 8207 if (!Angled) { 8208 // The current directory is on the include path for "quoted" includes. 8209 auto *CurFile = PP.getCurrentFileLexer()->getFileEntry(); 8210 if (CurFile && CurFile->getDir()) 8211 AddFilesFromIncludeDir(CurFile->getDir()->getName(), false); 8212 for (const auto &D : make_range(S.quoted_dir_begin(), S.quoted_dir_end())) 8213 AddFilesFromDirLookup(D, false); 8214 } 8215 for (const auto &D : make_range(S.angled_dir_begin(), S.angled_dir_end())) 8216 AddFilesFromDirLookup(D, false); 8217 for (const auto &D : make_range(S.system_dir_begin(), S.system_dir_end())) 8218 AddFilesFromDirLookup(D, true); 8219 8220 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 8221 Results.data(), Results.size()); 8222 } 8223 8224 void Sema::CodeCompleteNaturalLanguage() { 8225 HandleCodeCompleteResults(this, CodeCompleter, 8226 CodeCompletionContext::CCC_NaturalLanguage, 8227 nullptr, 0); 8228 } 8229 8230 void Sema::CodeCompleteAvailabilityPlatformName() { 8231 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 8232 CodeCompleter->getCodeCompletionTUInfo(), 8233 CodeCompletionContext::CCC_Other); 8234 Results.EnterNewScope(); 8235 static const char *Platforms[] = {"macOS", "iOS", "watchOS", "tvOS"}; 8236 for (const char *Platform : llvm::makeArrayRef(Platforms)) { 8237 Results.AddResult(CodeCompletionResult(Platform)); 8238 Results.AddResult(CodeCompletionResult(Results.getAllocator().CopyString( 8239 Twine(Platform) + "ApplicationExtension"))); 8240 } 8241 Results.ExitScope(); 8242 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 8243 Results.data(), Results.size()); 8244 } 8245 8246 void Sema::GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator, 8247 CodeCompletionTUInfo &CCTUInfo, 8248 SmallVectorImpl<CodeCompletionResult> &Results) { 8249 ResultBuilder Builder(*this, Allocator, CCTUInfo, 8250 CodeCompletionContext::CCC_Recovery); 8251 if (!CodeCompleter || CodeCompleter->includeGlobals()) { 8252 CodeCompletionDeclConsumer Consumer(Builder, 8253 Context.getTranslationUnitDecl()); 8254 LookupVisibleDecls(Context.getTranslationUnitDecl(), LookupAnyName, 8255 Consumer, 8256 !CodeCompleter || CodeCompleter->loadExternal()); 8257 } 8258 8259 if (!CodeCompleter || CodeCompleter->includeMacros()) 8260 AddMacroResults(PP, Builder, 8261 CodeCompleter ? CodeCompleter->loadExternal() : false, 8262 true); 8263 8264 Results.clear(); 8265 Results.insert(Results.end(), 8266 Builder.data(), Builder.data() + Builder.size()); 8267 } 8268