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