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