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