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