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