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