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