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