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