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