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 namespace { 4082 /// Information that allows to avoid completing redundant enumerators. 4083 struct CoveredEnumerators { 4084 llvm::SmallPtrSet<EnumConstantDecl *, 8> Seen; 4085 NestedNameSpecifier *SuggestedQualifier = nullptr; 4086 }; 4087 } // namespace 4088 4089 static void AddEnumerators(ResultBuilder &Results, ASTContext &Context, 4090 EnumDecl *Enum, DeclContext *CurContext, 4091 const CoveredEnumerators &Enumerators) { 4092 NestedNameSpecifier *Qualifier = Enumerators.SuggestedQualifier; 4093 if (Context.getLangOpts().CPlusPlus && !Qualifier && Enumerators.Seen.empty()) { 4094 // If there are no prior enumerators in C++, check whether we have to 4095 // qualify the names of the enumerators that we suggest, because they 4096 // may not be visible in this scope. 4097 Qualifier = getRequiredQualification(Context, CurContext, Enum); 4098 } 4099 4100 Results.EnterNewScope(); 4101 for (auto *E : Enum->enumerators()) { 4102 if (Enumerators.Seen.count(E)) 4103 continue; 4104 4105 CodeCompletionResult R(E, CCP_EnumInCase, Qualifier); 4106 Results.AddResult(R, CurContext, nullptr, false); 4107 } 4108 Results.ExitScope(); 4109 } 4110 4111 /// Perform code-completion in an expression context when we know what 4112 /// type we're looking for. 4113 void Sema::CodeCompleteExpression(Scope *S, 4114 const CodeCompleteExpressionData &Data) { 4115 ResultBuilder Results( 4116 *this, CodeCompleter->getAllocator(), 4117 CodeCompleter->getCodeCompletionTUInfo(), 4118 CodeCompletionContext( 4119 Data.IsParenthesized 4120 ? CodeCompletionContext::CCC_ParenthesizedExpression 4121 : CodeCompletionContext::CCC_Expression, 4122 Data.PreferredType)); 4123 auto PCC = 4124 Data.IsParenthesized ? PCC_ParenthesizedExpression : PCC_Expression; 4125 if (Data.ObjCCollection) 4126 Results.setFilter(&ResultBuilder::IsObjCCollection); 4127 else if (Data.IntegralConstantExpression) 4128 Results.setFilter(&ResultBuilder::IsIntegralConstantValue); 4129 else if (WantTypesInContext(PCC, getLangOpts())) 4130 Results.setFilter(&ResultBuilder::IsOrdinaryName); 4131 else 4132 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName); 4133 4134 if (!Data.PreferredType.isNull()) 4135 Results.setPreferredType(Data.PreferredType.getNonReferenceType()); 4136 4137 // Ignore any declarations that we were told that we don't care about. 4138 for (unsigned I = 0, N = Data.IgnoreDecls.size(); I != N; ++I) 4139 Results.Ignore(Data.IgnoreDecls[I]); 4140 4141 CodeCompletionDeclConsumer Consumer(Results, CurContext); 4142 LookupVisibleDecls(S, LookupOrdinaryName, Consumer, 4143 CodeCompleter->includeGlobals(), 4144 CodeCompleter->loadExternal()); 4145 4146 Results.EnterNewScope(); 4147 AddOrdinaryNameResults(PCC, S, *this, Results); 4148 Results.ExitScope(); 4149 4150 bool PreferredTypeIsPointer = false; 4151 if (!Data.PreferredType.isNull()) { 4152 PreferredTypeIsPointer = Data.PreferredType->isAnyPointerType() || 4153 Data.PreferredType->isMemberPointerType() || 4154 Data.PreferredType->isBlockPointerType(); 4155 if (Data.PreferredType->isEnumeralType()) { 4156 EnumDecl *Enum = Data.PreferredType->castAs<EnumType>()->getDecl(); 4157 if (auto *Def = Enum->getDefinition()) 4158 Enum = Def; 4159 // FIXME: collect covered enumerators in cases like: 4160 // if (x == my_enum::one) { ... } else if (x == ^) {} 4161 AddEnumerators(Results, Context, Enum, CurContext, CoveredEnumerators()); 4162 } 4163 } 4164 4165 if (S->getFnParent() && !Data.ObjCCollection && 4166 !Data.IntegralConstantExpression) 4167 AddPrettyFunctionResults(getLangOpts(), Results); 4168 4169 if (CodeCompleter->includeMacros()) 4170 AddMacroResults(PP, Results, CodeCompleter->loadExternal(), false, 4171 PreferredTypeIsPointer); 4172 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 4173 Results.data(), Results.size()); 4174 } 4175 4176 void Sema::CodeCompleteExpression(Scope *S, QualType PreferredType, 4177 bool IsParenthesized) { 4178 return CodeCompleteExpression( 4179 S, CodeCompleteExpressionData(PreferredType, IsParenthesized)); 4180 } 4181 4182 void Sema::CodeCompletePostfixExpression(Scope *S, ExprResult E, 4183 QualType PreferredType) { 4184 if (E.isInvalid()) 4185 CodeCompleteExpression(S, PreferredType); 4186 else if (getLangOpts().ObjC) 4187 CodeCompleteObjCInstanceMessage(S, E.get(), None, false); 4188 } 4189 4190 /// The set of properties that have already been added, referenced by 4191 /// property name. 4192 typedef llvm::SmallPtrSet<IdentifierInfo *, 16> AddedPropertiesSet; 4193 4194 /// Retrieve the container definition, if any? 4195 static ObjCContainerDecl *getContainerDef(ObjCContainerDecl *Container) { 4196 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) { 4197 if (Interface->hasDefinition()) 4198 return Interface->getDefinition(); 4199 4200 return Interface; 4201 } 4202 4203 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) { 4204 if (Protocol->hasDefinition()) 4205 return Protocol->getDefinition(); 4206 4207 return Protocol; 4208 } 4209 return Container; 4210 } 4211 4212 /// Adds a block invocation code completion result for the given block 4213 /// declaration \p BD. 4214 static void AddObjCBlockCall(ASTContext &Context, const PrintingPolicy &Policy, 4215 CodeCompletionBuilder &Builder, 4216 const NamedDecl *BD, 4217 const FunctionTypeLoc &BlockLoc, 4218 const FunctionProtoTypeLoc &BlockProtoLoc) { 4219 Builder.AddResultTypeChunk( 4220 GetCompletionTypeString(BlockLoc.getReturnLoc().getType(), Context, 4221 Policy, Builder.getAllocator())); 4222 4223 AddTypedNameChunk(Context, Policy, BD, Builder); 4224 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 4225 4226 if (BlockProtoLoc && BlockProtoLoc.getTypePtr()->isVariadic()) { 4227 Builder.AddPlaceholderChunk("..."); 4228 } else { 4229 for (unsigned I = 0, N = BlockLoc.getNumParams(); I != N; ++I) { 4230 if (I) 4231 Builder.AddChunk(CodeCompletionString::CK_Comma); 4232 4233 // Format the placeholder string. 4234 std::string PlaceholderStr = 4235 FormatFunctionParameter(Policy, BlockLoc.getParam(I)); 4236 4237 if (I == N - 1 && BlockProtoLoc && 4238 BlockProtoLoc.getTypePtr()->isVariadic()) 4239 PlaceholderStr += ", ..."; 4240 4241 // Add the placeholder string. 4242 Builder.AddPlaceholderChunk( 4243 Builder.getAllocator().CopyString(PlaceholderStr)); 4244 } 4245 } 4246 4247 Builder.AddChunk(CodeCompletionString::CK_RightParen); 4248 } 4249 4250 static void 4251 AddObjCProperties(const CodeCompletionContext &CCContext, 4252 ObjCContainerDecl *Container, bool AllowCategories, 4253 bool AllowNullaryMethods, DeclContext *CurContext, 4254 AddedPropertiesSet &AddedProperties, ResultBuilder &Results, 4255 bool IsBaseExprStatement = false, 4256 bool IsClassProperty = false, bool InOriginalClass = true) { 4257 typedef CodeCompletionResult Result; 4258 4259 // Retrieve the definition. 4260 Container = getContainerDef(Container); 4261 4262 // Add properties in this container. 4263 const auto AddProperty = [&](const ObjCPropertyDecl *P) { 4264 if (!AddedProperties.insert(P->getIdentifier()).second) 4265 return; 4266 4267 // FIXME: Provide block invocation completion for non-statement 4268 // expressions. 4269 if (!P->getType().getTypePtr()->isBlockPointerType() || 4270 !IsBaseExprStatement) { 4271 Result R = Result(P, Results.getBasePriority(P), nullptr); 4272 if (!InOriginalClass) 4273 setInBaseClass(R); 4274 Results.MaybeAddResult(R, CurContext); 4275 return; 4276 } 4277 4278 // Block setter and invocation completion is provided only when we are able 4279 // to find the FunctionProtoTypeLoc with parameter names for the block. 4280 FunctionTypeLoc BlockLoc; 4281 FunctionProtoTypeLoc BlockProtoLoc; 4282 findTypeLocationForBlockDecl(P->getTypeSourceInfo(), BlockLoc, 4283 BlockProtoLoc); 4284 if (!BlockLoc) { 4285 Result R = Result(P, Results.getBasePriority(P), nullptr); 4286 if (!InOriginalClass) 4287 setInBaseClass(R); 4288 Results.MaybeAddResult(R, CurContext); 4289 return; 4290 } 4291 4292 // The default completion result for block properties should be the block 4293 // invocation completion when the base expression is a statement. 4294 CodeCompletionBuilder Builder(Results.getAllocator(), 4295 Results.getCodeCompletionTUInfo()); 4296 AddObjCBlockCall(Container->getASTContext(), 4297 getCompletionPrintingPolicy(Results.getSema()), Builder, P, 4298 BlockLoc, BlockProtoLoc); 4299 Result R = Result(Builder.TakeString(), P, Results.getBasePriority(P)); 4300 if (!InOriginalClass) 4301 setInBaseClass(R); 4302 Results.MaybeAddResult(R, CurContext); 4303 4304 // Provide additional block setter completion iff the base expression is a 4305 // statement and the block property is mutable. 4306 if (!P->isReadOnly()) { 4307 CodeCompletionBuilder Builder(Results.getAllocator(), 4308 Results.getCodeCompletionTUInfo()); 4309 AddResultTypeChunk(Container->getASTContext(), 4310 getCompletionPrintingPolicy(Results.getSema()), P, 4311 CCContext.getBaseType(), Builder); 4312 Builder.AddTypedTextChunk( 4313 Results.getAllocator().CopyString(P->getName())); 4314 Builder.AddChunk(CodeCompletionString::CK_Equal); 4315 4316 std::string PlaceholderStr = formatBlockPlaceholder( 4317 getCompletionPrintingPolicy(Results.getSema()), P, BlockLoc, 4318 BlockProtoLoc, /*SuppressBlockName=*/true); 4319 // Add the placeholder string. 4320 Builder.AddPlaceholderChunk( 4321 Builder.getAllocator().CopyString(PlaceholderStr)); 4322 4323 // When completing blocks properties that return void the default 4324 // property completion result should show up before the setter, 4325 // otherwise the setter completion should show up before the default 4326 // property completion, as we normally want to use the result of the 4327 // call. 4328 Result R = 4329 Result(Builder.TakeString(), P, 4330 Results.getBasePriority(P) + 4331 (BlockLoc.getTypePtr()->getReturnType()->isVoidType() 4332 ? CCD_BlockPropertySetter 4333 : -CCD_BlockPropertySetter)); 4334 if (!InOriginalClass) 4335 setInBaseClass(R); 4336 Results.MaybeAddResult(R, CurContext); 4337 } 4338 }; 4339 4340 if (IsClassProperty) { 4341 for (const auto *P : Container->class_properties()) 4342 AddProperty(P); 4343 } else { 4344 for (const auto *P : Container->instance_properties()) 4345 AddProperty(P); 4346 } 4347 4348 // Add nullary methods or implicit class properties 4349 if (AllowNullaryMethods) { 4350 ASTContext &Context = Container->getASTContext(); 4351 PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema()); 4352 // Adds a method result 4353 const auto AddMethod = [&](const ObjCMethodDecl *M) { 4354 IdentifierInfo *Name = M->getSelector().getIdentifierInfoForSlot(0); 4355 if (!Name) 4356 return; 4357 if (!AddedProperties.insert(Name).second) 4358 return; 4359 CodeCompletionBuilder Builder(Results.getAllocator(), 4360 Results.getCodeCompletionTUInfo()); 4361 AddResultTypeChunk(Context, Policy, M, CCContext.getBaseType(), Builder); 4362 Builder.AddTypedTextChunk( 4363 Results.getAllocator().CopyString(Name->getName())); 4364 Result R = Result(Builder.TakeString(), M, 4365 CCP_MemberDeclaration + CCD_MethodAsProperty); 4366 if (!InOriginalClass) 4367 setInBaseClass(R); 4368 Results.MaybeAddResult(R, CurContext); 4369 }; 4370 4371 if (IsClassProperty) { 4372 for (const auto *M : Container->methods()) { 4373 // Gather the class method that can be used as implicit property 4374 // getters. Methods with arguments or methods that return void aren't 4375 // added to the results as they can't be used as a getter. 4376 if (!M->getSelector().isUnarySelector() || 4377 M->getReturnType()->isVoidType() || M->isInstanceMethod()) 4378 continue; 4379 AddMethod(M); 4380 } 4381 } else { 4382 for (auto *M : Container->methods()) { 4383 if (M->getSelector().isUnarySelector()) 4384 AddMethod(M); 4385 } 4386 } 4387 } 4388 4389 // Add properties in referenced protocols. 4390 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) { 4391 for (auto *P : Protocol->protocols()) 4392 AddObjCProperties(CCContext, P, AllowCategories, AllowNullaryMethods, 4393 CurContext, AddedProperties, Results, 4394 IsBaseExprStatement, IsClassProperty, 4395 /*InOriginalClass*/ false); 4396 } else if (ObjCInterfaceDecl *IFace = 4397 dyn_cast<ObjCInterfaceDecl>(Container)) { 4398 if (AllowCategories) { 4399 // Look through categories. 4400 for (auto *Cat : IFace->known_categories()) 4401 AddObjCProperties(CCContext, Cat, AllowCategories, AllowNullaryMethods, 4402 CurContext, AddedProperties, Results, 4403 IsBaseExprStatement, IsClassProperty, 4404 InOriginalClass); 4405 } 4406 4407 // Look through protocols. 4408 for (auto *I : IFace->all_referenced_protocols()) 4409 AddObjCProperties(CCContext, I, AllowCategories, AllowNullaryMethods, 4410 CurContext, AddedProperties, Results, 4411 IsBaseExprStatement, IsClassProperty, 4412 /*InOriginalClass*/ false); 4413 4414 // Look in the superclass. 4415 if (IFace->getSuperClass()) 4416 AddObjCProperties(CCContext, IFace->getSuperClass(), AllowCategories, 4417 AllowNullaryMethods, CurContext, AddedProperties, 4418 Results, IsBaseExprStatement, IsClassProperty, 4419 /*InOriginalClass*/ false); 4420 } else if (const auto *Category = 4421 dyn_cast<ObjCCategoryDecl>(Container)) { 4422 // Look through protocols. 4423 for (auto *P : Category->protocols()) 4424 AddObjCProperties(CCContext, P, AllowCategories, AllowNullaryMethods, 4425 CurContext, AddedProperties, Results, 4426 IsBaseExprStatement, IsClassProperty, 4427 /*InOriginalClass*/ false); 4428 } 4429 } 4430 4431 static void 4432 AddRecordMembersCompletionResults(Sema &SemaRef, ResultBuilder &Results, 4433 Scope *S, QualType BaseType, RecordDecl *RD, 4434 Optional<FixItHint> AccessOpFixIt) { 4435 // Indicate that we are performing a member access, and the cv-qualifiers 4436 // for the base object type. 4437 Results.setObjectTypeQualifiers(BaseType.getQualifiers()); 4438 4439 // Access to a C/C++ class, struct, or union. 4440 Results.allowNestedNameSpecifiers(); 4441 std::vector<FixItHint> FixIts; 4442 if (AccessOpFixIt) 4443 FixIts.emplace_back(AccessOpFixIt.getValue()); 4444 CodeCompletionDeclConsumer Consumer(Results, RD, BaseType, std::move(FixIts)); 4445 SemaRef.LookupVisibleDecls(RD, Sema::LookupMemberName, Consumer, 4446 SemaRef.CodeCompleter->includeGlobals(), 4447 /*IncludeDependentBases=*/true, 4448 SemaRef.CodeCompleter->loadExternal()); 4449 4450 if (SemaRef.getLangOpts().CPlusPlus) { 4451 if (!Results.empty()) { 4452 // The "template" keyword can follow "->" or "." in the grammar. 4453 // However, we only want to suggest the template keyword if something 4454 // is dependent. 4455 bool IsDependent = BaseType->isDependentType(); 4456 if (!IsDependent) { 4457 for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent()) 4458 if (DeclContext *Ctx = DepScope->getEntity()) { 4459 IsDependent = Ctx->isDependentContext(); 4460 break; 4461 } 4462 } 4463 4464 if (IsDependent) 4465 Results.AddResult(CodeCompletionResult("template")); 4466 } 4467 } 4468 } 4469 4470 void Sema::CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base, 4471 Expr *OtherOpBase, 4472 SourceLocation OpLoc, bool IsArrow, 4473 bool IsBaseExprStatement, 4474 QualType PreferredType) { 4475 if (!Base || !CodeCompleter) 4476 return; 4477 4478 ExprResult ConvertedBase = PerformMemberExprBaseConversion(Base, IsArrow); 4479 if (ConvertedBase.isInvalid()) 4480 return; 4481 QualType ConvertedBaseType = ConvertedBase.get()->getType(); 4482 4483 enum CodeCompletionContext::Kind contextKind; 4484 4485 if (IsArrow) { 4486 if (const auto *Ptr = ConvertedBaseType->getAs<PointerType>()) 4487 ConvertedBaseType = Ptr->getPointeeType(); 4488 } 4489 4490 if (IsArrow) { 4491 contextKind = CodeCompletionContext::CCC_ArrowMemberAccess; 4492 } else { 4493 if (ConvertedBaseType->isObjCObjectPointerType() || 4494 ConvertedBaseType->isObjCObjectOrInterfaceType()) { 4495 contextKind = CodeCompletionContext::CCC_ObjCPropertyAccess; 4496 } else { 4497 contextKind = CodeCompletionContext::CCC_DotMemberAccess; 4498 } 4499 } 4500 4501 CodeCompletionContext CCContext(contextKind, ConvertedBaseType); 4502 CCContext.setPreferredType(PreferredType); 4503 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 4504 CodeCompleter->getCodeCompletionTUInfo(), CCContext, 4505 &ResultBuilder::IsMember); 4506 4507 auto DoCompletion = [&](Expr *Base, bool IsArrow, 4508 Optional<FixItHint> AccessOpFixIt) -> bool { 4509 if (!Base) 4510 return false; 4511 4512 ExprResult ConvertedBase = PerformMemberExprBaseConversion(Base, IsArrow); 4513 if (ConvertedBase.isInvalid()) 4514 return false; 4515 Base = ConvertedBase.get(); 4516 4517 QualType BaseType = Base->getType(); 4518 4519 if (IsArrow) { 4520 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) 4521 BaseType = Ptr->getPointeeType(); 4522 else if (BaseType->isObjCObjectPointerType()) 4523 /*Do nothing*/; 4524 else 4525 return false; 4526 } 4527 4528 if (const RecordType *Record = BaseType->getAs<RecordType>()) { 4529 AddRecordMembersCompletionResults(*this, Results, S, BaseType, 4530 Record->getDecl(), 4531 std::move(AccessOpFixIt)); 4532 } else if (const auto *TST = 4533 BaseType->getAs<TemplateSpecializationType>()) { 4534 TemplateName TN = TST->getTemplateName(); 4535 if (const auto *TD = 4536 dyn_cast_or_null<ClassTemplateDecl>(TN.getAsTemplateDecl())) { 4537 CXXRecordDecl *RD = TD->getTemplatedDecl(); 4538 AddRecordMembersCompletionResults(*this, Results, S, BaseType, RD, 4539 std::move(AccessOpFixIt)); 4540 } 4541 } else if (const auto *ICNT = BaseType->getAs<InjectedClassNameType>()) { 4542 if (auto *RD = ICNT->getDecl()) 4543 AddRecordMembersCompletionResults(*this, Results, S, BaseType, RD, 4544 std::move(AccessOpFixIt)); 4545 } else if (!IsArrow && BaseType->isObjCObjectPointerType()) { 4546 // Objective-C property reference. 4547 AddedPropertiesSet AddedProperties; 4548 4549 if (const ObjCObjectPointerType *ObjCPtr = 4550 BaseType->getAsObjCInterfacePointerType()) { 4551 // Add property results based on our interface. 4552 assert(ObjCPtr && "Non-NULL pointer guaranteed above!"); 4553 AddObjCProperties(CCContext, ObjCPtr->getInterfaceDecl(), true, 4554 /*AllowNullaryMethods=*/true, CurContext, 4555 AddedProperties, Results, IsBaseExprStatement); 4556 } 4557 4558 // Add properties from the protocols in a qualified interface. 4559 for (auto *I : BaseType->getAs<ObjCObjectPointerType>()->quals()) 4560 AddObjCProperties(CCContext, I, true, /*AllowNullaryMethods=*/true, 4561 CurContext, AddedProperties, Results, 4562 IsBaseExprStatement, /*IsClassProperty*/ false, 4563 /*InOriginalClass*/ false); 4564 } else if ((IsArrow && BaseType->isObjCObjectPointerType()) || 4565 (!IsArrow && BaseType->isObjCObjectType())) { 4566 // Objective-C instance variable access. 4567 ObjCInterfaceDecl *Class = nullptr; 4568 if (const ObjCObjectPointerType *ObjCPtr = 4569 BaseType->getAs<ObjCObjectPointerType>()) 4570 Class = ObjCPtr->getInterfaceDecl(); 4571 else 4572 Class = BaseType->getAs<ObjCObjectType>()->getInterface(); 4573 4574 // Add all ivars from this class and its superclasses. 4575 if (Class) { 4576 CodeCompletionDeclConsumer Consumer(Results, Class, BaseType); 4577 Results.setFilter(&ResultBuilder::IsObjCIvar); 4578 LookupVisibleDecls( 4579 Class, LookupMemberName, Consumer, CodeCompleter->includeGlobals(), 4580 /*IncludeDependentBases=*/false, CodeCompleter->loadExternal()); 4581 } 4582 } 4583 4584 // FIXME: How do we cope with isa? 4585 return true; 4586 }; 4587 4588 Results.EnterNewScope(); 4589 4590 bool CompletionSucceded = DoCompletion(Base, IsArrow, None); 4591 if (CodeCompleter->includeFixIts()) { 4592 const CharSourceRange OpRange = 4593 CharSourceRange::getTokenRange(OpLoc, OpLoc); 4594 CompletionSucceded |= DoCompletion( 4595 OtherOpBase, !IsArrow, 4596 FixItHint::CreateReplacement(OpRange, IsArrow ? "." : "->")); 4597 } 4598 4599 Results.ExitScope(); 4600 4601 if (!CompletionSucceded) 4602 return; 4603 4604 // Hand off the results found for code completion. 4605 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 4606 Results.data(), Results.size()); 4607 } 4608 4609 void Sema::CodeCompleteObjCClassPropertyRefExpr(Scope *S, 4610 IdentifierInfo &ClassName, 4611 SourceLocation ClassNameLoc, 4612 bool IsBaseExprStatement) { 4613 IdentifierInfo *ClassNamePtr = &ClassName; 4614 ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(ClassNamePtr, ClassNameLoc); 4615 if (!IFace) 4616 return; 4617 CodeCompletionContext CCContext( 4618 CodeCompletionContext::CCC_ObjCPropertyAccess); 4619 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 4620 CodeCompleter->getCodeCompletionTUInfo(), CCContext, 4621 &ResultBuilder::IsMember); 4622 Results.EnterNewScope(); 4623 AddedPropertiesSet AddedProperties; 4624 AddObjCProperties(CCContext, IFace, true, 4625 /*AllowNullaryMethods=*/true, CurContext, AddedProperties, 4626 Results, IsBaseExprStatement, 4627 /*IsClassProperty=*/true); 4628 Results.ExitScope(); 4629 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 4630 Results.data(), Results.size()); 4631 } 4632 4633 void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) { 4634 if (!CodeCompleter) 4635 return; 4636 4637 ResultBuilder::LookupFilter Filter = nullptr; 4638 enum CodeCompletionContext::Kind ContextKind = 4639 CodeCompletionContext::CCC_Other; 4640 switch ((DeclSpec::TST)TagSpec) { 4641 case DeclSpec::TST_enum: 4642 Filter = &ResultBuilder::IsEnum; 4643 ContextKind = CodeCompletionContext::CCC_EnumTag; 4644 break; 4645 4646 case DeclSpec::TST_union: 4647 Filter = &ResultBuilder::IsUnion; 4648 ContextKind = CodeCompletionContext::CCC_UnionTag; 4649 break; 4650 4651 case DeclSpec::TST_struct: 4652 case DeclSpec::TST_class: 4653 case DeclSpec::TST_interface: 4654 Filter = &ResultBuilder::IsClassOrStruct; 4655 ContextKind = CodeCompletionContext::CCC_ClassOrStructTag; 4656 break; 4657 4658 default: 4659 llvm_unreachable("Unknown type specifier kind in CodeCompleteTag"); 4660 } 4661 4662 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 4663 CodeCompleter->getCodeCompletionTUInfo(), ContextKind); 4664 CodeCompletionDeclConsumer Consumer(Results, CurContext); 4665 4666 // First pass: look for tags. 4667 Results.setFilter(Filter); 4668 LookupVisibleDecls(S, LookupTagName, Consumer, 4669 CodeCompleter->includeGlobals(), 4670 CodeCompleter->loadExternal()); 4671 4672 if (CodeCompleter->includeGlobals()) { 4673 // Second pass: look for nested name specifiers. 4674 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier); 4675 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer, 4676 CodeCompleter->includeGlobals(), 4677 CodeCompleter->loadExternal()); 4678 } 4679 4680 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 4681 Results.data(), Results.size()); 4682 } 4683 4684 static void AddTypeQualifierResults(DeclSpec &DS, ResultBuilder &Results, 4685 const LangOptions &LangOpts) { 4686 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_const)) 4687 Results.AddResult("const"); 4688 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_volatile)) 4689 Results.AddResult("volatile"); 4690 if (LangOpts.C99 && !(DS.getTypeQualifiers() & DeclSpec::TQ_restrict)) 4691 Results.AddResult("restrict"); 4692 if (LangOpts.C11 && !(DS.getTypeQualifiers() & DeclSpec::TQ_atomic)) 4693 Results.AddResult("_Atomic"); 4694 if (LangOpts.MSVCCompat && !(DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)) 4695 Results.AddResult("__unaligned"); 4696 } 4697 4698 void Sema::CodeCompleteTypeQualifiers(DeclSpec &DS) { 4699 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 4700 CodeCompleter->getCodeCompletionTUInfo(), 4701 CodeCompletionContext::CCC_TypeQualifiers); 4702 Results.EnterNewScope(); 4703 AddTypeQualifierResults(DS, Results, LangOpts); 4704 Results.ExitScope(); 4705 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 4706 Results.data(), Results.size()); 4707 } 4708 4709 void Sema::CodeCompleteFunctionQualifiers(DeclSpec &DS, Declarator &D, 4710 const VirtSpecifiers *VS) { 4711 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 4712 CodeCompleter->getCodeCompletionTUInfo(), 4713 CodeCompletionContext::CCC_TypeQualifiers); 4714 Results.EnterNewScope(); 4715 AddTypeQualifierResults(DS, Results, LangOpts); 4716 if (LangOpts.CPlusPlus11) { 4717 Results.AddResult("noexcept"); 4718 if (D.getContext() == DeclaratorContext::MemberContext && 4719 !D.isCtorOrDtor() && !D.isStaticMember()) { 4720 if (!VS || !VS->isFinalSpecified()) 4721 Results.AddResult("final"); 4722 if (!VS || !VS->isOverrideSpecified()) 4723 Results.AddResult("override"); 4724 } 4725 } 4726 Results.ExitScope(); 4727 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 4728 Results.data(), Results.size()); 4729 } 4730 4731 void Sema::CodeCompleteBracketDeclarator(Scope *S) { 4732 CodeCompleteExpression(S, QualType(getASTContext().getSizeType())); 4733 } 4734 4735 void Sema::CodeCompleteCase(Scope *S) { 4736 if (getCurFunction()->SwitchStack.empty() || !CodeCompleter) 4737 return; 4738 4739 SwitchStmt *Switch = getCurFunction()->SwitchStack.back().getPointer(); 4740 // Condition expression might be invalid, do not continue in this case. 4741 if (!Switch->getCond()) 4742 return; 4743 QualType type = Switch->getCond()->IgnoreImplicit()->getType(); 4744 if (!type->isEnumeralType()) { 4745 CodeCompleteExpressionData Data(type); 4746 Data.IntegralConstantExpression = true; 4747 CodeCompleteExpression(S, Data); 4748 return; 4749 } 4750 4751 // Code-complete the cases of a switch statement over an enumeration type 4752 // by providing the list of 4753 EnumDecl *Enum = type->castAs<EnumType>()->getDecl(); 4754 if (EnumDecl *Def = Enum->getDefinition()) 4755 Enum = Def; 4756 4757 // Determine which enumerators we have already seen in the switch statement. 4758 // FIXME: Ideally, we would also be able to look *past* the code-completion 4759 // token, in case we are code-completing in the middle of the switch and not 4760 // at the end. However, we aren't able to do so at the moment. 4761 CoveredEnumerators Enumerators; 4762 for (SwitchCase *SC = Switch->getSwitchCaseList(); SC; 4763 SC = SC->getNextSwitchCase()) { 4764 CaseStmt *Case = dyn_cast<CaseStmt>(SC); 4765 if (!Case) 4766 continue; 4767 4768 Expr *CaseVal = Case->getLHS()->IgnoreParenCasts(); 4769 if (auto *DRE = dyn_cast<DeclRefExpr>(CaseVal)) 4770 if (auto *Enumerator = 4771 dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 4772 // We look into the AST of the case statement to determine which 4773 // enumerator was named. Alternatively, we could compute the value of 4774 // the integral constant expression, then compare it against the 4775 // values of each enumerator. However, value-based approach would not 4776 // work as well with C++ templates where enumerators declared within a 4777 // template are type- and value-dependent. 4778 Enumerators.Seen.insert(Enumerator); 4779 4780 // If this is a qualified-id, keep track of the nested-name-specifier 4781 // so that we can reproduce it as part of code completion, e.g., 4782 // 4783 // switch (TagD.getKind()) { 4784 // case TagDecl::TK_enum: 4785 // break; 4786 // case XXX 4787 // 4788 // At the XXX, our completions are TagDecl::TK_union, 4789 // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union, 4790 // TK_struct, and TK_class. 4791 Enumerators.SuggestedQualifier = DRE->getQualifier(); 4792 } 4793 } 4794 4795 // Add any enumerators that have not yet been mentioned. 4796 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 4797 CodeCompleter->getCodeCompletionTUInfo(), 4798 CodeCompletionContext::CCC_Expression); 4799 AddEnumerators(Results, Context, Enum, CurContext, Enumerators); 4800 4801 if (CodeCompleter->includeMacros()) { 4802 AddMacroResults(PP, Results, CodeCompleter->loadExternal(), false); 4803 } 4804 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 4805 Results.data(), Results.size()); 4806 } 4807 4808 static bool anyNullArguments(ArrayRef<Expr *> Args) { 4809 if (Args.size() && !Args.data()) 4810 return true; 4811 4812 for (unsigned I = 0; I != Args.size(); ++I) 4813 if (!Args[I]) 4814 return true; 4815 4816 return false; 4817 } 4818 4819 typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate; 4820 4821 static void mergeCandidatesWithResults( 4822 Sema &SemaRef, SmallVectorImpl<ResultCandidate> &Results, 4823 OverloadCandidateSet &CandidateSet, SourceLocation Loc) { 4824 // Sort the overload candidate set by placing the best overloads first. 4825 llvm::stable_sort(CandidateSet, [&](const OverloadCandidate &X, 4826 const OverloadCandidate &Y) { 4827 return isBetterOverloadCandidate(SemaRef, X, Y, Loc, 4828 CandidateSet.getKind()); 4829 }); 4830 4831 // Add the remaining viable overload candidates as code-completion results. 4832 for (OverloadCandidate &Candidate : CandidateSet) { 4833 if (Candidate.Function && Candidate.Function->isDeleted()) 4834 continue; 4835 if (Candidate.Viable) 4836 Results.push_back(ResultCandidate(Candidate.Function)); 4837 } 4838 } 4839 4840 /// Get the type of the Nth parameter from a given set of overload 4841 /// candidates. 4842 static QualType getParamType(Sema &SemaRef, 4843 ArrayRef<ResultCandidate> Candidates, unsigned N) { 4844 4845 // Given the overloads 'Candidates' for a function call matching all arguments 4846 // up to N, return the type of the Nth parameter if it is the same for all 4847 // overload candidates. 4848 QualType ParamType; 4849 for (auto &Candidate : Candidates) { 4850 if (const auto *FType = Candidate.getFunctionType()) 4851 if (const auto *Proto = dyn_cast<FunctionProtoType>(FType)) 4852 if (N < Proto->getNumParams()) { 4853 if (ParamType.isNull()) 4854 ParamType = Proto->getParamType(N); 4855 else if (!SemaRef.Context.hasSameUnqualifiedType( 4856 ParamType.getNonReferenceType(), 4857 Proto->getParamType(N).getNonReferenceType())) 4858 // Otherwise return a default-constructed QualType. 4859 return QualType(); 4860 } 4861 } 4862 4863 return ParamType; 4864 } 4865 4866 static QualType 4867 ProduceSignatureHelp(Sema &SemaRef, Scope *S, 4868 MutableArrayRef<ResultCandidate> Candidates, 4869 unsigned CurrentArg, SourceLocation OpenParLoc) { 4870 if (Candidates.empty()) 4871 return QualType(); 4872 SemaRef.CodeCompleter->ProcessOverloadCandidates( 4873 SemaRef, CurrentArg, Candidates.data(), Candidates.size(), OpenParLoc); 4874 return getParamType(SemaRef, Candidates, CurrentArg); 4875 } 4876 4877 QualType Sema::ProduceCallSignatureHelp(Scope *S, Expr *Fn, 4878 ArrayRef<Expr *> Args, 4879 SourceLocation OpenParLoc) { 4880 if (!CodeCompleter) 4881 return QualType(); 4882 4883 // FIXME: Provide support for variadic template functions. 4884 // Ignore type-dependent call expressions entirely. 4885 if (!Fn || Fn->isTypeDependent() || anyNullArguments(Args) || 4886 Expr::hasAnyTypeDependentArguments(Args)) { 4887 return QualType(); 4888 } 4889 4890 // Build an overload candidate set based on the functions we find. 4891 SourceLocation Loc = Fn->getExprLoc(); 4892 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); 4893 4894 SmallVector<ResultCandidate, 8> Results; 4895 4896 Expr *NakedFn = Fn->IgnoreParenCasts(); 4897 if (auto ULE = dyn_cast<UnresolvedLookupExpr>(NakedFn)) 4898 AddOverloadedCallCandidates(ULE, Args, CandidateSet, 4899 /*PartialOverloading=*/true); 4900 else if (auto UME = dyn_cast<UnresolvedMemberExpr>(NakedFn)) { 4901 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 4902 if (UME->hasExplicitTemplateArgs()) { 4903 UME->copyTemplateArgumentsInto(TemplateArgsBuffer); 4904 TemplateArgs = &TemplateArgsBuffer; 4905 } 4906 4907 // Add the base as first argument (use a nullptr if the base is implicit). 4908 SmallVector<Expr *, 12> ArgExprs( 4909 1, UME->isImplicitAccess() ? nullptr : UME->getBase()); 4910 ArgExprs.append(Args.begin(), Args.end()); 4911 UnresolvedSet<8> Decls; 4912 Decls.append(UME->decls_begin(), UME->decls_end()); 4913 const bool FirstArgumentIsBase = !UME->isImplicitAccess() && UME->getBase(); 4914 AddFunctionCandidates(Decls, ArgExprs, CandidateSet, TemplateArgs, 4915 /*SuppressUsedConversions=*/false, 4916 /*PartialOverloading=*/true, FirstArgumentIsBase); 4917 } else { 4918 FunctionDecl *FD = nullptr; 4919 if (auto *MCE = dyn_cast<MemberExpr>(NakedFn)) 4920 FD = dyn_cast<FunctionDecl>(MCE->getMemberDecl()); 4921 else if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) 4922 FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 4923 if (FD) { // We check whether it's a resolved function declaration. 4924 if (!getLangOpts().CPlusPlus || 4925 !FD->getType()->getAs<FunctionProtoType>()) 4926 Results.push_back(ResultCandidate(FD)); 4927 else 4928 AddOverloadCandidate(FD, DeclAccessPair::make(FD, FD->getAccess()), 4929 Args, CandidateSet, 4930 /*SuppressUsedConversions=*/false, 4931 /*PartialOverloading=*/true); 4932 4933 } else if (auto DC = NakedFn->getType()->getAsCXXRecordDecl()) { 4934 // If expression's type is CXXRecordDecl, it may overload the function 4935 // call operator, so we check if it does and add them as candidates. 4936 // A complete type is needed to lookup for member function call operators. 4937 if (isCompleteType(Loc, NakedFn->getType())) { 4938 DeclarationName OpName = 4939 Context.DeclarationNames.getCXXOperatorName(OO_Call); 4940 LookupResult R(*this, OpName, Loc, LookupOrdinaryName); 4941 LookupQualifiedName(R, DC); 4942 R.suppressDiagnostics(); 4943 SmallVector<Expr *, 12> ArgExprs(1, NakedFn); 4944 ArgExprs.append(Args.begin(), Args.end()); 4945 AddFunctionCandidates(R.asUnresolvedSet(), ArgExprs, CandidateSet, 4946 /*ExplicitArgs=*/nullptr, 4947 /*SuppressUsedConversions=*/false, 4948 /*PartialOverloading=*/true); 4949 } 4950 } else { 4951 // Lastly we check whether expression's type is function pointer or 4952 // function. 4953 QualType T = NakedFn->getType(); 4954 if (!T->getPointeeType().isNull()) 4955 T = T->getPointeeType(); 4956 4957 if (auto FP = T->getAs<FunctionProtoType>()) { 4958 if (!TooManyArguments(FP->getNumParams(), Args.size(), 4959 /*PartialOverloading=*/true) || 4960 FP->isVariadic()) 4961 Results.push_back(ResultCandidate(FP)); 4962 } else if (auto FT = T->getAs<FunctionType>()) 4963 // No prototype and declaration, it may be a K & R style function. 4964 Results.push_back(ResultCandidate(FT)); 4965 } 4966 } 4967 mergeCandidatesWithResults(*this, Results, CandidateSet, Loc); 4968 QualType ParamType = 4969 ProduceSignatureHelp(*this, S, Results, Args.size(), OpenParLoc); 4970 return !CandidateSet.empty() ? ParamType : QualType(); 4971 } 4972 4973 QualType Sema::ProduceConstructorSignatureHelp(Scope *S, QualType Type, 4974 SourceLocation Loc, 4975 ArrayRef<Expr *> Args, 4976 SourceLocation OpenParLoc) { 4977 if (!CodeCompleter) 4978 return QualType(); 4979 4980 // A complete type is needed to lookup for constructors. 4981 CXXRecordDecl *RD = 4982 isCompleteType(Loc, Type) ? Type->getAsCXXRecordDecl() : nullptr; 4983 if (!RD) 4984 return Type; 4985 4986 // FIXME: Provide support for member initializers. 4987 // FIXME: Provide support for variadic template constructors. 4988 4989 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); 4990 4991 for (NamedDecl *C : LookupConstructors(RD)) { 4992 if (auto *FD = dyn_cast<FunctionDecl>(C)) { 4993 AddOverloadCandidate(FD, DeclAccessPair::make(FD, C->getAccess()), Args, 4994 CandidateSet, 4995 /*SuppressUsedConversions=*/false, 4996 /*PartialOverloading=*/true, 4997 /*AllowExplicit*/ true); 4998 } else if (auto *FTD = dyn_cast<FunctionTemplateDecl>(C)) { 4999 AddTemplateOverloadCandidate( 5000 FTD, DeclAccessPair::make(FTD, C->getAccess()), 5001 /*ExplicitTemplateArgs=*/nullptr, Args, CandidateSet, 5002 /*SuppressUsedConversions=*/false, 5003 /*PartialOverloading=*/true); 5004 } 5005 } 5006 5007 SmallVector<ResultCandidate, 8> Results; 5008 mergeCandidatesWithResults(*this, Results, CandidateSet, Loc); 5009 return ProduceSignatureHelp(*this, S, Results, Args.size(), OpenParLoc); 5010 } 5011 5012 QualType Sema::ProduceCtorInitMemberSignatureHelp( 5013 Scope *S, Decl *ConstructorDecl, CXXScopeSpec SS, ParsedType TemplateTypeTy, 5014 ArrayRef<Expr *> ArgExprs, IdentifierInfo *II, SourceLocation OpenParLoc) { 5015 if (!CodeCompleter) 5016 return QualType(); 5017 5018 CXXConstructorDecl *Constructor = 5019 dyn_cast<CXXConstructorDecl>(ConstructorDecl); 5020 if (!Constructor) 5021 return QualType(); 5022 // FIXME: Add support for Base class constructors as well. 5023 if (ValueDecl *MemberDecl = tryLookupCtorInitMemberDecl( 5024 Constructor->getParent(), SS, TemplateTypeTy, II)) 5025 return ProduceConstructorSignatureHelp(getCurScope(), MemberDecl->getType(), 5026 MemberDecl->getLocation(), ArgExprs, 5027 OpenParLoc); 5028 return QualType(); 5029 } 5030 5031 void Sema::CodeCompleteInitializer(Scope *S, Decl *D) { 5032 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D); 5033 if (!VD) { 5034 CodeCompleteOrdinaryName(S, PCC_Expression); 5035 return; 5036 } 5037 5038 CodeCompleteExpressionData Data; 5039 Data.PreferredType = VD->getType(); 5040 // Ignore VD to avoid completing the variable itself, e.g. in 'int foo = ^'. 5041 Data.IgnoreDecls.push_back(VD); 5042 5043 CodeCompleteExpression(S, Data); 5044 } 5045 5046 void Sema::CodeCompleteAfterIf(Scope *S) { 5047 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5048 CodeCompleter->getCodeCompletionTUInfo(), 5049 mapCodeCompletionContext(*this, PCC_Statement)); 5050 Results.setFilter(&ResultBuilder::IsOrdinaryName); 5051 Results.EnterNewScope(); 5052 5053 CodeCompletionDeclConsumer Consumer(Results, CurContext); 5054 LookupVisibleDecls(S, LookupOrdinaryName, Consumer, 5055 CodeCompleter->includeGlobals(), 5056 CodeCompleter->loadExternal()); 5057 5058 AddOrdinaryNameResults(PCC_Statement, S, *this, Results); 5059 5060 // "else" block 5061 CodeCompletionBuilder Builder(Results.getAllocator(), 5062 Results.getCodeCompletionTUInfo()); 5063 Builder.AddTypedTextChunk("else"); 5064 if (Results.includeCodePatterns()) { 5065 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 5066 Builder.AddChunk(CodeCompletionString::CK_LeftBrace); 5067 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); 5068 Builder.AddPlaceholderChunk("statements"); 5069 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); 5070 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 5071 } 5072 Results.AddResult(Builder.TakeString()); 5073 5074 // "else if" block 5075 Builder.AddTypedTextChunk("else"); 5076 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 5077 Builder.AddTextChunk("if"); 5078 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 5079 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 5080 if (getLangOpts().CPlusPlus) 5081 Builder.AddPlaceholderChunk("condition"); 5082 else 5083 Builder.AddPlaceholderChunk("expression"); 5084 Builder.AddChunk(CodeCompletionString::CK_RightParen); 5085 if (Results.includeCodePatterns()) { 5086 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 5087 Builder.AddChunk(CodeCompletionString::CK_LeftBrace); 5088 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); 5089 Builder.AddPlaceholderChunk("statements"); 5090 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); 5091 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 5092 } 5093 Results.AddResult(Builder.TakeString()); 5094 5095 Results.ExitScope(); 5096 5097 if (S->getFnParent()) 5098 AddPrettyFunctionResults(getLangOpts(), Results); 5099 5100 if (CodeCompleter->includeMacros()) 5101 AddMacroResults(PP, Results, CodeCompleter->loadExternal(), false); 5102 5103 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 5104 Results.data(), Results.size()); 5105 } 5106 5107 void Sema::CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS, 5108 bool EnteringContext, QualType BaseType) { 5109 if (SS.isEmpty() || !CodeCompleter) 5110 return; 5111 5112 // We want to keep the scope specifier even if it's invalid (e.g. the scope 5113 // "a::b::" is not corresponding to any context/namespace in the AST), since 5114 // it can be useful for global code completion which have information about 5115 // contexts/symbols that are not in the AST. 5116 if (SS.isInvalid()) { 5117 CodeCompletionContext CC(CodeCompletionContext::CCC_Symbol); 5118 CC.setCXXScopeSpecifier(SS); 5119 // As SS is invalid, we try to collect accessible contexts from the current 5120 // scope with a dummy lookup so that the completion consumer can try to 5121 // guess what the specified scope is. 5122 ResultBuilder DummyResults(*this, CodeCompleter->getAllocator(), 5123 CodeCompleter->getCodeCompletionTUInfo(), CC); 5124 if (S->getEntity()) { 5125 CodeCompletionDeclConsumer Consumer(DummyResults, S->getEntity(), 5126 BaseType); 5127 LookupVisibleDecls(S, LookupOrdinaryName, Consumer, 5128 /*IncludeGlobalScope=*/false, 5129 /*LoadExternal=*/false); 5130 } 5131 HandleCodeCompleteResults(this, CodeCompleter, 5132 DummyResults.getCompletionContext(), nullptr, 0); 5133 return; 5134 } 5135 // Always pretend to enter a context to ensure that a dependent type 5136 // resolves to a dependent record. 5137 DeclContext *Ctx = computeDeclContext(SS, /*EnteringContext=*/true); 5138 if (!Ctx) 5139 return; 5140 5141 // Try to instantiate any non-dependent declaration contexts before 5142 // we look in them. 5143 if (!isDependentScopeSpecifier(SS) && RequireCompleteDeclContext(SS, Ctx)) 5144 return; 5145 5146 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5147 CodeCompleter->getCodeCompletionTUInfo(), 5148 CodeCompletionContext::CCC_Symbol); 5149 Results.EnterNewScope(); 5150 5151 // The "template" keyword can follow "::" in the grammar, but only 5152 // put it into the grammar if the nested-name-specifier is dependent. 5153 NestedNameSpecifier *NNS = SS.getScopeRep(); 5154 if (!Results.empty() && NNS->isDependent()) 5155 Results.AddResult("template"); 5156 5157 // Add calls to overridden virtual functions, if there are any. 5158 // 5159 // FIXME: This isn't wonderful, because we don't know whether we're actually 5160 // in a context that permits expressions. This is a general issue with 5161 // qualified-id completions. 5162 if (!EnteringContext) 5163 MaybeAddOverrideCalls(*this, Ctx, Results); 5164 Results.ExitScope(); 5165 5166 if (CodeCompleter->includeNamespaceLevelDecls() || 5167 (!Ctx->isNamespace() && !Ctx->isTranslationUnit())) { 5168 CodeCompletionDeclConsumer Consumer(Results, Ctx, BaseType); 5169 LookupVisibleDecls(Ctx, LookupOrdinaryName, Consumer, 5170 /*IncludeGlobalScope=*/true, 5171 /*IncludeDependentBases=*/true, 5172 CodeCompleter->loadExternal()); 5173 } 5174 5175 auto CC = Results.getCompletionContext(); 5176 CC.setCXXScopeSpecifier(SS); 5177 5178 HandleCodeCompleteResults(this, CodeCompleter, CC, Results.data(), 5179 Results.size()); 5180 } 5181 5182 void Sema::CodeCompleteUsing(Scope *S) { 5183 if (!CodeCompleter) 5184 return; 5185 5186 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5187 CodeCompleter->getCodeCompletionTUInfo(), 5188 // This can be both a using alias or using 5189 // declaration, in the former we expect a new name and a 5190 // symbol in the latter case. 5191 CodeCompletionContext::CCC_SymbolOrNewName, 5192 &ResultBuilder::IsNestedNameSpecifier); 5193 Results.EnterNewScope(); 5194 5195 // If we aren't in class scope, we could see the "namespace" keyword. 5196 if (!S->isClassScope()) 5197 Results.AddResult(CodeCompletionResult("namespace")); 5198 5199 // After "using", we can see anything that would start a 5200 // nested-name-specifier. 5201 CodeCompletionDeclConsumer Consumer(Results, CurContext); 5202 LookupVisibleDecls(S, LookupOrdinaryName, Consumer, 5203 CodeCompleter->includeGlobals(), 5204 CodeCompleter->loadExternal()); 5205 Results.ExitScope(); 5206 5207 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 5208 Results.data(), Results.size()); 5209 } 5210 5211 void Sema::CodeCompleteUsingDirective(Scope *S) { 5212 if (!CodeCompleter) 5213 return; 5214 5215 // After "using namespace", we expect to see a namespace name or namespace 5216 // alias. 5217 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5218 CodeCompleter->getCodeCompletionTUInfo(), 5219 CodeCompletionContext::CCC_Namespace, 5220 &ResultBuilder::IsNamespaceOrAlias); 5221 Results.EnterNewScope(); 5222 CodeCompletionDeclConsumer Consumer(Results, CurContext); 5223 LookupVisibleDecls(S, LookupOrdinaryName, Consumer, 5224 CodeCompleter->includeGlobals(), 5225 CodeCompleter->loadExternal()); 5226 Results.ExitScope(); 5227 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 5228 Results.data(), Results.size()); 5229 } 5230 5231 void Sema::CodeCompleteNamespaceDecl(Scope *S) { 5232 if (!CodeCompleter) 5233 return; 5234 5235 DeclContext *Ctx = S->getEntity(); 5236 if (!S->getParent()) 5237 Ctx = Context.getTranslationUnitDecl(); 5238 5239 bool SuppressedGlobalResults = 5240 Ctx && !CodeCompleter->includeGlobals() && isa<TranslationUnitDecl>(Ctx); 5241 5242 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5243 CodeCompleter->getCodeCompletionTUInfo(), 5244 SuppressedGlobalResults 5245 ? CodeCompletionContext::CCC_Namespace 5246 : CodeCompletionContext::CCC_Other, 5247 &ResultBuilder::IsNamespace); 5248 5249 if (Ctx && Ctx->isFileContext() && !SuppressedGlobalResults) { 5250 // We only want to see those namespaces that have already been defined 5251 // within this scope, because its likely that the user is creating an 5252 // extended namespace declaration. Keep track of the most recent 5253 // definition of each namespace. 5254 std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest; 5255 for (DeclContext::specific_decl_iterator<NamespaceDecl> 5256 NS(Ctx->decls_begin()), 5257 NSEnd(Ctx->decls_end()); 5258 NS != NSEnd; ++NS) 5259 OrigToLatest[NS->getOriginalNamespace()] = *NS; 5260 5261 // Add the most recent definition (or extended definition) of each 5262 // namespace to the list of results. 5263 Results.EnterNewScope(); 5264 for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator 5265 NS = OrigToLatest.begin(), 5266 NSEnd = OrigToLatest.end(); 5267 NS != NSEnd; ++NS) 5268 Results.AddResult( 5269 CodeCompletionResult(NS->second, Results.getBasePriority(NS->second), 5270 nullptr), 5271 CurContext, nullptr, false); 5272 Results.ExitScope(); 5273 } 5274 5275 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 5276 Results.data(), Results.size()); 5277 } 5278 5279 void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) { 5280 if (!CodeCompleter) 5281 return; 5282 5283 // After "namespace", we expect to see a namespace or alias. 5284 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5285 CodeCompleter->getCodeCompletionTUInfo(), 5286 CodeCompletionContext::CCC_Namespace, 5287 &ResultBuilder::IsNamespaceOrAlias); 5288 CodeCompletionDeclConsumer Consumer(Results, CurContext); 5289 LookupVisibleDecls(S, LookupOrdinaryName, Consumer, 5290 CodeCompleter->includeGlobals(), 5291 CodeCompleter->loadExternal()); 5292 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 5293 Results.data(), Results.size()); 5294 } 5295 5296 void Sema::CodeCompleteOperatorName(Scope *S) { 5297 if (!CodeCompleter) 5298 return; 5299 5300 typedef CodeCompletionResult Result; 5301 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5302 CodeCompleter->getCodeCompletionTUInfo(), 5303 CodeCompletionContext::CCC_Type, 5304 &ResultBuilder::IsType); 5305 Results.EnterNewScope(); 5306 5307 // Add the names of overloadable operators. 5308 #define OVERLOADED_OPERATOR(Name, Spelling, Token, Unary, Binary, MemberOnly) \ 5309 if (std::strcmp(Spelling, "?")) \ 5310 Results.AddResult(Result(Spelling)); 5311 #include "clang/Basic/OperatorKinds.def" 5312 5313 // Add any type names visible from the current scope 5314 Results.allowNestedNameSpecifiers(); 5315 CodeCompletionDeclConsumer Consumer(Results, CurContext); 5316 LookupVisibleDecls(S, LookupOrdinaryName, Consumer, 5317 CodeCompleter->includeGlobals(), 5318 CodeCompleter->loadExternal()); 5319 5320 // Add any type specifiers 5321 AddTypeSpecifierResults(getLangOpts(), Results); 5322 Results.ExitScope(); 5323 5324 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 5325 Results.data(), Results.size()); 5326 } 5327 5328 void Sema::CodeCompleteConstructorInitializer( 5329 Decl *ConstructorD, ArrayRef<CXXCtorInitializer *> Initializers) { 5330 if (!ConstructorD) 5331 return; 5332 5333 AdjustDeclIfTemplate(ConstructorD); 5334 5335 auto *Constructor = dyn_cast<CXXConstructorDecl>(ConstructorD); 5336 if (!Constructor) 5337 return; 5338 5339 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5340 CodeCompleter->getCodeCompletionTUInfo(), 5341 CodeCompletionContext::CCC_Symbol); 5342 Results.EnterNewScope(); 5343 5344 // Fill in any already-initialized fields or base classes. 5345 llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields; 5346 llvm::SmallPtrSet<CanQualType, 4> InitializedBases; 5347 for (unsigned I = 0, E = Initializers.size(); I != E; ++I) { 5348 if (Initializers[I]->isBaseInitializer()) 5349 InitializedBases.insert(Context.getCanonicalType( 5350 QualType(Initializers[I]->getBaseClass(), 0))); 5351 else 5352 InitializedFields.insert( 5353 cast<FieldDecl>(Initializers[I]->getAnyMember())); 5354 } 5355 5356 // Add completions for base classes. 5357 PrintingPolicy Policy = getCompletionPrintingPolicy(*this); 5358 bool SawLastInitializer = Initializers.empty(); 5359 CXXRecordDecl *ClassDecl = Constructor->getParent(); 5360 5361 auto GenerateCCS = [&](const NamedDecl *ND, const char *Name) { 5362 CodeCompletionBuilder Builder(Results.getAllocator(), 5363 Results.getCodeCompletionTUInfo()); 5364 Builder.AddTypedTextChunk(Name); 5365 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 5366 if (const auto *Function = dyn_cast<FunctionDecl>(ND)) 5367 AddFunctionParameterChunks(PP, Policy, Function, Builder); 5368 else if (const auto *FunTemplDecl = dyn_cast<FunctionTemplateDecl>(ND)) 5369 AddFunctionParameterChunks(PP, Policy, FunTemplDecl->getTemplatedDecl(), 5370 Builder); 5371 Builder.AddChunk(CodeCompletionString::CK_RightParen); 5372 return Builder.TakeString(); 5373 }; 5374 auto AddDefaultCtorInit = [&](const char *Name, const char *Type, 5375 const NamedDecl *ND) { 5376 CodeCompletionBuilder Builder(Results.getAllocator(), 5377 Results.getCodeCompletionTUInfo()); 5378 Builder.AddTypedTextChunk(Name); 5379 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 5380 Builder.AddPlaceholderChunk(Type); 5381 Builder.AddChunk(CodeCompletionString::CK_RightParen); 5382 if (ND) { 5383 auto CCR = CodeCompletionResult( 5384 Builder.TakeString(), ND, 5385 SawLastInitializer ? CCP_NextInitializer : CCP_MemberDeclaration); 5386 if (isa<FieldDecl>(ND)) 5387 CCR.CursorKind = CXCursor_MemberRef; 5388 return Results.AddResult(CCR); 5389 } 5390 return Results.AddResult(CodeCompletionResult( 5391 Builder.TakeString(), 5392 SawLastInitializer ? CCP_NextInitializer : CCP_MemberDeclaration)); 5393 }; 5394 auto AddCtorsWithName = [&](const CXXRecordDecl *RD, unsigned int Priority, 5395 const char *Name, const FieldDecl *FD) { 5396 if (!RD) 5397 return AddDefaultCtorInit(Name, 5398 FD ? Results.getAllocator().CopyString( 5399 FD->getType().getAsString(Policy)) 5400 : Name, 5401 FD); 5402 auto Ctors = getConstructors(Context, RD); 5403 if (Ctors.begin() == Ctors.end()) 5404 return AddDefaultCtorInit(Name, Name, RD); 5405 for (const NamedDecl *Ctor : Ctors) { 5406 auto CCR = CodeCompletionResult(GenerateCCS(Ctor, Name), RD, Priority); 5407 CCR.CursorKind = getCursorKindForDecl(Ctor); 5408 Results.AddResult(CCR); 5409 } 5410 }; 5411 auto AddBase = [&](const CXXBaseSpecifier &Base) { 5412 const char *BaseName = 5413 Results.getAllocator().CopyString(Base.getType().getAsString(Policy)); 5414 const auto *RD = Base.getType()->getAsCXXRecordDecl(); 5415 AddCtorsWithName( 5416 RD, SawLastInitializer ? CCP_NextInitializer : CCP_MemberDeclaration, 5417 BaseName, nullptr); 5418 }; 5419 auto AddField = [&](const FieldDecl *FD) { 5420 const char *FieldName = 5421 Results.getAllocator().CopyString(FD->getIdentifier()->getName()); 5422 const CXXRecordDecl *RD = FD->getType()->getAsCXXRecordDecl(); 5423 AddCtorsWithName( 5424 RD, SawLastInitializer ? CCP_NextInitializer : CCP_MemberDeclaration, 5425 FieldName, FD); 5426 }; 5427 5428 for (const auto &Base : ClassDecl->bases()) { 5429 if (!InitializedBases.insert(Context.getCanonicalType(Base.getType())) 5430 .second) { 5431 SawLastInitializer = 5432 !Initializers.empty() && Initializers.back()->isBaseInitializer() && 5433 Context.hasSameUnqualifiedType( 5434 Base.getType(), QualType(Initializers.back()->getBaseClass(), 0)); 5435 continue; 5436 } 5437 5438 AddBase(Base); 5439 SawLastInitializer = false; 5440 } 5441 5442 // Add completions for virtual base classes. 5443 for (const auto &Base : ClassDecl->vbases()) { 5444 if (!InitializedBases.insert(Context.getCanonicalType(Base.getType())) 5445 .second) { 5446 SawLastInitializer = 5447 !Initializers.empty() && Initializers.back()->isBaseInitializer() && 5448 Context.hasSameUnqualifiedType( 5449 Base.getType(), QualType(Initializers.back()->getBaseClass(), 0)); 5450 continue; 5451 } 5452 5453 AddBase(Base); 5454 SawLastInitializer = false; 5455 } 5456 5457 // Add completions for members. 5458 for (auto *Field : ClassDecl->fields()) { 5459 if (!InitializedFields.insert(cast<FieldDecl>(Field->getCanonicalDecl())) 5460 .second) { 5461 SawLastInitializer = !Initializers.empty() && 5462 Initializers.back()->isAnyMemberInitializer() && 5463 Initializers.back()->getAnyMember() == Field; 5464 continue; 5465 } 5466 5467 if (!Field->getDeclName()) 5468 continue; 5469 5470 AddField(Field); 5471 SawLastInitializer = false; 5472 } 5473 Results.ExitScope(); 5474 5475 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 5476 Results.data(), Results.size()); 5477 } 5478 5479 /// Determine whether this scope denotes a namespace. 5480 static bool isNamespaceScope(Scope *S) { 5481 DeclContext *DC = S->getEntity(); 5482 if (!DC) 5483 return false; 5484 5485 return DC->isFileContext(); 5486 } 5487 5488 void Sema::CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro, 5489 bool AfterAmpersand) { 5490 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5491 CodeCompleter->getCodeCompletionTUInfo(), 5492 CodeCompletionContext::CCC_Other); 5493 Results.EnterNewScope(); 5494 5495 // Note what has already been captured. 5496 llvm::SmallPtrSet<IdentifierInfo *, 4> Known; 5497 bool IncludedThis = false; 5498 for (const auto &C : Intro.Captures) { 5499 if (C.Kind == LCK_This) { 5500 IncludedThis = true; 5501 continue; 5502 } 5503 5504 Known.insert(C.Id); 5505 } 5506 5507 // Look for other capturable variables. 5508 for (; S && !isNamespaceScope(S); S = S->getParent()) { 5509 for (const auto *D : S->decls()) { 5510 const auto *Var = dyn_cast<VarDecl>(D); 5511 if (!Var || !Var->hasLocalStorage() || Var->hasAttr<BlocksAttr>()) 5512 continue; 5513 5514 if (Known.insert(Var->getIdentifier()).second) 5515 Results.AddResult(CodeCompletionResult(Var, CCP_LocalDeclaration), 5516 CurContext, nullptr, false); 5517 } 5518 } 5519 5520 // Add 'this', if it would be valid. 5521 if (!IncludedThis && !AfterAmpersand && Intro.Default != LCD_ByCopy) 5522 addThisCompletion(*this, Results); 5523 5524 Results.ExitScope(); 5525 5526 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 5527 Results.data(), Results.size()); 5528 } 5529 5530 /// Macro that optionally prepends an "@" to the string literal passed in via 5531 /// Keyword, depending on whether NeedAt is true or false. 5532 #define OBJC_AT_KEYWORD_NAME(NeedAt, Keyword) ((NeedAt) ? "@" Keyword : Keyword) 5533 5534 static void AddObjCImplementationResults(const LangOptions &LangOpts, 5535 ResultBuilder &Results, bool NeedAt) { 5536 typedef CodeCompletionResult Result; 5537 // Since we have an implementation, we can end it. 5538 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "end"))); 5539 5540 CodeCompletionBuilder Builder(Results.getAllocator(), 5541 Results.getCodeCompletionTUInfo()); 5542 if (LangOpts.ObjC) { 5543 // @dynamic 5544 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "dynamic")); 5545 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 5546 Builder.AddPlaceholderChunk("property"); 5547 Results.AddResult(Result(Builder.TakeString())); 5548 5549 // @synthesize 5550 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "synthesize")); 5551 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 5552 Builder.AddPlaceholderChunk("property"); 5553 Results.AddResult(Result(Builder.TakeString())); 5554 } 5555 } 5556 5557 static void AddObjCInterfaceResults(const LangOptions &LangOpts, 5558 ResultBuilder &Results, bool NeedAt) { 5559 typedef CodeCompletionResult Result; 5560 5561 // Since we have an interface or protocol, we can end it. 5562 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "end"))); 5563 5564 if (LangOpts.ObjC) { 5565 // @property 5566 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "property"))); 5567 5568 // @required 5569 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "required"))); 5570 5571 // @optional 5572 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "optional"))); 5573 } 5574 } 5575 5576 static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt) { 5577 typedef CodeCompletionResult Result; 5578 CodeCompletionBuilder Builder(Results.getAllocator(), 5579 Results.getCodeCompletionTUInfo()); 5580 5581 // @class name ; 5582 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "class")); 5583 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 5584 Builder.AddPlaceholderChunk("name"); 5585 Results.AddResult(Result(Builder.TakeString())); 5586 5587 if (Results.includeCodePatterns()) { 5588 // @interface name 5589 // FIXME: Could introduce the whole pattern, including superclasses and 5590 // such. 5591 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "interface")); 5592 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 5593 Builder.AddPlaceholderChunk("class"); 5594 Results.AddResult(Result(Builder.TakeString())); 5595 5596 // @protocol name 5597 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "protocol")); 5598 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 5599 Builder.AddPlaceholderChunk("protocol"); 5600 Results.AddResult(Result(Builder.TakeString())); 5601 5602 // @implementation name 5603 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "implementation")); 5604 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 5605 Builder.AddPlaceholderChunk("class"); 5606 Results.AddResult(Result(Builder.TakeString())); 5607 } 5608 5609 // @compatibility_alias name 5610 Builder.AddTypedTextChunk( 5611 OBJC_AT_KEYWORD_NAME(NeedAt, "compatibility_alias")); 5612 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 5613 Builder.AddPlaceholderChunk("alias"); 5614 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 5615 Builder.AddPlaceholderChunk("class"); 5616 Results.AddResult(Result(Builder.TakeString())); 5617 5618 if (Results.getSema().getLangOpts().Modules) { 5619 // @import name 5620 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "import")); 5621 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 5622 Builder.AddPlaceholderChunk("module"); 5623 Results.AddResult(Result(Builder.TakeString())); 5624 } 5625 } 5626 5627 void Sema::CodeCompleteObjCAtDirective(Scope *S) { 5628 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5629 CodeCompleter->getCodeCompletionTUInfo(), 5630 CodeCompletionContext::CCC_Other); 5631 Results.EnterNewScope(); 5632 if (isa<ObjCImplDecl>(CurContext)) 5633 AddObjCImplementationResults(getLangOpts(), Results, false); 5634 else if (CurContext->isObjCContainer()) 5635 AddObjCInterfaceResults(getLangOpts(), Results, false); 5636 else 5637 AddObjCTopLevelResults(Results, false); 5638 Results.ExitScope(); 5639 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 5640 Results.data(), Results.size()); 5641 } 5642 5643 static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt) { 5644 typedef CodeCompletionResult Result; 5645 CodeCompletionBuilder Builder(Results.getAllocator(), 5646 Results.getCodeCompletionTUInfo()); 5647 5648 // @encode ( type-name ) 5649 const char *EncodeType = "char[]"; 5650 if (Results.getSema().getLangOpts().CPlusPlus || 5651 Results.getSema().getLangOpts().ConstStrings) 5652 EncodeType = "const char[]"; 5653 Builder.AddResultTypeChunk(EncodeType); 5654 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "encode")); 5655 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 5656 Builder.AddPlaceholderChunk("type-name"); 5657 Builder.AddChunk(CodeCompletionString::CK_RightParen); 5658 Results.AddResult(Result(Builder.TakeString())); 5659 5660 // @protocol ( protocol-name ) 5661 Builder.AddResultTypeChunk("Protocol *"); 5662 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "protocol")); 5663 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 5664 Builder.AddPlaceholderChunk("protocol-name"); 5665 Builder.AddChunk(CodeCompletionString::CK_RightParen); 5666 Results.AddResult(Result(Builder.TakeString())); 5667 5668 // @selector ( selector ) 5669 Builder.AddResultTypeChunk("SEL"); 5670 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "selector")); 5671 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 5672 Builder.AddPlaceholderChunk("selector"); 5673 Builder.AddChunk(CodeCompletionString::CK_RightParen); 5674 Results.AddResult(Result(Builder.TakeString())); 5675 5676 // @"string" 5677 Builder.AddResultTypeChunk("NSString *"); 5678 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "\"")); 5679 Builder.AddPlaceholderChunk("string"); 5680 Builder.AddTextChunk("\""); 5681 Results.AddResult(Result(Builder.TakeString())); 5682 5683 // @[objects, ...] 5684 Builder.AddResultTypeChunk("NSArray *"); 5685 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "[")); 5686 Builder.AddPlaceholderChunk("objects, ..."); 5687 Builder.AddChunk(CodeCompletionString::CK_RightBracket); 5688 Results.AddResult(Result(Builder.TakeString())); 5689 5690 // @{key : object, ...} 5691 Builder.AddResultTypeChunk("NSDictionary *"); 5692 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "{")); 5693 Builder.AddPlaceholderChunk("key"); 5694 Builder.AddChunk(CodeCompletionString::CK_Colon); 5695 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 5696 Builder.AddPlaceholderChunk("object, ..."); 5697 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 5698 Results.AddResult(Result(Builder.TakeString())); 5699 5700 // @(expression) 5701 Builder.AddResultTypeChunk("id"); 5702 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "(")); 5703 Builder.AddPlaceholderChunk("expression"); 5704 Builder.AddChunk(CodeCompletionString::CK_RightParen); 5705 Results.AddResult(Result(Builder.TakeString())); 5706 } 5707 5708 static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt) { 5709 typedef CodeCompletionResult Result; 5710 CodeCompletionBuilder Builder(Results.getAllocator(), 5711 Results.getCodeCompletionTUInfo()); 5712 5713 if (Results.includeCodePatterns()) { 5714 // @try { statements } @catch ( declaration ) { statements } @finally 5715 // { statements } 5716 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "try")); 5717 Builder.AddChunk(CodeCompletionString::CK_LeftBrace); 5718 Builder.AddPlaceholderChunk("statements"); 5719 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 5720 Builder.AddTextChunk("@catch"); 5721 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 5722 Builder.AddPlaceholderChunk("parameter"); 5723 Builder.AddChunk(CodeCompletionString::CK_RightParen); 5724 Builder.AddChunk(CodeCompletionString::CK_LeftBrace); 5725 Builder.AddPlaceholderChunk("statements"); 5726 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 5727 Builder.AddTextChunk("@finally"); 5728 Builder.AddChunk(CodeCompletionString::CK_LeftBrace); 5729 Builder.AddPlaceholderChunk("statements"); 5730 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 5731 Results.AddResult(Result(Builder.TakeString())); 5732 } 5733 5734 // @throw 5735 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "throw")); 5736 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 5737 Builder.AddPlaceholderChunk("expression"); 5738 Results.AddResult(Result(Builder.TakeString())); 5739 5740 if (Results.includeCodePatterns()) { 5741 // @synchronized ( expression ) { statements } 5742 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "synchronized")); 5743 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 5744 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 5745 Builder.AddPlaceholderChunk("expression"); 5746 Builder.AddChunk(CodeCompletionString::CK_RightParen); 5747 Builder.AddChunk(CodeCompletionString::CK_LeftBrace); 5748 Builder.AddPlaceholderChunk("statements"); 5749 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 5750 Results.AddResult(Result(Builder.TakeString())); 5751 } 5752 } 5753 5754 static void AddObjCVisibilityResults(const LangOptions &LangOpts, 5755 ResultBuilder &Results, bool NeedAt) { 5756 typedef CodeCompletionResult Result; 5757 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "private"))); 5758 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "protected"))); 5759 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "public"))); 5760 if (LangOpts.ObjC) 5761 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "package"))); 5762 } 5763 5764 void Sema::CodeCompleteObjCAtVisibility(Scope *S) { 5765 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5766 CodeCompleter->getCodeCompletionTUInfo(), 5767 CodeCompletionContext::CCC_Other); 5768 Results.EnterNewScope(); 5769 AddObjCVisibilityResults(getLangOpts(), Results, false); 5770 Results.ExitScope(); 5771 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 5772 Results.data(), Results.size()); 5773 } 5774 5775 void Sema::CodeCompleteObjCAtStatement(Scope *S) { 5776 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5777 CodeCompleter->getCodeCompletionTUInfo(), 5778 CodeCompletionContext::CCC_Other); 5779 Results.EnterNewScope(); 5780 AddObjCStatementResults(Results, false); 5781 AddObjCExpressionResults(Results, false); 5782 Results.ExitScope(); 5783 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 5784 Results.data(), Results.size()); 5785 } 5786 5787 void Sema::CodeCompleteObjCAtExpression(Scope *S) { 5788 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5789 CodeCompleter->getCodeCompletionTUInfo(), 5790 CodeCompletionContext::CCC_Other); 5791 Results.EnterNewScope(); 5792 AddObjCExpressionResults(Results, false); 5793 Results.ExitScope(); 5794 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 5795 Results.data(), Results.size()); 5796 } 5797 5798 /// Determine whether the addition of the given flag to an Objective-C 5799 /// property's attributes will cause a conflict. 5800 static bool ObjCPropertyFlagConflicts(unsigned Attributes, unsigned NewFlag) { 5801 // Check if we've already added this flag. 5802 if (Attributes & NewFlag) 5803 return true; 5804 5805 Attributes |= NewFlag; 5806 5807 // Check for collisions with "readonly". 5808 if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) && 5809 (Attributes & ObjCDeclSpec::DQ_PR_readwrite)) 5810 return true; 5811 5812 // Check for more than one of { assign, copy, retain, strong, weak }. 5813 unsigned AssignCopyRetMask = 5814 Attributes & 5815 (ObjCDeclSpec::DQ_PR_assign | ObjCDeclSpec::DQ_PR_unsafe_unretained | 5816 ObjCDeclSpec::DQ_PR_copy | ObjCDeclSpec::DQ_PR_retain | 5817 ObjCDeclSpec::DQ_PR_strong | ObjCDeclSpec::DQ_PR_weak); 5818 if (AssignCopyRetMask && AssignCopyRetMask != ObjCDeclSpec::DQ_PR_assign && 5819 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_unsafe_unretained && 5820 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_copy && 5821 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_retain && 5822 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_strong && 5823 AssignCopyRetMask != ObjCDeclSpec::DQ_PR_weak) 5824 return true; 5825 5826 return false; 5827 } 5828 5829 void Sema::CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS) { 5830 if (!CodeCompleter) 5831 return; 5832 5833 unsigned Attributes = ODS.getPropertyAttributes(); 5834 5835 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5836 CodeCompleter->getCodeCompletionTUInfo(), 5837 CodeCompletionContext::CCC_Other); 5838 Results.EnterNewScope(); 5839 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readonly)) 5840 Results.AddResult(CodeCompletionResult("readonly")); 5841 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_assign)) 5842 Results.AddResult(CodeCompletionResult("assign")); 5843 if (!ObjCPropertyFlagConflicts(Attributes, 5844 ObjCDeclSpec::DQ_PR_unsafe_unretained)) 5845 Results.AddResult(CodeCompletionResult("unsafe_unretained")); 5846 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readwrite)) 5847 Results.AddResult(CodeCompletionResult("readwrite")); 5848 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_retain)) 5849 Results.AddResult(CodeCompletionResult("retain")); 5850 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_strong)) 5851 Results.AddResult(CodeCompletionResult("strong")); 5852 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_copy)) 5853 Results.AddResult(CodeCompletionResult("copy")); 5854 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nonatomic)) 5855 Results.AddResult(CodeCompletionResult("nonatomic")); 5856 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_atomic)) 5857 Results.AddResult(CodeCompletionResult("atomic")); 5858 5859 // Only suggest "weak" if we're compiling for ARC-with-weak-references or GC. 5860 if (getLangOpts().ObjCWeak || getLangOpts().getGC() != LangOptions::NonGC) 5861 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_weak)) 5862 Results.AddResult(CodeCompletionResult("weak")); 5863 5864 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_setter)) { 5865 CodeCompletionBuilder Setter(Results.getAllocator(), 5866 Results.getCodeCompletionTUInfo()); 5867 Setter.AddTypedTextChunk("setter"); 5868 Setter.AddTextChunk("="); 5869 Setter.AddPlaceholderChunk("method"); 5870 Results.AddResult(CodeCompletionResult(Setter.TakeString())); 5871 } 5872 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_getter)) { 5873 CodeCompletionBuilder Getter(Results.getAllocator(), 5874 Results.getCodeCompletionTUInfo()); 5875 Getter.AddTypedTextChunk("getter"); 5876 Getter.AddTextChunk("="); 5877 Getter.AddPlaceholderChunk("method"); 5878 Results.AddResult(CodeCompletionResult(Getter.TakeString())); 5879 } 5880 if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nullability)) { 5881 Results.AddResult(CodeCompletionResult("nonnull")); 5882 Results.AddResult(CodeCompletionResult("nullable")); 5883 Results.AddResult(CodeCompletionResult("null_unspecified")); 5884 Results.AddResult(CodeCompletionResult("null_resettable")); 5885 } 5886 Results.ExitScope(); 5887 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 5888 Results.data(), Results.size()); 5889 } 5890 5891 /// Describes the kind of Objective-C method that we want to find 5892 /// via code completion. 5893 enum ObjCMethodKind { 5894 MK_Any, ///< Any kind of method, provided it means other specified criteria. 5895 MK_ZeroArgSelector, ///< Zero-argument (unary) selector. 5896 MK_OneArgSelector ///< One-argument selector. 5897 }; 5898 5899 static bool isAcceptableObjCSelector(Selector Sel, ObjCMethodKind WantKind, 5900 ArrayRef<IdentifierInfo *> SelIdents, 5901 bool AllowSameLength = true) { 5902 unsigned NumSelIdents = SelIdents.size(); 5903 if (NumSelIdents > Sel.getNumArgs()) 5904 return false; 5905 5906 switch (WantKind) { 5907 case MK_Any: 5908 break; 5909 case MK_ZeroArgSelector: 5910 return Sel.isUnarySelector(); 5911 case MK_OneArgSelector: 5912 return Sel.getNumArgs() == 1; 5913 } 5914 5915 if (!AllowSameLength && NumSelIdents && NumSelIdents == Sel.getNumArgs()) 5916 return false; 5917 5918 for (unsigned I = 0; I != NumSelIdents; ++I) 5919 if (SelIdents[I] != Sel.getIdentifierInfoForSlot(I)) 5920 return false; 5921 5922 return true; 5923 } 5924 5925 static bool isAcceptableObjCMethod(ObjCMethodDecl *Method, 5926 ObjCMethodKind WantKind, 5927 ArrayRef<IdentifierInfo *> SelIdents, 5928 bool AllowSameLength = true) { 5929 return isAcceptableObjCSelector(Method->getSelector(), WantKind, SelIdents, 5930 AllowSameLength); 5931 } 5932 5933 /// A set of selectors, which is used to avoid introducing multiple 5934 /// completions with the same selector into the result set. 5935 typedef llvm::SmallPtrSet<Selector, 16> VisitedSelectorSet; 5936 5937 /// Add all of the Objective-C methods in the given Objective-C 5938 /// container to the set of results. 5939 /// 5940 /// The container will be a class, protocol, category, or implementation of 5941 /// any of the above. This mether will recurse to include methods from 5942 /// the superclasses of classes along with their categories, protocols, and 5943 /// implementations. 5944 /// 5945 /// \param Container the container in which we'll look to find methods. 5946 /// 5947 /// \param WantInstanceMethods Whether to add instance methods (only); if 5948 /// false, this routine will add factory methods (only). 5949 /// 5950 /// \param CurContext the context in which we're performing the lookup that 5951 /// finds methods. 5952 /// 5953 /// \param AllowSameLength Whether we allow a method to be added to the list 5954 /// when it has the same number of parameters as we have selector identifiers. 5955 /// 5956 /// \param Results the structure into which we'll add results. 5957 static void AddObjCMethods(ObjCContainerDecl *Container, 5958 bool WantInstanceMethods, ObjCMethodKind WantKind, 5959 ArrayRef<IdentifierInfo *> SelIdents, 5960 DeclContext *CurContext, 5961 VisitedSelectorSet &Selectors, bool AllowSameLength, 5962 ResultBuilder &Results, bool InOriginalClass = true, 5963 bool IsRootClass = false) { 5964 typedef CodeCompletionResult Result; 5965 Container = getContainerDef(Container); 5966 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container); 5967 IsRootClass = IsRootClass || (IFace && !IFace->getSuperClass()); 5968 for (ObjCMethodDecl *M : Container->methods()) { 5969 // The instance methods on the root class can be messaged via the 5970 // metaclass. 5971 if (M->isInstanceMethod() == WantInstanceMethods || 5972 (IsRootClass && !WantInstanceMethods)) { 5973 // Check whether the selector identifiers we've been given are a 5974 // subset of the identifiers for this particular method. 5975 if (!isAcceptableObjCMethod(M, WantKind, SelIdents, AllowSameLength)) 5976 continue; 5977 5978 if (!Selectors.insert(M->getSelector()).second) 5979 continue; 5980 5981 Result R = Result(M, Results.getBasePriority(M), nullptr); 5982 R.StartParameter = SelIdents.size(); 5983 R.AllParametersAreInformative = (WantKind != MK_Any); 5984 if (!InOriginalClass) 5985 setInBaseClass(R); 5986 Results.MaybeAddResult(R, CurContext); 5987 } 5988 } 5989 5990 // Visit the protocols of protocols. 5991 if (const auto *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) { 5992 if (Protocol->hasDefinition()) { 5993 const ObjCList<ObjCProtocolDecl> &Protocols = 5994 Protocol->getReferencedProtocols(); 5995 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(), 5996 E = Protocols.end(); 5997 I != E; ++I) 5998 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, CurContext, 5999 Selectors, AllowSameLength, Results, false, IsRootClass); 6000 } 6001 } 6002 6003 if (!IFace || !IFace->hasDefinition()) 6004 return; 6005 6006 // Add methods in protocols. 6007 for (ObjCProtocolDecl *I : IFace->protocols()) 6008 AddObjCMethods(I, WantInstanceMethods, WantKind, SelIdents, CurContext, 6009 Selectors, AllowSameLength, Results, false, IsRootClass); 6010 6011 // Add methods in categories. 6012 for (ObjCCategoryDecl *CatDecl : IFace->known_categories()) { 6013 AddObjCMethods(CatDecl, WantInstanceMethods, WantKind, SelIdents, 6014 CurContext, Selectors, AllowSameLength, Results, 6015 InOriginalClass, IsRootClass); 6016 6017 // Add a categories protocol methods. 6018 const ObjCList<ObjCProtocolDecl> &Protocols = 6019 CatDecl->getReferencedProtocols(); 6020 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(), 6021 E = Protocols.end(); 6022 I != E; ++I) 6023 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, CurContext, 6024 Selectors, AllowSameLength, Results, false, IsRootClass); 6025 6026 // Add methods in category implementations. 6027 if (ObjCCategoryImplDecl *Impl = CatDecl->getImplementation()) 6028 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents, CurContext, 6029 Selectors, AllowSameLength, Results, InOriginalClass, 6030 IsRootClass); 6031 } 6032 6033 // Add methods in superclass. 6034 // Avoid passing in IsRootClass since root classes won't have super classes. 6035 if (IFace->getSuperClass()) 6036 AddObjCMethods(IFace->getSuperClass(), WantInstanceMethods, WantKind, 6037 SelIdents, CurContext, Selectors, AllowSameLength, Results, 6038 /*IsRootClass=*/false); 6039 6040 // Add methods in our implementation, if any. 6041 if (ObjCImplementationDecl *Impl = IFace->getImplementation()) 6042 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents, CurContext, 6043 Selectors, AllowSameLength, Results, InOriginalClass, 6044 IsRootClass); 6045 } 6046 6047 void Sema::CodeCompleteObjCPropertyGetter(Scope *S) { 6048 // Try to find the interface where getters might live. 6049 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext); 6050 if (!Class) { 6051 if (ObjCCategoryDecl *Category = 6052 dyn_cast_or_null<ObjCCategoryDecl>(CurContext)) 6053 Class = Category->getClassInterface(); 6054 6055 if (!Class) 6056 return; 6057 } 6058 6059 // Find all of the potential getters. 6060 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 6061 CodeCompleter->getCodeCompletionTUInfo(), 6062 CodeCompletionContext::CCC_Other); 6063 Results.EnterNewScope(); 6064 6065 VisitedSelectorSet Selectors; 6066 AddObjCMethods(Class, true, MK_ZeroArgSelector, None, CurContext, Selectors, 6067 /*AllowSameLength=*/true, Results); 6068 Results.ExitScope(); 6069 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 6070 Results.data(), Results.size()); 6071 } 6072 6073 void Sema::CodeCompleteObjCPropertySetter(Scope *S) { 6074 // Try to find the interface where setters might live. 6075 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext); 6076 if (!Class) { 6077 if (ObjCCategoryDecl *Category = 6078 dyn_cast_or_null<ObjCCategoryDecl>(CurContext)) 6079 Class = Category->getClassInterface(); 6080 6081 if (!Class) 6082 return; 6083 } 6084 6085 // Find all of the potential getters. 6086 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 6087 CodeCompleter->getCodeCompletionTUInfo(), 6088 CodeCompletionContext::CCC_Other); 6089 Results.EnterNewScope(); 6090 6091 VisitedSelectorSet Selectors; 6092 AddObjCMethods(Class, true, MK_OneArgSelector, None, CurContext, Selectors, 6093 /*AllowSameLength=*/true, Results); 6094 6095 Results.ExitScope(); 6096 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 6097 Results.data(), Results.size()); 6098 } 6099 6100 void Sema::CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS, 6101 bool IsParameter) { 6102 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 6103 CodeCompleter->getCodeCompletionTUInfo(), 6104 CodeCompletionContext::CCC_Type); 6105 Results.EnterNewScope(); 6106 6107 // Add context-sensitive, Objective-C parameter-passing keywords. 6108 bool AddedInOut = false; 6109 if ((DS.getObjCDeclQualifier() & 6110 (ObjCDeclSpec::DQ_In | ObjCDeclSpec::DQ_Inout)) == 0) { 6111 Results.AddResult("in"); 6112 Results.AddResult("inout"); 6113 AddedInOut = true; 6114 } 6115 if ((DS.getObjCDeclQualifier() & 6116 (ObjCDeclSpec::DQ_Out | ObjCDeclSpec::DQ_Inout)) == 0) { 6117 Results.AddResult("out"); 6118 if (!AddedInOut) 6119 Results.AddResult("inout"); 6120 } 6121 if ((DS.getObjCDeclQualifier() & 6122 (ObjCDeclSpec::DQ_Bycopy | ObjCDeclSpec::DQ_Byref | 6123 ObjCDeclSpec::DQ_Oneway)) == 0) { 6124 Results.AddResult("bycopy"); 6125 Results.AddResult("byref"); 6126 Results.AddResult("oneway"); 6127 } 6128 if ((DS.getObjCDeclQualifier() & ObjCDeclSpec::DQ_CSNullability) == 0) { 6129 Results.AddResult("nonnull"); 6130 Results.AddResult("nullable"); 6131 Results.AddResult("null_unspecified"); 6132 } 6133 6134 // If we're completing the return type of an Objective-C method and the 6135 // identifier IBAction refers to a macro, provide a completion item for 6136 // an action, e.g., 6137 // IBAction)<#selector#>:(id)sender 6138 if (DS.getObjCDeclQualifier() == 0 && !IsParameter && 6139 PP.isMacroDefined("IBAction")) { 6140 CodeCompletionBuilder Builder(Results.getAllocator(), 6141 Results.getCodeCompletionTUInfo(), 6142 CCP_CodePattern, CXAvailability_Available); 6143 Builder.AddTypedTextChunk("IBAction"); 6144 Builder.AddChunk(CodeCompletionString::CK_RightParen); 6145 Builder.AddPlaceholderChunk("selector"); 6146 Builder.AddChunk(CodeCompletionString::CK_Colon); 6147 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 6148 Builder.AddTextChunk("id"); 6149 Builder.AddChunk(CodeCompletionString::CK_RightParen); 6150 Builder.AddTextChunk("sender"); 6151 Results.AddResult(CodeCompletionResult(Builder.TakeString())); 6152 } 6153 6154 // If we're completing the return type, provide 'instancetype'. 6155 if (!IsParameter) { 6156 Results.AddResult(CodeCompletionResult("instancetype")); 6157 } 6158 6159 // Add various builtin type names and specifiers. 6160 AddOrdinaryNameResults(PCC_Type, S, *this, Results); 6161 Results.ExitScope(); 6162 6163 // Add the various type names 6164 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName); 6165 CodeCompletionDeclConsumer Consumer(Results, CurContext); 6166 LookupVisibleDecls(S, LookupOrdinaryName, Consumer, 6167 CodeCompleter->includeGlobals(), 6168 CodeCompleter->loadExternal()); 6169 6170 if (CodeCompleter->includeMacros()) 6171 AddMacroResults(PP, Results, CodeCompleter->loadExternal(), false); 6172 6173 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 6174 Results.data(), Results.size()); 6175 } 6176 6177 /// When we have an expression with type "id", we may assume 6178 /// that it has some more-specific class type based on knowledge of 6179 /// common uses of Objective-C. This routine returns that class type, 6180 /// or NULL if no better result could be determined. 6181 static ObjCInterfaceDecl *GetAssumedMessageSendExprType(Expr *E) { 6182 auto *Msg = dyn_cast_or_null<ObjCMessageExpr>(E); 6183 if (!Msg) 6184 return nullptr; 6185 6186 Selector Sel = Msg->getSelector(); 6187 if (Sel.isNull()) 6188 return nullptr; 6189 6190 IdentifierInfo *Id = Sel.getIdentifierInfoForSlot(0); 6191 if (!Id) 6192 return nullptr; 6193 6194 ObjCMethodDecl *Method = Msg->getMethodDecl(); 6195 if (!Method) 6196 return nullptr; 6197 6198 // Determine the class that we're sending the message to. 6199 ObjCInterfaceDecl *IFace = nullptr; 6200 switch (Msg->getReceiverKind()) { 6201 case ObjCMessageExpr::Class: 6202 if (const ObjCObjectType *ObjType = 6203 Msg->getClassReceiver()->getAs<ObjCObjectType>()) 6204 IFace = ObjType->getInterface(); 6205 break; 6206 6207 case ObjCMessageExpr::Instance: { 6208 QualType T = Msg->getInstanceReceiver()->getType(); 6209 if (const ObjCObjectPointerType *Ptr = T->getAs<ObjCObjectPointerType>()) 6210 IFace = Ptr->getInterfaceDecl(); 6211 break; 6212 } 6213 6214 case ObjCMessageExpr::SuperInstance: 6215 case ObjCMessageExpr::SuperClass: 6216 break; 6217 } 6218 6219 if (!IFace) 6220 return nullptr; 6221 6222 ObjCInterfaceDecl *Super = IFace->getSuperClass(); 6223 if (Method->isInstanceMethod()) 6224 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName()) 6225 .Case("retain", IFace) 6226 .Case("strong", IFace) 6227 .Case("autorelease", IFace) 6228 .Case("copy", IFace) 6229 .Case("copyWithZone", IFace) 6230 .Case("mutableCopy", IFace) 6231 .Case("mutableCopyWithZone", IFace) 6232 .Case("awakeFromCoder", IFace) 6233 .Case("replacementObjectFromCoder", IFace) 6234 .Case("class", IFace) 6235 .Case("classForCoder", IFace) 6236 .Case("superclass", Super) 6237 .Default(nullptr); 6238 6239 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName()) 6240 .Case("new", IFace) 6241 .Case("alloc", IFace) 6242 .Case("allocWithZone", IFace) 6243 .Case("class", IFace) 6244 .Case("superclass", Super) 6245 .Default(nullptr); 6246 } 6247 6248 // Add a special completion for a message send to "super", which fills in the 6249 // most likely case of forwarding all of our arguments to the superclass 6250 // function. 6251 /// 6252 /// \param S The semantic analysis object. 6253 /// 6254 /// \param NeedSuperKeyword Whether we need to prefix this completion with 6255 /// the "super" keyword. Otherwise, we just need to provide the arguments. 6256 /// 6257 /// \param SelIdents The identifiers in the selector that have already been 6258 /// provided as arguments for a send to "super". 6259 /// 6260 /// \param Results The set of results to augment. 6261 /// 6262 /// \returns the Objective-C method declaration that would be invoked by 6263 /// this "super" completion. If NULL, no completion was added. 6264 static ObjCMethodDecl * 6265 AddSuperSendCompletion(Sema &S, bool NeedSuperKeyword, 6266 ArrayRef<IdentifierInfo *> SelIdents, 6267 ResultBuilder &Results) { 6268 ObjCMethodDecl *CurMethod = S.getCurMethodDecl(); 6269 if (!CurMethod) 6270 return nullptr; 6271 6272 ObjCInterfaceDecl *Class = CurMethod->getClassInterface(); 6273 if (!Class) 6274 return nullptr; 6275 6276 // Try to find a superclass method with the same selector. 6277 ObjCMethodDecl *SuperMethod = nullptr; 6278 while ((Class = Class->getSuperClass()) && !SuperMethod) { 6279 // Check in the class 6280 SuperMethod = Class->getMethod(CurMethod->getSelector(), 6281 CurMethod->isInstanceMethod()); 6282 6283 // Check in categories or class extensions. 6284 if (!SuperMethod) { 6285 for (const auto *Cat : Class->known_categories()) { 6286 if ((SuperMethod = Cat->getMethod(CurMethod->getSelector(), 6287 CurMethod->isInstanceMethod()))) 6288 break; 6289 } 6290 } 6291 } 6292 6293 if (!SuperMethod) 6294 return nullptr; 6295 6296 // Check whether the superclass method has the same signature. 6297 if (CurMethod->param_size() != SuperMethod->param_size() || 6298 CurMethod->isVariadic() != SuperMethod->isVariadic()) 6299 return nullptr; 6300 6301 for (ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin(), 6302 CurPEnd = CurMethod->param_end(), 6303 SuperP = SuperMethod->param_begin(); 6304 CurP != CurPEnd; ++CurP, ++SuperP) { 6305 // Make sure the parameter types are compatible. 6306 if (!S.Context.hasSameUnqualifiedType((*CurP)->getType(), 6307 (*SuperP)->getType())) 6308 return nullptr; 6309 6310 // Make sure we have a parameter name to forward! 6311 if (!(*CurP)->getIdentifier()) 6312 return nullptr; 6313 } 6314 6315 // We have a superclass method. Now, form the send-to-super completion. 6316 CodeCompletionBuilder Builder(Results.getAllocator(), 6317 Results.getCodeCompletionTUInfo()); 6318 6319 // Give this completion a return type. 6320 AddResultTypeChunk(S.Context, getCompletionPrintingPolicy(S), SuperMethod, 6321 Results.getCompletionContext().getBaseType(), Builder); 6322 6323 // If we need the "super" keyword, add it (plus some spacing). 6324 if (NeedSuperKeyword) { 6325 Builder.AddTypedTextChunk("super"); 6326 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 6327 } 6328 6329 Selector Sel = CurMethod->getSelector(); 6330 if (Sel.isUnarySelector()) { 6331 if (NeedSuperKeyword) 6332 Builder.AddTextChunk( 6333 Builder.getAllocator().CopyString(Sel.getNameForSlot(0))); 6334 else 6335 Builder.AddTypedTextChunk( 6336 Builder.getAllocator().CopyString(Sel.getNameForSlot(0))); 6337 } else { 6338 ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin(); 6339 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I, ++CurP) { 6340 if (I > SelIdents.size()) 6341 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 6342 6343 if (I < SelIdents.size()) 6344 Builder.AddInformativeChunk( 6345 Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":")); 6346 else if (NeedSuperKeyword || I > SelIdents.size()) { 6347 Builder.AddTextChunk( 6348 Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":")); 6349 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString( 6350 (*CurP)->getIdentifier()->getName())); 6351 } else { 6352 Builder.AddTypedTextChunk( 6353 Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":")); 6354 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString( 6355 (*CurP)->getIdentifier()->getName())); 6356 } 6357 } 6358 } 6359 6360 Results.AddResult(CodeCompletionResult(Builder.TakeString(), SuperMethod, 6361 CCP_SuperCompletion)); 6362 return SuperMethod; 6363 } 6364 6365 void Sema::CodeCompleteObjCMessageReceiver(Scope *S) { 6366 typedef CodeCompletionResult Result; 6367 ResultBuilder Results( 6368 *this, CodeCompleter->getAllocator(), 6369 CodeCompleter->getCodeCompletionTUInfo(), 6370 CodeCompletionContext::CCC_ObjCMessageReceiver, 6371 getLangOpts().CPlusPlus11 6372 ? &ResultBuilder::IsObjCMessageReceiverOrLambdaCapture 6373 : &ResultBuilder::IsObjCMessageReceiver); 6374 6375 CodeCompletionDeclConsumer Consumer(Results, CurContext); 6376 Results.EnterNewScope(); 6377 LookupVisibleDecls(S, LookupOrdinaryName, Consumer, 6378 CodeCompleter->includeGlobals(), 6379 CodeCompleter->loadExternal()); 6380 6381 // If we are in an Objective-C method inside a class that has a superclass, 6382 // add "super" as an option. 6383 if (ObjCMethodDecl *Method = getCurMethodDecl()) 6384 if (ObjCInterfaceDecl *Iface = Method->getClassInterface()) 6385 if (Iface->getSuperClass()) { 6386 Results.AddResult(Result("super")); 6387 6388 AddSuperSendCompletion(*this, /*NeedSuperKeyword=*/true, None, Results); 6389 } 6390 6391 if (getLangOpts().CPlusPlus11) 6392 addThisCompletion(*this, Results); 6393 6394 Results.ExitScope(); 6395 6396 if (CodeCompleter->includeMacros()) 6397 AddMacroResults(PP, Results, CodeCompleter->loadExternal(), false); 6398 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 6399 Results.data(), Results.size()); 6400 } 6401 6402 void Sema::CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc, 6403 ArrayRef<IdentifierInfo *> SelIdents, 6404 bool AtArgumentExpression) { 6405 ObjCInterfaceDecl *CDecl = nullptr; 6406 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) { 6407 // Figure out which interface we're in. 6408 CDecl = CurMethod->getClassInterface(); 6409 if (!CDecl) 6410 return; 6411 6412 // Find the superclass of this class. 6413 CDecl = CDecl->getSuperClass(); 6414 if (!CDecl) 6415 return; 6416 6417 if (CurMethod->isInstanceMethod()) { 6418 // We are inside an instance method, which means that the message 6419 // send [super ...] is actually calling an instance method on the 6420 // current object. 6421 return CodeCompleteObjCInstanceMessage(S, nullptr, SelIdents, 6422 AtArgumentExpression, CDecl); 6423 } 6424 6425 // Fall through to send to the superclass in CDecl. 6426 } else { 6427 // "super" may be the name of a type or variable. Figure out which 6428 // it is. 6429 IdentifierInfo *Super = getSuperIdentifier(); 6430 NamedDecl *ND = LookupSingleName(S, Super, SuperLoc, LookupOrdinaryName); 6431 if ((CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(ND))) { 6432 // "super" names an interface. Use it. 6433 } else if (TypeDecl *TD = dyn_cast_or_null<TypeDecl>(ND)) { 6434 if (const ObjCObjectType *Iface = 6435 Context.getTypeDeclType(TD)->getAs<ObjCObjectType>()) 6436 CDecl = Iface->getInterface(); 6437 } else if (ND && isa<UnresolvedUsingTypenameDecl>(ND)) { 6438 // "super" names an unresolved type; we can't be more specific. 6439 } else { 6440 // Assume that "super" names some kind of value and parse that way. 6441 CXXScopeSpec SS; 6442 SourceLocation TemplateKWLoc; 6443 UnqualifiedId id; 6444 id.setIdentifier(Super, SuperLoc); 6445 ExprResult SuperExpr = ActOnIdExpression(S, SS, TemplateKWLoc, id, 6446 /*HasTrailingLParen=*/false, 6447 /*IsAddressOfOperand=*/false); 6448 return CodeCompleteObjCInstanceMessage(S, (Expr *)SuperExpr.get(), 6449 SelIdents, AtArgumentExpression); 6450 } 6451 6452 // Fall through 6453 } 6454 6455 ParsedType Receiver; 6456 if (CDecl) 6457 Receiver = ParsedType::make(Context.getObjCInterfaceType(CDecl)); 6458 return CodeCompleteObjCClassMessage(S, Receiver, SelIdents, 6459 AtArgumentExpression, 6460 /*IsSuper=*/true); 6461 } 6462 6463 /// Given a set of code-completion results for the argument of a message 6464 /// send, determine the preferred type (if any) for that argument expression. 6465 static QualType getPreferredArgumentTypeForMessageSend(ResultBuilder &Results, 6466 unsigned NumSelIdents) { 6467 typedef CodeCompletionResult Result; 6468 ASTContext &Context = Results.getSema().Context; 6469 6470 QualType PreferredType; 6471 unsigned BestPriority = CCP_Unlikely * 2; 6472 Result *ResultsData = Results.data(); 6473 for (unsigned I = 0, N = Results.size(); I != N; ++I) { 6474 Result &R = ResultsData[I]; 6475 if (R.Kind == Result::RK_Declaration && 6476 isa<ObjCMethodDecl>(R.Declaration)) { 6477 if (R.Priority <= BestPriority) { 6478 const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(R.Declaration); 6479 if (NumSelIdents <= Method->param_size()) { 6480 QualType MyPreferredType = 6481 Method->parameters()[NumSelIdents - 1]->getType(); 6482 if (R.Priority < BestPriority || PreferredType.isNull()) { 6483 BestPriority = R.Priority; 6484 PreferredType = MyPreferredType; 6485 } else if (!Context.hasSameUnqualifiedType(PreferredType, 6486 MyPreferredType)) { 6487 PreferredType = QualType(); 6488 } 6489 } 6490 } 6491 } 6492 } 6493 6494 return PreferredType; 6495 } 6496 6497 static void AddClassMessageCompletions(Sema &SemaRef, Scope *S, 6498 ParsedType Receiver, 6499 ArrayRef<IdentifierInfo *> SelIdents, 6500 bool AtArgumentExpression, bool IsSuper, 6501 ResultBuilder &Results) { 6502 typedef CodeCompletionResult Result; 6503 ObjCInterfaceDecl *CDecl = nullptr; 6504 6505 // If the given name refers to an interface type, retrieve the 6506 // corresponding declaration. 6507 if (Receiver) { 6508 QualType T = SemaRef.GetTypeFromParser(Receiver, nullptr); 6509 if (!T.isNull()) 6510 if (const ObjCObjectType *Interface = T->getAs<ObjCObjectType>()) 6511 CDecl = Interface->getInterface(); 6512 } 6513 6514 // Add all of the factory methods in this Objective-C class, its protocols, 6515 // superclasses, categories, implementation, etc. 6516 Results.EnterNewScope(); 6517 6518 // If this is a send-to-super, try to add the special "super" send 6519 // completion. 6520 if (IsSuper) { 6521 if (ObjCMethodDecl *SuperMethod = 6522 AddSuperSendCompletion(SemaRef, false, SelIdents, Results)) 6523 Results.Ignore(SuperMethod); 6524 } 6525 6526 // If we're inside an Objective-C method definition, prefer its selector to 6527 // others. 6528 if (ObjCMethodDecl *CurMethod = SemaRef.getCurMethodDecl()) 6529 Results.setPreferredSelector(CurMethod->getSelector()); 6530 6531 VisitedSelectorSet Selectors; 6532 if (CDecl) 6533 AddObjCMethods(CDecl, false, MK_Any, SelIdents, SemaRef.CurContext, 6534 Selectors, AtArgumentExpression, Results); 6535 else { 6536 // We're messaging "id" as a type; provide all class/factory methods. 6537 6538 // If we have an external source, load the entire class method 6539 // pool from the AST file. 6540 if (SemaRef.getExternalSource()) { 6541 for (uint32_t I = 0, 6542 N = SemaRef.getExternalSource()->GetNumExternalSelectors(); 6543 I != N; ++I) { 6544 Selector Sel = SemaRef.getExternalSource()->GetExternalSelector(I); 6545 if (Sel.isNull() || SemaRef.MethodPool.count(Sel)) 6546 continue; 6547 6548 SemaRef.ReadMethodPool(Sel); 6549 } 6550 } 6551 6552 for (Sema::GlobalMethodPool::iterator M = SemaRef.MethodPool.begin(), 6553 MEnd = SemaRef.MethodPool.end(); 6554 M != MEnd; ++M) { 6555 for (ObjCMethodList *MethList = &M->second.second; 6556 MethList && MethList->getMethod(); MethList = MethList->getNext()) { 6557 if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents)) 6558 continue; 6559 6560 Result R(MethList->getMethod(), 6561 Results.getBasePriority(MethList->getMethod()), nullptr); 6562 R.StartParameter = SelIdents.size(); 6563 R.AllParametersAreInformative = false; 6564 Results.MaybeAddResult(R, SemaRef.CurContext); 6565 } 6566 } 6567 } 6568 6569 Results.ExitScope(); 6570 } 6571 6572 void Sema::CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver, 6573 ArrayRef<IdentifierInfo *> SelIdents, 6574 bool AtArgumentExpression, 6575 bool IsSuper) { 6576 6577 QualType T = this->GetTypeFromParser(Receiver); 6578 6579 ResultBuilder Results( 6580 *this, CodeCompleter->getAllocator(), 6581 CodeCompleter->getCodeCompletionTUInfo(), 6582 CodeCompletionContext(CodeCompletionContext::CCC_ObjCClassMessage, T, 6583 SelIdents)); 6584 6585 AddClassMessageCompletions(*this, S, Receiver, SelIdents, 6586 AtArgumentExpression, IsSuper, Results); 6587 6588 // If we're actually at the argument expression (rather than prior to the 6589 // selector), we're actually performing code completion for an expression. 6590 // Determine whether we have a single, best method. If so, we can 6591 // code-complete the expression using the corresponding parameter type as 6592 // our preferred type, improving completion results. 6593 if (AtArgumentExpression) { 6594 QualType PreferredType = 6595 getPreferredArgumentTypeForMessageSend(Results, SelIdents.size()); 6596 if (PreferredType.isNull()) 6597 CodeCompleteOrdinaryName(S, PCC_Expression); 6598 else 6599 CodeCompleteExpression(S, PreferredType); 6600 return; 6601 } 6602 6603 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 6604 Results.data(), Results.size()); 6605 } 6606 6607 void Sema::CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver, 6608 ArrayRef<IdentifierInfo *> SelIdents, 6609 bool AtArgumentExpression, 6610 ObjCInterfaceDecl *Super) { 6611 typedef CodeCompletionResult Result; 6612 6613 Expr *RecExpr = static_cast<Expr *>(Receiver); 6614 6615 // If necessary, apply function/array conversion to the receiver. 6616 // C99 6.7.5.3p[7,8]. 6617 if (RecExpr) { 6618 ExprResult Conv = DefaultFunctionArrayLvalueConversion(RecExpr); 6619 if (Conv.isInvalid()) // conversion failed. bail. 6620 return; 6621 RecExpr = Conv.get(); 6622 } 6623 QualType ReceiverType = RecExpr 6624 ? RecExpr->getType() 6625 : Super ? Context.getObjCObjectPointerType( 6626 Context.getObjCInterfaceType(Super)) 6627 : Context.getObjCIdType(); 6628 6629 // If we're messaging an expression with type "id" or "Class", check 6630 // whether we know something special about the receiver that allows 6631 // us to assume a more-specific receiver type. 6632 if (ReceiverType->isObjCIdType() || ReceiverType->isObjCClassType()) { 6633 if (ObjCInterfaceDecl *IFace = GetAssumedMessageSendExprType(RecExpr)) { 6634 if (ReceiverType->isObjCClassType()) 6635 return CodeCompleteObjCClassMessage( 6636 S, ParsedType::make(Context.getObjCInterfaceType(IFace)), SelIdents, 6637 AtArgumentExpression, Super); 6638 6639 ReceiverType = 6640 Context.getObjCObjectPointerType(Context.getObjCInterfaceType(IFace)); 6641 } 6642 } else if (RecExpr && getLangOpts().CPlusPlus) { 6643 ExprResult Conv = PerformContextuallyConvertToObjCPointer(RecExpr); 6644 if (Conv.isUsable()) { 6645 RecExpr = Conv.get(); 6646 ReceiverType = RecExpr->getType(); 6647 } 6648 } 6649 6650 // Build the set of methods we can see. 6651 ResultBuilder Results( 6652 *this, CodeCompleter->getAllocator(), 6653 CodeCompleter->getCodeCompletionTUInfo(), 6654 CodeCompletionContext(CodeCompletionContext::CCC_ObjCInstanceMessage, 6655 ReceiverType, SelIdents)); 6656 6657 Results.EnterNewScope(); 6658 6659 // If this is a send-to-super, try to add the special "super" send 6660 // completion. 6661 if (Super) { 6662 if (ObjCMethodDecl *SuperMethod = 6663 AddSuperSendCompletion(*this, false, SelIdents, Results)) 6664 Results.Ignore(SuperMethod); 6665 } 6666 6667 // If we're inside an Objective-C method definition, prefer its selector to 6668 // others. 6669 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) 6670 Results.setPreferredSelector(CurMethod->getSelector()); 6671 6672 // Keep track of the selectors we've already added. 6673 VisitedSelectorSet Selectors; 6674 6675 // Handle messages to Class. This really isn't a message to an instance 6676 // method, so we treat it the same way we would treat a message send to a 6677 // class method. 6678 if (ReceiverType->isObjCClassType() || 6679 ReceiverType->isObjCQualifiedClassType()) { 6680 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) { 6681 if (ObjCInterfaceDecl *ClassDecl = CurMethod->getClassInterface()) 6682 AddObjCMethods(ClassDecl, false, MK_Any, SelIdents, CurContext, 6683 Selectors, AtArgumentExpression, Results); 6684 } 6685 } 6686 // Handle messages to a qualified ID ("id<foo>"). 6687 else if (const ObjCObjectPointerType *QualID = 6688 ReceiverType->getAsObjCQualifiedIdType()) { 6689 // Search protocols for instance methods. 6690 for (auto *I : QualID->quals()) 6691 AddObjCMethods(I, true, MK_Any, SelIdents, CurContext, Selectors, 6692 AtArgumentExpression, Results); 6693 } 6694 // Handle messages to a pointer to interface type. 6695 else if (const ObjCObjectPointerType *IFacePtr = 6696 ReceiverType->getAsObjCInterfacePointerType()) { 6697 // Search the class, its superclasses, etc., for instance methods. 6698 AddObjCMethods(IFacePtr->getInterfaceDecl(), true, MK_Any, SelIdents, 6699 CurContext, Selectors, AtArgumentExpression, Results); 6700 6701 // Search protocols for instance methods. 6702 for (auto *I : IFacePtr->quals()) 6703 AddObjCMethods(I, true, MK_Any, SelIdents, CurContext, Selectors, 6704 AtArgumentExpression, Results); 6705 } 6706 // Handle messages to "id". 6707 else if (ReceiverType->isObjCIdType()) { 6708 // We're messaging "id", so provide all instance methods we know 6709 // about as code-completion results. 6710 6711 // If we have an external source, load the entire class method 6712 // pool from the AST file. 6713 if (ExternalSource) { 6714 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors(); 6715 I != N; ++I) { 6716 Selector Sel = ExternalSource->GetExternalSelector(I); 6717 if (Sel.isNull() || MethodPool.count(Sel)) 6718 continue; 6719 6720 ReadMethodPool(Sel); 6721 } 6722 } 6723 6724 for (GlobalMethodPool::iterator M = MethodPool.begin(), 6725 MEnd = MethodPool.end(); 6726 M != MEnd; ++M) { 6727 for (ObjCMethodList *MethList = &M->second.first; 6728 MethList && MethList->getMethod(); MethList = MethList->getNext()) { 6729 if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents)) 6730 continue; 6731 6732 if (!Selectors.insert(MethList->getMethod()->getSelector()).second) 6733 continue; 6734 6735 Result R(MethList->getMethod(), 6736 Results.getBasePriority(MethList->getMethod()), nullptr); 6737 R.StartParameter = SelIdents.size(); 6738 R.AllParametersAreInformative = false; 6739 Results.MaybeAddResult(R, CurContext); 6740 } 6741 } 6742 } 6743 Results.ExitScope(); 6744 6745 // If we're actually at the argument expression (rather than prior to the 6746 // selector), we're actually performing code completion for an expression. 6747 // Determine whether we have a single, best method. If so, we can 6748 // code-complete the expression using the corresponding parameter type as 6749 // our preferred type, improving completion results. 6750 if (AtArgumentExpression) { 6751 QualType PreferredType = 6752 getPreferredArgumentTypeForMessageSend(Results, SelIdents.size()); 6753 if (PreferredType.isNull()) 6754 CodeCompleteOrdinaryName(S, PCC_Expression); 6755 else 6756 CodeCompleteExpression(S, PreferredType); 6757 return; 6758 } 6759 6760 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 6761 Results.data(), Results.size()); 6762 } 6763 6764 void Sema::CodeCompleteObjCForCollection(Scope *S, 6765 DeclGroupPtrTy IterationVar) { 6766 CodeCompleteExpressionData Data; 6767 Data.ObjCCollection = true; 6768 6769 if (IterationVar.getAsOpaquePtr()) { 6770 DeclGroupRef DG = IterationVar.get(); 6771 for (DeclGroupRef::iterator I = DG.begin(), End = DG.end(); I != End; ++I) { 6772 if (*I) 6773 Data.IgnoreDecls.push_back(*I); 6774 } 6775 } 6776 6777 CodeCompleteExpression(S, Data); 6778 } 6779 6780 void Sema::CodeCompleteObjCSelector(Scope *S, 6781 ArrayRef<IdentifierInfo *> SelIdents) { 6782 // If we have an external source, load the entire class method 6783 // pool from the AST file. 6784 if (ExternalSource) { 6785 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors(); I != N; 6786 ++I) { 6787 Selector Sel = ExternalSource->GetExternalSelector(I); 6788 if (Sel.isNull() || MethodPool.count(Sel)) 6789 continue; 6790 6791 ReadMethodPool(Sel); 6792 } 6793 } 6794 6795 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 6796 CodeCompleter->getCodeCompletionTUInfo(), 6797 CodeCompletionContext::CCC_SelectorName); 6798 Results.EnterNewScope(); 6799 for (GlobalMethodPool::iterator M = MethodPool.begin(), 6800 MEnd = MethodPool.end(); 6801 M != MEnd; ++M) { 6802 6803 Selector Sel = M->first; 6804 if (!isAcceptableObjCSelector(Sel, MK_Any, SelIdents)) 6805 continue; 6806 6807 CodeCompletionBuilder Builder(Results.getAllocator(), 6808 Results.getCodeCompletionTUInfo()); 6809 if (Sel.isUnarySelector()) { 6810 Builder.AddTypedTextChunk( 6811 Builder.getAllocator().CopyString(Sel.getNameForSlot(0))); 6812 Results.AddResult(Builder.TakeString()); 6813 continue; 6814 } 6815 6816 std::string Accumulator; 6817 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I) { 6818 if (I == SelIdents.size()) { 6819 if (!Accumulator.empty()) { 6820 Builder.AddInformativeChunk( 6821 Builder.getAllocator().CopyString(Accumulator)); 6822 Accumulator.clear(); 6823 } 6824 } 6825 6826 Accumulator += Sel.getNameForSlot(I); 6827 Accumulator += ':'; 6828 } 6829 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(Accumulator)); 6830 Results.AddResult(Builder.TakeString()); 6831 } 6832 Results.ExitScope(); 6833 6834 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 6835 Results.data(), Results.size()); 6836 } 6837 6838 /// Add all of the protocol declarations that we find in the given 6839 /// (translation unit) context. 6840 static void AddProtocolResults(DeclContext *Ctx, DeclContext *CurContext, 6841 bool OnlyForwardDeclarations, 6842 ResultBuilder &Results) { 6843 typedef CodeCompletionResult Result; 6844 6845 for (const auto *D : Ctx->decls()) { 6846 // Record any protocols we find. 6847 if (const auto *Proto = dyn_cast<ObjCProtocolDecl>(D)) 6848 if (!OnlyForwardDeclarations || !Proto->hasDefinition()) 6849 Results.AddResult( 6850 Result(Proto, Results.getBasePriority(Proto), nullptr), CurContext, 6851 nullptr, false); 6852 } 6853 } 6854 6855 void Sema::CodeCompleteObjCProtocolReferences( 6856 ArrayRef<IdentifierLocPair> Protocols) { 6857 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 6858 CodeCompleter->getCodeCompletionTUInfo(), 6859 CodeCompletionContext::CCC_ObjCProtocolName); 6860 6861 if (CodeCompleter->includeGlobals()) { 6862 Results.EnterNewScope(); 6863 6864 // Tell the result set to ignore all of the protocols we have 6865 // already seen. 6866 // FIXME: This doesn't work when caching code-completion results. 6867 for (const IdentifierLocPair &Pair : Protocols) 6868 if (ObjCProtocolDecl *Protocol = LookupProtocol(Pair.first, Pair.second)) 6869 Results.Ignore(Protocol); 6870 6871 // Add all protocols. 6872 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, false, 6873 Results); 6874 6875 Results.ExitScope(); 6876 } 6877 6878 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 6879 Results.data(), Results.size()); 6880 } 6881 6882 void Sema::CodeCompleteObjCProtocolDecl(Scope *) { 6883 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 6884 CodeCompleter->getCodeCompletionTUInfo(), 6885 CodeCompletionContext::CCC_ObjCProtocolName); 6886 6887 if (CodeCompleter->includeGlobals()) { 6888 Results.EnterNewScope(); 6889 6890 // Add all protocols. 6891 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, true, 6892 Results); 6893 6894 Results.ExitScope(); 6895 } 6896 6897 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 6898 Results.data(), Results.size()); 6899 } 6900 6901 /// Add all of the Objective-C interface declarations that we find in 6902 /// the given (translation unit) context. 6903 static void AddInterfaceResults(DeclContext *Ctx, DeclContext *CurContext, 6904 bool OnlyForwardDeclarations, 6905 bool OnlyUnimplemented, 6906 ResultBuilder &Results) { 6907 typedef CodeCompletionResult Result; 6908 6909 for (const auto *D : Ctx->decls()) { 6910 // Record any interfaces we find. 6911 if (const auto *Class = dyn_cast<ObjCInterfaceDecl>(D)) 6912 if ((!OnlyForwardDeclarations || !Class->hasDefinition()) && 6913 (!OnlyUnimplemented || !Class->getImplementation())) 6914 Results.AddResult( 6915 Result(Class, Results.getBasePriority(Class), nullptr), CurContext, 6916 nullptr, false); 6917 } 6918 } 6919 6920 void Sema::CodeCompleteObjCInterfaceDecl(Scope *S) { 6921 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 6922 CodeCompleter->getCodeCompletionTUInfo(), 6923 CodeCompletionContext::CCC_ObjCInterfaceName); 6924 Results.EnterNewScope(); 6925 6926 if (CodeCompleter->includeGlobals()) { 6927 // Add all classes. 6928 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false, 6929 false, Results); 6930 } 6931 6932 Results.ExitScope(); 6933 6934 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 6935 Results.data(), Results.size()); 6936 } 6937 6938 void Sema::CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName, 6939 SourceLocation ClassNameLoc) { 6940 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 6941 CodeCompleter->getCodeCompletionTUInfo(), 6942 CodeCompletionContext::CCC_ObjCInterfaceName); 6943 Results.EnterNewScope(); 6944 6945 // Make sure that we ignore the class we're currently defining. 6946 NamedDecl *CurClass = 6947 LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName); 6948 if (CurClass && isa<ObjCInterfaceDecl>(CurClass)) 6949 Results.Ignore(CurClass); 6950 6951 if (CodeCompleter->includeGlobals()) { 6952 // Add all classes. 6953 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false, 6954 false, Results); 6955 } 6956 6957 Results.ExitScope(); 6958 6959 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 6960 Results.data(), Results.size()); 6961 } 6962 6963 void Sema::CodeCompleteObjCImplementationDecl(Scope *S) { 6964 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 6965 CodeCompleter->getCodeCompletionTUInfo(), 6966 CodeCompletionContext::CCC_ObjCImplementation); 6967 Results.EnterNewScope(); 6968 6969 if (CodeCompleter->includeGlobals()) { 6970 // Add all unimplemented classes. 6971 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false, 6972 true, Results); 6973 } 6974 6975 Results.ExitScope(); 6976 6977 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 6978 Results.data(), Results.size()); 6979 } 6980 6981 void Sema::CodeCompleteObjCInterfaceCategory(Scope *S, 6982 IdentifierInfo *ClassName, 6983 SourceLocation ClassNameLoc) { 6984 typedef CodeCompletionResult Result; 6985 6986 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 6987 CodeCompleter->getCodeCompletionTUInfo(), 6988 CodeCompletionContext::CCC_ObjCCategoryName); 6989 6990 // Ignore any categories we find that have already been implemented by this 6991 // interface. 6992 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames; 6993 NamedDecl *CurClass = 6994 LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName); 6995 if (ObjCInterfaceDecl *Class = 6996 dyn_cast_or_null<ObjCInterfaceDecl>(CurClass)) { 6997 for (const auto *Cat : Class->visible_categories()) 6998 CategoryNames.insert(Cat->getIdentifier()); 6999 } 7000 7001 // Add all of the categories we know about. 7002 Results.EnterNewScope(); 7003 TranslationUnitDecl *TU = Context.getTranslationUnitDecl(); 7004 for (const auto *D : TU->decls()) 7005 if (const auto *Category = dyn_cast<ObjCCategoryDecl>(D)) 7006 if (CategoryNames.insert(Category->getIdentifier()).second) 7007 Results.AddResult( 7008 Result(Category, Results.getBasePriority(Category), nullptr), 7009 CurContext, nullptr, false); 7010 Results.ExitScope(); 7011 7012 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 7013 Results.data(), Results.size()); 7014 } 7015 7016 void Sema::CodeCompleteObjCImplementationCategory(Scope *S, 7017 IdentifierInfo *ClassName, 7018 SourceLocation ClassNameLoc) { 7019 typedef CodeCompletionResult Result; 7020 7021 // Find the corresponding interface. If we couldn't find the interface, the 7022 // program itself is ill-formed. However, we'll try to be helpful still by 7023 // providing the list of all of the categories we know about. 7024 NamedDecl *CurClass = 7025 LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName); 7026 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass); 7027 if (!Class) 7028 return CodeCompleteObjCInterfaceCategory(S, ClassName, ClassNameLoc); 7029 7030 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 7031 CodeCompleter->getCodeCompletionTUInfo(), 7032 CodeCompletionContext::CCC_ObjCCategoryName); 7033 7034 // Add all of the categories that have have corresponding interface 7035 // declarations in this class and any of its superclasses, except for 7036 // already-implemented categories in the class itself. 7037 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames; 7038 Results.EnterNewScope(); 7039 bool IgnoreImplemented = true; 7040 while (Class) { 7041 for (const auto *Cat : Class->visible_categories()) { 7042 if ((!IgnoreImplemented || !Cat->getImplementation()) && 7043 CategoryNames.insert(Cat->getIdentifier()).second) 7044 Results.AddResult(Result(Cat, Results.getBasePriority(Cat), nullptr), 7045 CurContext, nullptr, false); 7046 } 7047 7048 Class = Class->getSuperClass(); 7049 IgnoreImplemented = false; 7050 } 7051 Results.ExitScope(); 7052 7053 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 7054 Results.data(), Results.size()); 7055 } 7056 7057 void Sema::CodeCompleteObjCPropertyDefinition(Scope *S) { 7058 CodeCompletionContext CCContext(CodeCompletionContext::CCC_Other); 7059 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 7060 CodeCompleter->getCodeCompletionTUInfo(), CCContext); 7061 7062 // Figure out where this @synthesize lives. 7063 ObjCContainerDecl *Container = 7064 dyn_cast_or_null<ObjCContainerDecl>(CurContext); 7065 if (!Container || (!isa<ObjCImplementationDecl>(Container) && 7066 !isa<ObjCCategoryImplDecl>(Container))) 7067 return; 7068 7069 // Ignore any properties that have already been implemented. 7070 Container = getContainerDef(Container); 7071 for (const auto *D : Container->decls()) 7072 if (const auto *PropertyImpl = dyn_cast<ObjCPropertyImplDecl>(D)) 7073 Results.Ignore(PropertyImpl->getPropertyDecl()); 7074 7075 // Add any properties that we find. 7076 AddedPropertiesSet AddedProperties; 7077 Results.EnterNewScope(); 7078 if (ObjCImplementationDecl *ClassImpl = 7079 dyn_cast<ObjCImplementationDecl>(Container)) 7080 AddObjCProperties(CCContext, ClassImpl->getClassInterface(), false, 7081 /*AllowNullaryMethods=*/false, CurContext, 7082 AddedProperties, Results); 7083 else 7084 AddObjCProperties(CCContext, 7085 cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl(), 7086 false, /*AllowNullaryMethods=*/false, CurContext, 7087 AddedProperties, Results); 7088 Results.ExitScope(); 7089 7090 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 7091 Results.data(), Results.size()); 7092 } 7093 7094 void Sema::CodeCompleteObjCPropertySynthesizeIvar( 7095 Scope *S, IdentifierInfo *PropertyName) { 7096 typedef CodeCompletionResult Result; 7097 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 7098 CodeCompleter->getCodeCompletionTUInfo(), 7099 CodeCompletionContext::CCC_Other); 7100 7101 // Figure out where this @synthesize lives. 7102 ObjCContainerDecl *Container = 7103 dyn_cast_or_null<ObjCContainerDecl>(CurContext); 7104 if (!Container || (!isa<ObjCImplementationDecl>(Container) && 7105 !isa<ObjCCategoryImplDecl>(Container))) 7106 return; 7107 7108 // Figure out which interface we're looking into. 7109 ObjCInterfaceDecl *Class = nullptr; 7110 if (ObjCImplementationDecl *ClassImpl = 7111 dyn_cast<ObjCImplementationDecl>(Container)) 7112 Class = ClassImpl->getClassInterface(); 7113 else 7114 Class = cast<ObjCCategoryImplDecl>(Container) 7115 ->getCategoryDecl() 7116 ->getClassInterface(); 7117 7118 // Determine the type of the property we're synthesizing. 7119 QualType PropertyType = Context.getObjCIdType(); 7120 if (Class) { 7121 if (ObjCPropertyDecl *Property = Class->FindPropertyDeclaration( 7122 PropertyName, ObjCPropertyQueryKind::OBJC_PR_query_instance)) { 7123 PropertyType = 7124 Property->getType().getNonReferenceType().getUnqualifiedType(); 7125 7126 // Give preference to ivars 7127 Results.setPreferredType(PropertyType); 7128 } 7129 } 7130 7131 // Add all of the instance variables in this class and its superclasses. 7132 Results.EnterNewScope(); 7133 bool SawSimilarlyNamedIvar = false; 7134 std::string NameWithPrefix; 7135 NameWithPrefix += '_'; 7136 NameWithPrefix += PropertyName->getName(); 7137 std::string NameWithSuffix = PropertyName->getName().str(); 7138 NameWithSuffix += '_'; 7139 for (; Class; Class = Class->getSuperClass()) { 7140 for (ObjCIvarDecl *Ivar = Class->all_declared_ivar_begin(); Ivar; 7141 Ivar = Ivar->getNextIvar()) { 7142 Results.AddResult(Result(Ivar, Results.getBasePriority(Ivar), nullptr), 7143 CurContext, nullptr, false); 7144 7145 // Determine whether we've seen an ivar with a name similar to the 7146 // property. 7147 if ((PropertyName == Ivar->getIdentifier() || 7148 NameWithPrefix == Ivar->getName() || 7149 NameWithSuffix == Ivar->getName())) { 7150 SawSimilarlyNamedIvar = true; 7151 7152 // Reduce the priority of this result by one, to give it a slight 7153 // advantage over other results whose names don't match so closely. 7154 if (Results.size() && 7155 Results.data()[Results.size() - 1].Kind == 7156 CodeCompletionResult::RK_Declaration && 7157 Results.data()[Results.size() - 1].Declaration == Ivar) 7158 Results.data()[Results.size() - 1].Priority--; 7159 } 7160 } 7161 } 7162 7163 if (!SawSimilarlyNamedIvar) { 7164 // Create ivar result _propName, that the user can use to synthesize 7165 // an ivar of the appropriate type. 7166 unsigned Priority = CCP_MemberDeclaration + 1; 7167 typedef CodeCompletionResult Result; 7168 CodeCompletionAllocator &Allocator = Results.getAllocator(); 7169 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo(), 7170 Priority, CXAvailability_Available); 7171 7172 PrintingPolicy Policy = getCompletionPrintingPolicy(*this); 7173 Builder.AddResultTypeChunk( 7174 GetCompletionTypeString(PropertyType, Context, Policy, Allocator)); 7175 Builder.AddTypedTextChunk(Allocator.CopyString(NameWithPrefix)); 7176 Results.AddResult( 7177 Result(Builder.TakeString(), Priority, CXCursor_ObjCIvarDecl)); 7178 } 7179 7180 Results.ExitScope(); 7181 7182 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 7183 Results.data(), Results.size()); 7184 } 7185 7186 // Mapping from selectors to the methods that implement that selector, along 7187 // with the "in original class" flag. 7188 typedef llvm::DenseMap<Selector, 7189 llvm::PointerIntPair<ObjCMethodDecl *, 1, bool>> 7190 KnownMethodsMap; 7191 7192 /// Find all of the methods that reside in the given container 7193 /// (and its superclasses, protocols, etc.) that meet the given 7194 /// criteria. Insert those methods into the map of known methods, 7195 /// indexed by selector so they can be easily found. 7196 static void FindImplementableMethods(ASTContext &Context, 7197 ObjCContainerDecl *Container, 7198 Optional<bool> WantInstanceMethods, 7199 QualType ReturnType, 7200 KnownMethodsMap &KnownMethods, 7201 bool InOriginalClass = true) { 7202 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)) { 7203 // Make sure we have a definition; that's what we'll walk. 7204 if (!IFace->hasDefinition()) 7205 return; 7206 7207 IFace = IFace->getDefinition(); 7208 Container = IFace; 7209 7210 const ObjCList<ObjCProtocolDecl> &Protocols = 7211 IFace->getReferencedProtocols(); 7212 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(), 7213 E = Protocols.end(); 7214 I != E; ++I) 7215 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType, 7216 KnownMethods, InOriginalClass); 7217 7218 // Add methods from any class extensions and categories. 7219 for (auto *Cat : IFace->visible_categories()) { 7220 FindImplementableMethods(Context, Cat, WantInstanceMethods, ReturnType, 7221 KnownMethods, false); 7222 } 7223 7224 // Visit the superclass. 7225 if (IFace->getSuperClass()) 7226 FindImplementableMethods(Context, IFace->getSuperClass(), 7227 WantInstanceMethods, ReturnType, KnownMethods, 7228 false); 7229 } 7230 7231 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) { 7232 // Recurse into protocols. 7233 const ObjCList<ObjCProtocolDecl> &Protocols = 7234 Category->getReferencedProtocols(); 7235 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(), 7236 E = Protocols.end(); 7237 I != E; ++I) 7238 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType, 7239 KnownMethods, InOriginalClass); 7240 7241 // If this category is the original class, jump to the interface. 7242 if (InOriginalClass && Category->getClassInterface()) 7243 FindImplementableMethods(Context, Category->getClassInterface(), 7244 WantInstanceMethods, ReturnType, KnownMethods, 7245 false); 7246 } 7247 7248 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) { 7249 // Make sure we have a definition; that's what we'll walk. 7250 if (!Protocol->hasDefinition()) 7251 return; 7252 Protocol = Protocol->getDefinition(); 7253 Container = Protocol; 7254 7255 // Recurse into protocols. 7256 const ObjCList<ObjCProtocolDecl> &Protocols = 7257 Protocol->getReferencedProtocols(); 7258 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(), 7259 E = Protocols.end(); 7260 I != E; ++I) 7261 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType, 7262 KnownMethods, false); 7263 } 7264 7265 // Add methods in this container. This operation occurs last because 7266 // we want the methods from this container to override any methods 7267 // we've previously seen with the same selector. 7268 for (auto *M : Container->methods()) { 7269 if (!WantInstanceMethods || M->isInstanceMethod() == *WantInstanceMethods) { 7270 if (!ReturnType.isNull() && 7271 !Context.hasSameUnqualifiedType(ReturnType, M->getReturnType())) 7272 continue; 7273 7274 KnownMethods[M->getSelector()] = 7275 KnownMethodsMap::mapped_type(M, InOriginalClass); 7276 } 7277 } 7278 } 7279 7280 /// Add the parenthesized return or parameter type chunk to a code 7281 /// completion string. 7282 static void AddObjCPassingTypeChunk(QualType Type, unsigned ObjCDeclQuals, 7283 ASTContext &Context, 7284 const PrintingPolicy &Policy, 7285 CodeCompletionBuilder &Builder) { 7286 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7287 std::string Quals = formatObjCParamQualifiers(ObjCDeclQuals, Type); 7288 if (!Quals.empty()) 7289 Builder.AddTextChunk(Builder.getAllocator().CopyString(Quals)); 7290 Builder.AddTextChunk( 7291 GetCompletionTypeString(Type, Context, Policy, Builder.getAllocator())); 7292 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7293 } 7294 7295 /// Determine whether the given class is or inherits from a class by 7296 /// the given name. 7297 static bool InheritsFromClassNamed(ObjCInterfaceDecl *Class, StringRef Name) { 7298 if (!Class) 7299 return false; 7300 7301 if (Class->getIdentifier() && Class->getIdentifier()->getName() == Name) 7302 return true; 7303 7304 return InheritsFromClassNamed(Class->getSuperClass(), Name); 7305 } 7306 7307 /// Add code completions for Objective-C Key-Value Coding (KVC) and 7308 /// Key-Value Observing (KVO). 7309 static void AddObjCKeyValueCompletions(ObjCPropertyDecl *Property, 7310 bool IsInstanceMethod, 7311 QualType ReturnType, ASTContext &Context, 7312 VisitedSelectorSet &KnownSelectors, 7313 ResultBuilder &Results) { 7314 IdentifierInfo *PropName = Property->getIdentifier(); 7315 if (!PropName || PropName->getLength() == 0) 7316 return; 7317 7318 PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema()); 7319 7320 // Builder that will create each code completion. 7321 typedef CodeCompletionResult Result; 7322 CodeCompletionAllocator &Allocator = Results.getAllocator(); 7323 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo()); 7324 7325 // The selector table. 7326 SelectorTable &Selectors = Context.Selectors; 7327 7328 // The property name, copied into the code completion allocation region 7329 // on demand. 7330 struct KeyHolder { 7331 CodeCompletionAllocator &Allocator; 7332 StringRef Key; 7333 const char *CopiedKey; 7334 7335 KeyHolder(CodeCompletionAllocator &Allocator, StringRef Key) 7336 : Allocator(Allocator), Key(Key), CopiedKey(nullptr) {} 7337 7338 operator const char *() { 7339 if (CopiedKey) 7340 return CopiedKey; 7341 7342 return CopiedKey = Allocator.CopyString(Key); 7343 } 7344 } Key(Allocator, PropName->getName()); 7345 7346 // The uppercased name of the property name. 7347 std::string UpperKey = PropName->getName(); 7348 if (!UpperKey.empty()) 7349 UpperKey[0] = toUppercase(UpperKey[0]); 7350 7351 bool ReturnTypeMatchesProperty = 7352 ReturnType.isNull() || 7353 Context.hasSameUnqualifiedType(ReturnType.getNonReferenceType(), 7354 Property->getType()); 7355 bool ReturnTypeMatchesVoid = ReturnType.isNull() || ReturnType->isVoidType(); 7356 7357 // Add the normal accessor -(type)key. 7358 if (IsInstanceMethod && 7359 KnownSelectors.insert(Selectors.getNullarySelector(PropName)).second && 7360 ReturnTypeMatchesProperty && !Property->getGetterMethodDecl()) { 7361 if (ReturnType.isNull()) 7362 AddObjCPassingTypeChunk(Property->getType(), /*Quals=*/0, Context, Policy, 7363 Builder); 7364 7365 Builder.AddTypedTextChunk(Key); 7366 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern, 7367 CXCursor_ObjCInstanceMethodDecl)); 7368 } 7369 7370 // If we have an integral or boolean property (or the user has provided 7371 // an integral or boolean return type), add the accessor -(type)isKey. 7372 if (IsInstanceMethod && 7373 ((!ReturnType.isNull() && 7374 (ReturnType->isIntegerType() || ReturnType->isBooleanType())) || 7375 (ReturnType.isNull() && (Property->getType()->isIntegerType() || 7376 Property->getType()->isBooleanType())))) { 7377 std::string SelectorName = (Twine("is") + UpperKey).str(); 7378 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 7379 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId)) 7380 .second) { 7381 if (ReturnType.isNull()) { 7382 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7383 Builder.AddTextChunk("BOOL"); 7384 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7385 } 7386 7387 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorId->getName())); 7388 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern, 7389 CXCursor_ObjCInstanceMethodDecl)); 7390 } 7391 } 7392 7393 // Add the normal mutator. 7394 if (IsInstanceMethod && ReturnTypeMatchesVoid && 7395 !Property->getSetterMethodDecl()) { 7396 std::string SelectorName = (Twine("set") + UpperKey).str(); 7397 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 7398 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 7399 if (ReturnType.isNull()) { 7400 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7401 Builder.AddTextChunk("void"); 7402 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7403 } 7404 7405 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorId->getName())); 7406 Builder.AddTypedTextChunk(":"); 7407 AddObjCPassingTypeChunk(Property->getType(), /*Quals=*/0, Context, Policy, 7408 Builder); 7409 Builder.AddTextChunk(Key); 7410 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern, 7411 CXCursor_ObjCInstanceMethodDecl)); 7412 } 7413 } 7414 7415 // Indexed and unordered accessors 7416 unsigned IndexedGetterPriority = CCP_CodePattern; 7417 unsigned IndexedSetterPriority = CCP_CodePattern; 7418 unsigned UnorderedGetterPriority = CCP_CodePattern; 7419 unsigned UnorderedSetterPriority = CCP_CodePattern; 7420 if (const auto *ObjCPointer = 7421 Property->getType()->getAs<ObjCObjectPointerType>()) { 7422 if (ObjCInterfaceDecl *IFace = ObjCPointer->getInterfaceDecl()) { 7423 // If this interface type is not provably derived from a known 7424 // collection, penalize the corresponding completions. 7425 if (!InheritsFromClassNamed(IFace, "NSMutableArray")) { 7426 IndexedSetterPriority += CCD_ProbablyNotObjCCollection; 7427 if (!InheritsFromClassNamed(IFace, "NSArray")) 7428 IndexedGetterPriority += CCD_ProbablyNotObjCCollection; 7429 } 7430 7431 if (!InheritsFromClassNamed(IFace, "NSMutableSet")) { 7432 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection; 7433 if (!InheritsFromClassNamed(IFace, "NSSet")) 7434 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection; 7435 } 7436 } 7437 } else { 7438 IndexedGetterPriority += CCD_ProbablyNotObjCCollection; 7439 IndexedSetterPriority += CCD_ProbablyNotObjCCollection; 7440 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection; 7441 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection; 7442 } 7443 7444 // Add -(NSUInteger)countOf<key> 7445 if (IsInstanceMethod && 7446 (ReturnType.isNull() || ReturnType->isIntegerType())) { 7447 std::string SelectorName = (Twine("countOf") + UpperKey).str(); 7448 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 7449 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId)) 7450 .second) { 7451 if (ReturnType.isNull()) { 7452 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7453 Builder.AddTextChunk("NSUInteger"); 7454 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7455 } 7456 7457 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorId->getName())); 7458 Results.AddResult( 7459 Result(Builder.TakeString(), 7460 std::min(IndexedGetterPriority, UnorderedGetterPriority), 7461 CXCursor_ObjCInstanceMethodDecl)); 7462 } 7463 } 7464 7465 // Indexed getters 7466 // Add -(id)objectInKeyAtIndex:(NSUInteger)index 7467 if (IsInstanceMethod && 7468 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) { 7469 std::string SelectorName = (Twine("objectIn") + UpperKey + "AtIndex").str(); 7470 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 7471 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 7472 if (ReturnType.isNull()) { 7473 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7474 Builder.AddTextChunk("id"); 7475 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7476 } 7477 7478 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 7479 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7480 Builder.AddTextChunk("NSUInteger"); 7481 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7482 Builder.AddTextChunk("index"); 7483 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority, 7484 CXCursor_ObjCInstanceMethodDecl)); 7485 } 7486 } 7487 7488 // Add -(NSArray *)keyAtIndexes:(NSIndexSet *)indexes 7489 if (IsInstanceMethod && 7490 (ReturnType.isNull() || 7491 (ReturnType->isObjCObjectPointerType() && 7492 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() && 7493 ReturnType->getAs<ObjCObjectPointerType>() 7494 ->getInterfaceDecl() 7495 ->getName() == "NSArray"))) { 7496 std::string SelectorName = (Twine(Property->getName()) + "AtIndexes").str(); 7497 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 7498 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 7499 if (ReturnType.isNull()) { 7500 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7501 Builder.AddTextChunk("NSArray *"); 7502 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7503 } 7504 7505 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 7506 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7507 Builder.AddTextChunk("NSIndexSet *"); 7508 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7509 Builder.AddTextChunk("indexes"); 7510 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority, 7511 CXCursor_ObjCInstanceMethodDecl)); 7512 } 7513 } 7514 7515 // Add -(void)getKey:(type **)buffer range:(NSRange)inRange 7516 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 7517 std::string SelectorName = (Twine("get") + UpperKey).str(); 7518 IdentifierInfo *SelectorIds[2] = {&Context.Idents.get(SelectorName), 7519 &Context.Idents.get("range")}; 7520 7521 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) { 7522 if (ReturnType.isNull()) { 7523 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7524 Builder.AddTextChunk("void"); 7525 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7526 } 7527 7528 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 7529 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7530 Builder.AddPlaceholderChunk("object-type"); 7531 Builder.AddTextChunk(" **"); 7532 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7533 Builder.AddTextChunk("buffer"); 7534 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7535 Builder.AddTypedTextChunk("range:"); 7536 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7537 Builder.AddTextChunk("NSRange"); 7538 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7539 Builder.AddTextChunk("inRange"); 7540 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority, 7541 CXCursor_ObjCInstanceMethodDecl)); 7542 } 7543 } 7544 7545 // Mutable indexed accessors 7546 7547 // - (void)insertObject:(type *)object inKeyAtIndex:(NSUInteger)index 7548 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 7549 std::string SelectorName = (Twine("in") + UpperKey + "AtIndex").str(); 7550 IdentifierInfo *SelectorIds[2] = {&Context.Idents.get("insertObject"), 7551 &Context.Idents.get(SelectorName)}; 7552 7553 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) { 7554 if (ReturnType.isNull()) { 7555 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7556 Builder.AddTextChunk("void"); 7557 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7558 } 7559 7560 Builder.AddTypedTextChunk("insertObject:"); 7561 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7562 Builder.AddPlaceholderChunk("object-type"); 7563 Builder.AddTextChunk(" *"); 7564 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7565 Builder.AddTextChunk("object"); 7566 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7567 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 7568 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7569 Builder.AddPlaceholderChunk("NSUInteger"); 7570 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7571 Builder.AddTextChunk("index"); 7572 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority, 7573 CXCursor_ObjCInstanceMethodDecl)); 7574 } 7575 } 7576 7577 // - (void)insertKey:(NSArray *)array atIndexes:(NSIndexSet *)indexes 7578 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 7579 std::string SelectorName = (Twine("insert") + UpperKey).str(); 7580 IdentifierInfo *SelectorIds[2] = {&Context.Idents.get(SelectorName), 7581 &Context.Idents.get("atIndexes")}; 7582 7583 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) { 7584 if (ReturnType.isNull()) { 7585 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7586 Builder.AddTextChunk("void"); 7587 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7588 } 7589 7590 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 7591 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7592 Builder.AddTextChunk("NSArray *"); 7593 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7594 Builder.AddTextChunk("array"); 7595 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7596 Builder.AddTypedTextChunk("atIndexes:"); 7597 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7598 Builder.AddPlaceholderChunk("NSIndexSet *"); 7599 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7600 Builder.AddTextChunk("indexes"); 7601 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority, 7602 CXCursor_ObjCInstanceMethodDecl)); 7603 } 7604 } 7605 7606 // -(void)removeObjectFromKeyAtIndex:(NSUInteger)index 7607 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 7608 std::string SelectorName = 7609 (Twine("removeObjectFrom") + UpperKey + "AtIndex").str(); 7610 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 7611 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 7612 if (ReturnType.isNull()) { 7613 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7614 Builder.AddTextChunk("void"); 7615 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7616 } 7617 7618 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 7619 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7620 Builder.AddTextChunk("NSUInteger"); 7621 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7622 Builder.AddTextChunk("index"); 7623 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority, 7624 CXCursor_ObjCInstanceMethodDecl)); 7625 } 7626 } 7627 7628 // -(void)removeKeyAtIndexes:(NSIndexSet *)indexes 7629 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 7630 std::string SelectorName = (Twine("remove") + UpperKey + "AtIndexes").str(); 7631 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 7632 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).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.AddTextChunk("NSIndexSet *"); 7642 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7643 Builder.AddTextChunk("indexes"); 7644 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority, 7645 CXCursor_ObjCInstanceMethodDecl)); 7646 } 7647 } 7648 7649 // - (void)replaceObjectInKeyAtIndex:(NSUInteger)index withObject:(id)object 7650 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 7651 std::string SelectorName = 7652 (Twine("replaceObjectIn") + UpperKey + "AtIndex").str(); 7653 IdentifierInfo *SelectorIds[2] = {&Context.Idents.get(SelectorName), 7654 &Context.Idents.get("withObject")}; 7655 7656 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) { 7657 if (ReturnType.isNull()) { 7658 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7659 Builder.AddTextChunk("void"); 7660 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7661 } 7662 7663 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 7664 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7665 Builder.AddPlaceholderChunk("NSUInteger"); 7666 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7667 Builder.AddTextChunk("index"); 7668 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7669 Builder.AddTypedTextChunk("withObject:"); 7670 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7671 Builder.AddTextChunk("id"); 7672 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7673 Builder.AddTextChunk("object"); 7674 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority, 7675 CXCursor_ObjCInstanceMethodDecl)); 7676 } 7677 } 7678 7679 // - (void)replaceKeyAtIndexes:(NSIndexSet *)indexes withKey:(NSArray *)array 7680 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 7681 std::string SelectorName1 = 7682 (Twine("replace") + UpperKey + "AtIndexes").str(); 7683 std::string SelectorName2 = (Twine("with") + UpperKey).str(); 7684 IdentifierInfo *SelectorIds[2] = {&Context.Idents.get(SelectorName1), 7685 &Context.Idents.get(SelectorName2)}; 7686 7687 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) { 7688 if (ReturnType.isNull()) { 7689 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7690 Builder.AddTextChunk("void"); 7691 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7692 } 7693 7694 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName1 + ":")); 7695 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7696 Builder.AddPlaceholderChunk("NSIndexSet *"); 7697 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7698 Builder.AddTextChunk("indexes"); 7699 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7700 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName2 + ":")); 7701 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7702 Builder.AddTextChunk("NSArray *"); 7703 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7704 Builder.AddTextChunk("array"); 7705 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority, 7706 CXCursor_ObjCInstanceMethodDecl)); 7707 } 7708 } 7709 7710 // Unordered getters 7711 // - (NSEnumerator *)enumeratorOfKey 7712 if (IsInstanceMethod && 7713 (ReturnType.isNull() || 7714 (ReturnType->isObjCObjectPointerType() && 7715 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() && 7716 ReturnType->getAs<ObjCObjectPointerType>() 7717 ->getInterfaceDecl() 7718 ->getName() == "NSEnumerator"))) { 7719 std::string SelectorName = (Twine("enumeratorOf") + UpperKey).str(); 7720 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 7721 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId)) 7722 .second) { 7723 if (ReturnType.isNull()) { 7724 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7725 Builder.AddTextChunk("NSEnumerator *"); 7726 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7727 } 7728 7729 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName)); 7730 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority, 7731 CXCursor_ObjCInstanceMethodDecl)); 7732 } 7733 } 7734 7735 // - (type *)memberOfKey:(type *)object 7736 if (IsInstanceMethod && 7737 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) { 7738 std::string SelectorName = (Twine("memberOf") + UpperKey).str(); 7739 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 7740 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 7741 if (ReturnType.isNull()) { 7742 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7743 Builder.AddPlaceholderChunk("object-type"); 7744 Builder.AddTextChunk(" *"); 7745 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7746 } 7747 7748 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 7749 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7750 if (ReturnType.isNull()) { 7751 Builder.AddPlaceholderChunk("object-type"); 7752 Builder.AddTextChunk(" *"); 7753 } else { 7754 Builder.AddTextChunk(GetCompletionTypeString( 7755 ReturnType, Context, Policy, Builder.getAllocator())); 7756 } 7757 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7758 Builder.AddTextChunk("object"); 7759 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority, 7760 CXCursor_ObjCInstanceMethodDecl)); 7761 } 7762 } 7763 7764 // Mutable unordered accessors 7765 // - (void)addKeyObject:(type *)object 7766 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 7767 std::string SelectorName = 7768 (Twine("add") + UpperKey + Twine("Object")).str(); 7769 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 7770 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 7771 if (ReturnType.isNull()) { 7772 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7773 Builder.AddTextChunk("void"); 7774 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7775 } 7776 7777 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 7778 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7779 Builder.AddPlaceholderChunk("object-type"); 7780 Builder.AddTextChunk(" *"); 7781 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7782 Builder.AddTextChunk("object"); 7783 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority, 7784 CXCursor_ObjCInstanceMethodDecl)); 7785 } 7786 } 7787 7788 // - (void)addKey:(NSSet *)objects 7789 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 7790 std::string SelectorName = (Twine("add") + UpperKey).str(); 7791 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 7792 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 7793 if (ReturnType.isNull()) { 7794 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7795 Builder.AddTextChunk("void"); 7796 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7797 } 7798 7799 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 7800 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7801 Builder.AddTextChunk("NSSet *"); 7802 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7803 Builder.AddTextChunk("objects"); 7804 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority, 7805 CXCursor_ObjCInstanceMethodDecl)); 7806 } 7807 } 7808 7809 // - (void)removeKeyObject:(type *)object 7810 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 7811 std::string SelectorName = 7812 (Twine("remove") + UpperKey + Twine("Object")).str(); 7813 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 7814 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 7815 if (ReturnType.isNull()) { 7816 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7817 Builder.AddTextChunk("void"); 7818 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7819 } 7820 7821 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 7822 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7823 Builder.AddPlaceholderChunk("object-type"); 7824 Builder.AddTextChunk(" *"); 7825 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7826 Builder.AddTextChunk("object"); 7827 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority, 7828 CXCursor_ObjCInstanceMethodDecl)); 7829 } 7830 } 7831 7832 // - (void)removeKey:(NSSet *)objects 7833 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 7834 std::string SelectorName = (Twine("remove") + UpperKey).str(); 7835 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 7836 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 7837 if (ReturnType.isNull()) { 7838 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7839 Builder.AddTextChunk("void"); 7840 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7841 } 7842 7843 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 7844 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7845 Builder.AddTextChunk("NSSet *"); 7846 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7847 Builder.AddTextChunk("objects"); 7848 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority, 7849 CXCursor_ObjCInstanceMethodDecl)); 7850 } 7851 } 7852 7853 // - (void)intersectKey:(NSSet *)objects 7854 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 7855 std::string SelectorName = (Twine("intersect") + UpperKey).str(); 7856 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 7857 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 7858 if (ReturnType.isNull()) { 7859 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7860 Builder.AddTextChunk("void"); 7861 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7862 } 7863 7864 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 7865 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7866 Builder.AddTextChunk("NSSet *"); 7867 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7868 Builder.AddTextChunk("objects"); 7869 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority, 7870 CXCursor_ObjCInstanceMethodDecl)); 7871 } 7872 } 7873 7874 // Key-Value Observing 7875 // + (NSSet *)keyPathsForValuesAffectingKey 7876 if (!IsInstanceMethod && 7877 (ReturnType.isNull() || 7878 (ReturnType->isObjCObjectPointerType() && 7879 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() && 7880 ReturnType->getAs<ObjCObjectPointerType>() 7881 ->getInterfaceDecl() 7882 ->getName() == "NSSet"))) { 7883 std::string SelectorName = 7884 (Twine("keyPathsForValuesAffecting") + UpperKey).str(); 7885 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 7886 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId)) 7887 .second) { 7888 if (ReturnType.isNull()) { 7889 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7890 Builder.AddTextChunk("NSSet<NSString *> *"); 7891 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7892 } 7893 7894 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName)); 7895 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern, 7896 CXCursor_ObjCClassMethodDecl)); 7897 } 7898 } 7899 7900 // + (BOOL)automaticallyNotifiesObserversForKey 7901 if (!IsInstanceMethod && 7902 (ReturnType.isNull() || ReturnType->isIntegerType() || 7903 ReturnType->isBooleanType())) { 7904 std::string SelectorName = 7905 (Twine("automaticallyNotifiesObserversOf") + UpperKey).str(); 7906 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 7907 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId)) 7908 .second) { 7909 if (ReturnType.isNull()) { 7910 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7911 Builder.AddTextChunk("BOOL"); 7912 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7913 } 7914 7915 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName)); 7916 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern, 7917 CXCursor_ObjCClassMethodDecl)); 7918 } 7919 } 7920 } 7921 7922 void Sema::CodeCompleteObjCMethodDecl(Scope *S, Optional<bool> IsInstanceMethod, 7923 ParsedType ReturnTy) { 7924 // Determine the return type of the method we're declaring, if 7925 // provided. 7926 QualType ReturnType = GetTypeFromParser(ReturnTy); 7927 Decl *IDecl = nullptr; 7928 if (CurContext->isObjCContainer()) { 7929 ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext); 7930 IDecl = OCD; 7931 } 7932 // Determine where we should start searching for methods. 7933 ObjCContainerDecl *SearchDecl = nullptr; 7934 bool IsInImplementation = false; 7935 if (Decl *D = IDecl) { 7936 if (ObjCImplementationDecl *Impl = dyn_cast<ObjCImplementationDecl>(D)) { 7937 SearchDecl = Impl->getClassInterface(); 7938 IsInImplementation = true; 7939 } else if (ObjCCategoryImplDecl *CatImpl = 7940 dyn_cast<ObjCCategoryImplDecl>(D)) { 7941 SearchDecl = CatImpl->getCategoryDecl(); 7942 IsInImplementation = true; 7943 } else 7944 SearchDecl = dyn_cast<ObjCContainerDecl>(D); 7945 } 7946 7947 if (!SearchDecl && S) { 7948 if (DeclContext *DC = S->getEntity()) 7949 SearchDecl = dyn_cast<ObjCContainerDecl>(DC); 7950 } 7951 7952 if (!SearchDecl) { 7953 HandleCodeCompleteResults(this, CodeCompleter, 7954 CodeCompletionContext::CCC_Other, nullptr, 0); 7955 return; 7956 } 7957 7958 // Find all of the methods that we could declare/implement here. 7959 KnownMethodsMap KnownMethods; 7960 FindImplementableMethods(Context, SearchDecl, IsInstanceMethod, ReturnType, 7961 KnownMethods); 7962 7963 // Add declarations or definitions for each of the known methods. 7964 typedef CodeCompletionResult Result; 7965 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 7966 CodeCompleter->getCodeCompletionTUInfo(), 7967 CodeCompletionContext::CCC_Other); 7968 Results.EnterNewScope(); 7969 PrintingPolicy Policy = getCompletionPrintingPolicy(*this); 7970 for (KnownMethodsMap::iterator M = KnownMethods.begin(), 7971 MEnd = KnownMethods.end(); 7972 M != MEnd; ++M) { 7973 ObjCMethodDecl *Method = M->second.getPointer(); 7974 CodeCompletionBuilder Builder(Results.getAllocator(), 7975 Results.getCodeCompletionTUInfo()); 7976 7977 // Add the '-'/'+' prefix if it wasn't provided yet. 7978 if (!IsInstanceMethod) { 7979 Builder.AddTextChunk(Method->isInstanceMethod() ? "-" : "+"); 7980 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7981 } 7982 7983 // If the result type was not already provided, add it to the 7984 // pattern as (type). 7985 if (ReturnType.isNull()) { 7986 QualType ResTy = Method->getSendResultType().stripObjCKindOfType(Context); 7987 AttributedType::stripOuterNullability(ResTy); 7988 AddObjCPassingTypeChunk(ResTy, Method->getObjCDeclQualifier(), Context, 7989 Policy, Builder); 7990 } 7991 7992 Selector Sel = Method->getSelector(); 7993 7994 // Add the first part of the selector to the pattern. 7995 Builder.AddTypedTextChunk( 7996 Builder.getAllocator().CopyString(Sel.getNameForSlot(0))); 7997 7998 // Add parameters to the pattern. 7999 unsigned I = 0; 8000 for (ObjCMethodDecl::param_iterator P = Method->param_begin(), 8001 PEnd = Method->param_end(); 8002 P != PEnd; (void)++P, ++I) { 8003 // Add the part of the selector name. 8004 if (I == 0) 8005 Builder.AddTypedTextChunk(":"); 8006 else if (I < Sel.getNumArgs()) { 8007 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 8008 Builder.AddTypedTextChunk( 8009 Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":")); 8010 } else 8011 break; 8012 8013 // Add the parameter type. 8014 QualType ParamType; 8015 if ((*P)->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 8016 ParamType = (*P)->getType(); 8017 else 8018 ParamType = (*P)->getOriginalType(); 8019 ParamType = ParamType.substObjCTypeArgs( 8020 Context, {}, ObjCSubstitutionContext::Parameter); 8021 AttributedType::stripOuterNullability(ParamType); 8022 AddObjCPassingTypeChunk(ParamType, (*P)->getObjCDeclQualifier(), Context, 8023 Policy, Builder); 8024 8025 if (IdentifierInfo *Id = (*P)->getIdentifier()) 8026 Builder.AddTextChunk(Builder.getAllocator().CopyString(Id->getName())); 8027 } 8028 8029 if (Method->isVariadic()) { 8030 if (Method->param_size() > 0) 8031 Builder.AddChunk(CodeCompletionString::CK_Comma); 8032 Builder.AddTextChunk("..."); 8033 } 8034 8035 if (IsInImplementation && Results.includeCodePatterns()) { 8036 // We will be defining the method here, so add a compound statement. 8037 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 8038 Builder.AddChunk(CodeCompletionString::CK_LeftBrace); 8039 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); 8040 if (!Method->getReturnType()->isVoidType()) { 8041 // If the result type is not void, add a return clause. 8042 Builder.AddTextChunk("return"); 8043 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 8044 Builder.AddPlaceholderChunk("expression"); 8045 Builder.AddChunk(CodeCompletionString::CK_SemiColon); 8046 } else 8047 Builder.AddPlaceholderChunk("statements"); 8048 8049 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); 8050 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 8051 } 8052 8053 unsigned Priority = CCP_CodePattern; 8054 auto R = Result(Builder.TakeString(), Method, Priority); 8055 if (!M->second.getInt()) 8056 setInBaseClass(R); 8057 Results.AddResult(std::move(R)); 8058 } 8059 8060 // Add Key-Value-Coding and Key-Value-Observing accessor methods for all of 8061 // the properties in this class and its categories. 8062 if (Context.getLangOpts().ObjC) { 8063 SmallVector<ObjCContainerDecl *, 4> Containers; 8064 Containers.push_back(SearchDecl); 8065 8066 VisitedSelectorSet KnownSelectors; 8067 for (KnownMethodsMap::iterator M = KnownMethods.begin(), 8068 MEnd = KnownMethods.end(); 8069 M != MEnd; ++M) 8070 KnownSelectors.insert(M->first); 8071 8072 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(SearchDecl); 8073 if (!IFace) 8074 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(SearchDecl)) 8075 IFace = Category->getClassInterface(); 8076 8077 if (IFace) 8078 for (auto *Cat : IFace->visible_categories()) 8079 Containers.push_back(Cat); 8080 8081 if (IsInstanceMethod) { 8082 for (unsigned I = 0, N = Containers.size(); I != N; ++I) 8083 for (auto *P : Containers[I]->instance_properties()) 8084 AddObjCKeyValueCompletions(P, *IsInstanceMethod, ReturnType, Context, 8085 KnownSelectors, Results); 8086 } 8087 } 8088 8089 Results.ExitScope(); 8090 8091 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 8092 Results.data(), Results.size()); 8093 } 8094 8095 void Sema::CodeCompleteObjCMethodDeclSelector( 8096 Scope *S, bool IsInstanceMethod, bool AtParameterName, ParsedType ReturnTy, 8097 ArrayRef<IdentifierInfo *> SelIdents) { 8098 // If we have an external source, load the entire class method 8099 // pool from the AST file. 8100 if (ExternalSource) { 8101 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors(); I != N; 8102 ++I) { 8103 Selector Sel = ExternalSource->GetExternalSelector(I); 8104 if (Sel.isNull() || MethodPool.count(Sel)) 8105 continue; 8106 8107 ReadMethodPool(Sel); 8108 } 8109 } 8110 8111 // Build the set of methods we can see. 8112 typedef CodeCompletionResult Result; 8113 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 8114 CodeCompleter->getCodeCompletionTUInfo(), 8115 CodeCompletionContext::CCC_Other); 8116 8117 if (ReturnTy) 8118 Results.setPreferredType(GetTypeFromParser(ReturnTy).getNonReferenceType()); 8119 8120 Results.EnterNewScope(); 8121 for (GlobalMethodPool::iterator M = MethodPool.begin(), 8122 MEnd = MethodPool.end(); 8123 M != MEnd; ++M) { 8124 for (ObjCMethodList *MethList = IsInstanceMethod ? &M->second.first 8125 : &M->second.second; 8126 MethList && MethList->getMethod(); MethList = MethList->getNext()) { 8127 if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents)) 8128 continue; 8129 8130 if (AtParameterName) { 8131 // Suggest parameter names we've seen before. 8132 unsigned NumSelIdents = SelIdents.size(); 8133 if (NumSelIdents && 8134 NumSelIdents <= MethList->getMethod()->param_size()) { 8135 ParmVarDecl *Param = 8136 MethList->getMethod()->parameters()[NumSelIdents - 1]; 8137 if (Param->getIdentifier()) { 8138 CodeCompletionBuilder Builder(Results.getAllocator(), 8139 Results.getCodeCompletionTUInfo()); 8140 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString( 8141 Param->getIdentifier()->getName())); 8142 Results.AddResult(Builder.TakeString()); 8143 } 8144 } 8145 8146 continue; 8147 } 8148 8149 Result R(MethList->getMethod(), 8150 Results.getBasePriority(MethList->getMethod()), nullptr); 8151 R.StartParameter = SelIdents.size(); 8152 R.AllParametersAreInformative = false; 8153 R.DeclaringEntity = true; 8154 Results.MaybeAddResult(R, CurContext); 8155 } 8156 } 8157 8158 Results.ExitScope(); 8159 8160 if (!AtParameterName && !SelIdents.empty() && 8161 SelIdents.front()->getName().startswith("init")) { 8162 for (const auto &M : PP.macros()) { 8163 if (M.first->getName() != "NS_DESIGNATED_INITIALIZER") 8164 continue; 8165 Results.EnterNewScope(); 8166 CodeCompletionBuilder Builder(Results.getAllocator(), 8167 Results.getCodeCompletionTUInfo()); 8168 Builder.AddTypedTextChunk( 8169 Builder.getAllocator().CopyString(M.first->getName())); 8170 Results.AddResult(CodeCompletionResult(Builder.TakeString(), CCP_Macro, 8171 CXCursor_MacroDefinition)); 8172 Results.ExitScope(); 8173 } 8174 } 8175 8176 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 8177 Results.data(), Results.size()); 8178 } 8179 8180 void Sema::CodeCompletePreprocessorDirective(bool InConditional) { 8181 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 8182 CodeCompleter->getCodeCompletionTUInfo(), 8183 CodeCompletionContext::CCC_PreprocessorDirective); 8184 Results.EnterNewScope(); 8185 8186 // #if <condition> 8187 CodeCompletionBuilder Builder(Results.getAllocator(), 8188 Results.getCodeCompletionTUInfo()); 8189 Builder.AddTypedTextChunk("if"); 8190 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 8191 Builder.AddPlaceholderChunk("condition"); 8192 Results.AddResult(Builder.TakeString()); 8193 8194 // #ifdef <macro> 8195 Builder.AddTypedTextChunk("ifdef"); 8196 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 8197 Builder.AddPlaceholderChunk("macro"); 8198 Results.AddResult(Builder.TakeString()); 8199 8200 // #ifndef <macro> 8201 Builder.AddTypedTextChunk("ifndef"); 8202 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 8203 Builder.AddPlaceholderChunk("macro"); 8204 Results.AddResult(Builder.TakeString()); 8205 8206 if (InConditional) { 8207 // #elif <condition> 8208 Builder.AddTypedTextChunk("elif"); 8209 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 8210 Builder.AddPlaceholderChunk("condition"); 8211 Results.AddResult(Builder.TakeString()); 8212 8213 // #else 8214 Builder.AddTypedTextChunk("else"); 8215 Results.AddResult(Builder.TakeString()); 8216 8217 // #endif 8218 Builder.AddTypedTextChunk("endif"); 8219 Results.AddResult(Builder.TakeString()); 8220 } 8221 8222 // #include "header" 8223 Builder.AddTypedTextChunk("include"); 8224 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 8225 Builder.AddTextChunk("\""); 8226 Builder.AddPlaceholderChunk("header"); 8227 Builder.AddTextChunk("\""); 8228 Results.AddResult(Builder.TakeString()); 8229 8230 // #include <header> 8231 Builder.AddTypedTextChunk("include"); 8232 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 8233 Builder.AddTextChunk("<"); 8234 Builder.AddPlaceholderChunk("header"); 8235 Builder.AddTextChunk(">"); 8236 Results.AddResult(Builder.TakeString()); 8237 8238 // #define <macro> 8239 Builder.AddTypedTextChunk("define"); 8240 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 8241 Builder.AddPlaceholderChunk("macro"); 8242 Results.AddResult(Builder.TakeString()); 8243 8244 // #define <macro>(<args>) 8245 Builder.AddTypedTextChunk("define"); 8246 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 8247 Builder.AddPlaceholderChunk("macro"); 8248 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 8249 Builder.AddPlaceholderChunk("args"); 8250 Builder.AddChunk(CodeCompletionString::CK_RightParen); 8251 Results.AddResult(Builder.TakeString()); 8252 8253 // #undef <macro> 8254 Builder.AddTypedTextChunk("undef"); 8255 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 8256 Builder.AddPlaceholderChunk("macro"); 8257 Results.AddResult(Builder.TakeString()); 8258 8259 // #line <number> 8260 Builder.AddTypedTextChunk("line"); 8261 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 8262 Builder.AddPlaceholderChunk("number"); 8263 Results.AddResult(Builder.TakeString()); 8264 8265 // #line <number> "filename" 8266 Builder.AddTypedTextChunk("line"); 8267 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 8268 Builder.AddPlaceholderChunk("number"); 8269 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 8270 Builder.AddTextChunk("\""); 8271 Builder.AddPlaceholderChunk("filename"); 8272 Builder.AddTextChunk("\""); 8273 Results.AddResult(Builder.TakeString()); 8274 8275 // #error <message> 8276 Builder.AddTypedTextChunk("error"); 8277 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 8278 Builder.AddPlaceholderChunk("message"); 8279 Results.AddResult(Builder.TakeString()); 8280 8281 // #pragma <arguments> 8282 Builder.AddTypedTextChunk("pragma"); 8283 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 8284 Builder.AddPlaceholderChunk("arguments"); 8285 Results.AddResult(Builder.TakeString()); 8286 8287 if (getLangOpts().ObjC) { 8288 // #import "header" 8289 Builder.AddTypedTextChunk("import"); 8290 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 8291 Builder.AddTextChunk("\""); 8292 Builder.AddPlaceholderChunk("header"); 8293 Builder.AddTextChunk("\""); 8294 Results.AddResult(Builder.TakeString()); 8295 8296 // #import <header> 8297 Builder.AddTypedTextChunk("import"); 8298 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 8299 Builder.AddTextChunk("<"); 8300 Builder.AddPlaceholderChunk("header"); 8301 Builder.AddTextChunk(">"); 8302 Results.AddResult(Builder.TakeString()); 8303 } 8304 8305 // #include_next "header" 8306 Builder.AddTypedTextChunk("include_next"); 8307 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 8308 Builder.AddTextChunk("\""); 8309 Builder.AddPlaceholderChunk("header"); 8310 Builder.AddTextChunk("\""); 8311 Results.AddResult(Builder.TakeString()); 8312 8313 // #include_next <header> 8314 Builder.AddTypedTextChunk("include_next"); 8315 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 8316 Builder.AddTextChunk("<"); 8317 Builder.AddPlaceholderChunk("header"); 8318 Builder.AddTextChunk(">"); 8319 Results.AddResult(Builder.TakeString()); 8320 8321 // #warning <message> 8322 Builder.AddTypedTextChunk("warning"); 8323 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 8324 Builder.AddPlaceholderChunk("message"); 8325 Results.AddResult(Builder.TakeString()); 8326 8327 // Note: #ident and #sccs are such crazy anachronisms that we don't provide 8328 // completions for them. And __include_macros is a Clang-internal extension 8329 // that we don't want to encourage anyone to use. 8330 8331 // FIXME: we don't support #assert or #unassert, so don't suggest them. 8332 Results.ExitScope(); 8333 8334 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 8335 Results.data(), Results.size()); 8336 } 8337 8338 void Sema::CodeCompleteInPreprocessorConditionalExclusion(Scope *S) { 8339 CodeCompleteOrdinaryName(S, S->getFnParent() ? Sema::PCC_RecoveryInFunction 8340 : Sema::PCC_Namespace); 8341 } 8342 8343 void Sema::CodeCompletePreprocessorMacroName(bool IsDefinition) { 8344 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 8345 CodeCompleter->getCodeCompletionTUInfo(), 8346 IsDefinition ? CodeCompletionContext::CCC_MacroName 8347 : CodeCompletionContext::CCC_MacroNameUse); 8348 if (!IsDefinition && (!CodeCompleter || CodeCompleter->includeMacros())) { 8349 // Add just the names of macros, not their arguments. 8350 CodeCompletionBuilder Builder(Results.getAllocator(), 8351 Results.getCodeCompletionTUInfo()); 8352 Results.EnterNewScope(); 8353 for (Preprocessor::macro_iterator M = PP.macro_begin(), 8354 MEnd = PP.macro_end(); 8355 M != MEnd; ++M) { 8356 Builder.AddTypedTextChunk( 8357 Builder.getAllocator().CopyString(M->first->getName())); 8358 Results.AddResult(CodeCompletionResult( 8359 Builder.TakeString(), CCP_CodePattern, CXCursor_MacroDefinition)); 8360 } 8361 Results.ExitScope(); 8362 } else if (IsDefinition) { 8363 // FIXME: Can we detect when the user just wrote an include guard above? 8364 } 8365 8366 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 8367 Results.data(), Results.size()); 8368 } 8369 8370 void Sema::CodeCompletePreprocessorExpression() { 8371 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 8372 CodeCompleter->getCodeCompletionTUInfo(), 8373 CodeCompletionContext::CCC_PreprocessorExpression); 8374 8375 if (!CodeCompleter || CodeCompleter->includeMacros()) 8376 AddMacroResults(PP, Results, 8377 CodeCompleter ? CodeCompleter->loadExternal() : false, 8378 true); 8379 8380 // defined (<macro>) 8381 Results.EnterNewScope(); 8382 CodeCompletionBuilder Builder(Results.getAllocator(), 8383 Results.getCodeCompletionTUInfo()); 8384 Builder.AddTypedTextChunk("defined"); 8385 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 8386 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 8387 Builder.AddPlaceholderChunk("macro"); 8388 Builder.AddChunk(CodeCompletionString::CK_RightParen); 8389 Results.AddResult(Builder.TakeString()); 8390 Results.ExitScope(); 8391 8392 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 8393 Results.data(), Results.size()); 8394 } 8395 8396 void Sema::CodeCompletePreprocessorMacroArgument(Scope *S, 8397 IdentifierInfo *Macro, 8398 MacroInfo *MacroInfo, 8399 unsigned Argument) { 8400 // FIXME: In the future, we could provide "overload" results, much like we 8401 // do for function calls. 8402 8403 // Now just ignore this. There will be another code-completion callback 8404 // for the expanded tokens. 8405 } 8406 8407 // This handles completion inside an #include filename, e.g. #include <foo/ba 8408 // We look for the directory "foo" under each directory on the include path, 8409 // list its files, and reassemble the appropriate #include. 8410 void Sema::CodeCompleteIncludedFile(llvm::StringRef Dir, bool Angled) { 8411 // RelDir should use /, but unescaped \ is possible on windows! 8412 // Our completions will normalize to / for simplicity, this case is rare. 8413 std::string RelDir = llvm::sys::path::convert_to_slash(Dir); 8414 // We need the native slashes for the actual file system interactions. 8415 SmallString<128> NativeRelDir = StringRef(RelDir); 8416 llvm::sys::path::native(NativeRelDir); 8417 llvm::vfs::FileSystem &FS = 8418 getSourceManager().getFileManager().getVirtualFileSystem(); 8419 8420 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 8421 CodeCompleter->getCodeCompletionTUInfo(), 8422 CodeCompletionContext::CCC_IncludedFile); 8423 llvm::DenseSet<StringRef> SeenResults; // To deduplicate results. 8424 8425 // Helper: adds one file or directory completion result. 8426 auto AddCompletion = [&](StringRef Filename, bool IsDirectory) { 8427 SmallString<64> TypedChunk = Filename; 8428 // Directory completion is up to the slash, e.g. <sys/ 8429 TypedChunk.push_back(IsDirectory ? '/' : Angled ? '>' : '"'); 8430 auto R = SeenResults.insert(TypedChunk); 8431 if (R.second) { // New completion 8432 const char *InternedTyped = Results.getAllocator().CopyString(TypedChunk); 8433 *R.first = InternedTyped; // Avoid dangling StringRef. 8434 CodeCompletionBuilder Builder(CodeCompleter->getAllocator(), 8435 CodeCompleter->getCodeCompletionTUInfo()); 8436 Builder.AddTypedTextChunk(InternedTyped); 8437 // The result is a "Pattern", which is pretty opaque. 8438 // We may want to include the real filename to allow smart ranking. 8439 Results.AddResult(CodeCompletionResult(Builder.TakeString())); 8440 } 8441 }; 8442 8443 // Helper: scans IncludeDir for nice files, and adds results for each. 8444 auto AddFilesFromIncludeDir = [&](StringRef IncludeDir, 8445 bool IsSystem, 8446 DirectoryLookup::LookupType_t LookupType) { 8447 llvm::SmallString<128> Dir = IncludeDir; 8448 if (!NativeRelDir.empty()) { 8449 if (LookupType == DirectoryLookup::LT_Framework) { 8450 // For a framework dir, #include <Foo/Bar/> actually maps to 8451 // a path of Foo.framework/Headers/Bar/. 8452 auto Begin = llvm::sys::path::begin(NativeRelDir); 8453 auto End = llvm::sys::path::end(NativeRelDir); 8454 8455 llvm::sys::path::append(Dir, *Begin + ".framework", "Headers"); 8456 llvm::sys::path::append(Dir, ++Begin, End); 8457 } else { 8458 llvm::sys::path::append(Dir, NativeRelDir); 8459 } 8460 } 8461 8462 std::error_code EC; 8463 unsigned Count = 0; 8464 for (auto It = FS.dir_begin(Dir, EC); 8465 !EC && It != llvm::vfs::directory_iterator(); It.increment(EC)) { 8466 if (++Count == 2500) // If we happen to hit a huge directory, 8467 break; // bail out early so we're not too slow. 8468 StringRef Filename = llvm::sys::path::filename(It->path()); 8469 switch (It->type()) { 8470 case llvm::sys::fs::file_type::directory_file: 8471 // All entries in a framework directory must have a ".framework" suffix, 8472 // but the suffix does not appear in the source code's include/import. 8473 if (LookupType == DirectoryLookup::LT_Framework && 8474 NativeRelDir.empty() && !Filename.consume_back(".framework")) 8475 break; 8476 8477 AddCompletion(Filename, /*IsDirectory=*/true); 8478 break; 8479 case llvm::sys::fs::file_type::regular_file: 8480 // Only files that really look like headers. (Except in system dirs). 8481 if (!IsSystem) { 8482 // Header extensions from Types.def, which we can't depend on here. 8483 if (!(Filename.endswith_lower(".h") || 8484 Filename.endswith_lower(".hh") || 8485 Filename.endswith_lower(".hpp") || 8486 Filename.endswith_lower(".inc"))) 8487 break; 8488 } 8489 AddCompletion(Filename, /*IsDirectory=*/false); 8490 break; 8491 default: 8492 break; 8493 } 8494 } 8495 }; 8496 8497 // Helper: adds results relative to IncludeDir, if possible. 8498 auto AddFilesFromDirLookup = [&](const DirectoryLookup &IncludeDir, 8499 bool IsSystem) { 8500 switch (IncludeDir.getLookupType()) { 8501 case DirectoryLookup::LT_HeaderMap: 8502 // header maps are not (currently) enumerable. 8503 break; 8504 case DirectoryLookup::LT_NormalDir: 8505 AddFilesFromIncludeDir(IncludeDir.getDir()->getName(), IsSystem, 8506 DirectoryLookup::LT_NormalDir); 8507 break; 8508 case DirectoryLookup::LT_Framework: 8509 AddFilesFromIncludeDir(IncludeDir.getFrameworkDir()->getName(), IsSystem, 8510 DirectoryLookup::LT_Framework); 8511 break; 8512 } 8513 }; 8514 8515 // Finally with all our helpers, we can scan the include path. 8516 // Do this in standard order so deduplication keeps the right file. 8517 // (In case we decide to add more details to the results later). 8518 const auto &S = PP.getHeaderSearchInfo(); 8519 using llvm::make_range; 8520 if (!Angled) { 8521 // The current directory is on the include path for "quoted" includes. 8522 auto *CurFile = PP.getCurrentFileLexer()->getFileEntry(); 8523 if (CurFile && CurFile->getDir()) 8524 AddFilesFromIncludeDir(CurFile->getDir()->getName(), false, 8525 DirectoryLookup::LT_NormalDir); 8526 for (const auto &D : make_range(S.quoted_dir_begin(), S.quoted_dir_end())) 8527 AddFilesFromDirLookup(D, false); 8528 } 8529 for (const auto &D : make_range(S.angled_dir_begin(), S.angled_dir_end())) 8530 AddFilesFromDirLookup(D, false); 8531 for (const auto &D : make_range(S.system_dir_begin(), S.system_dir_end())) 8532 AddFilesFromDirLookup(D, true); 8533 8534 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 8535 Results.data(), Results.size()); 8536 } 8537 8538 void Sema::CodeCompleteNaturalLanguage() { 8539 HandleCodeCompleteResults(this, CodeCompleter, 8540 CodeCompletionContext::CCC_NaturalLanguage, nullptr, 8541 0); 8542 } 8543 8544 void Sema::CodeCompleteAvailabilityPlatformName() { 8545 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 8546 CodeCompleter->getCodeCompletionTUInfo(), 8547 CodeCompletionContext::CCC_Other); 8548 Results.EnterNewScope(); 8549 static const char *Platforms[] = {"macOS", "iOS", "watchOS", "tvOS"}; 8550 for (const char *Platform : llvm::makeArrayRef(Platforms)) { 8551 Results.AddResult(CodeCompletionResult(Platform)); 8552 Results.AddResult(CodeCompletionResult(Results.getAllocator().CopyString( 8553 Twine(Platform) + "ApplicationExtension"))); 8554 } 8555 Results.ExitScope(); 8556 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 8557 Results.data(), Results.size()); 8558 } 8559 8560 void Sema::GatherGlobalCodeCompletions( 8561 CodeCompletionAllocator &Allocator, CodeCompletionTUInfo &CCTUInfo, 8562 SmallVectorImpl<CodeCompletionResult> &Results) { 8563 ResultBuilder Builder(*this, Allocator, CCTUInfo, 8564 CodeCompletionContext::CCC_Recovery); 8565 if (!CodeCompleter || CodeCompleter->includeGlobals()) { 8566 CodeCompletionDeclConsumer Consumer(Builder, 8567 Context.getTranslationUnitDecl()); 8568 LookupVisibleDecls(Context.getTranslationUnitDecl(), LookupAnyName, 8569 Consumer, 8570 !CodeCompleter || CodeCompleter->loadExternal()); 8571 } 8572 8573 if (!CodeCompleter || CodeCompleter->includeMacros()) 8574 AddMacroResults(PP, Builder, 8575 CodeCompleter ? CodeCompleter->loadExternal() : false, 8576 true); 8577 8578 Results.clear(); 8579 Results.insert(Results.end(), Builder.data(), 8580 Builder.data() + Builder.size()); 8581 } 8582