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