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