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/HeuristicResolver.h" 38 #include "clang/Sema/Lookup.h" 39 #include "clang/Sema/Overload.h" 40 #include "clang/Sema/ParsedAttr.h" 41 #include "clang/Sema/ParsedTemplate.h" 42 #include "clang/Sema/Scope.h" 43 #include "clang/Sema/ScopeInfo.h" 44 #include "clang/Sema/Sema.h" 45 #include "clang/Sema/SemaCodeCompletion.h" 46 #include "clang/Sema/SemaObjC.h" 47 #include "llvm/ADT/ArrayRef.h" 48 #include "llvm/ADT/DenseSet.h" 49 #include "llvm/ADT/SmallBitVector.h" 50 #include "llvm/ADT/SmallPtrSet.h" 51 #include "llvm/ADT/SmallString.h" 52 #include "llvm/ADT/StringSwitch.h" 53 #include "llvm/ADT/Twine.h" 54 #include "llvm/ADT/iterator_range.h" 55 #include "llvm/Support/Casting.h" 56 #include "llvm/Support/Path.h" 57 #include "llvm/Support/raw_ostream.h" 58 59 #include <list> 60 #include <map> 61 #include <optional> 62 #include <string> 63 #include <vector> 64 65 using namespace clang; 66 using namespace sema; 67 68 namespace { 69 /// A container of code-completion results. 70 class ResultBuilder { 71 public: 72 /// The type of a name-lookup filter, which can be provided to the 73 /// name-lookup routines to specify which declarations should be included in 74 /// the result set (when it returns true) and which declarations should be 75 /// filtered out (returns false). 76 typedef bool (ResultBuilder::*LookupFilter)(const NamedDecl *) const; 77 78 typedef CodeCompletionResult Result; 79 80 private: 81 /// The actual results we have found. 82 std::vector<Result> Results; 83 84 /// A record of all of the declarations we have found and placed 85 /// into the result set, used to ensure that no declaration ever gets into 86 /// the result set twice. 87 llvm::SmallPtrSet<const Decl *, 16> AllDeclsFound; 88 89 typedef std::pair<const NamedDecl *, unsigned> DeclIndexPair; 90 91 /// An entry in the shadow map, which is optimized to store 92 /// a single (declaration, index) mapping (the common case) but 93 /// can also store a list of (declaration, index) mappings. 94 class ShadowMapEntry { 95 typedef SmallVector<DeclIndexPair, 4> DeclIndexPairVector; 96 97 /// Contains either the solitary NamedDecl * or a vector 98 /// of (declaration, index) pairs. 99 llvm::PointerUnion<const NamedDecl *, DeclIndexPairVector *> DeclOrVector; 100 101 /// When the entry contains a single declaration, this is 102 /// the index associated with that entry. 103 unsigned SingleDeclIndex = 0; 104 105 public: 106 ShadowMapEntry() = default; 107 ShadowMapEntry(const ShadowMapEntry &) = delete; 108 ShadowMapEntry(ShadowMapEntry &&Move) { *this = std::move(Move); } 109 ShadowMapEntry &operator=(const ShadowMapEntry &) = delete; 110 ShadowMapEntry &operator=(ShadowMapEntry &&Move) { 111 SingleDeclIndex = Move.SingleDeclIndex; 112 DeclOrVector = Move.DeclOrVector; 113 Move.DeclOrVector = nullptr; 114 return *this; 115 } 116 117 void Add(const NamedDecl *ND, unsigned Index) { 118 if (DeclOrVector.isNull()) { 119 // 0 - > 1 elements: just set the single element information. 120 DeclOrVector = ND; 121 SingleDeclIndex = Index; 122 return; 123 } 124 125 if (const NamedDecl *PrevND = dyn_cast<const NamedDecl *>(DeclOrVector)) { 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 cast<DeclIndexPairVector *>(DeclOrVector) 135 ->push_back(DeclIndexPair(ND, Index)); 136 } 137 138 ~ShadowMapEntry() { 139 if (DeclIndexPairVector *Vec = 140 dyn_cast_if_present<DeclIndexPairVector *>(DeclOrVector)) { 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 (isa<const NamedDecl *>(DeclOrIterator)) { 663 DeclOrIterator = (NamedDecl *)nullptr; 664 SingleDeclIndex = 0; 665 return *this; 666 } 667 668 const DeclIndexPair *I = cast<const DeclIndexPair *>(DeclOrIterator); 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 = dyn_cast<const NamedDecl *>(DeclOrIterator)) 682 return reference(ND, SingleDeclIndex); 683 684 return *cast<const DeclIndexPair *>(DeclOrIterator); 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 = dyn_cast<const NamedDecl *>(DeclOrVector)) 706 return iterator(ND, SingleDeclIndex); 707 708 return iterator(cast<DeclIndexPairVector *>(DeclOrVector)->begin()); 709 } 710 711 ResultBuilder::ShadowMapEntry::iterator 712 ResultBuilder::ShadowMapEntry::end() const { 713 if (isa<const NamedDecl *>(DeclOrVector) || DeclOrVector.isNull()) 714 return iterator(); 715 716 return iterator(cast<DeclIndexPairVector *>(DeclOrVector)->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, HeuristicResolver &Resolver) { 5740 if (E->getType().isNull()) 5741 return QualType(); 5742 E = E->IgnoreParenImpCasts(); 5743 QualType Unresolved = E->getType(); 5744 // Resolve DependentNameType 5745 if (const auto *DNT = Unresolved->getAs<DependentNameType>()) { 5746 if (auto Decls = Resolver.resolveDependentNameType(DNT); 5747 Decls.size() == 1) { 5748 if (const auto *TD = dyn_cast<TypeDecl>(Decls[0])) 5749 return QualType(TD->getTypeForDecl(), 0); 5750 } 5751 } 5752 // We only resolve DependentTy, or undeduced autos (including auto* etc). 5753 if (!Unresolved->isSpecificBuiltinType(BuiltinType::Dependent)) { 5754 AutoType *Auto = Unresolved->getContainedAutoType(); 5755 if (!Auto || !Auto->isUndeducedAutoType()) 5756 return Unresolved; 5757 } 5758 // A call: approximate-resolve callee to a function type, get its return type 5759 if (const CallExpr *CE = llvm::dyn_cast<CallExpr>(E)) { 5760 QualType Callee = getApproximateType(CE->getCallee(), Resolver); 5761 if (Callee.isNull() || 5762 Callee->isSpecificPlaceholderType(BuiltinType::BoundMember)) 5763 Callee = Expr::findBoundMemberType(CE->getCallee()); 5764 if (Callee.isNull()) 5765 return Unresolved; 5766 5767 if (const auto *FnTypePtr = Callee->getAs<PointerType>()) { 5768 Callee = FnTypePtr->getPointeeType(); 5769 } else if (const auto *BPT = Callee->getAs<BlockPointerType>()) { 5770 Callee = BPT->getPointeeType(); 5771 } 5772 if (const FunctionType *FnType = Callee->getAs<FunctionType>()) 5773 return FnType->getReturnType().getNonReferenceType(); 5774 5775 // Unresolved call: try to guess the return type. 5776 if (const auto *OE = llvm::dyn_cast<OverloadExpr>(CE->getCallee())) { 5777 // If all candidates have the same approximate return type, use it. 5778 // Discard references and const to allow more to be "the same". 5779 // (In particular, if there's one candidate + ADL, resolve it). 5780 const Type *Common = nullptr; 5781 for (const auto *D : OE->decls()) { 5782 QualType ReturnType; 5783 if (const auto *FD = llvm::dyn_cast<FunctionDecl>(D)) 5784 ReturnType = FD->getReturnType(); 5785 else if (const auto *FTD = llvm::dyn_cast<FunctionTemplateDecl>(D)) 5786 ReturnType = FTD->getTemplatedDecl()->getReturnType(); 5787 if (ReturnType.isNull()) 5788 continue; 5789 const Type *Candidate = 5790 ReturnType.getNonReferenceType().getCanonicalType().getTypePtr(); 5791 if (Common && Common != Candidate) 5792 return Unresolved; // Multiple candidates. 5793 Common = Candidate; 5794 } 5795 if (Common != nullptr) 5796 return QualType(Common, 0); 5797 } 5798 } 5799 // A dependent member: approximate-resolve the base, then lookup. 5800 if (const auto *CDSME = llvm::dyn_cast<CXXDependentScopeMemberExpr>(E)) { 5801 QualType Base = CDSME->isImplicitAccess() 5802 ? CDSME->getBaseType() 5803 : getApproximateType(CDSME->getBase(), Resolver); 5804 if (CDSME->isArrow() && !Base.isNull()) 5805 Base = Base->getPointeeType(); // could handle unique_ptr etc here? 5806 auto *RD = 5807 Base.isNull() 5808 ? nullptr 5809 : llvm::dyn_cast_or_null<CXXRecordDecl>(getAsRecordDecl(Base)); 5810 if (RD && RD->isCompleteDefinition()) { 5811 // Look up member heuristically, including in bases. 5812 for (const auto *Member : RD->lookupDependentName( 5813 CDSME->getMember(), [](const NamedDecl *Member) { 5814 return llvm::isa<ValueDecl>(Member); 5815 })) { 5816 return llvm::cast<ValueDecl>(Member)->getType().getNonReferenceType(); 5817 } 5818 } 5819 } 5820 // A reference to an `auto` variable: approximate-resolve its initializer. 5821 if (const auto *DRE = llvm::dyn_cast<DeclRefExpr>(E)) { 5822 if (const auto *VD = llvm::dyn_cast<VarDecl>(DRE->getDecl())) { 5823 if (VD->hasInit()) 5824 return getApproximateType(VD->getInit(), Resolver); 5825 } 5826 } 5827 if (const auto *UO = llvm::dyn_cast<UnaryOperator>(E)) { 5828 if (UO->getOpcode() == UnaryOperatorKind::UO_Deref) { 5829 // We recurse into the subexpression because it could be of dependent 5830 // type. 5831 if (auto Pointee = 5832 getApproximateType(UO->getSubExpr(), Resolver)->getPointeeType(); 5833 !Pointee.isNull()) 5834 return Pointee; 5835 // Our caller expects a non-null result, even though the SubType is 5836 // supposed to have a pointee. Fall through to Unresolved anyway. 5837 } 5838 } 5839 return Unresolved; 5840 } 5841 5842 // If \p Base is ParenListExpr, assume a chain of comma operators and pick the 5843 // last expr. We expect other ParenListExprs to be resolved to e.g. constructor 5844 // calls before here. (So the ParenListExpr should be nonempty, but check just 5845 // in case) 5846 Expr *unwrapParenList(Expr *Base) { 5847 if (auto *PLE = llvm::dyn_cast_or_null<ParenListExpr>(Base)) { 5848 if (PLE->getNumExprs() == 0) 5849 return nullptr; 5850 Base = PLE->getExpr(PLE->getNumExprs() - 1); 5851 } 5852 return Base; 5853 } 5854 5855 } // namespace 5856 5857 void SemaCodeCompletion::CodeCompleteMemberReferenceExpr( 5858 Scope *S, Expr *Base, Expr *OtherOpBase, SourceLocation OpLoc, bool IsArrow, 5859 bool IsBaseExprStatement, QualType PreferredType) { 5860 Base = unwrapParenList(Base); 5861 OtherOpBase = unwrapParenList(OtherOpBase); 5862 if (!Base || !CodeCompleter) 5863 return; 5864 5865 ExprResult ConvertedBase = 5866 SemaRef.PerformMemberExprBaseConversion(Base, IsArrow); 5867 if (ConvertedBase.isInvalid()) 5868 return; 5869 QualType ConvertedBaseType = 5870 getApproximateType(ConvertedBase.get(), Resolver); 5871 5872 enum CodeCompletionContext::Kind contextKind; 5873 5874 if (IsArrow) { 5875 if (QualType PointeeType = Resolver.getPointeeType(ConvertedBaseType); 5876 !PointeeType.isNull()) { 5877 ConvertedBaseType = PointeeType; 5878 } 5879 } 5880 5881 if (IsArrow) { 5882 contextKind = CodeCompletionContext::CCC_ArrowMemberAccess; 5883 } else { 5884 if (ConvertedBaseType->isObjCObjectPointerType() || 5885 ConvertedBaseType->isObjCObjectOrInterfaceType()) { 5886 contextKind = CodeCompletionContext::CCC_ObjCPropertyAccess; 5887 } else { 5888 contextKind = CodeCompletionContext::CCC_DotMemberAccess; 5889 } 5890 } 5891 5892 CodeCompletionContext CCContext(contextKind, ConvertedBaseType); 5893 CCContext.setPreferredType(PreferredType); 5894 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(), 5895 CodeCompleter->getCodeCompletionTUInfo(), CCContext, 5896 &ResultBuilder::IsMember); 5897 5898 auto DoCompletion = [&](Expr *Base, bool IsArrow, 5899 std::optional<FixItHint> AccessOpFixIt) -> bool { 5900 if (!Base) 5901 return false; 5902 5903 ExprResult ConvertedBase = 5904 SemaRef.PerformMemberExprBaseConversion(Base, IsArrow); 5905 if (ConvertedBase.isInvalid()) 5906 return false; 5907 Base = ConvertedBase.get(); 5908 5909 QualType BaseType = getApproximateType(Base, Resolver); 5910 if (BaseType.isNull()) 5911 return false; 5912 ExprValueKind BaseKind = Base->getValueKind(); 5913 5914 if (IsArrow) { 5915 if (QualType PointeeType = Resolver.getPointeeType(BaseType); 5916 !PointeeType.isNull()) { 5917 BaseType = PointeeType; 5918 BaseKind = VK_LValue; 5919 } else if (BaseType->isObjCObjectPointerType() || 5920 BaseType->isTemplateTypeParmType()) { 5921 // Both cases (dot/arrow) handled below. 5922 } else { 5923 return false; 5924 } 5925 } 5926 5927 if (RecordDecl *RD = getAsRecordDecl(BaseType)) { 5928 AddRecordMembersCompletionResults(SemaRef, Results, S, BaseType, BaseKind, 5929 RD, std::move(AccessOpFixIt)); 5930 } else if (const auto *TTPT = 5931 dyn_cast<TemplateTypeParmType>(BaseType.getTypePtr())) { 5932 auto Operator = 5933 IsArrow ? ConceptInfo::Member::Arrow : ConceptInfo::Member::Dot; 5934 for (const auto &R : ConceptInfo(*TTPT, S).members()) { 5935 if (R.Operator != Operator) 5936 continue; 5937 CodeCompletionResult Result( 5938 R.render(SemaRef, CodeCompleter->getAllocator(), 5939 CodeCompleter->getCodeCompletionTUInfo())); 5940 if (AccessOpFixIt) 5941 Result.FixIts.push_back(*AccessOpFixIt); 5942 Results.AddResult(std::move(Result)); 5943 } 5944 } else if (!IsArrow && BaseType->isObjCObjectPointerType()) { 5945 // Objective-C property reference. Bail if we're performing fix-it code 5946 // completion since Objective-C properties are normally backed by ivars, 5947 // most Objective-C fix-its here would have little value. 5948 if (AccessOpFixIt) { 5949 return false; 5950 } 5951 AddedPropertiesSet AddedProperties; 5952 5953 if (const ObjCObjectPointerType *ObjCPtr = 5954 BaseType->getAsObjCInterfacePointerType()) { 5955 // Add property results based on our interface. 5956 assert(ObjCPtr && "Non-NULL pointer guaranteed above!"); 5957 AddObjCProperties(CCContext, ObjCPtr->getInterfaceDecl(), true, 5958 /*AllowNullaryMethods=*/true, SemaRef.CurContext, 5959 AddedProperties, Results, IsBaseExprStatement); 5960 } 5961 5962 // Add properties from the protocols in a qualified interface. 5963 for (auto *I : BaseType->castAs<ObjCObjectPointerType>()->quals()) 5964 AddObjCProperties(CCContext, I, true, /*AllowNullaryMethods=*/true, 5965 SemaRef.CurContext, AddedProperties, Results, 5966 IsBaseExprStatement, /*IsClassProperty*/ false, 5967 /*InOriginalClass*/ false); 5968 } else if ((IsArrow && BaseType->isObjCObjectPointerType()) || 5969 (!IsArrow && BaseType->isObjCObjectType())) { 5970 // Objective-C instance variable access. Bail if we're performing fix-it 5971 // code completion since Objective-C properties are normally backed by 5972 // ivars, most Objective-C fix-its here would have little value. 5973 if (AccessOpFixIt) { 5974 return false; 5975 } 5976 ObjCInterfaceDecl *Class = nullptr; 5977 if (const ObjCObjectPointerType *ObjCPtr = 5978 BaseType->getAs<ObjCObjectPointerType>()) 5979 Class = ObjCPtr->getInterfaceDecl(); 5980 else 5981 Class = BaseType->castAs<ObjCObjectType>()->getInterface(); 5982 5983 // Add all ivars from this class and its superclasses. 5984 if (Class) { 5985 CodeCompletionDeclConsumer Consumer(Results, Class, BaseType); 5986 Results.setFilter(&ResultBuilder::IsObjCIvar); 5987 SemaRef.LookupVisibleDecls(Class, Sema::LookupMemberName, Consumer, 5988 CodeCompleter->includeGlobals(), 5989 /*IncludeDependentBases=*/false, 5990 CodeCompleter->loadExternal()); 5991 } 5992 } 5993 5994 // FIXME: How do we cope with isa? 5995 return true; 5996 }; 5997 5998 Results.EnterNewScope(); 5999 6000 bool CompletionSucceded = DoCompletion(Base, IsArrow, std::nullopt); 6001 if (CodeCompleter->includeFixIts()) { 6002 const CharSourceRange OpRange = 6003 CharSourceRange::getTokenRange(OpLoc, OpLoc); 6004 CompletionSucceded |= DoCompletion( 6005 OtherOpBase, !IsArrow, 6006 FixItHint::CreateReplacement(OpRange, IsArrow ? "." : "->")); 6007 } 6008 6009 Results.ExitScope(); 6010 6011 if (!CompletionSucceded) 6012 return; 6013 6014 // Hand off the results found for code completion. 6015 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 6016 Results.getCompletionContext(), Results.data(), 6017 Results.size()); 6018 } 6019 6020 void SemaCodeCompletion::CodeCompleteObjCClassPropertyRefExpr( 6021 Scope *S, const IdentifierInfo &ClassName, SourceLocation ClassNameLoc, 6022 bool IsBaseExprStatement) { 6023 const IdentifierInfo *ClassNamePtr = &ClassName; 6024 ObjCInterfaceDecl *IFace = 6025 SemaRef.ObjC().getObjCInterfaceDecl(ClassNamePtr, ClassNameLoc); 6026 if (!IFace) 6027 return; 6028 CodeCompletionContext CCContext( 6029 CodeCompletionContext::CCC_ObjCPropertyAccess); 6030 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(), 6031 CodeCompleter->getCodeCompletionTUInfo(), CCContext, 6032 &ResultBuilder::IsMember); 6033 Results.EnterNewScope(); 6034 AddedPropertiesSet AddedProperties; 6035 AddObjCProperties(CCContext, IFace, true, 6036 /*AllowNullaryMethods=*/true, SemaRef.CurContext, 6037 AddedProperties, Results, IsBaseExprStatement, 6038 /*IsClassProperty=*/true); 6039 Results.ExitScope(); 6040 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 6041 Results.getCompletionContext(), Results.data(), 6042 Results.size()); 6043 } 6044 6045 void SemaCodeCompletion::CodeCompleteTag(Scope *S, unsigned TagSpec) { 6046 if (!CodeCompleter) 6047 return; 6048 6049 ResultBuilder::LookupFilter Filter = nullptr; 6050 enum CodeCompletionContext::Kind ContextKind = 6051 CodeCompletionContext::CCC_Other; 6052 switch ((DeclSpec::TST)TagSpec) { 6053 case DeclSpec::TST_enum: 6054 Filter = &ResultBuilder::IsEnum; 6055 ContextKind = CodeCompletionContext::CCC_EnumTag; 6056 break; 6057 6058 case DeclSpec::TST_union: 6059 Filter = &ResultBuilder::IsUnion; 6060 ContextKind = CodeCompletionContext::CCC_UnionTag; 6061 break; 6062 6063 case DeclSpec::TST_struct: 6064 case DeclSpec::TST_class: 6065 case DeclSpec::TST_interface: 6066 Filter = &ResultBuilder::IsClassOrStruct; 6067 ContextKind = CodeCompletionContext::CCC_ClassOrStructTag; 6068 break; 6069 6070 default: 6071 llvm_unreachable("Unknown type specifier kind in CodeCompleteTag"); 6072 } 6073 6074 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(), 6075 CodeCompleter->getCodeCompletionTUInfo(), ContextKind); 6076 CodeCompletionDeclConsumer Consumer(Results, SemaRef.CurContext); 6077 6078 // First pass: look for tags. 6079 Results.setFilter(Filter); 6080 SemaRef.LookupVisibleDecls(S, Sema::LookupTagName, Consumer, 6081 CodeCompleter->includeGlobals(), 6082 CodeCompleter->loadExternal()); 6083 6084 if (CodeCompleter->includeGlobals()) { 6085 // Second pass: look for nested name specifiers. 6086 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier); 6087 SemaRef.LookupVisibleDecls(S, Sema::LookupNestedNameSpecifierName, Consumer, 6088 CodeCompleter->includeGlobals(), 6089 CodeCompleter->loadExternal()); 6090 } 6091 6092 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 6093 Results.getCompletionContext(), Results.data(), 6094 Results.size()); 6095 } 6096 6097 static void AddTypeQualifierResults(DeclSpec &DS, ResultBuilder &Results, 6098 const LangOptions &LangOpts) { 6099 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_const)) 6100 Results.AddResult("const"); 6101 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_volatile)) 6102 Results.AddResult("volatile"); 6103 if (LangOpts.C99 && !(DS.getTypeQualifiers() & DeclSpec::TQ_restrict)) 6104 Results.AddResult("restrict"); 6105 if (LangOpts.C11 && !(DS.getTypeQualifiers() & DeclSpec::TQ_atomic)) 6106 Results.AddResult("_Atomic"); 6107 if (LangOpts.MSVCCompat && !(DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)) 6108 Results.AddResult("__unaligned"); 6109 } 6110 6111 void SemaCodeCompletion::CodeCompleteTypeQualifiers(DeclSpec &DS) { 6112 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(), 6113 CodeCompleter->getCodeCompletionTUInfo(), 6114 CodeCompletionContext::CCC_TypeQualifiers); 6115 Results.EnterNewScope(); 6116 AddTypeQualifierResults(DS, Results, getLangOpts()); 6117 Results.ExitScope(); 6118 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 6119 Results.getCompletionContext(), Results.data(), 6120 Results.size()); 6121 } 6122 6123 void SemaCodeCompletion::CodeCompleteFunctionQualifiers( 6124 DeclSpec &DS, Declarator &D, const VirtSpecifiers *VS) { 6125 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(), 6126 CodeCompleter->getCodeCompletionTUInfo(), 6127 CodeCompletionContext::CCC_TypeQualifiers); 6128 Results.EnterNewScope(); 6129 AddTypeQualifierResults(DS, Results, getLangOpts()); 6130 if (getLangOpts().CPlusPlus11) { 6131 Results.AddResult("noexcept"); 6132 if (D.getContext() == DeclaratorContext::Member && !D.isCtorOrDtor() && 6133 !D.isStaticMember()) { 6134 if (!VS || !VS->isFinalSpecified()) 6135 Results.AddResult("final"); 6136 if (!VS || !VS->isOverrideSpecified()) 6137 Results.AddResult("override"); 6138 } 6139 } 6140 Results.ExitScope(); 6141 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 6142 Results.getCompletionContext(), Results.data(), 6143 Results.size()); 6144 } 6145 6146 void SemaCodeCompletion::CodeCompleteBracketDeclarator(Scope *S) { 6147 CodeCompleteExpression(S, QualType(getASTContext().getSizeType())); 6148 } 6149 6150 void SemaCodeCompletion::CodeCompleteCase(Scope *S) { 6151 if (SemaRef.getCurFunction()->SwitchStack.empty() || !CodeCompleter) 6152 return; 6153 6154 SwitchStmt *Switch = 6155 SemaRef.getCurFunction()->SwitchStack.back().getPointer(); 6156 // Condition expression might be invalid, do not continue in this case. 6157 if (!Switch->getCond()) 6158 return; 6159 QualType type = Switch->getCond()->IgnoreImplicit()->getType(); 6160 if (!type->isEnumeralType()) { 6161 CodeCompleteExpressionData Data(type); 6162 Data.IntegralConstantExpression = true; 6163 CodeCompleteExpression(S, Data); 6164 return; 6165 } 6166 6167 // Code-complete the cases of a switch statement over an enumeration type 6168 // by providing the list of 6169 EnumDecl *Enum = type->castAs<EnumType>()->getDecl(); 6170 if (EnumDecl *Def = Enum->getDefinition()) 6171 Enum = Def; 6172 6173 // Determine which enumerators we have already seen in the switch statement. 6174 // FIXME: Ideally, we would also be able to look *past* the code-completion 6175 // token, in case we are code-completing in the middle of the switch and not 6176 // at the end. However, we aren't able to do so at the moment. 6177 CoveredEnumerators Enumerators; 6178 for (SwitchCase *SC = Switch->getSwitchCaseList(); SC; 6179 SC = SC->getNextSwitchCase()) { 6180 CaseStmt *Case = dyn_cast<CaseStmt>(SC); 6181 if (!Case) 6182 continue; 6183 6184 Expr *CaseVal = Case->getLHS()->IgnoreParenCasts(); 6185 if (auto *DRE = dyn_cast<DeclRefExpr>(CaseVal)) 6186 if (auto *Enumerator = 6187 dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 6188 // We look into the AST of the case statement to determine which 6189 // enumerator was named. Alternatively, we could compute the value of 6190 // the integral constant expression, then compare it against the 6191 // values of each enumerator. However, value-based approach would not 6192 // work as well with C++ templates where enumerators declared within a 6193 // template are type- and value-dependent. 6194 Enumerators.Seen.insert(Enumerator); 6195 6196 // If this is a qualified-id, keep track of the nested-name-specifier 6197 // so that we can reproduce it as part of code completion, e.g., 6198 // 6199 // switch (TagD.getKind()) { 6200 // case TagDecl::TK_enum: 6201 // break; 6202 // case XXX 6203 // 6204 // At the XXX, our completions are TagDecl::TK_union, 6205 // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union, 6206 // TK_struct, and TK_class. 6207 Enumerators.SuggestedQualifier = DRE->getQualifier(); 6208 } 6209 } 6210 6211 // Add any enumerators that have not yet been mentioned. 6212 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(), 6213 CodeCompleter->getCodeCompletionTUInfo(), 6214 CodeCompletionContext::CCC_Expression); 6215 AddEnumerators(Results, getASTContext(), Enum, SemaRef.CurContext, 6216 Enumerators); 6217 6218 if (CodeCompleter->includeMacros()) { 6219 AddMacroResults(SemaRef.PP, Results, CodeCompleter->loadExternal(), false); 6220 } 6221 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 6222 Results.getCompletionContext(), Results.data(), 6223 Results.size()); 6224 } 6225 6226 static bool anyNullArguments(ArrayRef<Expr *> Args) { 6227 if (Args.size() && !Args.data()) 6228 return true; 6229 6230 for (unsigned I = 0; I != Args.size(); ++I) 6231 if (!Args[I]) 6232 return true; 6233 6234 return false; 6235 } 6236 6237 typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate; 6238 6239 static void mergeCandidatesWithResults( 6240 Sema &SemaRef, SmallVectorImpl<ResultCandidate> &Results, 6241 OverloadCandidateSet &CandidateSet, SourceLocation Loc, size_t ArgSize) { 6242 // Sort the overload candidate set by placing the best overloads first. 6243 llvm::stable_sort(CandidateSet, [&](const OverloadCandidate &X, 6244 const OverloadCandidate &Y) { 6245 return isBetterOverloadCandidate(SemaRef, X, Y, Loc, 6246 CandidateSet.getKind()); 6247 }); 6248 6249 // Add the remaining viable overload candidates as code-completion results. 6250 for (OverloadCandidate &Candidate : CandidateSet) { 6251 if (Candidate.Function) { 6252 if (Candidate.Function->isDeleted()) 6253 continue; 6254 if (shouldEnforceArgLimit(/*PartialOverloading=*/true, 6255 Candidate.Function) && 6256 Candidate.Function->getNumParams() <= ArgSize && 6257 // Having zero args is annoying, normally we don't surface a function 6258 // with 2 params, if you already have 2 params, because you are 6259 // inserting the 3rd now. But with zero, it helps the user to figure 6260 // out there are no overloads that take any arguments. Hence we are 6261 // keeping the overload. 6262 ArgSize > 0) 6263 continue; 6264 } 6265 if (Candidate.Viable) 6266 Results.push_back(ResultCandidate(Candidate.Function)); 6267 } 6268 } 6269 6270 /// Get the type of the Nth parameter from a given set of overload 6271 /// candidates. 6272 static QualType getParamType(Sema &SemaRef, 6273 ArrayRef<ResultCandidate> Candidates, unsigned N) { 6274 6275 // Given the overloads 'Candidates' for a function call matching all arguments 6276 // up to N, return the type of the Nth parameter if it is the same for all 6277 // overload candidates. 6278 QualType ParamType; 6279 for (auto &Candidate : Candidates) { 6280 QualType CandidateParamType = Candidate.getParamType(N); 6281 if (CandidateParamType.isNull()) 6282 continue; 6283 if (ParamType.isNull()) { 6284 ParamType = CandidateParamType; 6285 continue; 6286 } 6287 if (!SemaRef.Context.hasSameUnqualifiedType( 6288 ParamType.getNonReferenceType(), 6289 CandidateParamType.getNonReferenceType())) 6290 // Two conflicting types, give up. 6291 return QualType(); 6292 } 6293 6294 return ParamType; 6295 } 6296 6297 static QualType 6298 ProduceSignatureHelp(Sema &SemaRef, MutableArrayRef<ResultCandidate> Candidates, 6299 unsigned CurrentArg, SourceLocation OpenParLoc, 6300 bool Braced) { 6301 if (Candidates.empty()) 6302 return QualType(); 6303 if (SemaRef.getPreprocessor().isCodeCompletionReached()) 6304 SemaRef.CodeCompletion().CodeCompleter->ProcessOverloadCandidates( 6305 SemaRef, CurrentArg, Candidates.data(), Candidates.size(), OpenParLoc, 6306 Braced); 6307 return getParamType(SemaRef, Candidates, CurrentArg); 6308 } 6309 6310 // Given a callee expression `Fn`, if the call is through a function pointer, 6311 // try to find the declaration of the corresponding function pointer type, 6312 // so that we can recover argument names from it. 6313 static FunctionProtoTypeLoc GetPrototypeLoc(Expr *Fn) { 6314 TypeLoc Target; 6315 6316 if (const auto *T = Fn->getType().getTypePtr()->getAs<TypedefType>()) { 6317 Target = T->getDecl()->getTypeSourceInfo()->getTypeLoc(); 6318 6319 } else if (const auto *DR = dyn_cast<DeclRefExpr>(Fn)) { 6320 const auto *D = DR->getDecl(); 6321 if (const auto *const VD = dyn_cast<VarDecl>(D)) { 6322 Target = VD->getTypeSourceInfo()->getTypeLoc(); 6323 } 6324 } else if (const auto *ME = dyn_cast<MemberExpr>(Fn)) { 6325 const auto *MD = ME->getMemberDecl(); 6326 if (const auto *FD = dyn_cast<FieldDecl>(MD)) { 6327 Target = FD->getTypeSourceInfo()->getTypeLoc(); 6328 } 6329 } 6330 6331 if (!Target) 6332 return {}; 6333 6334 // Unwrap types that may be wrapping the function type 6335 while (true) { 6336 if (auto P = Target.getAs<PointerTypeLoc>()) { 6337 Target = P.getPointeeLoc(); 6338 continue; 6339 } 6340 if (auto A = Target.getAs<AttributedTypeLoc>()) { 6341 Target = A.getModifiedLoc(); 6342 continue; 6343 } 6344 if (auto P = Target.getAs<ParenTypeLoc>()) { 6345 Target = P.getInnerLoc(); 6346 continue; 6347 } 6348 break; 6349 } 6350 6351 if (auto F = Target.getAs<FunctionProtoTypeLoc>()) { 6352 return F; 6353 } 6354 6355 return {}; 6356 } 6357 6358 QualType 6359 SemaCodeCompletion::ProduceCallSignatureHelp(Expr *Fn, ArrayRef<Expr *> Args, 6360 SourceLocation OpenParLoc) { 6361 Fn = unwrapParenList(Fn); 6362 if (!CodeCompleter || !Fn) 6363 return QualType(); 6364 6365 // FIXME: Provide support for variadic template functions. 6366 // Ignore type-dependent call expressions entirely. 6367 if (Fn->isTypeDependent() || anyNullArguments(Args)) 6368 return QualType(); 6369 // In presence of dependent args we surface all possible signatures using the 6370 // non-dependent args in the prefix. Afterwards we do a post filtering to make 6371 // sure provided candidates satisfy parameter count restrictions. 6372 auto ArgsWithoutDependentTypes = 6373 Args.take_while([](Expr *Arg) { return !Arg->isTypeDependent(); }); 6374 6375 SmallVector<ResultCandidate, 8> Results; 6376 6377 Expr *NakedFn = Fn->IgnoreParenCasts(); 6378 // Build an overload candidate set based on the functions we find. 6379 SourceLocation Loc = Fn->getExprLoc(); 6380 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); 6381 6382 if (auto ULE = dyn_cast<UnresolvedLookupExpr>(NakedFn)) { 6383 SemaRef.AddOverloadedCallCandidates(ULE, ArgsWithoutDependentTypes, 6384 CandidateSet, 6385 /*PartialOverloading=*/true); 6386 } else if (auto UME = dyn_cast<UnresolvedMemberExpr>(NakedFn)) { 6387 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 6388 if (UME->hasExplicitTemplateArgs()) { 6389 UME->copyTemplateArgumentsInto(TemplateArgsBuffer); 6390 TemplateArgs = &TemplateArgsBuffer; 6391 } 6392 6393 // Add the base as first argument (use a nullptr if the base is implicit). 6394 SmallVector<Expr *, 12> ArgExprs( 6395 1, UME->isImplicitAccess() ? nullptr : UME->getBase()); 6396 ArgExprs.append(ArgsWithoutDependentTypes.begin(), 6397 ArgsWithoutDependentTypes.end()); 6398 UnresolvedSet<8> Decls; 6399 Decls.append(UME->decls_begin(), UME->decls_end()); 6400 const bool FirstArgumentIsBase = !UME->isImplicitAccess() && UME->getBase(); 6401 SemaRef.AddFunctionCandidates(Decls, ArgExprs, CandidateSet, TemplateArgs, 6402 /*SuppressUserConversions=*/false, 6403 /*PartialOverloading=*/true, 6404 FirstArgumentIsBase); 6405 } else { 6406 FunctionDecl *FD = nullptr; 6407 if (auto *MCE = dyn_cast<MemberExpr>(NakedFn)) 6408 FD = dyn_cast<FunctionDecl>(MCE->getMemberDecl()); 6409 else if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) 6410 FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 6411 if (FD) { // We check whether it's a resolved function declaration. 6412 if (!getLangOpts().CPlusPlus || 6413 !FD->getType()->getAs<FunctionProtoType>()) 6414 Results.push_back(ResultCandidate(FD)); 6415 else 6416 SemaRef.AddOverloadCandidate(FD, 6417 DeclAccessPair::make(FD, FD->getAccess()), 6418 ArgsWithoutDependentTypes, CandidateSet, 6419 /*SuppressUserConversions=*/false, 6420 /*PartialOverloading=*/true); 6421 6422 } else if (auto DC = NakedFn->getType()->getAsCXXRecordDecl()) { 6423 // If expression's type is CXXRecordDecl, it may overload the function 6424 // call operator, so we check if it does and add them as candidates. 6425 // A complete type is needed to lookup for member function call operators. 6426 if (SemaRef.isCompleteType(Loc, NakedFn->getType())) { 6427 DeclarationName OpName = 6428 getASTContext().DeclarationNames.getCXXOperatorName(OO_Call); 6429 LookupResult R(SemaRef, OpName, Loc, Sema::LookupOrdinaryName); 6430 SemaRef.LookupQualifiedName(R, DC); 6431 R.suppressDiagnostics(); 6432 SmallVector<Expr *, 12> ArgExprs(1, NakedFn); 6433 ArgExprs.append(ArgsWithoutDependentTypes.begin(), 6434 ArgsWithoutDependentTypes.end()); 6435 SemaRef.AddFunctionCandidates(R.asUnresolvedSet(), ArgExprs, 6436 CandidateSet, 6437 /*ExplicitArgs=*/nullptr, 6438 /*SuppressUserConversions=*/false, 6439 /*PartialOverloading=*/true); 6440 } 6441 } else { 6442 // Lastly we check whether expression's type is function pointer or 6443 // function. 6444 6445 FunctionProtoTypeLoc P = GetPrototypeLoc(NakedFn); 6446 QualType T = NakedFn->getType(); 6447 if (!T->getPointeeType().isNull()) 6448 T = T->getPointeeType(); 6449 6450 if (auto FP = T->getAs<FunctionProtoType>()) { 6451 if (!SemaRef.TooManyArguments(FP->getNumParams(), 6452 ArgsWithoutDependentTypes.size(), 6453 /*PartialOverloading=*/true) || 6454 FP->isVariadic()) { 6455 if (P) { 6456 Results.push_back(ResultCandidate(P)); 6457 } else { 6458 Results.push_back(ResultCandidate(FP)); 6459 } 6460 } 6461 } else if (auto FT = T->getAs<FunctionType>()) 6462 // No prototype and declaration, it may be a K & R style function. 6463 Results.push_back(ResultCandidate(FT)); 6464 } 6465 } 6466 mergeCandidatesWithResults(SemaRef, Results, CandidateSet, Loc, Args.size()); 6467 QualType ParamType = ProduceSignatureHelp(SemaRef, Results, Args.size(), 6468 OpenParLoc, /*Braced=*/false); 6469 return !CandidateSet.empty() ? ParamType : QualType(); 6470 } 6471 6472 // Determine which param to continue aggregate initialization from after 6473 // a designated initializer. 6474 // 6475 // Given struct S { int a,b,c,d,e; }: 6476 // after `S{.b=1,` we want to suggest c to continue 6477 // after `S{.b=1, 2,` we continue with d (this is legal C and ext in C++) 6478 // after `S{.b=1, .a=2,` we continue with b (this is legal C and ext in C++) 6479 // 6480 // Possible outcomes: 6481 // - we saw a designator for a field, and continue from the returned index. 6482 // Only aggregate initialization is allowed. 6483 // - we saw a designator, but it was complex or we couldn't find the field. 6484 // Only aggregate initialization is possible, but we can't assist with it. 6485 // Returns an out-of-range index. 6486 // - we saw no designators, just positional arguments. 6487 // Returns std::nullopt. 6488 static std::optional<unsigned> 6489 getNextAggregateIndexAfterDesignatedInit(const ResultCandidate &Aggregate, 6490 ArrayRef<Expr *> Args) { 6491 static constexpr unsigned Invalid = std::numeric_limits<unsigned>::max(); 6492 assert(Aggregate.getKind() == ResultCandidate::CK_Aggregate); 6493 6494 // Look for designated initializers. 6495 // They're in their syntactic form, not yet resolved to fields. 6496 const IdentifierInfo *DesignatedFieldName = nullptr; 6497 unsigned ArgsAfterDesignator = 0; 6498 for (const Expr *Arg : Args) { 6499 if (const auto *DIE = dyn_cast<DesignatedInitExpr>(Arg)) { 6500 if (DIE->size() == 1 && DIE->getDesignator(0)->isFieldDesignator()) { 6501 DesignatedFieldName = DIE->getDesignator(0)->getFieldName(); 6502 ArgsAfterDesignator = 0; 6503 } else { 6504 return Invalid; // Complicated designator. 6505 } 6506 } else if (isa<DesignatedInitUpdateExpr>(Arg)) { 6507 return Invalid; // Unsupported. 6508 } else { 6509 ++ArgsAfterDesignator; 6510 } 6511 } 6512 if (!DesignatedFieldName) 6513 return std::nullopt; 6514 6515 // Find the index within the class's fields. 6516 // (Probing getParamDecl() directly would be quadratic in number of fields). 6517 unsigned DesignatedIndex = 0; 6518 const FieldDecl *DesignatedField = nullptr; 6519 for (const auto *Field : Aggregate.getAggregate()->fields()) { 6520 if (Field->getIdentifier() == DesignatedFieldName) { 6521 DesignatedField = Field; 6522 break; 6523 } 6524 ++DesignatedIndex; 6525 } 6526 if (!DesignatedField) 6527 return Invalid; // Designator referred to a missing field, give up. 6528 6529 // Find the index within the aggregate (which may have leading bases). 6530 unsigned AggregateSize = Aggregate.getNumParams(); 6531 while (DesignatedIndex < AggregateSize && 6532 Aggregate.getParamDecl(DesignatedIndex) != DesignatedField) 6533 ++DesignatedIndex; 6534 6535 // Continue from the index after the last named field. 6536 return DesignatedIndex + ArgsAfterDesignator + 1; 6537 } 6538 6539 QualType SemaCodeCompletion::ProduceConstructorSignatureHelp( 6540 QualType Type, SourceLocation Loc, ArrayRef<Expr *> Args, 6541 SourceLocation OpenParLoc, bool Braced) { 6542 if (!CodeCompleter) 6543 return QualType(); 6544 SmallVector<ResultCandidate, 8> Results; 6545 6546 // A complete type is needed to lookup for constructors. 6547 RecordDecl *RD = 6548 SemaRef.isCompleteType(Loc, Type) ? Type->getAsRecordDecl() : nullptr; 6549 if (!RD) 6550 return Type; 6551 CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD); 6552 6553 // Consider aggregate initialization. 6554 // We don't check that types so far are correct. 6555 // We also don't handle C99/C++17 brace-elision, we assume init-list elements 6556 // are 1:1 with fields. 6557 // FIXME: it would be nice to support "unwrapping" aggregates that contain 6558 // a single subaggregate, like std::array<T, N> -> T __elements[N]. 6559 if (Braced && !RD->isUnion() && 6560 (!getLangOpts().CPlusPlus || (CRD && CRD->isAggregate()))) { 6561 ResultCandidate AggregateSig(RD); 6562 unsigned AggregateSize = AggregateSig.getNumParams(); 6563 6564 if (auto NextIndex = 6565 getNextAggregateIndexAfterDesignatedInit(AggregateSig, Args)) { 6566 // A designator was used, only aggregate init is possible. 6567 if (*NextIndex >= AggregateSize) 6568 return Type; 6569 Results.push_back(AggregateSig); 6570 return ProduceSignatureHelp(SemaRef, Results, *NextIndex, OpenParLoc, 6571 Braced); 6572 } 6573 6574 // Describe aggregate initialization, but also constructors below. 6575 if (Args.size() < AggregateSize) 6576 Results.push_back(AggregateSig); 6577 } 6578 6579 // FIXME: Provide support for member initializers. 6580 // FIXME: Provide support for variadic template constructors. 6581 6582 if (CRD) { 6583 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); 6584 for (NamedDecl *C : SemaRef.LookupConstructors(CRD)) { 6585 if (auto *FD = dyn_cast<FunctionDecl>(C)) { 6586 // FIXME: we can't yet provide correct signature help for initializer 6587 // list constructors, so skip them entirely. 6588 if (Braced && getLangOpts().CPlusPlus && 6589 SemaRef.isInitListConstructor(FD)) 6590 continue; 6591 SemaRef.AddOverloadCandidate( 6592 FD, DeclAccessPair::make(FD, C->getAccess()), Args, CandidateSet, 6593 /*SuppressUserConversions=*/false, 6594 /*PartialOverloading=*/true, 6595 /*AllowExplicit*/ true); 6596 } else if (auto *FTD = dyn_cast<FunctionTemplateDecl>(C)) { 6597 if (Braced && getLangOpts().CPlusPlus && 6598 SemaRef.isInitListConstructor(FTD->getTemplatedDecl())) 6599 continue; 6600 6601 SemaRef.AddTemplateOverloadCandidate( 6602 FTD, DeclAccessPair::make(FTD, C->getAccess()), 6603 /*ExplicitTemplateArgs=*/nullptr, Args, CandidateSet, 6604 /*SuppressUserConversions=*/false, 6605 /*PartialOverloading=*/true); 6606 } 6607 } 6608 mergeCandidatesWithResults(SemaRef, Results, CandidateSet, Loc, 6609 Args.size()); 6610 } 6611 6612 return ProduceSignatureHelp(SemaRef, Results, Args.size(), OpenParLoc, 6613 Braced); 6614 } 6615 6616 QualType SemaCodeCompletion::ProduceCtorInitMemberSignatureHelp( 6617 Decl *ConstructorDecl, CXXScopeSpec SS, ParsedType TemplateTypeTy, 6618 ArrayRef<Expr *> ArgExprs, IdentifierInfo *II, SourceLocation OpenParLoc, 6619 bool Braced) { 6620 if (!CodeCompleter) 6621 return QualType(); 6622 6623 CXXConstructorDecl *Constructor = 6624 dyn_cast<CXXConstructorDecl>(ConstructorDecl); 6625 if (!Constructor) 6626 return QualType(); 6627 // FIXME: Add support for Base class constructors as well. 6628 if (ValueDecl *MemberDecl = SemaRef.tryLookupCtorInitMemberDecl( 6629 Constructor->getParent(), SS, TemplateTypeTy, II)) 6630 return ProduceConstructorSignatureHelp(MemberDecl->getType(), 6631 MemberDecl->getLocation(), ArgExprs, 6632 OpenParLoc, Braced); 6633 return QualType(); 6634 } 6635 6636 static bool argMatchesTemplateParams(const ParsedTemplateArgument &Arg, 6637 unsigned Index, 6638 const TemplateParameterList &Params) { 6639 const NamedDecl *Param; 6640 if (Index < Params.size()) 6641 Param = Params.getParam(Index); 6642 else if (Params.hasParameterPack()) 6643 Param = Params.asArray().back(); 6644 else 6645 return false; // too many args 6646 6647 switch (Arg.getKind()) { 6648 case ParsedTemplateArgument::Type: 6649 return llvm::isa<TemplateTypeParmDecl>(Param); // constraints not checked 6650 case ParsedTemplateArgument::NonType: 6651 return llvm::isa<NonTypeTemplateParmDecl>(Param); // type not checked 6652 case ParsedTemplateArgument::Template: 6653 return llvm::isa<TemplateTemplateParmDecl>(Param); // signature not checked 6654 } 6655 llvm_unreachable("Unhandled switch case"); 6656 } 6657 6658 QualType SemaCodeCompletion::ProduceTemplateArgumentSignatureHelp( 6659 TemplateTy ParsedTemplate, ArrayRef<ParsedTemplateArgument> Args, 6660 SourceLocation LAngleLoc) { 6661 if (!CodeCompleter || !ParsedTemplate) 6662 return QualType(); 6663 6664 SmallVector<ResultCandidate, 8> Results; 6665 auto Consider = [&](const TemplateDecl *TD) { 6666 // Only add if the existing args are compatible with the template. 6667 bool Matches = true; 6668 for (unsigned I = 0; I < Args.size(); ++I) { 6669 if (!argMatchesTemplateParams(Args[I], I, *TD->getTemplateParameters())) { 6670 Matches = false; 6671 break; 6672 } 6673 } 6674 if (Matches) 6675 Results.emplace_back(TD); 6676 }; 6677 6678 TemplateName Template = ParsedTemplate.get(); 6679 if (const auto *TD = Template.getAsTemplateDecl()) { 6680 Consider(TD); 6681 } else if (const auto *OTS = Template.getAsOverloadedTemplate()) { 6682 for (const NamedDecl *ND : *OTS) 6683 if (const auto *TD = llvm::dyn_cast<TemplateDecl>(ND)) 6684 Consider(TD); 6685 } 6686 return ProduceSignatureHelp(SemaRef, Results, Args.size(), LAngleLoc, 6687 /*Braced=*/false); 6688 } 6689 6690 static QualType getDesignatedType(QualType BaseType, const Designation &Desig) { 6691 for (unsigned I = 0; I < Desig.getNumDesignators(); ++I) { 6692 if (BaseType.isNull()) 6693 break; 6694 QualType NextType; 6695 const auto &D = Desig.getDesignator(I); 6696 if (D.isArrayDesignator() || D.isArrayRangeDesignator()) { 6697 if (BaseType->isArrayType()) 6698 NextType = BaseType->getAsArrayTypeUnsafe()->getElementType(); 6699 } else { 6700 assert(D.isFieldDesignator()); 6701 auto *RD = getAsRecordDecl(BaseType); 6702 if (RD && RD->isCompleteDefinition()) { 6703 for (const auto *Member : RD->lookup(D.getFieldDecl())) 6704 if (const FieldDecl *FD = llvm::dyn_cast<FieldDecl>(Member)) { 6705 NextType = FD->getType(); 6706 break; 6707 } 6708 } 6709 } 6710 BaseType = NextType; 6711 } 6712 return BaseType; 6713 } 6714 6715 void SemaCodeCompletion::CodeCompleteDesignator( 6716 QualType BaseType, llvm::ArrayRef<Expr *> InitExprs, const Designation &D) { 6717 BaseType = getDesignatedType(BaseType, D); 6718 if (BaseType.isNull()) 6719 return; 6720 const auto *RD = getAsRecordDecl(BaseType); 6721 if (!RD || RD->fields().empty()) 6722 return; 6723 6724 CodeCompletionContext CCC(CodeCompletionContext::CCC_DotMemberAccess, 6725 BaseType); 6726 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(), 6727 CodeCompleter->getCodeCompletionTUInfo(), CCC); 6728 6729 Results.EnterNewScope(); 6730 for (const Decl *D : RD->decls()) { 6731 const FieldDecl *FD; 6732 if (auto *IFD = dyn_cast<IndirectFieldDecl>(D)) 6733 FD = IFD->getAnonField(); 6734 else if (auto *DFD = dyn_cast<FieldDecl>(D)) 6735 FD = DFD; 6736 else 6737 continue; 6738 6739 // FIXME: Make use of previous designators to mark any fields before those 6740 // inaccessible, and also compute the next initializer priority. 6741 ResultBuilder::Result Result(FD, Results.getBasePriority(FD)); 6742 Results.AddResult(Result, SemaRef.CurContext, /*Hiding=*/nullptr); 6743 } 6744 Results.ExitScope(); 6745 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 6746 Results.getCompletionContext(), Results.data(), 6747 Results.size()); 6748 } 6749 6750 void SemaCodeCompletion::CodeCompleteInitializer(Scope *S, Decl *D) { 6751 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D); 6752 if (!VD) { 6753 CodeCompleteOrdinaryName(S, PCC_Expression); 6754 return; 6755 } 6756 6757 CodeCompleteExpressionData Data; 6758 Data.PreferredType = VD->getType(); 6759 // Ignore VD to avoid completing the variable itself, e.g. in 'int foo = ^'. 6760 Data.IgnoreDecls.push_back(VD); 6761 6762 CodeCompleteExpression(S, Data); 6763 } 6764 6765 void SemaCodeCompletion::CodeCompleteAfterIf(Scope *S, bool IsBracedThen) { 6766 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(), 6767 CodeCompleter->getCodeCompletionTUInfo(), 6768 mapCodeCompletionContext(SemaRef, PCC_Statement)); 6769 Results.setFilter(&ResultBuilder::IsOrdinaryName); 6770 Results.EnterNewScope(); 6771 6772 CodeCompletionDeclConsumer Consumer(Results, SemaRef.CurContext); 6773 SemaRef.LookupVisibleDecls(S, Sema::LookupOrdinaryName, Consumer, 6774 CodeCompleter->includeGlobals(), 6775 CodeCompleter->loadExternal()); 6776 6777 AddOrdinaryNameResults(PCC_Statement, S, SemaRef, Results); 6778 6779 // "else" block 6780 CodeCompletionBuilder Builder(Results.getAllocator(), 6781 Results.getCodeCompletionTUInfo()); 6782 6783 auto AddElseBodyPattern = [&] { 6784 if (IsBracedThen) { 6785 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 6786 Builder.AddChunk(CodeCompletionString::CK_LeftBrace); 6787 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); 6788 Builder.AddPlaceholderChunk("statements"); 6789 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); 6790 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 6791 } else { 6792 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); 6793 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 6794 Builder.AddPlaceholderChunk("statement"); 6795 Builder.AddChunk(CodeCompletionString::CK_SemiColon); 6796 } 6797 }; 6798 Builder.AddTypedTextChunk("else"); 6799 if (Results.includeCodePatterns()) 6800 AddElseBodyPattern(); 6801 Results.AddResult(Builder.TakeString()); 6802 6803 // "else if" block 6804 Builder.AddTypedTextChunk("else if"); 6805 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 6806 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 6807 if (getLangOpts().CPlusPlus) 6808 Builder.AddPlaceholderChunk("condition"); 6809 else 6810 Builder.AddPlaceholderChunk("expression"); 6811 Builder.AddChunk(CodeCompletionString::CK_RightParen); 6812 if (Results.includeCodePatterns()) { 6813 AddElseBodyPattern(); 6814 } 6815 Results.AddResult(Builder.TakeString()); 6816 6817 Results.ExitScope(); 6818 6819 if (S->getFnParent()) 6820 AddPrettyFunctionResults(getLangOpts(), Results); 6821 6822 if (CodeCompleter->includeMacros()) 6823 AddMacroResults(SemaRef.PP, Results, CodeCompleter->loadExternal(), false); 6824 6825 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 6826 Results.getCompletionContext(), Results.data(), 6827 Results.size()); 6828 } 6829 6830 void SemaCodeCompletion::CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS, 6831 bool EnteringContext, 6832 bool IsUsingDeclaration, 6833 QualType BaseType, 6834 QualType PreferredType) { 6835 if (SS.isEmpty() || !CodeCompleter) 6836 return; 6837 6838 CodeCompletionContext CC(CodeCompletionContext::CCC_Symbol, PreferredType); 6839 CC.setIsUsingDeclaration(IsUsingDeclaration); 6840 CC.setCXXScopeSpecifier(SS); 6841 6842 // We want to keep the scope specifier even if it's invalid (e.g. the scope 6843 // "a::b::" is not corresponding to any context/namespace in the AST), since 6844 // it can be useful for global code completion which have information about 6845 // contexts/symbols that are not in the AST. 6846 if (SS.isInvalid()) { 6847 // As SS is invalid, we try to collect accessible contexts from the current 6848 // scope with a dummy lookup so that the completion consumer can try to 6849 // guess what the specified scope is. 6850 ResultBuilder DummyResults(SemaRef, CodeCompleter->getAllocator(), 6851 CodeCompleter->getCodeCompletionTUInfo(), CC); 6852 if (!PreferredType.isNull()) 6853 DummyResults.setPreferredType(PreferredType); 6854 if (S->getEntity()) { 6855 CodeCompletionDeclConsumer Consumer(DummyResults, S->getEntity(), 6856 BaseType); 6857 SemaRef.LookupVisibleDecls(S, Sema::LookupOrdinaryName, Consumer, 6858 /*IncludeGlobalScope=*/false, 6859 /*LoadExternal=*/false); 6860 } 6861 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 6862 DummyResults.getCompletionContext(), nullptr, 0); 6863 return; 6864 } 6865 // Always pretend to enter a context to ensure that a dependent type 6866 // resolves to a dependent record. 6867 DeclContext *Ctx = SemaRef.computeDeclContext(SS, /*EnteringContext=*/true); 6868 6869 // Try to instantiate any non-dependent declaration contexts before 6870 // we look in them. Bail out if we fail. 6871 NestedNameSpecifier *NNS = SS.getScopeRep(); 6872 if (NNS != nullptr && SS.isValid() && !NNS->isDependent()) { 6873 if (Ctx == nullptr || SemaRef.RequireCompleteDeclContext(SS, Ctx)) 6874 return; 6875 } 6876 6877 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(), 6878 CodeCompleter->getCodeCompletionTUInfo(), CC); 6879 if (!PreferredType.isNull()) 6880 Results.setPreferredType(PreferredType); 6881 Results.EnterNewScope(); 6882 6883 // The "template" keyword can follow "::" in the grammar, but only 6884 // put it into the grammar if the nested-name-specifier is dependent. 6885 // FIXME: results is always empty, this appears to be dead. 6886 if (!Results.empty() && NNS && NNS->isDependent()) 6887 Results.AddResult("template"); 6888 6889 // If the scope is a concept-constrained type parameter, infer nested 6890 // members based on the constraints. 6891 if (NNS) { 6892 if (const auto *TTPT = 6893 dyn_cast_or_null<TemplateTypeParmType>(NNS->getAsType())) { 6894 for (const auto &R : ConceptInfo(*TTPT, S).members()) { 6895 if (R.Operator != ConceptInfo::Member::Colons) 6896 continue; 6897 Results.AddResult(CodeCompletionResult( 6898 R.render(SemaRef, CodeCompleter->getAllocator(), 6899 CodeCompleter->getCodeCompletionTUInfo()))); 6900 } 6901 } 6902 } 6903 6904 // Add calls to overridden virtual functions, if there are any. 6905 // 6906 // FIXME: This isn't wonderful, because we don't know whether we're actually 6907 // in a context that permits expressions. This is a general issue with 6908 // qualified-id completions. 6909 if (Ctx && !EnteringContext) 6910 MaybeAddOverrideCalls(SemaRef, Ctx, Results); 6911 Results.ExitScope(); 6912 6913 if (Ctx && 6914 (CodeCompleter->includeNamespaceLevelDecls() || !Ctx->isFileContext())) { 6915 CodeCompletionDeclConsumer Consumer(Results, Ctx, BaseType); 6916 SemaRef.LookupVisibleDecls(Ctx, Sema::LookupOrdinaryName, Consumer, 6917 /*IncludeGlobalScope=*/true, 6918 /*IncludeDependentBases=*/true, 6919 CodeCompleter->loadExternal()); 6920 } 6921 6922 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 6923 Results.getCompletionContext(), Results.data(), 6924 Results.size()); 6925 } 6926 6927 void SemaCodeCompletion::CodeCompleteUsing(Scope *S) { 6928 if (!CodeCompleter) 6929 return; 6930 6931 // This can be both a using alias or using declaration, in the former we 6932 // expect a new name and a symbol in the latter case. 6933 CodeCompletionContext Context(CodeCompletionContext::CCC_SymbolOrNewName); 6934 Context.setIsUsingDeclaration(true); 6935 6936 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(), 6937 CodeCompleter->getCodeCompletionTUInfo(), Context, 6938 &ResultBuilder::IsNestedNameSpecifier); 6939 Results.EnterNewScope(); 6940 6941 // If we aren't in class scope, we could see the "namespace" keyword. 6942 if (!S->isClassScope()) 6943 Results.AddResult(CodeCompletionResult("namespace")); 6944 6945 // After "using", we can see anything that would start a 6946 // nested-name-specifier. 6947 CodeCompletionDeclConsumer Consumer(Results, SemaRef.CurContext); 6948 SemaRef.LookupVisibleDecls(S, Sema::LookupOrdinaryName, Consumer, 6949 CodeCompleter->includeGlobals(), 6950 CodeCompleter->loadExternal()); 6951 Results.ExitScope(); 6952 6953 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 6954 Results.getCompletionContext(), Results.data(), 6955 Results.size()); 6956 } 6957 6958 void SemaCodeCompletion::CodeCompleteUsingDirective(Scope *S) { 6959 if (!CodeCompleter) 6960 return; 6961 6962 // After "using namespace", we expect to see a namespace name or namespace 6963 // alias. 6964 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(), 6965 CodeCompleter->getCodeCompletionTUInfo(), 6966 CodeCompletionContext::CCC_Namespace, 6967 &ResultBuilder::IsNamespaceOrAlias); 6968 Results.EnterNewScope(); 6969 CodeCompletionDeclConsumer Consumer(Results, SemaRef.CurContext); 6970 SemaRef.LookupVisibleDecls(S, Sema::LookupOrdinaryName, Consumer, 6971 CodeCompleter->includeGlobals(), 6972 CodeCompleter->loadExternal()); 6973 Results.ExitScope(); 6974 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 6975 Results.getCompletionContext(), Results.data(), 6976 Results.size()); 6977 } 6978 6979 void SemaCodeCompletion::CodeCompleteNamespaceDecl(Scope *S) { 6980 if (!CodeCompleter) 6981 return; 6982 6983 DeclContext *Ctx = S->getEntity(); 6984 if (!S->getParent()) 6985 Ctx = getASTContext().getTranslationUnitDecl(); 6986 6987 bool SuppressedGlobalResults = 6988 Ctx && !CodeCompleter->includeGlobals() && isa<TranslationUnitDecl>(Ctx); 6989 6990 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(), 6991 CodeCompleter->getCodeCompletionTUInfo(), 6992 SuppressedGlobalResults 6993 ? CodeCompletionContext::CCC_Namespace 6994 : CodeCompletionContext::CCC_Other, 6995 &ResultBuilder::IsNamespace); 6996 6997 if (Ctx && Ctx->isFileContext() && !SuppressedGlobalResults) { 6998 // We only want to see those namespaces that have already been defined 6999 // within this scope, because its likely that the user is creating an 7000 // extended namespace declaration. Keep track of the most recent 7001 // definition of each namespace. 7002 std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest; 7003 for (DeclContext::specific_decl_iterator<NamespaceDecl> 7004 NS(Ctx->decls_begin()), 7005 NSEnd(Ctx->decls_end()); 7006 NS != NSEnd; ++NS) 7007 OrigToLatest[NS->getFirstDecl()] = *NS; 7008 7009 // Add the most recent definition (or extended definition) of each 7010 // namespace to the list of results. 7011 Results.EnterNewScope(); 7012 for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator 7013 NS = OrigToLatest.begin(), 7014 NSEnd = OrigToLatest.end(); 7015 NS != NSEnd; ++NS) 7016 Results.AddResult( 7017 CodeCompletionResult(NS->second, Results.getBasePriority(NS->second), 7018 nullptr), 7019 SemaRef.CurContext, nullptr, false); 7020 Results.ExitScope(); 7021 } 7022 7023 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 7024 Results.getCompletionContext(), Results.data(), 7025 Results.size()); 7026 } 7027 7028 void SemaCodeCompletion::CodeCompleteNamespaceAliasDecl(Scope *S) { 7029 if (!CodeCompleter) 7030 return; 7031 7032 // After "namespace", we expect to see a namespace or alias. 7033 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(), 7034 CodeCompleter->getCodeCompletionTUInfo(), 7035 CodeCompletionContext::CCC_Namespace, 7036 &ResultBuilder::IsNamespaceOrAlias); 7037 CodeCompletionDeclConsumer Consumer(Results, SemaRef.CurContext); 7038 SemaRef.LookupVisibleDecls(S, Sema::LookupOrdinaryName, Consumer, 7039 CodeCompleter->includeGlobals(), 7040 CodeCompleter->loadExternal()); 7041 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 7042 Results.getCompletionContext(), Results.data(), 7043 Results.size()); 7044 } 7045 7046 void SemaCodeCompletion::CodeCompleteOperatorName(Scope *S) { 7047 if (!CodeCompleter) 7048 return; 7049 7050 typedef CodeCompletionResult Result; 7051 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(), 7052 CodeCompleter->getCodeCompletionTUInfo(), 7053 CodeCompletionContext::CCC_Type, 7054 &ResultBuilder::IsType); 7055 Results.EnterNewScope(); 7056 7057 // Add the names of overloadable operators. Note that OO_Conditional is not 7058 // actually overloadable. 7059 #define OVERLOADED_OPERATOR(Name, Spelling, Token, Unary, Binary, MemberOnly) \ 7060 if (OO_##Name != OO_Conditional) \ 7061 Results.AddResult(Result(Spelling)); 7062 #include "clang/Basic/OperatorKinds.def" 7063 7064 // Add any type names visible from the current scope 7065 Results.allowNestedNameSpecifiers(); 7066 CodeCompletionDeclConsumer Consumer(Results, SemaRef.CurContext); 7067 SemaRef.LookupVisibleDecls(S, Sema::LookupOrdinaryName, Consumer, 7068 CodeCompleter->includeGlobals(), 7069 CodeCompleter->loadExternal()); 7070 7071 // Add any type specifiers 7072 AddTypeSpecifierResults(getLangOpts(), Results); 7073 Results.ExitScope(); 7074 7075 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 7076 Results.getCompletionContext(), Results.data(), 7077 Results.size()); 7078 } 7079 7080 void SemaCodeCompletion::CodeCompleteConstructorInitializer( 7081 Decl *ConstructorD, ArrayRef<CXXCtorInitializer *> Initializers) { 7082 if (!ConstructorD) 7083 return; 7084 7085 SemaRef.AdjustDeclIfTemplate(ConstructorD); 7086 7087 auto *Constructor = dyn_cast<CXXConstructorDecl>(ConstructorD); 7088 if (!Constructor) 7089 return; 7090 7091 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(), 7092 CodeCompleter->getCodeCompletionTUInfo(), 7093 CodeCompletionContext::CCC_Symbol); 7094 Results.EnterNewScope(); 7095 7096 // Fill in any already-initialized fields or base classes. 7097 llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields; 7098 llvm::SmallPtrSet<CanQualType, 4> InitializedBases; 7099 for (unsigned I = 0, E = Initializers.size(); I != E; ++I) { 7100 if (Initializers[I]->isBaseInitializer()) 7101 InitializedBases.insert(getASTContext().getCanonicalType( 7102 QualType(Initializers[I]->getBaseClass(), 0))); 7103 else 7104 InitializedFields.insert( 7105 cast<FieldDecl>(Initializers[I]->getAnyMember())); 7106 } 7107 7108 // Add completions for base classes. 7109 PrintingPolicy Policy = getCompletionPrintingPolicy(SemaRef); 7110 bool SawLastInitializer = Initializers.empty(); 7111 CXXRecordDecl *ClassDecl = Constructor->getParent(); 7112 7113 auto GenerateCCS = [&](const NamedDecl *ND, const char *Name) { 7114 CodeCompletionBuilder Builder(Results.getAllocator(), 7115 Results.getCodeCompletionTUInfo()); 7116 Builder.AddTypedTextChunk(Name); 7117 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7118 if (const auto *Function = dyn_cast<FunctionDecl>(ND)) 7119 AddFunctionParameterChunks(SemaRef.PP, Policy, Function, Builder); 7120 else if (const auto *FunTemplDecl = dyn_cast<FunctionTemplateDecl>(ND)) 7121 AddFunctionParameterChunks(SemaRef.PP, Policy, 7122 FunTemplDecl->getTemplatedDecl(), Builder); 7123 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7124 return Builder.TakeString(); 7125 }; 7126 auto AddDefaultCtorInit = [&](const char *Name, const char *Type, 7127 const NamedDecl *ND) { 7128 CodeCompletionBuilder Builder(Results.getAllocator(), 7129 Results.getCodeCompletionTUInfo()); 7130 Builder.AddTypedTextChunk(Name); 7131 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7132 Builder.AddPlaceholderChunk(Type); 7133 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7134 if (ND) { 7135 auto CCR = CodeCompletionResult( 7136 Builder.TakeString(), ND, 7137 SawLastInitializer ? CCP_NextInitializer : CCP_MemberDeclaration); 7138 if (isa<FieldDecl>(ND)) 7139 CCR.CursorKind = CXCursor_MemberRef; 7140 return Results.AddResult(CCR); 7141 } 7142 return Results.AddResult(CodeCompletionResult( 7143 Builder.TakeString(), 7144 SawLastInitializer ? CCP_NextInitializer : CCP_MemberDeclaration)); 7145 }; 7146 auto AddCtorsWithName = [&](const CXXRecordDecl *RD, unsigned int Priority, 7147 const char *Name, const FieldDecl *FD) { 7148 if (!RD) 7149 return AddDefaultCtorInit(Name, 7150 FD ? Results.getAllocator().CopyString( 7151 FD->getType().getAsString(Policy)) 7152 : Name, 7153 FD); 7154 auto Ctors = getConstructors(getASTContext(), RD); 7155 if (Ctors.begin() == Ctors.end()) 7156 return AddDefaultCtorInit(Name, Name, RD); 7157 for (const NamedDecl *Ctor : Ctors) { 7158 auto CCR = CodeCompletionResult(GenerateCCS(Ctor, Name), RD, Priority); 7159 CCR.CursorKind = getCursorKindForDecl(Ctor); 7160 Results.AddResult(CCR); 7161 } 7162 }; 7163 auto AddBase = [&](const CXXBaseSpecifier &Base) { 7164 const char *BaseName = 7165 Results.getAllocator().CopyString(Base.getType().getAsString(Policy)); 7166 const auto *RD = Base.getType()->getAsCXXRecordDecl(); 7167 AddCtorsWithName( 7168 RD, SawLastInitializer ? CCP_NextInitializer : CCP_MemberDeclaration, 7169 BaseName, nullptr); 7170 }; 7171 auto AddField = [&](const FieldDecl *FD) { 7172 const char *FieldName = 7173 Results.getAllocator().CopyString(FD->getIdentifier()->getName()); 7174 const CXXRecordDecl *RD = FD->getType()->getAsCXXRecordDecl(); 7175 AddCtorsWithName( 7176 RD, SawLastInitializer ? CCP_NextInitializer : CCP_MemberDeclaration, 7177 FieldName, FD); 7178 }; 7179 7180 for (const auto &Base : ClassDecl->bases()) { 7181 if (!InitializedBases 7182 .insert(getASTContext().getCanonicalType(Base.getType())) 7183 .second) { 7184 SawLastInitializer = 7185 !Initializers.empty() && Initializers.back()->isBaseInitializer() && 7186 getASTContext().hasSameUnqualifiedType( 7187 Base.getType(), QualType(Initializers.back()->getBaseClass(), 0)); 7188 continue; 7189 } 7190 7191 AddBase(Base); 7192 SawLastInitializer = false; 7193 } 7194 7195 // Add completions for virtual base classes. 7196 for (const auto &Base : ClassDecl->vbases()) { 7197 if (!InitializedBases 7198 .insert(getASTContext().getCanonicalType(Base.getType())) 7199 .second) { 7200 SawLastInitializer = 7201 !Initializers.empty() && Initializers.back()->isBaseInitializer() && 7202 getASTContext().hasSameUnqualifiedType( 7203 Base.getType(), QualType(Initializers.back()->getBaseClass(), 0)); 7204 continue; 7205 } 7206 7207 AddBase(Base); 7208 SawLastInitializer = false; 7209 } 7210 7211 // Add completions for members. 7212 for (auto *Field : ClassDecl->fields()) { 7213 if (!InitializedFields.insert(cast<FieldDecl>(Field->getCanonicalDecl())) 7214 .second) { 7215 SawLastInitializer = !Initializers.empty() && 7216 Initializers.back()->isAnyMemberInitializer() && 7217 Initializers.back()->getAnyMember() == Field; 7218 continue; 7219 } 7220 7221 if (!Field->getDeclName()) 7222 continue; 7223 7224 AddField(Field); 7225 SawLastInitializer = false; 7226 } 7227 Results.ExitScope(); 7228 7229 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 7230 Results.getCompletionContext(), Results.data(), 7231 Results.size()); 7232 } 7233 7234 /// Determine whether this scope denotes a namespace. 7235 static bool isNamespaceScope(Scope *S) { 7236 DeclContext *DC = S->getEntity(); 7237 if (!DC) 7238 return false; 7239 7240 return DC->isFileContext(); 7241 } 7242 7243 void SemaCodeCompletion::CodeCompleteLambdaIntroducer(Scope *S, 7244 LambdaIntroducer &Intro, 7245 bool AfterAmpersand) { 7246 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(), 7247 CodeCompleter->getCodeCompletionTUInfo(), 7248 CodeCompletionContext::CCC_Other); 7249 Results.EnterNewScope(); 7250 7251 // Note what has already been captured. 7252 llvm::SmallPtrSet<IdentifierInfo *, 4> Known; 7253 bool IncludedThis = false; 7254 for (const auto &C : Intro.Captures) { 7255 if (C.Kind == LCK_This) { 7256 IncludedThis = true; 7257 continue; 7258 } 7259 7260 Known.insert(C.Id); 7261 } 7262 7263 // Look for other capturable variables. 7264 for (; S && !isNamespaceScope(S); S = S->getParent()) { 7265 for (const auto *D : S->decls()) { 7266 const auto *Var = dyn_cast<VarDecl>(D); 7267 if (!Var || !Var->hasLocalStorage() || Var->hasAttr<BlocksAttr>()) 7268 continue; 7269 7270 if (Known.insert(Var->getIdentifier()).second) 7271 Results.AddResult(CodeCompletionResult(Var, CCP_LocalDeclaration), 7272 SemaRef.CurContext, nullptr, false); 7273 } 7274 } 7275 7276 // Add 'this', if it would be valid. 7277 if (!IncludedThis && !AfterAmpersand && Intro.Default != LCD_ByCopy) 7278 addThisCompletion(SemaRef, Results); 7279 7280 Results.ExitScope(); 7281 7282 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 7283 Results.getCompletionContext(), Results.data(), 7284 Results.size()); 7285 } 7286 7287 void SemaCodeCompletion::CodeCompleteAfterFunctionEquals(Declarator &D) { 7288 if (!getLangOpts().CPlusPlus11) 7289 return; 7290 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(), 7291 CodeCompleter->getCodeCompletionTUInfo(), 7292 CodeCompletionContext::CCC_Other); 7293 auto ShouldAddDefault = [&D, this]() { 7294 if (!D.isFunctionDeclarator()) 7295 return false; 7296 auto &Id = D.getName(); 7297 if (Id.getKind() == UnqualifiedIdKind::IK_DestructorName) 7298 return true; 7299 // FIXME(liuhui): Ideally, we should check the constructor parameter list to 7300 // verify that it is the default, copy or move constructor? 7301 if (Id.getKind() == UnqualifiedIdKind::IK_ConstructorName && 7302 D.getFunctionTypeInfo().NumParams <= 1) 7303 return true; 7304 if (Id.getKind() == UnqualifiedIdKind::IK_OperatorFunctionId) { 7305 auto Op = Id.OperatorFunctionId.Operator; 7306 // FIXME(liuhui): Ideally, we should check the function parameter list to 7307 // verify that it is the copy or move assignment? 7308 if (Op == OverloadedOperatorKind::OO_Equal) 7309 return true; 7310 if (getLangOpts().CPlusPlus20 && 7311 (Op == OverloadedOperatorKind::OO_EqualEqual || 7312 Op == OverloadedOperatorKind::OO_ExclaimEqual || 7313 Op == OverloadedOperatorKind::OO_Less || 7314 Op == OverloadedOperatorKind::OO_LessEqual || 7315 Op == OverloadedOperatorKind::OO_Greater || 7316 Op == OverloadedOperatorKind::OO_GreaterEqual || 7317 Op == OverloadedOperatorKind::OO_Spaceship)) 7318 return true; 7319 } 7320 return false; 7321 }; 7322 7323 Results.EnterNewScope(); 7324 if (ShouldAddDefault()) 7325 Results.AddResult("default"); 7326 // FIXME(liuhui): Ideally, we should only provide `delete` completion for the 7327 // first function declaration. 7328 Results.AddResult("delete"); 7329 Results.ExitScope(); 7330 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 7331 Results.getCompletionContext(), Results.data(), 7332 Results.size()); 7333 } 7334 7335 /// Macro that optionally prepends an "@" to the string literal passed in via 7336 /// Keyword, depending on whether NeedAt is true or false. 7337 #define OBJC_AT_KEYWORD_NAME(NeedAt, Keyword) ((NeedAt) ? "@" Keyword : Keyword) 7338 7339 static void AddObjCImplementationResults(const LangOptions &LangOpts, 7340 ResultBuilder &Results, bool NeedAt) { 7341 typedef CodeCompletionResult Result; 7342 // Since we have an implementation, we can end it. 7343 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "end"))); 7344 7345 CodeCompletionBuilder Builder(Results.getAllocator(), 7346 Results.getCodeCompletionTUInfo()); 7347 if (LangOpts.ObjC) { 7348 // @dynamic 7349 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "dynamic")); 7350 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7351 Builder.AddPlaceholderChunk("property"); 7352 Results.AddResult(Result(Builder.TakeString())); 7353 7354 // @synthesize 7355 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "synthesize")); 7356 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7357 Builder.AddPlaceholderChunk("property"); 7358 Results.AddResult(Result(Builder.TakeString())); 7359 } 7360 } 7361 7362 static void AddObjCInterfaceResults(const LangOptions &LangOpts, 7363 ResultBuilder &Results, bool NeedAt) { 7364 typedef CodeCompletionResult Result; 7365 7366 // Since we have an interface or protocol, we can end it. 7367 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "end"))); 7368 7369 if (LangOpts.ObjC) { 7370 // @property 7371 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "property"))); 7372 7373 // @required 7374 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "required"))); 7375 7376 // @optional 7377 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "optional"))); 7378 } 7379 } 7380 7381 static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt) { 7382 typedef CodeCompletionResult Result; 7383 CodeCompletionBuilder Builder(Results.getAllocator(), 7384 Results.getCodeCompletionTUInfo()); 7385 7386 // @class name ; 7387 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "class")); 7388 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7389 Builder.AddPlaceholderChunk("name"); 7390 Results.AddResult(Result(Builder.TakeString())); 7391 7392 if (Results.includeCodePatterns()) { 7393 // @interface name 7394 // FIXME: Could introduce the whole pattern, including superclasses and 7395 // such. 7396 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "interface")); 7397 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7398 Builder.AddPlaceholderChunk("class"); 7399 Results.AddResult(Result(Builder.TakeString())); 7400 7401 // @protocol name 7402 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "protocol")); 7403 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7404 Builder.AddPlaceholderChunk("protocol"); 7405 Results.AddResult(Result(Builder.TakeString())); 7406 7407 // @implementation name 7408 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "implementation")); 7409 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7410 Builder.AddPlaceholderChunk("class"); 7411 Results.AddResult(Result(Builder.TakeString())); 7412 } 7413 7414 // @compatibility_alias name 7415 Builder.AddTypedTextChunk( 7416 OBJC_AT_KEYWORD_NAME(NeedAt, "compatibility_alias")); 7417 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7418 Builder.AddPlaceholderChunk("alias"); 7419 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7420 Builder.AddPlaceholderChunk("class"); 7421 Results.AddResult(Result(Builder.TakeString())); 7422 7423 if (Results.getSema().getLangOpts().Modules) { 7424 // @import name 7425 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "import")); 7426 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7427 Builder.AddPlaceholderChunk("module"); 7428 Results.AddResult(Result(Builder.TakeString())); 7429 } 7430 } 7431 7432 void SemaCodeCompletion::CodeCompleteObjCAtDirective(Scope *S) { 7433 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(), 7434 CodeCompleter->getCodeCompletionTUInfo(), 7435 CodeCompletionContext::CCC_Other); 7436 Results.EnterNewScope(); 7437 if (isa<ObjCImplDecl>(SemaRef.CurContext)) 7438 AddObjCImplementationResults(getLangOpts(), Results, false); 7439 else if (SemaRef.CurContext->isObjCContainer()) 7440 AddObjCInterfaceResults(getLangOpts(), Results, false); 7441 else 7442 AddObjCTopLevelResults(Results, false); 7443 Results.ExitScope(); 7444 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 7445 Results.getCompletionContext(), Results.data(), 7446 Results.size()); 7447 } 7448 7449 static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt) { 7450 typedef CodeCompletionResult Result; 7451 CodeCompletionBuilder Builder(Results.getAllocator(), 7452 Results.getCodeCompletionTUInfo()); 7453 7454 // @encode ( type-name ) 7455 const char *EncodeType = "char[]"; 7456 if (Results.getSema().getLangOpts().CPlusPlus || 7457 Results.getSema().getLangOpts().ConstStrings) 7458 EncodeType = "const char[]"; 7459 Builder.AddResultTypeChunk(EncodeType); 7460 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "encode")); 7461 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7462 Builder.AddPlaceholderChunk("type-name"); 7463 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7464 Results.AddResult(Result(Builder.TakeString())); 7465 7466 // @protocol ( protocol-name ) 7467 Builder.AddResultTypeChunk("Protocol *"); 7468 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "protocol")); 7469 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7470 Builder.AddPlaceholderChunk("protocol-name"); 7471 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7472 Results.AddResult(Result(Builder.TakeString())); 7473 7474 // @selector ( selector ) 7475 Builder.AddResultTypeChunk("SEL"); 7476 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "selector")); 7477 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7478 Builder.AddPlaceholderChunk("selector"); 7479 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7480 Results.AddResult(Result(Builder.TakeString())); 7481 7482 // @"string" 7483 Builder.AddResultTypeChunk("NSString *"); 7484 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "\"")); 7485 Builder.AddPlaceholderChunk("string"); 7486 Builder.AddTextChunk("\""); 7487 Results.AddResult(Result(Builder.TakeString())); 7488 7489 // @[objects, ...] 7490 Builder.AddResultTypeChunk("NSArray *"); 7491 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "[")); 7492 Builder.AddPlaceholderChunk("objects, ..."); 7493 Builder.AddChunk(CodeCompletionString::CK_RightBracket); 7494 Results.AddResult(Result(Builder.TakeString())); 7495 7496 // @{key : object, ...} 7497 Builder.AddResultTypeChunk("NSDictionary *"); 7498 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "{")); 7499 Builder.AddPlaceholderChunk("key"); 7500 Builder.AddChunk(CodeCompletionString::CK_Colon); 7501 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7502 Builder.AddPlaceholderChunk("object, ..."); 7503 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 7504 Results.AddResult(Result(Builder.TakeString())); 7505 7506 // @(expression) 7507 Builder.AddResultTypeChunk("id"); 7508 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "(")); 7509 Builder.AddPlaceholderChunk("expression"); 7510 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7511 Results.AddResult(Result(Builder.TakeString())); 7512 } 7513 7514 static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt) { 7515 typedef CodeCompletionResult Result; 7516 CodeCompletionBuilder Builder(Results.getAllocator(), 7517 Results.getCodeCompletionTUInfo()); 7518 7519 if (Results.includeCodePatterns()) { 7520 // @try { statements } @catch ( declaration ) { statements } @finally 7521 // { statements } 7522 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "try")); 7523 Builder.AddChunk(CodeCompletionString::CK_LeftBrace); 7524 Builder.AddPlaceholderChunk("statements"); 7525 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 7526 Builder.AddTextChunk("@catch"); 7527 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7528 Builder.AddPlaceholderChunk("parameter"); 7529 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7530 Builder.AddChunk(CodeCompletionString::CK_LeftBrace); 7531 Builder.AddPlaceholderChunk("statements"); 7532 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 7533 Builder.AddTextChunk("@finally"); 7534 Builder.AddChunk(CodeCompletionString::CK_LeftBrace); 7535 Builder.AddPlaceholderChunk("statements"); 7536 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 7537 Results.AddResult(Result(Builder.TakeString())); 7538 } 7539 7540 // @throw 7541 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "throw")); 7542 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7543 Builder.AddPlaceholderChunk("expression"); 7544 Results.AddResult(Result(Builder.TakeString())); 7545 7546 if (Results.includeCodePatterns()) { 7547 // @synchronized ( expression ) { statements } 7548 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "synchronized")); 7549 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7550 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7551 Builder.AddPlaceholderChunk("expression"); 7552 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7553 Builder.AddChunk(CodeCompletionString::CK_LeftBrace); 7554 Builder.AddPlaceholderChunk("statements"); 7555 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 7556 Results.AddResult(Result(Builder.TakeString())); 7557 } 7558 } 7559 7560 static void AddObjCVisibilityResults(const LangOptions &LangOpts, 7561 ResultBuilder &Results, bool NeedAt) { 7562 typedef CodeCompletionResult Result; 7563 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "private"))); 7564 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "protected"))); 7565 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "public"))); 7566 if (LangOpts.ObjC) 7567 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "package"))); 7568 } 7569 7570 void SemaCodeCompletion::CodeCompleteObjCAtVisibility(Scope *S) { 7571 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(), 7572 CodeCompleter->getCodeCompletionTUInfo(), 7573 CodeCompletionContext::CCC_Other); 7574 Results.EnterNewScope(); 7575 AddObjCVisibilityResults(getLangOpts(), Results, false); 7576 Results.ExitScope(); 7577 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 7578 Results.getCompletionContext(), Results.data(), 7579 Results.size()); 7580 } 7581 7582 void SemaCodeCompletion::CodeCompleteObjCAtStatement(Scope *S) { 7583 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(), 7584 CodeCompleter->getCodeCompletionTUInfo(), 7585 CodeCompletionContext::CCC_Other); 7586 Results.EnterNewScope(); 7587 AddObjCStatementResults(Results, false); 7588 AddObjCExpressionResults(Results, false); 7589 Results.ExitScope(); 7590 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 7591 Results.getCompletionContext(), Results.data(), 7592 Results.size()); 7593 } 7594 7595 void SemaCodeCompletion::CodeCompleteObjCAtExpression(Scope *S) { 7596 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(), 7597 CodeCompleter->getCodeCompletionTUInfo(), 7598 CodeCompletionContext::CCC_Other); 7599 Results.EnterNewScope(); 7600 AddObjCExpressionResults(Results, false); 7601 Results.ExitScope(); 7602 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 7603 Results.getCompletionContext(), Results.data(), 7604 Results.size()); 7605 } 7606 7607 /// Determine whether the addition of the given flag to an Objective-C 7608 /// property's attributes will cause a conflict. 7609 static bool ObjCPropertyFlagConflicts(unsigned Attributes, unsigned NewFlag) { 7610 // Check if we've already added this flag. 7611 if (Attributes & NewFlag) 7612 return true; 7613 7614 Attributes |= NewFlag; 7615 7616 // Check for collisions with "readonly". 7617 if ((Attributes & ObjCPropertyAttribute::kind_readonly) && 7618 (Attributes & ObjCPropertyAttribute::kind_readwrite)) 7619 return true; 7620 7621 // Check for more than one of { assign, copy, retain, strong, weak }. 7622 unsigned AssignCopyRetMask = 7623 Attributes & 7624 (ObjCPropertyAttribute::kind_assign | 7625 ObjCPropertyAttribute::kind_unsafe_unretained | 7626 ObjCPropertyAttribute::kind_copy | ObjCPropertyAttribute::kind_retain | 7627 ObjCPropertyAttribute::kind_strong | ObjCPropertyAttribute::kind_weak); 7628 if (AssignCopyRetMask && 7629 AssignCopyRetMask != ObjCPropertyAttribute::kind_assign && 7630 AssignCopyRetMask != ObjCPropertyAttribute::kind_unsafe_unretained && 7631 AssignCopyRetMask != ObjCPropertyAttribute::kind_copy && 7632 AssignCopyRetMask != ObjCPropertyAttribute::kind_retain && 7633 AssignCopyRetMask != ObjCPropertyAttribute::kind_strong && 7634 AssignCopyRetMask != ObjCPropertyAttribute::kind_weak) 7635 return true; 7636 7637 return false; 7638 } 7639 7640 void SemaCodeCompletion::CodeCompleteObjCPropertyFlags(Scope *S, 7641 ObjCDeclSpec &ODS) { 7642 if (!CodeCompleter) 7643 return; 7644 7645 unsigned Attributes = ODS.getPropertyAttributes(); 7646 7647 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(), 7648 CodeCompleter->getCodeCompletionTUInfo(), 7649 CodeCompletionContext::CCC_Other); 7650 Results.EnterNewScope(); 7651 if (!ObjCPropertyFlagConflicts(Attributes, 7652 ObjCPropertyAttribute::kind_readonly)) 7653 Results.AddResult(CodeCompletionResult("readonly")); 7654 if (!ObjCPropertyFlagConflicts(Attributes, 7655 ObjCPropertyAttribute::kind_assign)) 7656 Results.AddResult(CodeCompletionResult("assign")); 7657 if (!ObjCPropertyFlagConflicts(Attributes, 7658 ObjCPropertyAttribute::kind_unsafe_unretained)) 7659 Results.AddResult(CodeCompletionResult("unsafe_unretained")); 7660 if (!ObjCPropertyFlagConflicts(Attributes, 7661 ObjCPropertyAttribute::kind_readwrite)) 7662 Results.AddResult(CodeCompletionResult("readwrite")); 7663 if (!ObjCPropertyFlagConflicts(Attributes, 7664 ObjCPropertyAttribute::kind_retain)) 7665 Results.AddResult(CodeCompletionResult("retain")); 7666 if (!ObjCPropertyFlagConflicts(Attributes, 7667 ObjCPropertyAttribute::kind_strong)) 7668 Results.AddResult(CodeCompletionResult("strong")); 7669 if (!ObjCPropertyFlagConflicts(Attributes, ObjCPropertyAttribute::kind_copy)) 7670 Results.AddResult(CodeCompletionResult("copy")); 7671 if (!ObjCPropertyFlagConflicts(Attributes, 7672 ObjCPropertyAttribute::kind_nonatomic)) 7673 Results.AddResult(CodeCompletionResult("nonatomic")); 7674 if (!ObjCPropertyFlagConflicts(Attributes, 7675 ObjCPropertyAttribute::kind_atomic)) 7676 Results.AddResult(CodeCompletionResult("atomic")); 7677 7678 // Only suggest "weak" if we're compiling for ARC-with-weak-references or GC. 7679 if (getLangOpts().ObjCWeak || getLangOpts().getGC() != LangOptions::NonGC) 7680 if (!ObjCPropertyFlagConflicts(Attributes, 7681 ObjCPropertyAttribute::kind_weak)) 7682 Results.AddResult(CodeCompletionResult("weak")); 7683 7684 if (!ObjCPropertyFlagConflicts(Attributes, 7685 ObjCPropertyAttribute::kind_setter)) { 7686 CodeCompletionBuilder Setter(Results.getAllocator(), 7687 Results.getCodeCompletionTUInfo()); 7688 Setter.AddTypedTextChunk("setter"); 7689 Setter.AddTextChunk("="); 7690 Setter.AddPlaceholderChunk("method"); 7691 Results.AddResult(CodeCompletionResult(Setter.TakeString())); 7692 } 7693 if (!ObjCPropertyFlagConflicts(Attributes, 7694 ObjCPropertyAttribute::kind_getter)) { 7695 CodeCompletionBuilder Getter(Results.getAllocator(), 7696 Results.getCodeCompletionTUInfo()); 7697 Getter.AddTypedTextChunk("getter"); 7698 Getter.AddTextChunk("="); 7699 Getter.AddPlaceholderChunk("method"); 7700 Results.AddResult(CodeCompletionResult(Getter.TakeString())); 7701 } 7702 if (!ObjCPropertyFlagConflicts(Attributes, 7703 ObjCPropertyAttribute::kind_nullability)) { 7704 Results.AddResult(CodeCompletionResult("nonnull")); 7705 Results.AddResult(CodeCompletionResult("nullable")); 7706 Results.AddResult(CodeCompletionResult("null_unspecified")); 7707 Results.AddResult(CodeCompletionResult("null_resettable")); 7708 } 7709 Results.ExitScope(); 7710 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 7711 Results.getCompletionContext(), Results.data(), 7712 Results.size()); 7713 } 7714 7715 /// Describes the kind of Objective-C method that we want to find 7716 /// via code completion. 7717 enum ObjCMethodKind { 7718 MK_Any, ///< Any kind of method, provided it means other specified criteria. 7719 MK_ZeroArgSelector, ///< Zero-argument (unary) selector. 7720 MK_OneArgSelector ///< One-argument selector. 7721 }; 7722 7723 static bool isAcceptableObjCSelector(Selector Sel, ObjCMethodKind WantKind, 7724 ArrayRef<const IdentifierInfo *> SelIdents, 7725 bool AllowSameLength = true) { 7726 unsigned NumSelIdents = SelIdents.size(); 7727 if (NumSelIdents > Sel.getNumArgs()) 7728 return false; 7729 7730 switch (WantKind) { 7731 case MK_Any: 7732 break; 7733 case MK_ZeroArgSelector: 7734 return Sel.isUnarySelector(); 7735 case MK_OneArgSelector: 7736 return Sel.getNumArgs() == 1; 7737 } 7738 7739 if (!AllowSameLength && NumSelIdents && NumSelIdents == Sel.getNumArgs()) 7740 return false; 7741 7742 for (unsigned I = 0; I != NumSelIdents; ++I) 7743 if (SelIdents[I] != Sel.getIdentifierInfoForSlot(I)) 7744 return false; 7745 7746 return true; 7747 } 7748 7749 static bool isAcceptableObjCMethod(ObjCMethodDecl *Method, 7750 ObjCMethodKind WantKind, 7751 ArrayRef<const IdentifierInfo *> SelIdents, 7752 bool AllowSameLength = true) { 7753 return isAcceptableObjCSelector(Method->getSelector(), WantKind, SelIdents, 7754 AllowSameLength); 7755 } 7756 7757 /// A set of selectors, which is used to avoid introducing multiple 7758 /// completions with the same selector into the result set. 7759 typedef llvm::SmallPtrSet<Selector, 16> VisitedSelectorSet; 7760 7761 /// Add all of the Objective-C methods in the given Objective-C 7762 /// container to the set of results. 7763 /// 7764 /// The container will be a class, protocol, category, or implementation of 7765 /// any of the above. This mether will recurse to include methods from 7766 /// the superclasses of classes along with their categories, protocols, and 7767 /// implementations. 7768 /// 7769 /// \param Container the container in which we'll look to find methods. 7770 /// 7771 /// \param WantInstanceMethods Whether to add instance methods (only); if 7772 /// false, this routine will add factory methods (only). 7773 /// 7774 /// \param CurContext the context in which we're performing the lookup that 7775 /// finds methods. 7776 /// 7777 /// \param AllowSameLength Whether we allow a method to be added to the list 7778 /// when it has the same number of parameters as we have selector identifiers. 7779 /// 7780 /// \param Results the structure into which we'll add results. 7781 static void AddObjCMethods(ObjCContainerDecl *Container, 7782 bool WantInstanceMethods, ObjCMethodKind WantKind, 7783 ArrayRef<const IdentifierInfo *> SelIdents, 7784 DeclContext *CurContext, 7785 VisitedSelectorSet &Selectors, bool AllowSameLength, 7786 ResultBuilder &Results, bool InOriginalClass = true, 7787 bool IsRootClass = false) { 7788 typedef CodeCompletionResult Result; 7789 Container = getContainerDef(Container); 7790 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container); 7791 IsRootClass = IsRootClass || (IFace && !IFace->getSuperClass()); 7792 for (ObjCMethodDecl *M : Container->methods()) { 7793 // The instance methods on the root class can be messaged via the 7794 // metaclass. 7795 if (M->isInstanceMethod() == WantInstanceMethods || 7796 (IsRootClass && !WantInstanceMethods)) { 7797 // Check whether the selector identifiers we've been given are a 7798 // subset of the identifiers for this particular method. 7799 if (!isAcceptableObjCMethod(M, WantKind, SelIdents, AllowSameLength)) 7800 continue; 7801 7802 if (!Selectors.insert(M->getSelector()).second) 7803 continue; 7804 7805 Result R = Result(M, Results.getBasePriority(M), nullptr); 7806 R.StartParameter = SelIdents.size(); 7807 R.AllParametersAreInformative = (WantKind != MK_Any); 7808 if (!InOriginalClass) 7809 setInBaseClass(R); 7810 Results.MaybeAddResult(R, CurContext); 7811 } 7812 } 7813 7814 // Visit the protocols of protocols. 7815 if (const auto *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) { 7816 if (Protocol->hasDefinition()) { 7817 const ObjCList<ObjCProtocolDecl> &Protocols = 7818 Protocol->getReferencedProtocols(); 7819 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(), 7820 E = Protocols.end(); 7821 I != E; ++I) 7822 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, CurContext, 7823 Selectors, AllowSameLength, Results, false, IsRootClass); 7824 } 7825 } 7826 7827 if (!IFace || !IFace->hasDefinition()) 7828 return; 7829 7830 // Add methods in protocols. 7831 for (ObjCProtocolDecl *I : IFace->protocols()) 7832 AddObjCMethods(I, WantInstanceMethods, WantKind, SelIdents, CurContext, 7833 Selectors, AllowSameLength, Results, false, IsRootClass); 7834 7835 // Add methods in categories. 7836 for (ObjCCategoryDecl *CatDecl : IFace->known_categories()) { 7837 AddObjCMethods(CatDecl, WantInstanceMethods, WantKind, SelIdents, 7838 CurContext, Selectors, AllowSameLength, Results, 7839 InOriginalClass, IsRootClass); 7840 7841 // Add a categories protocol methods. 7842 const ObjCList<ObjCProtocolDecl> &Protocols = 7843 CatDecl->getReferencedProtocols(); 7844 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(), 7845 E = Protocols.end(); 7846 I != E; ++I) 7847 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, CurContext, 7848 Selectors, AllowSameLength, Results, false, IsRootClass); 7849 7850 // Add methods in category implementations. 7851 if (ObjCCategoryImplDecl *Impl = CatDecl->getImplementation()) 7852 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents, CurContext, 7853 Selectors, AllowSameLength, Results, InOriginalClass, 7854 IsRootClass); 7855 } 7856 7857 // Add methods in superclass. 7858 // Avoid passing in IsRootClass since root classes won't have super classes. 7859 if (IFace->getSuperClass()) 7860 AddObjCMethods(IFace->getSuperClass(), WantInstanceMethods, WantKind, 7861 SelIdents, CurContext, Selectors, AllowSameLength, Results, 7862 /*IsRootClass=*/false); 7863 7864 // Add methods in our implementation, if any. 7865 if (ObjCImplementationDecl *Impl = IFace->getImplementation()) 7866 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents, CurContext, 7867 Selectors, AllowSameLength, Results, InOriginalClass, 7868 IsRootClass); 7869 } 7870 7871 void SemaCodeCompletion::CodeCompleteObjCPropertyGetter(Scope *S) { 7872 // Try to find the interface where getters might live. 7873 ObjCInterfaceDecl *Class = 7874 dyn_cast_or_null<ObjCInterfaceDecl>(SemaRef.CurContext); 7875 if (!Class) { 7876 if (ObjCCategoryDecl *Category = 7877 dyn_cast_or_null<ObjCCategoryDecl>(SemaRef.CurContext)) 7878 Class = Category->getClassInterface(); 7879 7880 if (!Class) 7881 return; 7882 } 7883 7884 // Find all of the potential getters. 7885 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(), 7886 CodeCompleter->getCodeCompletionTUInfo(), 7887 CodeCompletionContext::CCC_Other); 7888 Results.EnterNewScope(); 7889 7890 VisitedSelectorSet Selectors; 7891 AddObjCMethods(Class, true, MK_ZeroArgSelector, {}, SemaRef.CurContext, 7892 Selectors, 7893 /*AllowSameLength=*/true, Results); 7894 Results.ExitScope(); 7895 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 7896 Results.getCompletionContext(), Results.data(), 7897 Results.size()); 7898 } 7899 7900 void SemaCodeCompletion::CodeCompleteObjCPropertySetter(Scope *S) { 7901 // Try to find the interface where setters might live. 7902 ObjCInterfaceDecl *Class = 7903 dyn_cast_or_null<ObjCInterfaceDecl>(SemaRef.CurContext); 7904 if (!Class) { 7905 if (ObjCCategoryDecl *Category = 7906 dyn_cast_or_null<ObjCCategoryDecl>(SemaRef.CurContext)) 7907 Class = Category->getClassInterface(); 7908 7909 if (!Class) 7910 return; 7911 } 7912 7913 // Find all of the potential getters. 7914 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(), 7915 CodeCompleter->getCodeCompletionTUInfo(), 7916 CodeCompletionContext::CCC_Other); 7917 Results.EnterNewScope(); 7918 7919 VisitedSelectorSet Selectors; 7920 AddObjCMethods(Class, true, MK_OneArgSelector, {}, SemaRef.CurContext, 7921 Selectors, 7922 /*AllowSameLength=*/true, Results); 7923 7924 Results.ExitScope(); 7925 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 7926 Results.getCompletionContext(), Results.data(), 7927 Results.size()); 7928 } 7929 7930 void SemaCodeCompletion::CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS, 7931 bool IsParameter) { 7932 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(), 7933 CodeCompleter->getCodeCompletionTUInfo(), 7934 CodeCompletionContext::CCC_Type); 7935 Results.EnterNewScope(); 7936 7937 // Add context-sensitive, Objective-C parameter-passing keywords. 7938 bool AddedInOut = false; 7939 if ((DS.getObjCDeclQualifier() & 7940 (ObjCDeclSpec::DQ_In | ObjCDeclSpec::DQ_Inout)) == 0) { 7941 Results.AddResult("in"); 7942 Results.AddResult("inout"); 7943 AddedInOut = true; 7944 } 7945 if ((DS.getObjCDeclQualifier() & 7946 (ObjCDeclSpec::DQ_Out | ObjCDeclSpec::DQ_Inout)) == 0) { 7947 Results.AddResult("out"); 7948 if (!AddedInOut) 7949 Results.AddResult("inout"); 7950 } 7951 if ((DS.getObjCDeclQualifier() & 7952 (ObjCDeclSpec::DQ_Bycopy | ObjCDeclSpec::DQ_Byref | 7953 ObjCDeclSpec::DQ_Oneway)) == 0) { 7954 Results.AddResult("bycopy"); 7955 Results.AddResult("byref"); 7956 Results.AddResult("oneway"); 7957 } 7958 if ((DS.getObjCDeclQualifier() & ObjCDeclSpec::DQ_CSNullability) == 0) { 7959 Results.AddResult("nonnull"); 7960 Results.AddResult("nullable"); 7961 Results.AddResult("null_unspecified"); 7962 } 7963 7964 // If we're completing the return type of an Objective-C method and the 7965 // identifier IBAction refers to a macro, provide a completion item for 7966 // an action, e.g., 7967 // IBAction)<#selector#>:(id)sender 7968 if (DS.getObjCDeclQualifier() == 0 && !IsParameter && 7969 SemaRef.PP.isMacroDefined("IBAction")) { 7970 CodeCompletionBuilder Builder(Results.getAllocator(), 7971 Results.getCodeCompletionTUInfo(), 7972 CCP_CodePattern, CXAvailability_Available); 7973 Builder.AddTypedTextChunk("IBAction"); 7974 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7975 Builder.AddPlaceholderChunk("selector"); 7976 Builder.AddChunk(CodeCompletionString::CK_Colon); 7977 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7978 Builder.AddTextChunk("id"); 7979 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7980 Builder.AddTextChunk("sender"); 7981 Results.AddResult(CodeCompletionResult(Builder.TakeString())); 7982 } 7983 7984 // If we're completing the return type, provide 'instancetype'. 7985 if (!IsParameter) { 7986 Results.AddResult(CodeCompletionResult("instancetype")); 7987 } 7988 7989 // Add various builtin type names and specifiers. 7990 AddOrdinaryNameResults(PCC_Type, S, SemaRef, Results); 7991 Results.ExitScope(); 7992 7993 // Add the various type names 7994 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName); 7995 CodeCompletionDeclConsumer Consumer(Results, SemaRef.CurContext); 7996 SemaRef.LookupVisibleDecls(S, Sema::LookupOrdinaryName, Consumer, 7997 CodeCompleter->includeGlobals(), 7998 CodeCompleter->loadExternal()); 7999 8000 if (CodeCompleter->includeMacros()) 8001 AddMacroResults(SemaRef.PP, Results, CodeCompleter->loadExternal(), false); 8002 8003 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 8004 Results.getCompletionContext(), Results.data(), 8005 Results.size()); 8006 } 8007 8008 /// When we have an expression with type "id", we may assume 8009 /// that it has some more-specific class type based on knowledge of 8010 /// common uses of Objective-C. This routine returns that class type, 8011 /// or NULL if no better result could be determined. 8012 static ObjCInterfaceDecl *GetAssumedMessageSendExprType(Expr *E) { 8013 auto *Msg = dyn_cast_or_null<ObjCMessageExpr>(E); 8014 if (!Msg) 8015 return nullptr; 8016 8017 Selector Sel = Msg->getSelector(); 8018 if (Sel.isNull()) 8019 return nullptr; 8020 8021 const IdentifierInfo *Id = Sel.getIdentifierInfoForSlot(0); 8022 if (!Id) 8023 return nullptr; 8024 8025 ObjCMethodDecl *Method = Msg->getMethodDecl(); 8026 if (!Method) 8027 return nullptr; 8028 8029 // Determine the class that we're sending the message to. 8030 ObjCInterfaceDecl *IFace = nullptr; 8031 switch (Msg->getReceiverKind()) { 8032 case ObjCMessageExpr::Class: 8033 if (const ObjCObjectType *ObjType = 8034 Msg->getClassReceiver()->getAs<ObjCObjectType>()) 8035 IFace = ObjType->getInterface(); 8036 break; 8037 8038 case ObjCMessageExpr::Instance: { 8039 QualType T = Msg->getInstanceReceiver()->getType(); 8040 if (const ObjCObjectPointerType *Ptr = T->getAs<ObjCObjectPointerType>()) 8041 IFace = Ptr->getInterfaceDecl(); 8042 break; 8043 } 8044 8045 case ObjCMessageExpr::SuperInstance: 8046 case ObjCMessageExpr::SuperClass: 8047 break; 8048 } 8049 8050 if (!IFace) 8051 return nullptr; 8052 8053 ObjCInterfaceDecl *Super = IFace->getSuperClass(); 8054 if (Method->isInstanceMethod()) 8055 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName()) 8056 .Case("retain", IFace) 8057 .Case("strong", IFace) 8058 .Case("autorelease", IFace) 8059 .Case("copy", IFace) 8060 .Case("copyWithZone", IFace) 8061 .Case("mutableCopy", IFace) 8062 .Case("mutableCopyWithZone", IFace) 8063 .Case("awakeFromCoder", IFace) 8064 .Case("replacementObjectFromCoder", IFace) 8065 .Case("class", IFace) 8066 .Case("classForCoder", IFace) 8067 .Case("superclass", Super) 8068 .Default(nullptr); 8069 8070 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName()) 8071 .Case("new", IFace) 8072 .Case("alloc", IFace) 8073 .Case("allocWithZone", IFace) 8074 .Case("class", IFace) 8075 .Case("superclass", Super) 8076 .Default(nullptr); 8077 } 8078 8079 // Add a special completion for a message send to "super", which fills in the 8080 // most likely case of forwarding all of our arguments to the superclass 8081 // function. 8082 /// 8083 /// \param S The semantic analysis object. 8084 /// 8085 /// \param NeedSuperKeyword Whether we need to prefix this completion with 8086 /// the "super" keyword. Otherwise, we just need to provide the arguments. 8087 /// 8088 /// \param SelIdents The identifiers in the selector that have already been 8089 /// provided as arguments for a send to "super". 8090 /// 8091 /// \param Results The set of results to augment. 8092 /// 8093 /// \returns the Objective-C method declaration that would be invoked by 8094 /// this "super" completion. If NULL, no completion was added. 8095 static ObjCMethodDecl * 8096 AddSuperSendCompletion(Sema &S, bool NeedSuperKeyword, 8097 ArrayRef<const IdentifierInfo *> SelIdents, 8098 ResultBuilder &Results) { 8099 ObjCMethodDecl *CurMethod = S.getCurMethodDecl(); 8100 if (!CurMethod) 8101 return nullptr; 8102 8103 ObjCInterfaceDecl *Class = CurMethod->getClassInterface(); 8104 if (!Class) 8105 return nullptr; 8106 8107 // Try to find a superclass method with the same selector. 8108 ObjCMethodDecl *SuperMethod = nullptr; 8109 while ((Class = Class->getSuperClass()) && !SuperMethod) { 8110 // Check in the class 8111 SuperMethod = Class->getMethod(CurMethod->getSelector(), 8112 CurMethod->isInstanceMethod()); 8113 8114 // Check in categories or class extensions. 8115 if (!SuperMethod) { 8116 for (const auto *Cat : Class->known_categories()) { 8117 if ((SuperMethod = Cat->getMethod(CurMethod->getSelector(), 8118 CurMethod->isInstanceMethod()))) 8119 break; 8120 } 8121 } 8122 } 8123 8124 if (!SuperMethod) 8125 return nullptr; 8126 8127 // Check whether the superclass method has the same signature. 8128 if (CurMethod->param_size() != SuperMethod->param_size() || 8129 CurMethod->isVariadic() != SuperMethod->isVariadic()) 8130 return nullptr; 8131 8132 for (ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin(), 8133 CurPEnd = CurMethod->param_end(), 8134 SuperP = SuperMethod->param_begin(); 8135 CurP != CurPEnd; ++CurP, ++SuperP) { 8136 // Make sure the parameter types are compatible. 8137 if (!S.Context.hasSameUnqualifiedType((*CurP)->getType(), 8138 (*SuperP)->getType())) 8139 return nullptr; 8140 8141 // Make sure we have a parameter name to forward! 8142 if (!(*CurP)->getIdentifier()) 8143 return nullptr; 8144 } 8145 8146 // We have a superclass method. Now, form the send-to-super completion. 8147 CodeCompletionBuilder Builder(Results.getAllocator(), 8148 Results.getCodeCompletionTUInfo()); 8149 8150 // Give this completion a return type. 8151 AddResultTypeChunk(S.Context, getCompletionPrintingPolicy(S), SuperMethod, 8152 Results.getCompletionContext().getBaseType(), Builder); 8153 8154 // If we need the "super" keyword, add it (plus some spacing). 8155 if (NeedSuperKeyword) { 8156 Builder.AddTypedTextChunk("super"); 8157 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 8158 } 8159 8160 Selector Sel = CurMethod->getSelector(); 8161 if (Sel.isUnarySelector()) { 8162 if (NeedSuperKeyword) 8163 Builder.AddTextChunk( 8164 Builder.getAllocator().CopyString(Sel.getNameForSlot(0))); 8165 else 8166 Builder.AddTypedTextChunk( 8167 Builder.getAllocator().CopyString(Sel.getNameForSlot(0))); 8168 } else { 8169 ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin(); 8170 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I, ++CurP) { 8171 if (I > SelIdents.size()) 8172 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 8173 8174 if (I < SelIdents.size()) 8175 Builder.AddInformativeChunk( 8176 Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":")); 8177 else if (NeedSuperKeyword || I > SelIdents.size()) { 8178 Builder.AddTextChunk( 8179 Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":")); 8180 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString( 8181 (*CurP)->getIdentifier()->getName())); 8182 } else { 8183 Builder.AddTypedTextChunk( 8184 Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":")); 8185 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString( 8186 (*CurP)->getIdentifier()->getName())); 8187 } 8188 } 8189 } 8190 8191 Results.AddResult(CodeCompletionResult(Builder.TakeString(), SuperMethod, 8192 CCP_SuperCompletion)); 8193 return SuperMethod; 8194 } 8195 8196 void SemaCodeCompletion::CodeCompleteObjCMessageReceiver(Scope *S) { 8197 typedef CodeCompletionResult Result; 8198 ResultBuilder Results( 8199 SemaRef, CodeCompleter->getAllocator(), 8200 CodeCompleter->getCodeCompletionTUInfo(), 8201 CodeCompletionContext::CCC_ObjCMessageReceiver, 8202 getLangOpts().CPlusPlus11 8203 ? &ResultBuilder::IsObjCMessageReceiverOrLambdaCapture 8204 : &ResultBuilder::IsObjCMessageReceiver); 8205 8206 CodeCompletionDeclConsumer Consumer(Results, SemaRef.CurContext); 8207 Results.EnterNewScope(); 8208 SemaRef.LookupVisibleDecls(S, Sema::LookupOrdinaryName, Consumer, 8209 CodeCompleter->includeGlobals(), 8210 CodeCompleter->loadExternal()); 8211 8212 // If we are in an Objective-C method inside a class that has a superclass, 8213 // add "super" as an option. 8214 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) 8215 if (ObjCInterfaceDecl *Iface = Method->getClassInterface()) 8216 if (Iface->getSuperClass()) { 8217 Results.AddResult(Result("super")); 8218 8219 AddSuperSendCompletion(SemaRef, /*NeedSuperKeyword=*/true, {}, Results); 8220 } 8221 8222 if (getLangOpts().CPlusPlus11) 8223 addThisCompletion(SemaRef, Results); 8224 8225 Results.ExitScope(); 8226 8227 if (CodeCompleter->includeMacros()) 8228 AddMacroResults(SemaRef.PP, Results, CodeCompleter->loadExternal(), false); 8229 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 8230 Results.getCompletionContext(), Results.data(), 8231 Results.size()); 8232 } 8233 8234 void SemaCodeCompletion::CodeCompleteObjCSuperMessage( 8235 Scope *S, SourceLocation SuperLoc, 8236 ArrayRef<const IdentifierInfo *> SelIdents, bool AtArgumentExpression) { 8237 ObjCInterfaceDecl *CDecl = nullptr; 8238 if (ObjCMethodDecl *CurMethod = SemaRef.getCurMethodDecl()) { 8239 // Figure out which interface we're in. 8240 CDecl = CurMethod->getClassInterface(); 8241 if (!CDecl) 8242 return; 8243 8244 // Find the superclass of this class. 8245 CDecl = CDecl->getSuperClass(); 8246 if (!CDecl) 8247 return; 8248 8249 if (CurMethod->isInstanceMethod()) { 8250 // We are inside an instance method, which means that the message 8251 // send [super ...] is actually calling an instance method on the 8252 // current object. 8253 return CodeCompleteObjCInstanceMessage(S, nullptr, SelIdents, 8254 AtArgumentExpression, CDecl); 8255 } 8256 8257 // Fall through to send to the superclass in CDecl. 8258 } else { 8259 // "super" may be the name of a type or variable. Figure out which 8260 // it is. 8261 const IdentifierInfo *Super = SemaRef.getSuperIdentifier(); 8262 NamedDecl *ND = 8263 SemaRef.LookupSingleName(S, Super, SuperLoc, Sema::LookupOrdinaryName); 8264 if ((CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(ND))) { 8265 // "super" names an interface. Use it. 8266 } else if (TypeDecl *TD = dyn_cast_or_null<TypeDecl>(ND)) { 8267 if (const ObjCObjectType *Iface = 8268 getASTContext().getTypeDeclType(TD)->getAs<ObjCObjectType>()) 8269 CDecl = Iface->getInterface(); 8270 } else if (ND && isa<UnresolvedUsingTypenameDecl>(ND)) { 8271 // "super" names an unresolved type; we can't be more specific. 8272 } else { 8273 // Assume that "super" names some kind of value and parse that way. 8274 CXXScopeSpec SS; 8275 SourceLocation TemplateKWLoc; 8276 UnqualifiedId id; 8277 id.setIdentifier(Super, SuperLoc); 8278 ExprResult SuperExpr = 8279 SemaRef.ActOnIdExpression(S, SS, TemplateKWLoc, id, 8280 /*HasTrailingLParen=*/false, 8281 /*IsAddressOfOperand=*/false); 8282 return CodeCompleteObjCInstanceMessage(S, (Expr *)SuperExpr.get(), 8283 SelIdents, AtArgumentExpression); 8284 } 8285 8286 // Fall through 8287 } 8288 8289 ParsedType Receiver; 8290 if (CDecl) 8291 Receiver = ParsedType::make(getASTContext().getObjCInterfaceType(CDecl)); 8292 return CodeCompleteObjCClassMessage(S, Receiver, SelIdents, 8293 AtArgumentExpression, 8294 /*IsSuper=*/true); 8295 } 8296 8297 /// Given a set of code-completion results for the argument of a message 8298 /// send, determine the preferred type (if any) for that argument expression. 8299 static QualType getPreferredArgumentTypeForMessageSend(ResultBuilder &Results, 8300 unsigned NumSelIdents) { 8301 typedef CodeCompletionResult Result; 8302 ASTContext &Context = Results.getSema().Context; 8303 8304 QualType PreferredType; 8305 unsigned BestPriority = CCP_Unlikely * 2; 8306 Result *ResultsData = Results.data(); 8307 for (unsigned I = 0, N = Results.size(); I != N; ++I) { 8308 Result &R = ResultsData[I]; 8309 if (R.Kind == Result::RK_Declaration && 8310 isa<ObjCMethodDecl>(R.Declaration)) { 8311 if (R.Priority <= BestPriority) { 8312 const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(R.Declaration); 8313 if (NumSelIdents <= Method->param_size()) { 8314 QualType MyPreferredType = 8315 Method->parameters()[NumSelIdents - 1]->getType(); 8316 if (R.Priority < BestPriority || PreferredType.isNull()) { 8317 BestPriority = R.Priority; 8318 PreferredType = MyPreferredType; 8319 } else if (!Context.hasSameUnqualifiedType(PreferredType, 8320 MyPreferredType)) { 8321 PreferredType = QualType(); 8322 } 8323 } 8324 } 8325 } 8326 } 8327 8328 return PreferredType; 8329 } 8330 8331 static void 8332 AddClassMessageCompletions(Sema &SemaRef, Scope *S, ParsedType Receiver, 8333 ArrayRef<const IdentifierInfo *> SelIdents, 8334 bool AtArgumentExpression, bool IsSuper, 8335 ResultBuilder &Results) { 8336 typedef CodeCompletionResult Result; 8337 ObjCInterfaceDecl *CDecl = nullptr; 8338 8339 // If the given name refers to an interface type, retrieve the 8340 // corresponding declaration. 8341 if (Receiver) { 8342 QualType T = SemaRef.GetTypeFromParser(Receiver, nullptr); 8343 if (!T.isNull()) 8344 if (const ObjCObjectType *Interface = T->getAs<ObjCObjectType>()) 8345 CDecl = Interface->getInterface(); 8346 } 8347 8348 // Add all of the factory methods in this Objective-C class, its protocols, 8349 // superclasses, categories, implementation, etc. 8350 Results.EnterNewScope(); 8351 8352 // If this is a send-to-super, try to add the special "super" send 8353 // completion. 8354 if (IsSuper) { 8355 if (ObjCMethodDecl *SuperMethod = 8356 AddSuperSendCompletion(SemaRef, false, SelIdents, Results)) 8357 Results.Ignore(SuperMethod); 8358 } 8359 8360 // If we're inside an Objective-C method definition, prefer its selector to 8361 // others. 8362 if (ObjCMethodDecl *CurMethod = SemaRef.getCurMethodDecl()) 8363 Results.setPreferredSelector(CurMethod->getSelector()); 8364 8365 VisitedSelectorSet Selectors; 8366 if (CDecl) 8367 AddObjCMethods(CDecl, false, MK_Any, SelIdents, SemaRef.CurContext, 8368 Selectors, AtArgumentExpression, Results); 8369 else { 8370 // We're messaging "id" as a type; provide all class/factory methods. 8371 8372 // If we have an external source, load the entire class method 8373 // pool from the AST file. 8374 if (SemaRef.getExternalSource()) { 8375 for (uint32_t I = 0, 8376 N = SemaRef.getExternalSource()->GetNumExternalSelectors(); 8377 I != N; ++I) { 8378 Selector Sel = SemaRef.getExternalSource()->GetExternalSelector(I); 8379 if (Sel.isNull() || SemaRef.ObjC().MethodPool.count(Sel)) 8380 continue; 8381 8382 SemaRef.ObjC().ReadMethodPool(Sel); 8383 } 8384 } 8385 8386 for (SemaObjC::GlobalMethodPool::iterator 8387 M = SemaRef.ObjC().MethodPool.begin(), 8388 MEnd = SemaRef.ObjC().MethodPool.end(); 8389 M != MEnd; ++M) { 8390 for (ObjCMethodList *MethList = &M->second.second; 8391 MethList && MethList->getMethod(); MethList = MethList->getNext()) { 8392 if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents)) 8393 continue; 8394 8395 Result R(MethList->getMethod(), 8396 Results.getBasePriority(MethList->getMethod()), nullptr); 8397 R.StartParameter = SelIdents.size(); 8398 R.AllParametersAreInformative = false; 8399 Results.MaybeAddResult(R, SemaRef.CurContext); 8400 } 8401 } 8402 } 8403 8404 Results.ExitScope(); 8405 } 8406 8407 void SemaCodeCompletion::CodeCompleteObjCClassMessage( 8408 Scope *S, ParsedType Receiver, ArrayRef<const IdentifierInfo *> SelIdents, 8409 bool AtArgumentExpression, bool IsSuper) { 8410 8411 QualType T = SemaRef.GetTypeFromParser(Receiver); 8412 8413 ResultBuilder Results( 8414 SemaRef, CodeCompleter->getAllocator(), 8415 CodeCompleter->getCodeCompletionTUInfo(), 8416 CodeCompletionContext(CodeCompletionContext::CCC_ObjCClassMessage, T, 8417 SelIdents)); 8418 8419 AddClassMessageCompletions(SemaRef, S, Receiver, SelIdents, 8420 AtArgumentExpression, IsSuper, Results); 8421 8422 // If we're actually at the argument expression (rather than prior to the 8423 // selector), we're actually performing code completion for an expression. 8424 // Determine whether we have a single, best method. If so, we can 8425 // code-complete the expression using the corresponding parameter type as 8426 // our preferred type, improving completion results. 8427 if (AtArgumentExpression) { 8428 QualType PreferredType = 8429 getPreferredArgumentTypeForMessageSend(Results, SelIdents.size()); 8430 if (PreferredType.isNull()) 8431 CodeCompleteOrdinaryName(S, PCC_Expression); 8432 else 8433 CodeCompleteExpression(S, PreferredType); 8434 return; 8435 } 8436 8437 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 8438 Results.getCompletionContext(), Results.data(), 8439 Results.size()); 8440 } 8441 8442 void SemaCodeCompletion::CodeCompleteObjCInstanceMessage( 8443 Scope *S, Expr *Receiver, ArrayRef<const IdentifierInfo *> SelIdents, 8444 bool AtArgumentExpression, ObjCInterfaceDecl *Super) { 8445 typedef CodeCompletionResult Result; 8446 ASTContext &Context = getASTContext(); 8447 8448 Expr *RecExpr = static_cast<Expr *>(Receiver); 8449 8450 // If necessary, apply function/array conversion to the receiver. 8451 // C99 6.7.5.3p[7,8]. 8452 if (RecExpr) { 8453 ExprResult Conv = SemaRef.DefaultFunctionArrayLvalueConversion(RecExpr); 8454 if (Conv.isInvalid()) // conversion failed. bail. 8455 return; 8456 RecExpr = Conv.get(); 8457 } 8458 QualType ReceiverType = RecExpr 8459 ? RecExpr->getType() 8460 : Super ? Context.getObjCObjectPointerType( 8461 Context.getObjCInterfaceType(Super)) 8462 : Context.getObjCIdType(); 8463 8464 // If we're messaging an expression with type "id" or "Class", check 8465 // whether we know something special about the receiver that allows 8466 // us to assume a more-specific receiver type. 8467 if (ReceiverType->isObjCIdType() || ReceiverType->isObjCClassType()) { 8468 if (ObjCInterfaceDecl *IFace = GetAssumedMessageSendExprType(RecExpr)) { 8469 if (ReceiverType->isObjCClassType()) 8470 return CodeCompleteObjCClassMessage( 8471 S, ParsedType::make(Context.getObjCInterfaceType(IFace)), SelIdents, 8472 AtArgumentExpression, Super); 8473 8474 ReceiverType = 8475 Context.getObjCObjectPointerType(Context.getObjCInterfaceType(IFace)); 8476 } 8477 } else if (RecExpr && getLangOpts().CPlusPlus) { 8478 ExprResult Conv = SemaRef.PerformContextuallyConvertToObjCPointer(RecExpr); 8479 if (Conv.isUsable()) { 8480 RecExpr = Conv.get(); 8481 ReceiverType = RecExpr->getType(); 8482 } 8483 } 8484 8485 // Build the set of methods we can see. 8486 ResultBuilder Results( 8487 SemaRef, CodeCompleter->getAllocator(), 8488 CodeCompleter->getCodeCompletionTUInfo(), 8489 CodeCompletionContext(CodeCompletionContext::CCC_ObjCInstanceMessage, 8490 ReceiverType, SelIdents)); 8491 8492 Results.EnterNewScope(); 8493 8494 // If this is a send-to-super, try to add the special "super" send 8495 // completion. 8496 if (Super) { 8497 if (ObjCMethodDecl *SuperMethod = 8498 AddSuperSendCompletion(SemaRef, false, SelIdents, Results)) 8499 Results.Ignore(SuperMethod); 8500 } 8501 8502 // If we're inside an Objective-C method definition, prefer its selector to 8503 // others. 8504 if (ObjCMethodDecl *CurMethod = SemaRef.getCurMethodDecl()) 8505 Results.setPreferredSelector(CurMethod->getSelector()); 8506 8507 // Keep track of the selectors we've already added. 8508 VisitedSelectorSet Selectors; 8509 8510 // Handle messages to Class. This really isn't a message to an instance 8511 // method, so we treat it the same way we would treat a message send to a 8512 // class method. 8513 if (ReceiverType->isObjCClassType() || 8514 ReceiverType->isObjCQualifiedClassType()) { 8515 if (ObjCMethodDecl *CurMethod = SemaRef.getCurMethodDecl()) { 8516 if (ObjCInterfaceDecl *ClassDecl = CurMethod->getClassInterface()) 8517 AddObjCMethods(ClassDecl, false, MK_Any, SelIdents, SemaRef.CurContext, 8518 Selectors, AtArgumentExpression, Results); 8519 } 8520 } 8521 // Handle messages to a qualified ID ("id<foo>"). 8522 else if (const ObjCObjectPointerType *QualID = 8523 ReceiverType->getAsObjCQualifiedIdType()) { 8524 // Search protocols for instance methods. 8525 for (auto *I : QualID->quals()) 8526 AddObjCMethods(I, true, MK_Any, SelIdents, SemaRef.CurContext, Selectors, 8527 AtArgumentExpression, Results); 8528 } 8529 // Handle messages to a pointer to interface type. 8530 else if (const ObjCObjectPointerType *IFacePtr = 8531 ReceiverType->getAsObjCInterfacePointerType()) { 8532 // Search the class, its superclasses, etc., for instance methods. 8533 AddObjCMethods(IFacePtr->getInterfaceDecl(), true, MK_Any, SelIdents, 8534 SemaRef.CurContext, Selectors, AtArgumentExpression, 8535 Results); 8536 8537 // Search protocols for instance methods. 8538 for (auto *I : IFacePtr->quals()) 8539 AddObjCMethods(I, true, MK_Any, SelIdents, SemaRef.CurContext, Selectors, 8540 AtArgumentExpression, Results); 8541 } 8542 // Handle messages to "id". 8543 else if (ReceiverType->isObjCIdType()) { 8544 // We're messaging "id", so provide all instance methods we know 8545 // about as code-completion results. 8546 8547 // If we have an external source, load the entire class method 8548 // pool from the AST file. 8549 if (SemaRef.ExternalSource) { 8550 for (uint32_t I = 0, 8551 N = SemaRef.ExternalSource->GetNumExternalSelectors(); 8552 I != N; ++I) { 8553 Selector Sel = SemaRef.ExternalSource->GetExternalSelector(I); 8554 if (Sel.isNull() || SemaRef.ObjC().MethodPool.count(Sel)) 8555 continue; 8556 8557 SemaRef.ObjC().ReadMethodPool(Sel); 8558 } 8559 } 8560 8561 for (SemaObjC::GlobalMethodPool::iterator 8562 M = SemaRef.ObjC().MethodPool.begin(), 8563 MEnd = SemaRef.ObjC().MethodPool.end(); 8564 M != MEnd; ++M) { 8565 for (ObjCMethodList *MethList = &M->second.first; 8566 MethList && MethList->getMethod(); MethList = MethList->getNext()) { 8567 if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents)) 8568 continue; 8569 8570 if (!Selectors.insert(MethList->getMethod()->getSelector()).second) 8571 continue; 8572 8573 Result R(MethList->getMethod(), 8574 Results.getBasePriority(MethList->getMethod()), nullptr); 8575 R.StartParameter = SelIdents.size(); 8576 R.AllParametersAreInformative = false; 8577 Results.MaybeAddResult(R, SemaRef.CurContext); 8578 } 8579 } 8580 } 8581 Results.ExitScope(); 8582 8583 // If we're actually at the argument expression (rather than prior to the 8584 // selector), we're actually performing code completion for an expression. 8585 // Determine whether we have a single, best method. If so, we can 8586 // code-complete the expression using the corresponding parameter type as 8587 // our preferred type, improving completion results. 8588 if (AtArgumentExpression) { 8589 QualType PreferredType = 8590 getPreferredArgumentTypeForMessageSend(Results, SelIdents.size()); 8591 if (PreferredType.isNull()) 8592 CodeCompleteOrdinaryName(S, PCC_Expression); 8593 else 8594 CodeCompleteExpression(S, PreferredType); 8595 return; 8596 } 8597 8598 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 8599 Results.getCompletionContext(), Results.data(), 8600 Results.size()); 8601 } 8602 8603 void SemaCodeCompletion::CodeCompleteObjCForCollection( 8604 Scope *S, DeclGroupPtrTy IterationVar) { 8605 CodeCompleteExpressionData Data; 8606 Data.ObjCCollection = true; 8607 8608 if (IterationVar.getAsOpaquePtr()) { 8609 DeclGroupRef DG = IterationVar.get(); 8610 for (DeclGroupRef::iterator I = DG.begin(), End = DG.end(); I != End; ++I) { 8611 if (*I) 8612 Data.IgnoreDecls.push_back(*I); 8613 } 8614 } 8615 8616 CodeCompleteExpression(S, Data); 8617 } 8618 8619 void SemaCodeCompletion::CodeCompleteObjCSelector( 8620 Scope *S, ArrayRef<const IdentifierInfo *> SelIdents) { 8621 // If we have an external source, load the entire class method 8622 // pool from the AST file. 8623 if (SemaRef.ExternalSource) { 8624 for (uint32_t I = 0, N = SemaRef.ExternalSource->GetNumExternalSelectors(); 8625 I != N; ++I) { 8626 Selector Sel = SemaRef.ExternalSource->GetExternalSelector(I); 8627 if (Sel.isNull() || SemaRef.ObjC().MethodPool.count(Sel)) 8628 continue; 8629 8630 SemaRef.ObjC().ReadMethodPool(Sel); 8631 } 8632 } 8633 8634 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(), 8635 CodeCompleter->getCodeCompletionTUInfo(), 8636 CodeCompletionContext::CCC_SelectorName); 8637 Results.EnterNewScope(); 8638 for (SemaObjC::GlobalMethodPool::iterator 8639 M = SemaRef.ObjC().MethodPool.begin(), 8640 MEnd = SemaRef.ObjC().MethodPool.end(); 8641 M != MEnd; ++M) { 8642 8643 Selector Sel = M->first; 8644 if (!isAcceptableObjCSelector(Sel, MK_Any, SelIdents)) 8645 continue; 8646 8647 CodeCompletionBuilder Builder(Results.getAllocator(), 8648 Results.getCodeCompletionTUInfo()); 8649 if (Sel.isUnarySelector()) { 8650 Builder.AddTypedTextChunk( 8651 Builder.getAllocator().CopyString(Sel.getNameForSlot(0))); 8652 Results.AddResult(Builder.TakeString()); 8653 continue; 8654 } 8655 8656 std::string Accumulator; 8657 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I) { 8658 if (I == SelIdents.size()) { 8659 if (!Accumulator.empty()) { 8660 Builder.AddInformativeChunk( 8661 Builder.getAllocator().CopyString(Accumulator)); 8662 Accumulator.clear(); 8663 } 8664 } 8665 8666 Accumulator += Sel.getNameForSlot(I); 8667 Accumulator += ':'; 8668 } 8669 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(Accumulator)); 8670 Results.AddResult(Builder.TakeString()); 8671 } 8672 Results.ExitScope(); 8673 8674 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 8675 Results.getCompletionContext(), Results.data(), 8676 Results.size()); 8677 } 8678 8679 /// Add all of the protocol declarations that we find in the given 8680 /// (translation unit) context. 8681 static void AddProtocolResults(DeclContext *Ctx, DeclContext *CurContext, 8682 bool OnlyForwardDeclarations, 8683 ResultBuilder &Results) { 8684 typedef CodeCompletionResult Result; 8685 8686 for (const auto *D : Ctx->decls()) { 8687 // Record any protocols we find. 8688 if (const auto *Proto = dyn_cast<ObjCProtocolDecl>(D)) 8689 if (!OnlyForwardDeclarations || !Proto->hasDefinition()) 8690 Results.AddResult( 8691 Result(Proto, Results.getBasePriority(Proto), nullptr), CurContext, 8692 nullptr, false); 8693 } 8694 } 8695 8696 void SemaCodeCompletion::CodeCompleteObjCProtocolReferences( 8697 ArrayRef<IdentifierLocPair> Protocols) { 8698 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(), 8699 CodeCompleter->getCodeCompletionTUInfo(), 8700 CodeCompletionContext::CCC_ObjCProtocolName); 8701 8702 if (CodeCompleter->includeGlobals()) { 8703 Results.EnterNewScope(); 8704 8705 // Tell the result set to ignore all of the protocols we have 8706 // already seen. 8707 // FIXME: This doesn't work when caching code-completion results. 8708 for (const IdentifierLocPair &Pair : Protocols) 8709 if (ObjCProtocolDecl *Protocol = 8710 SemaRef.ObjC().LookupProtocol(Pair.first, Pair.second)) 8711 Results.Ignore(Protocol); 8712 8713 // Add all protocols. 8714 AddProtocolResults(getASTContext().getTranslationUnitDecl(), 8715 SemaRef.CurContext, false, Results); 8716 8717 Results.ExitScope(); 8718 } 8719 8720 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 8721 Results.getCompletionContext(), Results.data(), 8722 Results.size()); 8723 } 8724 8725 void SemaCodeCompletion::CodeCompleteObjCProtocolDecl(Scope *) { 8726 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(), 8727 CodeCompleter->getCodeCompletionTUInfo(), 8728 CodeCompletionContext::CCC_ObjCProtocolName); 8729 8730 if (CodeCompleter->includeGlobals()) { 8731 Results.EnterNewScope(); 8732 8733 // Add all protocols. 8734 AddProtocolResults(getASTContext().getTranslationUnitDecl(), 8735 SemaRef.CurContext, true, Results); 8736 8737 Results.ExitScope(); 8738 } 8739 8740 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 8741 Results.getCompletionContext(), Results.data(), 8742 Results.size()); 8743 } 8744 8745 /// Add all of the Objective-C interface declarations that we find in 8746 /// the given (translation unit) context. 8747 static void AddInterfaceResults(DeclContext *Ctx, DeclContext *CurContext, 8748 bool OnlyForwardDeclarations, 8749 bool OnlyUnimplemented, 8750 ResultBuilder &Results) { 8751 typedef CodeCompletionResult Result; 8752 8753 for (const auto *D : Ctx->decls()) { 8754 // Record any interfaces we find. 8755 if (const auto *Class = dyn_cast<ObjCInterfaceDecl>(D)) 8756 if ((!OnlyForwardDeclarations || !Class->hasDefinition()) && 8757 (!OnlyUnimplemented || !Class->getImplementation())) 8758 Results.AddResult( 8759 Result(Class, Results.getBasePriority(Class), nullptr), CurContext, 8760 nullptr, false); 8761 } 8762 } 8763 8764 void SemaCodeCompletion::CodeCompleteObjCInterfaceDecl(Scope *S) { 8765 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(), 8766 CodeCompleter->getCodeCompletionTUInfo(), 8767 CodeCompletionContext::CCC_ObjCInterfaceName); 8768 Results.EnterNewScope(); 8769 8770 if (CodeCompleter->includeGlobals()) { 8771 // Add all classes. 8772 AddInterfaceResults(getASTContext().getTranslationUnitDecl(), 8773 SemaRef.CurContext, false, false, Results); 8774 } 8775 8776 Results.ExitScope(); 8777 8778 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 8779 Results.getCompletionContext(), Results.data(), 8780 Results.size()); 8781 } 8782 8783 void SemaCodeCompletion::CodeCompleteObjCClassForwardDecl(Scope *S) { 8784 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(), 8785 CodeCompleter->getCodeCompletionTUInfo(), 8786 CodeCompletionContext::CCC_ObjCClassForwardDecl); 8787 Results.EnterNewScope(); 8788 8789 if (CodeCompleter->includeGlobals()) { 8790 // Add all classes. 8791 AddInterfaceResults(getASTContext().getTranslationUnitDecl(), 8792 SemaRef.CurContext, false, false, Results); 8793 } 8794 8795 Results.ExitScope(); 8796 8797 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 8798 Results.getCompletionContext(), Results.data(), 8799 Results.size()); 8800 } 8801 8802 void SemaCodeCompletion::CodeCompleteObjCSuperclass( 8803 Scope *S, IdentifierInfo *ClassName, SourceLocation ClassNameLoc) { 8804 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(), 8805 CodeCompleter->getCodeCompletionTUInfo(), 8806 CodeCompletionContext::CCC_ObjCInterfaceName); 8807 Results.EnterNewScope(); 8808 8809 // Make sure that we ignore the class we're currently defining. 8810 NamedDecl *CurClass = SemaRef.LookupSingleName( 8811 SemaRef.TUScope, ClassName, ClassNameLoc, Sema::LookupOrdinaryName); 8812 if (CurClass && isa<ObjCInterfaceDecl>(CurClass)) 8813 Results.Ignore(CurClass); 8814 8815 if (CodeCompleter->includeGlobals()) { 8816 // Add all classes. 8817 AddInterfaceResults(getASTContext().getTranslationUnitDecl(), 8818 SemaRef.CurContext, false, false, Results); 8819 } 8820 8821 Results.ExitScope(); 8822 8823 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 8824 Results.getCompletionContext(), Results.data(), 8825 Results.size()); 8826 } 8827 8828 void SemaCodeCompletion::CodeCompleteObjCImplementationDecl(Scope *S) { 8829 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(), 8830 CodeCompleter->getCodeCompletionTUInfo(), 8831 CodeCompletionContext::CCC_ObjCImplementation); 8832 Results.EnterNewScope(); 8833 8834 if (CodeCompleter->includeGlobals()) { 8835 // Add all unimplemented classes. 8836 AddInterfaceResults(getASTContext().getTranslationUnitDecl(), 8837 SemaRef.CurContext, false, true, Results); 8838 } 8839 8840 Results.ExitScope(); 8841 8842 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 8843 Results.getCompletionContext(), Results.data(), 8844 Results.size()); 8845 } 8846 8847 void SemaCodeCompletion::CodeCompleteObjCInterfaceCategory( 8848 Scope *S, IdentifierInfo *ClassName, SourceLocation ClassNameLoc) { 8849 typedef CodeCompletionResult Result; 8850 8851 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(), 8852 CodeCompleter->getCodeCompletionTUInfo(), 8853 CodeCompletionContext::CCC_ObjCCategoryName); 8854 8855 // Ignore any categories we find that have already been implemented by this 8856 // interface. 8857 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames; 8858 NamedDecl *CurClass = SemaRef.LookupSingleName( 8859 SemaRef.TUScope, ClassName, ClassNameLoc, Sema::LookupOrdinaryName); 8860 if (ObjCInterfaceDecl *Class = 8861 dyn_cast_or_null<ObjCInterfaceDecl>(CurClass)) { 8862 for (const auto *Cat : Class->visible_categories()) 8863 CategoryNames.insert(Cat->getIdentifier()); 8864 } 8865 8866 // Add all of the categories we know about. 8867 Results.EnterNewScope(); 8868 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 8869 for (const auto *D : TU->decls()) 8870 if (const auto *Category = dyn_cast<ObjCCategoryDecl>(D)) 8871 if (CategoryNames.insert(Category->getIdentifier()).second) 8872 Results.AddResult( 8873 Result(Category, Results.getBasePriority(Category), nullptr), 8874 SemaRef.CurContext, nullptr, false); 8875 Results.ExitScope(); 8876 8877 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 8878 Results.getCompletionContext(), Results.data(), 8879 Results.size()); 8880 } 8881 8882 void SemaCodeCompletion::CodeCompleteObjCImplementationCategory( 8883 Scope *S, IdentifierInfo *ClassName, SourceLocation ClassNameLoc) { 8884 typedef CodeCompletionResult Result; 8885 8886 // Find the corresponding interface. If we couldn't find the interface, the 8887 // program itself is ill-formed. However, we'll try to be helpful still by 8888 // providing the list of all of the categories we know about. 8889 NamedDecl *CurClass = SemaRef.LookupSingleName( 8890 SemaRef.TUScope, ClassName, ClassNameLoc, Sema::LookupOrdinaryName); 8891 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass); 8892 if (!Class) 8893 return CodeCompleteObjCInterfaceCategory(S, ClassName, ClassNameLoc); 8894 8895 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(), 8896 CodeCompleter->getCodeCompletionTUInfo(), 8897 CodeCompletionContext::CCC_ObjCCategoryName); 8898 8899 // Add all of the categories that have corresponding interface 8900 // declarations in this class and any of its superclasses, except for 8901 // already-implemented categories in the class itself. 8902 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames; 8903 Results.EnterNewScope(); 8904 bool IgnoreImplemented = true; 8905 while (Class) { 8906 for (const auto *Cat : Class->visible_categories()) { 8907 if ((!IgnoreImplemented || !Cat->getImplementation()) && 8908 CategoryNames.insert(Cat->getIdentifier()).second) 8909 Results.AddResult(Result(Cat, Results.getBasePriority(Cat), nullptr), 8910 SemaRef.CurContext, nullptr, false); 8911 } 8912 8913 Class = Class->getSuperClass(); 8914 IgnoreImplemented = false; 8915 } 8916 Results.ExitScope(); 8917 8918 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 8919 Results.getCompletionContext(), Results.data(), 8920 Results.size()); 8921 } 8922 8923 void SemaCodeCompletion::CodeCompleteObjCPropertyDefinition(Scope *S) { 8924 CodeCompletionContext CCContext(CodeCompletionContext::CCC_Other); 8925 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(), 8926 CodeCompleter->getCodeCompletionTUInfo(), CCContext); 8927 8928 // Figure out where this @synthesize lives. 8929 ObjCContainerDecl *Container = 8930 dyn_cast_or_null<ObjCContainerDecl>(SemaRef.CurContext); 8931 if (!Container || (!isa<ObjCImplementationDecl>(Container) && 8932 !isa<ObjCCategoryImplDecl>(Container))) 8933 return; 8934 8935 // Ignore any properties that have already been implemented. 8936 Container = getContainerDef(Container); 8937 for (const auto *D : Container->decls()) 8938 if (const auto *PropertyImpl = dyn_cast<ObjCPropertyImplDecl>(D)) 8939 Results.Ignore(PropertyImpl->getPropertyDecl()); 8940 8941 // Add any properties that we find. 8942 AddedPropertiesSet AddedProperties; 8943 Results.EnterNewScope(); 8944 if (ObjCImplementationDecl *ClassImpl = 8945 dyn_cast<ObjCImplementationDecl>(Container)) 8946 AddObjCProperties(CCContext, ClassImpl->getClassInterface(), false, 8947 /*AllowNullaryMethods=*/false, SemaRef.CurContext, 8948 AddedProperties, Results); 8949 else 8950 AddObjCProperties(CCContext, 8951 cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl(), 8952 false, /*AllowNullaryMethods=*/false, SemaRef.CurContext, 8953 AddedProperties, Results); 8954 Results.ExitScope(); 8955 8956 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 8957 Results.getCompletionContext(), Results.data(), 8958 Results.size()); 8959 } 8960 8961 void SemaCodeCompletion::CodeCompleteObjCPropertySynthesizeIvar( 8962 Scope *S, IdentifierInfo *PropertyName) { 8963 typedef CodeCompletionResult Result; 8964 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(), 8965 CodeCompleter->getCodeCompletionTUInfo(), 8966 CodeCompletionContext::CCC_Other); 8967 8968 // Figure out where this @synthesize lives. 8969 ObjCContainerDecl *Container = 8970 dyn_cast_or_null<ObjCContainerDecl>(SemaRef.CurContext); 8971 if (!Container || (!isa<ObjCImplementationDecl>(Container) && 8972 !isa<ObjCCategoryImplDecl>(Container))) 8973 return; 8974 8975 // Figure out which interface we're looking into. 8976 ObjCInterfaceDecl *Class = nullptr; 8977 if (ObjCImplementationDecl *ClassImpl = 8978 dyn_cast<ObjCImplementationDecl>(Container)) 8979 Class = ClassImpl->getClassInterface(); 8980 else 8981 Class = cast<ObjCCategoryImplDecl>(Container) 8982 ->getCategoryDecl() 8983 ->getClassInterface(); 8984 8985 // Determine the type of the property we're synthesizing. 8986 QualType PropertyType = getASTContext().getObjCIdType(); 8987 if (Class) { 8988 if (ObjCPropertyDecl *Property = Class->FindPropertyDeclaration( 8989 PropertyName, ObjCPropertyQueryKind::OBJC_PR_query_instance)) { 8990 PropertyType = 8991 Property->getType().getNonReferenceType().getUnqualifiedType(); 8992 8993 // Give preference to ivars 8994 Results.setPreferredType(PropertyType); 8995 } 8996 } 8997 8998 // Add all of the instance variables in this class and its superclasses. 8999 Results.EnterNewScope(); 9000 bool SawSimilarlyNamedIvar = false; 9001 std::string NameWithPrefix; 9002 NameWithPrefix += '_'; 9003 NameWithPrefix += PropertyName->getName(); 9004 std::string NameWithSuffix = PropertyName->getName().str(); 9005 NameWithSuffix += '_'; 9006 for (; Class; Class = Class->getSuperClass()) { 9007 for (ObjCIvarDecl *Ivar = Class->all_declared_ivar_begin(); Ivar; 9008 Ivar = Ivar->getNextIvar()) { 9009 Results.AddResult(Result(Ivar, Results.getBasePriority(Ivar), nullptr), 9010 SemaRef.CurContext, nullptr, false); 9011 9012 // Determine whether we've seen an ivar with a name similar to the 9013 // property. 9014 if ((PropertyName == Ivar->getIdentifier() || 9015 NameWithPrefix == Ivar->getName() || 9016 NameWithSuffix == Ivar->getName())) { 9017 SawSimilarlyNamedIvar = true; 9018 9019 // Reduce the priority of this result by one, to give it a slight 9020 // advantage over other results whose names don't match so closely. 9021 if (Results.size() && 9022 Results.data()[Results.size() - 1].Kind == 9023 CodeCompletionResult::RK_Declaration && 9024 Results.data()[Results.size() - 1].Declaration == Ivar) 9025 Results.data()[Results.size() - 1].Priority--; 9026 } 9027 } 9028 } 9029 9030 if (!SawSimilarlyNamedIvar) { 9031 // Create ivar result _propName, that the user can use to synthesize 9032 // an ivar of the appropriate type. 9033 unsigned Priority = CCP_MemberDeclaration + 1; 9034 typedef CodeCompletionResult Result; 9035 CodeCompletionAllocator &Allocator = Results.getAllocator(); 9036 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo(), 9037 Priority, CXAvailability_Available); 9038 9039 PrintingPolicy Policy = getCompletionPrintingPolicy(SemaRef); 9040 Builder.AddResultTypeChunk(GetCompletionTypeString( 9041 PropertyType, getASTContext(), Policy, Allocator)); 9042 Builder.AddTypedTextChunk(Allocator.CopyString(NameWithPrefix)); 9043 Results.AddResult( 9044 Result(Builder.TakeString(), Priority, CXCursor_ObjCIvarDecl)); 9045 } 9046 9047 Results.ExitScope(); 9048 9049 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 9050 Results.getCompletionContext(), Results.data(), 9051 Results.size()); 9052 } 9053 9054 // Mapping from selectors to the methods that implement that selector, along 9055 // with the "in original class" flag. 9056 typedef llvm::DenseMap<Selector, 9057 llvm::PointerIntPair<ObjCMethodDecl *, 1, bool>> 9058 KnownMethodsMap; 9059 9060 /// Find all of the methods that reside in the given container 9061 /// (and its superclasses, protocols, etc.) that meet the given 9062 /// criteria. Insert those methods into the map of known methods, 9063 /// indexed by selector so they can be easily found. 9064 static void FindImplementableMethods(ASTContext &Context, 9065 ObjCContainerDecl *Container, 9066 std::optional<bool> WantInstanceMethods, 9067 QualType ReturnType, 9068 KnownMethodsMap &KnownMethods, 9069 bool InOriginalClass = true) { 9070 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)) { 9071 // Make sure we have a definition; that's what we'll walk. 9072 if (!IFace->hasDefinition()) 9073 return; 9074 9075 IFace = IFace->getDefinition(); 9076 Container = IFace; 9077 9078 const ObjCList<ObjCProtocolDecl> &Protocols = 9079 IFace->getReferencedProtocols(); 9080 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(), 9081 E = Protocols.end(); 9082 I != E; ++I) 9083 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType, 9084 KnownMethods, InOriginalClass); 9085 9086 // Add methods from any class extensions and categories. 9087 for (auto *Cat : IFace->visible_categories()) { 9088 FindImplementableMethods(Context, Cat, WantInstanceMethods, ReturnType, 9089 KnownMethods, false); 9090 } 9091 9092 // Visit the superclass. 9093 if (IFace->getSuperClass()) 9094 FindImplementableMethods(Context, IFace->getSuperClass(), 9095 WantInstanceMethods, ReturnType, KnownMethods, 9096 false); 9097 } 9098 9099 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) { 9100 // Recurse into protocols. 9101 const ObjCList<ObjCProtocolDecl> &Protocols = 9102 Category->getReferencedProtocols(); 9103 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(), 9104 E = Protocols.end(); 9105 I != E; ++I) 9106 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType, 9107 KnownMethods, InOriginalClass); 9108 9109 // If this category is the original class, jump to the interface. 9110 if (InOriginalClass && Category->getClassInterface()) 9111 FindImplementableMethods(Context, Category->getClassInterface(), 9112 WantInstanceMethods, ReturnType, KnownMethods, 9113 false); 9114 } 9115 9116 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) { 9117 // Make sure we have a definition; that's what we'll walk. 9118 if (!Protocol->hasDefinition()) 9119 return; 9120 Protocol = Protocol->getDefinition(); 9121 Container = Protocol; 9122 9123 // Recurse into protocols. 9124 const ObjCList<ObjCProtocolDecl> &Protocols = 9125 Protocol->getReferencedProtocols(); 9126 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(), 9127 E = Protocols.end(); 9128 I != E; ++I) 9129 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType, 9130 KnownMethods, false); 9131 } 9132 9133 // Add methods in this container. This operation occurs last because 9134 // we want the methods from this container to override any methods 9135 // we've previously seen with the same selector. 9136 for (auto *M : Container->methods()) { 9137 if (!WantInstanceMethods || M->isInstanceMethod() == *WantInstanceMethods) { 9138 if (!ReturnType.isNull() && 9139 !Context.hasSameUnqualifiedType(ReturnType, M->getReturnType())) 9140 continue; 9141 9142 KnownMethods[M->getSelector()] = 9143 KnownMethodsMap::mapped_type(M, InOriginalClass); 9144 } 9145 } 9146 } 9147 9148 /// Add the parenthesized return or parameter type chunk to a code 9149 /// completion string. 9150 static void AddObjCPassingTypeChunk(QualType Type, unsigned ObjCDeclQuals, 9151 ASTContext &Context, 9152 const PrintingPolicy &Policy, 9153 CodeCompletionBuilder &Builder) { 9154 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 9155 std::string Quals = formatObjCParamQualifiers(ObjCDeclQuals, Type); 9156 if (!Quals.empty()) 9157 Builder.AddTextChunk(Builder.getAllocator().CopyString(Quals)); 9158 Builder.AddTextChunk( 9159 GetCompletionTypeString(Type, Context, Policy, Builder.getAllocator())); 9160 Builder.AddChunk(CodeCompletionString::CK_RightParen); 9161 } 9162 9163 /// Determine whether the given class is or inherits from a class by 9164 /// the given name. 9165 static bool InheritsFromClassNamed(ObjCInterfaceDecl *Class, StringRef Name) { 9166 if (!Class) 9167 return false; 9168 9169 if (Class->getIdentifier() && Class->getIdentifier()->getName() == Name) 9170 return true; 9171 9172 return InheritsFromClassNamed(Class->getSuperClass(), Name); 9173 } 9174 9175 /// Add code completions for Objective-C Key-Value Coding (KVC) and 9176 /// Key-Value Observing (KVO). 9177 static void AddObjCKeyValueCompletions(ObjCPropertyDecl *Property, 9178 bool IsInstanceMethod, 9179 QualType ReturnType, ASTContext &Context, 9180 VisitedSelectorSet &KnownSelectors, 9181 ResultBuilder &Results) { 9182 IdentifierInfo *PropName = Property->getIdentifier(); 9183 if (!PropName || PropName->getLength() == 0) 9184 return; 9185 9186 PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema()); 9187 9188 // Builder that will create each code completion. 9189 typedef CodeCompletionResult Result; 9190 CodeCompletionAllocator &Allocator = Results.getAllocator(); 9191 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo()); 9192 9193 // The selector table. 9194 SelectorTable &Selectors = Context.Selectors; 9195 9196 // The property name, copied into the code completion allocation region 9197 // on demand. 9198 struct KeyHolder { 9199 CodeCompletionAllocator &Allocator; 9200 StringRef Key; 9201 const char *CopiedKey; 9202 9203 KeyHolder(CodeCompletionAllocator &Allocator, StringRef Key) 9204 : Allocator(Allocator), Key(Key), CopiedKey(nullptr) {} 9205 9206 operator const char *() { 9207 if (CopiedKey) 9208 return CopiedKey; 9209 9210 return CopiedKey = Allocator.CopyString(Key); 9211 } 9212 } Key(Allocator, PropName->getName()); 9213 9214 // The uppercased name of the property name. 9215 std::string UpperKey = std::string(PropName->getName()); 9216 if (!UpperKey.empty()) 9217 UpperKey[0] = toUppercase(UpperKey[0]); 9218 9219 bool ReturnTypeMatchesProperty = 9220 ReturnType.isNull() || 9221 Context.hasSameUnqualifiedType(ReturnType.getNonReferenceType(), 9222 Property->getType()); 9223 bool ReturnTypeMatchesVoid = ReturnType.isNull() || ReturnType->isVoidType(); 9224 9225 // Add the normal accessor -(type)key. 9226 if (IsInstanceMethod && 9227 KnownSelectors.insert(Selectors.getNullarySelector(PropName)).second && 9228 ReturnTypeMatchesProperty && !Property->getGetterMethodDecl()) { 9229 if (ReturnType.isNull()) 9230 AddObjCPassingTypeChunk(Property->getType(), /*Quals=*/0, Context, Policy, 9231 Builder); 9232 9233 Builder.AddTypedTextChunk(Key); 9234 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern, 9235 CXCursor_ObjCInstanceMethodDecl)); 9236 } 9237 9238 // If we have an integral or boolean property (or the user has provided 9239 // an integral or boolean return type), add the accessor -(type)isKey. 9240 if (IsInstanceMethod && 9241 ((!ReturnType.isNull() && 9242 (ReturnType->isIntegerType() || ReturnType->isBooleanType())) || 9243 (ReturnType.isNull() && (Property->getType()->isIntegerType() || 9244 Property->getType()->isBooleanType())))) { 9245 std::string SelectorName = (Twine("is") + UpperKey).str(); 9246 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 9247 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId)) 9248 .second) { 9249 if (ReturnType.isNull()) { 9250 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 9251 Builder.AddTextChunk("BOOL"); 9252 Builder.AddChunk(CodeCompletionString::CK_RightParen); 9253 } 9254 9255 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorId->getName())); 9256 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern, 9257 CXCursor_ObjCInstanceMethodDecl)); 9258 } 9259 } 9260 9261 // Add the normal mutator. 9262 if (IsInstanceMethod && ReturnTypeMatchesVoid && 9263 !Property->getSetterMethodDecl()) { 9264 std::string SelectorName = (Twine("set") + UpperKey).str(); 9265 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 9266 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 9267 if (ReturnType.isNull()) { 9268 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 9269 Builder.AddTextChunk("void"); 9270 Builder.AddChunk(CodeCompletionString::CK_RightParen); 9271 } 9272 9273 Builder.AddTypedTextChunk( 9274 Allocator.CopyString(SelectorId->getName() + ":")); 9275 AddObjCPassingTypeChunk(Property->getType(), /*Quals=*/0, Context, Policy, 9276 Builder); 9277 Builder.AddTextChunk(Key); 9278 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern, 9279 CXCursor_ObjCInstanceMethodDecl)); 9280 } 9281 } 9282 9283 // Indexed and unordered accessors 9284 unsigned IndexedGetterPriority = CCP_CodePattern; 9285 unsigned IndexedSetterPriority = CCP_CodePattern; 9286 unsigned UnorderedGetterPriority = CCP_CodePattern; 9287 unsigned UnorderedSetterPriority = CCP_CodePattern; 9288 if (const auto *ObjCPointer = 9289 Property->getType()->getAs<ObjCObjectPointerType>()) { 9290 if (ObjCInterfaceDecl *IFace = ObjCPointer->getInterfaceDecl()) { 9291 // If this interface type is not provably derived from a known 9292 // collection, penalize the corresponding completions. 9293 if (!InheritsFromClassNamed(IFace, "NSMutableArray")) { 9294 IndexedSetterPriority += CCD_ProbablyNotObjCCollection; 9295 if (!InheritsFromClassNamed(IFace, "NSArray")) 9296 IndexedGetterPriority += CCD_ProbablyNotObjCCollection; 9297 } 9298 9299 if (!InheritsFromClassNamed(IFace, "NSMutableSet")) { 9300 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection; 9301 if (!InheritsFromClassNamed(IFace, "NSSet")) 9302 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection; 9303 } 9304 } 9305 } else { 9306 IndexedGetterPriority += CCD_ProbablyNotObjCCollection; 9307 IndexedSetterPriority += CCD_ProbablyNotObjCCollection; 9308 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection; 9309 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection; 9310 } 9311 9312 // Add -(NSUInteger)countOf<key> 9313 if (IsInstanceMethod && 9314 (ReturnType.isNull() || ReturnType->isIntegerType())) { 9315 std::string SelectorName = (Twine("countOf") + UpperKey).str(); 9316 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 9317 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId)) 9318 .second) { 9319 if (ReturnType.isNull()) { 9320 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 9321 Builder.AddTextChunk("NSUInteger"); 9322 Builder.AddChunk(CodeCompletionString::CK_RightParen); 9323 } 9324 9325 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorId->getName())); 9326 Results.AddResult( 9327 Result(Builder.TakeString(), 9328 std::min(IndexedGetterPriority, UnorderedGetterPriority), 9329 CXCursor_ObjCInstanceMethodDecl)); 9330 } 9331 } 9332 9333 // Indexed getters 9334 // Add -(id)objectInKeyAtIndex:(NSUInteger)index 9335 if (IsInstanceMethod && 9336 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) { 9337 std::string SelectorName = (Twine("objectIn") + UpperKey + "AtIndex").str(); 9338 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 9339 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 9340 if (ReturnType.isNull()) { 9341 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 9342 Builder.AddTextChunk("id"); 9343 Builder.AddChunk(CodeCompletionString::CK_RightParen); 9344 } 9345 9346 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 9347 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 9348 Builder.AddTextChunk("NSUInteger"); 9349 Builder.AddChunk(CodeCompletionString::CK_RightParen); 9350 Builder.AddTextChunk("index"); 9351 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority, 9352 CXCursor_ObjCInstanceMethodDecl)); 9353 } 9354 } 9355 9356 // Add -(NSArray *)keyAtIndexes:(NSIndexSet *)indexes 9357 if (IsInstanceMethod && 9358 (ReturnType.isNull() || 9359 (ReturnType->isObjCObjectPointerType() && 9360 ReturnType->castAs<ObjCObjectPointerType>()->getInterfaceDecl() && 9361 ReturnType->castAs<ObjCObjectPointerType>() 9362 ->getInterfaceDecl() 9363 ->getName() == "NSArray"))) { 9364 std::string SelectorName = (Twine(Property->getName()) + "AtIndexes").str(); 9365 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 9366 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 9367 if (ReturnType.isNull()) { 9368 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 9369 Builder.AddTextChunk("NSArray *"); 9370 Builder.AddChunk(CodeCompletionString::CK_RightParen); 9371 } 9372 9373 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 9374 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 9375 Builder.AddTextChunk("NSIndexSet *"); 9376 Builder.AddChunk(CodeCompletionString::CK_RightParen); 9377 Builder.AddTextChunk("indexes"); 9378 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority, 9379 CXCursor_ObjCInstanceMethodDecl)); 9380 } 9381 } 9382 9383 // Add -(void)getKey:(type **)buffer range:(NSRange)inRange 9384 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 9385 std::string SelectorName = (Twine("get") + UpperKey).str(); 9386 const IdentifierInfo *SelectorIds[2] = {&Context.Idents.get(SelectorName), 9387 &Context.Idents.get("range")}; 9388 9389 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) { 9390 if (ReturnType.isNull()) { 9391 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 9392 Builder.AddTextChunk("void"); 9393 Builder.AddChunk(CodeCompletionString::CK_RightParen); 9394 } 9395 9396 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 9397 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 9398 Builder.AddPlaceholderChunk("object-type"); 9399 Builder.AddTextChunk(" **"); 9400 Builder.AddChunk(CodeCompletionString::CK_RightParen); 9401 Builder.AddTextChunk("buffer"); 9402 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 9403 Builder.AddTypedTextChunk("range:"); 9404 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 9405 Builder.AddTextChunk("NSRange"); 9406 Builder.AddChunk(CodeCompletionString::CK_RightParen); 9407 Builder.AddTextChunk("inRange"); 9408 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority, 9409 CXCursor_ObjCInstanceMethodDecl)); 9410 } 9411 } 9412 9413 // Mutable indexed accessors 9414 9415 // - (void)insertObject:(type *)object inKeyAtIndex:(NSUInteger)index 9416 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 9417 std::string SelectorName = (Twine("in") + UpperKey + "AtIndex").str(); 9418 const IdentifierInfo *SelectorIds[2] = {&Context.Idents.get("insertObject"), 9419 &Context.Idents.get(SelectorName)}; 9420 9421 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) { 9422 if (ReturnType.isNull()) { 9423 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 9424 Builder.AddTextChunk("void"); 9425 Builder.AddChunk(CodeCompletionString::CK_RightParen); 9426 } 9427 9428 Builder.AddTypedTextChunk("insertObject:"); 9429 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 9430 Builder.AddPlaceholderChunk("object-type"); 9431 Builder.AddTextChunk(" *"); 9432 Builder.AddChunk(CodeCompletionString::CK_RightParen); 9433 Builder.AddTextChunk("object"); 9434 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 9435 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 9436 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 9437 Builder.AddPlaceholderChunk("NSUInteger"); 9438 Builder.AddChunk(CodeCompletionString::CK_RightParen); 9439 Builder.AddTextChunk("index"); 9440 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority, 9441 CXCursor_ObjCInstanceMethodDecl)); 9442 } 9443 } 9444 9445 // - (void)insertKey:(NSArray *)array atIndexes:(NSIndexSet *)indexes 9446 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 9447 std::string SelectorName = (Twine("insert") + UpperKey).str(); 9448 const IdentifierInfo *SelectorIds[2] = {&Context.Idents.get(SelectorName), 9449 &Context.Idents.get("atIndexes")}; 9450 9451 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) { 9452 if (ReturnType.isNull()) { 9453 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 9454 Builder.AddTextChunk("void"); 9455 Builder.AddChunk(CodeCompletionString::CK_RightParen); 9456 } 9457 9458 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 9459 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 9460 Builder.AddTextChunk("NSArray *"); 9461 Builder.AddChunk(CodeCompletionString::CK_RightParen); 9462 Builder.AddTextChunk("array"); 9463 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 9464 Builder.AddTypedTextChunk("atIndexes:"); 9465 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 9466 Builder.AddPlaceholderChunk("NSIndexSet *"); 9467 Builder.AddChunk(CodeCompletionString::CK_RightParen); 9468 Builder.AddTextChunk("indexes"); 9469 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority, 9470 CXCursor_ObjCInstanceMethodDecl)); 9471 } 9472 } 9473 9474 // -(void)removeObjectFromKeyAtIndex:(NSUInteger)index 9475 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 9476 std::string SelectorName = 9477 (Twine("removeObjectFrom") + UpperKey + "AtIndex").str(); 9478 const IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 9479 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 9480 if (ReturnType.isNull()) { 9481 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 9482 Builder.AddTextChunk("void"); 9483 Builder.AddChunk(CodeCompletionString::CK_RightParen); 9484 } 9485 9486 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 9487 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 9488 Builder.AddTextChunk("NSUInteger"); 9489 Builder.AddChunk(CodeCompletionString::CK_RightParen); 9490 Builder.AddTextChunk("index"); 9491 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority, 9492 CXCursor_ObjCInstanceMethodDecl)); 9493 } 9494 } 9495 9496 // -(void)removeKeyAtIndexes:(NSIndexSet *)indexes 9497 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 9498 std::string SelectorName = (Twine("remove") + UpperKey + "AtIndexes").str(); 9499 const IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 9500 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 9501 if (ReturnType.isNull()) { 9502 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 9503 Builder.AddTextChunk("void"); 9504 Builder.AddChunk(CodeCompletionString::CK_RightParen); 9505 } 9506 9507 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 9508 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 9509 Builder.AddTextChunk("NSIndexSet *"); 9510 Builder.AddChunk(CodeCompletionString::CK_RightParen); 9511 Builder.AddTextChunk("indexes"); 9512 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority, 9513 CXCursor_ObjCInstanceMethodDecl)); 9514 } 9515 } 9516 9517 // - (void)replaceObjectInKeyAtIndex:(NSUInteger)index withObject:(id)object 9518 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 9519 std::string SelectorName = 9520 (Twine("replaceObjectIn") + UpperKey + "AtIndex").str(); 9521 const IdentifierInfo *SelectorIds[2] = {&Context.Idents.get(SelectorName), 9522 &Context.Idents.get("withObject")}; 9523 9524 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) { 9525 if (ReturnType.isNull()) { 9526 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 9527 Builder.AddTextChunk("void"); 9528 Builder.AddChunk(CodeCompletionString::CK_RightParen); 9529 } 9530 9531 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 9532 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 9533 Builder.AddPlaceholderChunk("NSUInteger"); 9534 Builder.AddChunk(CodeCompletionString::CK_RightParen); 9535 Builder.AddTextChunk("index"); 9536 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 9537 Builder.AddTypedTextChunk("withObject:"); 9538 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 9539 Builder.AddTextChunk("id"); 9540 Builder.AddChunk(CodeCompletionString::CK_RightParen); 9541 Builder.AddTextChunk("object"); 9542 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority, 9543 CXCursor_ObjCInstanceMethodDecl)); 9544 } 9545 } 9546 9547 // - (void)replaceKeyAtIndexes:(NSIndexSet *)indexes withKey:(NSArray *)array 9548 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 9549 std::string SelectorName1 = 9550 (Twine("replace") + UpperKey + "AtIndexes").str(); 9551 std::string SelectorName2 = (Twine("with") + UpperKey).str(); 9552 const IdentifierInfo *SelectorIds[2] = {&Context.Idents.get(SelectorName1), 9553 &Context.Idents.get(SelectorName2)}; 9554 9555 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) { 9556 if (ReturnType.isNull()) { 9557 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 9558 Builder.AddTextChunk("void"); 9559 Builder.AddChunk(CodeCompletionString::CK_RightParen); 9560 } 9561 9562 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName1 + ":")); 9563 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 9564 Builder.AddPlaceholderChunk("NSIndexSet *"); 9565 Builder.AddChunk(CodeCompletionString::CK_RightParen); 9566 Builder.AddTextChunk("indexes"); 9567 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 9568 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName2 + ":")); 9569 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 9570 Builder.AddTextChunk("NSArray *"); 9571 Builder.AddChunk(CodeCompletionString::CK_RightParen); 9572 Builder.AddTextChunk("array"); 9573 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority, 9574 CXCursor_ObjCInstanceMethodDecl)); 9575 } 9576 } 9577 9578 // Unordered getters 9579 // - (NSEnumerator *)enumeratorOfKey 9580 if (IsInstanceMethod && 9581 (ReturnType.isNull() || 9582 (ReturnType->isObjCObjectPointerType() && 9583 ReturnType->castAs<ObjCObjectPointerType>()->getInterfaceDecl() && 9584 ReturnType->castAs<ObjCObjectPointerType>() 9585 ->getInterfaceDecl() 9586 ->getName() == "NSEnumerator"))) { 9587 std::string SelectorName = (Twine("enumeratorOf") + UpperKey).str(); 9588 const IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 9589 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId)) 9590 .second) { 9591 if (ReturnType.isNull()) { 9592 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 9593 Builder.AddTextChunk("NSEnumerator *"); 9594 Builder.AddChunk(CodeCompletionString::CK_RightParen); 9595 } 9596 9597 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName)); 9598 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority, 9599 CXCursor_ObjCInstanceMethodDecl)); 9600 } 9601 } 9602 9603 // - (type *)memberOfKey:(type *)object 9604 if (IsInstanceMethod && 9605 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) { 9606 std::string SelectorName = (Twine("memberOf") + UpperKey).str(); 9607 const IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 9608 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 9609 if (ReturnType.isNull()) { 9610 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 9611 Builder.AddPlaceholderChunk("object-type"); 9612 Builder.AddTextChunk(" *"); 9613 Builder.AddChunk(CodeCompletionString::CK_RightParen); 9614 } 9615 9616 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 9617 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 9618 if (ReturnType.isNull()) { 9619 Builder.AddPlaceholderChunk("object-type"); 9620 Builder.AddTextChunk(" *"); 9621 } else { 9622 Builder.AddTextChunk(GetCompletionTypeString( 9623 ReturnType, Context, Policy, Builder.getAllocator())); 9624 } 9625 Builder.AddChunk(CodeCompletionString::CK_RightParen); 9626 Builder.AddTextChunk("object"); 9627 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority, 9628 CXCursor_ObjCInstanceMethodDecl)); 9629 } 9630 } 9631 9632 // Mutable unordered accessors 9633 // - (void)addKeyObject:(type *)object 9634 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 9635 std::string SelectorName = 9636 (Twine("add") + UpperKey + Twine("Object")).str(); 9637 const IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 9638 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 9639 if (ReturnType.isNull()) { 9640 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 9641 Builder.AddTextChunk("void"); 9642 Builder.AddChunk(CodeCompletionString::CK_RightParen); 9643 } 9644 9645 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 9646 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 9647 Builder.AddPlaceholderChunk("object-type"); 9648 Builder.AddTextChunk(" *"); 9649 Builder.AddChunk(CodeCompletionString::CK_RightParen); 9650 Builder.AddTextChunk("object"); 9651 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority, 9652 CXCursor_ObjCInstanceMethodDecl)); 9653 } 9654 } 9655 9656 // - (void)addKey:(NSSet *)objects 9657 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 9658 std::string SelectorName = (Twine("add") + UpperKey).str(); 9659 const IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 9660 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 9661 if (ReturnType.isNull()) { 9662 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 9663 Builder.AddTextChunk("void"); 9664 Builder.AddChunk(CodeCompletionString::CK_RightParen); 9665 } 9666 9667 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 9668 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 9669 Builder.AddTextChunk("NSSet *"); 9670 Builder.AddChunk(CodeCompletionString::CK_RightParen); 9671 Builder.AddTextChunk("objects"); 9672 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority, 9673 CXCursor_ObjCInstanceMethodDecl)); 9674 } 9675 } 9676 9677 // - (void)removeKeyObject:(type *)object 9678 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 9679 std::string SelectorName = 9680 (Twine("remove") + UpperKey + Twine("Object")).str(); 9681 const IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 9682 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 9683 if (ReturnType.isNull()) { 9684 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 9685 Builder.AddTextChunk("void"); 9686 Builder.AddChunk(CodeCompletionString::CK_RightParen); 9687 } 9688 9689 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 9690 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 9691 Builder.AddPlaceholderChunk("object-type"); 9692 Builder.AddTextChunk(" *"); 9693 Builder.AddChunk(CodeCompletionString::CK_RightParen); 9694 Builder.AddTextChunk("object"); 9695 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority, 9696 CXCursor_ObjCInstanceMethodDecl)); 9697 } 9698 } 9699 9700 // - (void)removeKey:(NSSet *)objects 9701 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 9702 std::string SelectorName = (Twine("remove") + UpperKey).str(); 9703 const IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 9704 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 9705 if (ReturnType.isNull()) { 9706 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 9707 Builder.AddTextChunk("void"); 9708 Builder.AddChunk(CodeCompletionString::CK_RightParen); 9709 } 9710 9711 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 9712 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 9713 Builder.AddTextChunk("NSSet *"); 9714 Builder.AddChunk(CodeCompletionString::CK_RightParen); 9715 Builder.AddTextChunk("objects"); 9716 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority, 9717 CXCursor_ObjCInstanceMethodDecl)); 9718 } 9719 } 9720 9721 // - (void)intersectKey:(NSSet *)objects 9722 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 9723 std::string SelectorName = (Twine("intersect") + UpperKey).str(); 9724 const IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 9725 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 9726 if (ReturnType.isNull()) { 9727 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 9728 Builder.AddTextChunk("void"); 9729 Builder.AddChunk(CodeCompletionString::CK_RightParen); 9730 } 9731 9732 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 9733 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 9734 Builder.AddTextChunk("NSSet *"); 9735 Builder.AddChunk(CodeCompletionString::CK_RightParen); 9736 Builder.AddTextChunk("objects"); 9737 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority, 9738 CXCursor_ObjCInstanceMethodDecl)); 9739 } 9740 } 9741 9742 // Key-Value Observing 9743 // + (NSSet *)keyPathsForValuesAffectingKey 9744 if (!IsInstanceMethod && 9745 (ReturnType.isNull() || 9746 (ReturnType->isObjCObjectPointerType() && 9747 ReturnType->castAs<ObjCObjectPointerType>()->getInterfaceDecl() && 9748 ReturnType->castAs<ObjCObjectPointerType>() 9749 ->getInterfaceDecl() 9750 ->getName() == "NSSet"))) { 9751 std::string SelectorName = 9752 (Twine("keyPathsForValuesAffecting") + UpperKey).str(); 9753 const IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 9754 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId)) 9755 .second) { 9756 if (ReturnType.isNull()) { 9757 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 9758 Builder.AddTextChunk("NSSet<NSString *> *"); 9759 Builder.AddChunk(CodeCompletionString::CK_RightParen); 9760 } 9761 9762 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName)); 9763 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern, 9764 CXCursor_ObjCClassMethodDecl)); 9765 } 9766 } 9767 9768 // + (BOOL)automaticallyNotifiesObserversForKey 9769 if (!IsInstanceMethod && 9770 (ReturnType.isNull() || ReturnType->isIntegerType() || 9771 ReturnType->isBooleanType())) { 9772 std::string SelectorName = 9773 (Twine("automaticallyNotifiesObserversOf") + UpperKey).str(); 9774 const IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 9775 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId)) 9776 .second) { 9777 if (ReturnType.isNull()) { 9778 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 9779 Builder.AddTextChunk("BOOL"); 9780 Builder.AddChunk(CodeCompletionString::CK_RightParen); 9781 } 9782 9783 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName)); 9784 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern, 9785 CXCursor_ObjCClassMethodDecl)); 9786 } 9787 } 9788 } 9789 9790 void SemaCodeCompletion::CodeCompleteObjCMethodDecl( 9791 Scope *S, std::optional<bool> IsInstanceMethod, ParsedType ReturnTy) { 9792 ASTContext &Context = getASTContext(); 9793 // Determine the return type of the method we're declaring, if 9794 // provided. 9795 QualType ReturnType = SemaRef.GetTypeFromParser(ReturnTy); 9796 Decl *IDecl = nullptr; 9797 if (SemaRef.CurContext->isObjCContainer()) { 9798 ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(SemaRef.CurContext); 9799 IDecl = OCD; 9800 } 9801 // Determine where we should start searching for methods. 9802 ObjCContainerDecl *SearchDecl = nullptr; 9803 bool IsInImplementation = false; 9804 if (Decl *D = IDecl) { 9805 if (ObjCImplementationDecl *Impl = dyn_cast<ObjCImplementationDecl>(D)) { 9806 SearchDecl = Impl->getClassInterface(); 9807 IsInImplementation = true; 9808 } else if (ObjCCategoryImplDecl *CatImpl = 9809 dyn_cast<ObjCCategoryImplDecl>(D)) { 9810 SearchDecl = CatImpl->getCategoryDecl(); 9811 IsInImplementation = true; 9812 } else 9813 SearchDecl = dyn_cast<ObjCContainerDecl>(D); 9814 } 9815 9816 if (!SearchDecl && S) { 9817 if (DeclContext *DC = S->getEntity()) 9818 SearchDecl = dyn_cast<ObjCContainerDecl>(DC); 9819 } 9820 9821 if (!SearchDecl) { 9822 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 9823 CodeCompletionContext::CCC_Other, nullptr, 0); 9824 return; 9825 } 9826 9827 // Find all of the methods that we could declare/implement here. 9828 KnownMethodsMap KnownMethods; 9829 FindImplementableMethods(Context, SearchDecl, IsInstanceMethod, ReturnType, 9830 KnownMethods); 9831 9832 // Add declarations or definitions for each of the known methods. 9833 typedef CodeCompletionResult Result; 9834 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(), 9835 CodeCompleter->getCodeCompletionTUInfo(), 9836 CodeCompletionContext::CCC_Other); 9837 Results.EnterNewScope(); 9838 PrintingPolicy Policy = getCompletionPrintingPolicy(SemaRef); 9839 for (KnownMethodsMap::iterator M = KnownMethods.begin(), 9840 MEnd = KnownMethods.end(); 9841 M != MEnd; ++M) { 9842 ObjCMethodDecl *Method = M->second.getPointer(); 9843 CodeCompletionBuilder Builder(Results.getAllocator(), 9844 Results.getCodeCompletionTUInfo()); 9845 9846 // Add the '-'/'+' prefix if it wasn't provided yet. 9847 if (!IsInstanceMethod) { 9848 Builder.AddTextChunk(Method->isInstanceMethod() ? "-" : "+"); 9849 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 9850 } 9851 9852 // If the result type was not already provided, add it to the 9853 // pattern as (type). 9854 if (ReturnType.isNull()) { 9855 QualType ResTy = Method->getSendResultType().stripObjCKindOfType(Context); 9856 AttributedType::stripOuterNullability(ResTy); 9857 AddObjCPassingTypeChunk(ResTy, Method->getObjCDeclQualifier(), Context, 9858 Policy, Builder); 9859 } 9860 9861 Selector Sel = Method->getSelector(); 9862 9863 if (Sel.isUnarySelector()) { 9864 // Unary selectors have no arguments. 9865 Builder.AddTypedTextChunk( 9866 Builder.getAllocator().CopyString(Sel.getNameForSlot(0))); 9867 } else { 9868 // Add all parameters to the pattern. 9869 unsigned I = 0; 9870 for (ObjCMethodDecl::param_iterator P = Method->param_begin(), 9871 PEnd = Method->param_end(); 9872 P != PEnd; (void)++P, ++I) { 9873 // Add the part of the selector name. 9874 if (I == 0) 9875 Builder.AddTypedTextChunk( 9876 Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":")); 9877 else if (I < Sel.getNumArgs()) { 9878 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 9879 Builder.AddTypedTextChunk( 9880 Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":")); 9881 } else 9882 break; 9883 9884 // Add the parameter type. 9885 QualType ParamType; 9886 if ((*P)->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 9887 ParamType = (*P)->getType(); 9888 else 9889 ParamType = (*P)->getOriginalType(); 9890 ParamType = ParamType.substObjCTypeArgs( 9891 Context, {}, ObjCSubstitutionContext::Parameter); 9892 AttributedType::stripOuterNullability(ParamType); 9893 AddObjCPassingTypeChunk(ParamType, (*P)->getObjCDeclQualifier(), 9894 Context, Policy, Builder); 9895 9896 if (IdentifierInfo *Id = (*P)->getIdentifier()) 9897 Builder.AddTextChunk( 9898 Builder.getAllocator().CopyString(Id->getName())); 9899 } 9900 } 9901 9902 if (Method->isVariadic()) { 9903 if (Method->param_size() > 0) 9904 Builder.AddChunk(CodeCompletionString::CK_Comma); 9905 Builder.AddTextChunk("..."); 9906 } 9907 9908 if (IsInImplementation && Results.includeCodePatterns()) { 9909 // We will be defining the method here, so add a compound statement. 9910 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 9911 Builder.AddChunk(CodeCompletionString::CK_LeftBrace); 9912 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); 9913 if (!Method->getReturnType()->isVoidType()) { 9914 // If the result type is not void, add a return clause. 9915 Builder.AddTextChunk("return"); 9916 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 9917 Builder.AddPlaceholderChunk("expression"); 9918 Builder.AddChunk(CodeCompletionString::CK_SemiColon); 9919 } else 9920 Builder.AddPlaceholderChunk("statements"); 9921 9922 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); 9923 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 9924 } 9925 9926 unsigned Priority = CCP_CodePattern; 9927 auto R = Result(Builder.TakeString(), Method, Priority); 9928 if (!M->second.getInt()) 9929 setInBaseClass(R); 9930 Results.AddResult(std::move(R)); 9931 } 9932 9933 // Add Key-Value-Coding and Key-Value-Observing accessor methods for all of 9934 // the properties in this class and its categories. 9935 if (Context.getLangOpts().ObjC) { 9936 SmallVector<ObjCContainerDecl *, 4> Containers; 9937 Containers.push_back(SearchDecl); 9938 9939 VisitedSelectorSet KnownSelectors; 9940 for (KnownMethodsMap::iterator M = KnownMethods.begin(), 9941 MEnd = KnownMethods.end(); 9942 M != MEnd; ++M) 9943 KnownSelectors.insert(M->first); 9944 9945 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(SearchDecl); 9946 if (!IFace) 9947 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(SearchDecl)) 9948 IFace = Category->getClassInterface(); 9949 9950 if (IFace) 9951 llvm::append_range(Containers, IFace->visible_categories()); 9952 9953 if (IsInstanceMethod) { 9954 for (unsigned I = 0, N = Containers.size(); I != N; ++I) 9955 for (auto *P : Containers[I]->instance_properties()) 9956 AddObjCKeyValueCompletions(P, *IsInstanceMethod, ReturnType, Context, 9957 KnownSelectors, Results); 9958 } 9959 } 9960 9961 Results.ExitScope(); 9962 9963 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 9964 Results.getCompletionContext(), Results.data(), 9965 Results.size()); 9966 } 9967 9968 void SemaCodeCompletion::CodeCompleteObjCMethodDeclSelector( 9969 Scope *S, bool IsInstanceMethod, bool AtParameterName, ParsedType ReturnTy, 9970 ArrayRef<const IdentifierInfo *> SelIdents) { 9971 // If we have an external source, load the entire class method 9972 // pool from the AST file. 9973 if (SemaRef.ExternalSource) { 9974 for (uint32_t I = 0, N = SemaRef.ExternalSource->GetNumExternalSelectors(); 9975 I != N; ++I) { 9976 Selector Sel = SemaRef.ExternalSource->GetExternalSelector(I); 9977 if (Sel.isNull() || SemaRef.ObjC().MethodPool.count(Sel)) 9978 continue; 9979 9980 SemaRef.ObjC().ReadMethodPool(Sel); 9981 } 9982 } 9983 9984 // Build the set of methods we can see. 9985 typedef CodeCompletionResult Result; 9986 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(), 9987 CodeCompleter->getCodeCompletionTUInfo(), 9988 CodeCompletionContext::CCC_Other); 9989 9990 if (ReturnTy) 9991 Results.setPreferredType( 9992 SemaRef.GetTypeFromParser(ReturnTy).getNonReferenceType()); 9993 9994 Results.EnterNewScope(); 9995 for (SemaObjC::GlobalMethodPool::iterator 9996 M = SemaRef.ObjC().MethodPool.begin(), 9997 MEnd = SemaRef.ObjC().MethodPool.end(); 9998 M != MEnd; ++M) { 9999 for (ObjCMethodList *MethList = IsInstanceMethod ? &M->second.first 10000 : &M->second.second; 10001 MethList && MethList->getMethod(); MethList = MethList->getNext()) { 10002 if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents)) 10003 continue; 10004 10005 if (AtParameterName) { 10006 // Suggest parameter names we've seen before. 10007 unsigned NumSelIdents = SelIdents.size(); 10008 if (NumSelIdents && 10009 NumSelIdents <= MethList->getMethod()->param_size()) { 10010 ParmVarDecl *Param = 10011 MethList->getMethod()->parameters()[NumSelIdents - 1]; 10012 if (Param->getIdentifier()) { 10013 CodeCompletionBuilder Builder(Results.getAllocator(), 10014 Results.getCodeCompletionTUInfo()); 10015 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString( 10016 Param->getIdentifier()->getName())); 10017 Results.AddResult(Builder.TakeString()); 10018 } 10019 } 10020 10021 continue; 10022 } 10023 10024 Result R(MethList->getMethod(), 10025 Results.getBasePriority(MethList->getMethod()), nullptr); 10026 R.StartParameter = SelIdents.size(); 10027 R.AllParametersAreInformative = false; 10028 R.DeclaringEntity = true; 10029 Results.MaybeAddResult(R, SemaRef.CurContext); 10030 } 10031 } 10032 10033 Results.ExitScope(); 10034 10035 if (!AtParameterName && !SelIdents.empty() && 10036 SelIdents.front()->getName().starts_with("init")) { 10037 for (const auto &M : SemaRef.PP.macros()) { 10038 if (M.first->getName() != "NS_DESIGNATED_INITIALIZER") 10039 continue; 10040 Results.EnterNewScope(); 10041 CodeCompletionBuilder Builder(Results.getAllocator(), 10042 Results.getCodeCompletionTUInfo()); 10043 Builder.AddTypedTextChunk( 10044 Builder.getAllocator().CopyString(M.first->getName())); 10045 Results.AddResult(CodeCompletionResult(Builder.TakeString(), CCP_Macro, 10046 CXCursor_MacroDefinition)); 10047 Results.ExitScope(); 10048 } 10049 } 10050 10051 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 10052 Results.getCompletionContext(), Results.data(), 10053 Results.size()); 10054 } 10055 10056 void SemaCodeCompletion::CodeCompletePreprocessorDirective(bool InConditional) { 10057 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(), 10058 CodeCompleter->getCodeCompletionTUInfo(), 10059 CodeCompletionContext::CCC_PreprocessorDirective); 10060 Results.EnterNewScope(); 10061 10062 // #if <condition> 10063 CodeCompletionBuilder Builder(Results.getAllocator(), 10064 Results.getCodeCompletionTUInfo()); 10065 Builder.AddTypedTextChunk("if"); 10066 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 10067 Builder.AddPlaceholderChunk("condition"); 10068 Results.AddResult(Builder.TakeString()); 10069 10070 // #ifdef <macro> 10071 Builder.AddTypedTextChunk("ifdef"); 10072 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 10073 Builder.AddPlaceholderChunk("macro"); 10074 Results.AddResult(Builder.TakeString()); 10075 10076 // #ifndef <macro> 10077 Builder.AddTypedTextChunk("ifndef"); 10078 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 10079 Builder.AddPlaceholderChunk("macro"); 10080 Results.AddResult(Builder.TakeString()); 10081 10082 if (InConditional) { 10083 // #elif <condition> 10084 Builder.AddTypedTextChunk("elif"); 10085 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 10086 Builder.AddPlaceholderChunk("condition"); 10087 Results.AddResult(Builder.TakeString()); 10088 10089 // #elifdef <macro> 10090 Builder.AddTypedTextChunk("elifdef"); 10091 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 10092 Builder.AddPlaceholderChunk("macro"); 10093 Results.AddResult(Builder.TakeString()); 10094 10095 // #elifndef <macro> 10096 Builder.AddTypedTextChunk("elifndef"); 10097 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 10098 Builder.AddPlaceholderChunk("macro"); 10099 Results.AddResult(Builder.TakeString()); 10100 10101 // #else 10102 Builder.AddTypedTextChunk("else"); 10103 Results.AddResult(Builder.TakeString()); 10104 10105 // #endif 10106 Builder.AddTypedTextChunk("endif"); 10107 Results.AddResult(Builder.TakeString()); 10108 } 10109 10110 // #include "header" 10111 Builder.AddTypedTextChunk("include"); 10112 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 10113 Builder.AddTextChunk("\""); 10114 Builder.AddPlaceholderChunk("header"); 10115 Builder.AddTextChunk("\""); 10116 Results.AddResult(Builder.TakeString()); 10117 10118 // #include <header> 10119 Builder.AddTypedTextChunk("include"); 10120 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 10121 Builder.AddTextChunk("<"); 10122 Builder.AddPlaceholderChunk("header"); 10123 Builder.AddTextChunk(">"); 10124 Results.AddResult(Builder.TakeString()); 10125 10126 // #define <macro> 10127 Builder.AddTypedTextChunk("define"); 10128 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 10129 Builder.AddPlaceholderChunk("macro"); 10130 Results.AddResult(Builder.TakeString()); 10131 10132 // #define <macro>(<args>) 10133 Builder.AddTypedTextChunk("define"); 10134 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 10135 Builder.AddPlaceholderChunk("macro"); 10136 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 10137 Builder.AddPlaceholderChunk("args"); 10138 Builder.AddChunk(CodeCompletionString::CK_RightParen); 10139 Results.AddResult(Builder.TakeString()); 10140 10141 // #undef <macro> 10142 Builder.AddTypedTextChunk("undef"); 10143 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 10144 Builder.AddPlaceholderChunk("macro"); 10145 Results.AddResult(Builder.TakeString()); 10146 10147 // #line <number> 10148 Builder.AddTypedTextChunk("line"); 10149 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 10150 Builder.AddPlaceholderChunk("number"); 10151 Results.AddResult(Builder.TakeString()); 10152 10153 // #line <number> "filename" 10154 Builder.AddTypedTextChunk("line"); 10155 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 10156 Builder.AddPlaceholderChunk("number"); 10157 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 10158 Builder.AddTextChunk("\""); 10159 Builder.AddPlaceholderChunk("filename"); 10160 Builder.AddTextChunk("\""); 10161 Results.AddResult(Builder.TakeString()); 10162 10163 // #error <message> 10164 Builder.AddTypedTextChunk("error"); 10165 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 10166 Builder.AddPlaceholderChunk("message"); 10167 Results.AddResult(Builder.TakeString()); 10168 10169 // #pragma <arguments> 10170 Builder.AddTypedTextChunk("pragma"); 10171 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 10172 Builder.AddPlaceholderChunk("arguments"); 10173 Results.AddResult(Builder.TakeString()); 10174 10175 if (getLangOpts().ObjC) { 10176 // #import "header" 10177 Builder.AddTypedTextChunk("import"); 10178 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 10179 Builder.AddTextChunk("\""); 10180 Builder.AddPlaceholderChunk("header"); 10181 Builder.AddTextChunk("\""); 10182 Results.AddResult(Builder.TakeString()); 10183 10184 // #import <header> 10185 Builder.AddTypedTextChunk("import"); 10186 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 10187 Builder.AddTextChunk("<"); 10188 Builder.AddPlaceholderChunk("header"); 10189 Builder.AddTextChunk(">"); 10190 Results.AddResult(Builder.TakeString()); 10191 } 10192 10193 // #include_next "header" 10194 Builder.AddTypedTextChunk("include_next"); 10195 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 10196 Builder.AddTextChunk("\""); 10197 Builder.AddPlaceholderChunk("header"); 10198 Builder.AddTextChunk("\""); 10199 Results.AddResult(Builder.TakeString()); 10200 10201 // #include_next <header> 10202 Builder.AddTypedTextChunk("include_next"); 10203 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 10204 Builder.AddTextChunk("<"); 10205 Builder.AddPlaceholderChunk("header"); 10206 Builder.AddTextChunk(">"); 10207 Results.AddResult(Builder.TakeString()); 10208 10209 // #warning <message> 10210 Builder.AddTypedTextChunk("warning"); 10211 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 10212 Builder.AddPlaceholderChunk("message"); 10213 Results.AddResult(Builder.TakeString()); 10214 10215 // Note: #ident and #sccs are such crazy anachronisms that we don't provide 10216 // completions for them. And __include_macros is a Clang-internal extension 10217 // that we don't want to encourage anyone to use. 10218 10219 // FIXME: we don't support #assert or #unassert, so don't suggest them. 10220 Results.ExitScope(); 10221 10222 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 10223 Results.getCompletionContext(), Results.data(), 10224 Results.size()); 10225 } 10226 10227 void SemaCodeCompletion::CodeCompleteInPreprocessorConditionalExclusion( 10228 Scope *S) { 10229 CodeCompleteOrdinaryName(S, S->getFnParent() 10230 ? SemaCodeCompletion::PCC_RecoveryInFunction 10231 : SemaCodeCompletion::PCC_Namespace); 10232 } 10233 10234 void SemaCodeCompletion::CodeCompletePreprocessorMacroName(bool IsDefinition) { 10235 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(), 10236 CodeCompleter->getCodeCompletionTUInfo(), 10237 IsDefinition ? CodeCompletionContext::CCC_MacroName 10238 : CodeCompletionContext::CCC_MacroNameUse); 10239 if (!IsDefinition && CodeCompleter->includeMacros()) { 10240 // Add just the names of macros, not their arguments. 10241 CodeCompletionBuilder Builder(Results.getAllocator(), 10242 Results.getCodeCompletionTUInfo()); 10243 Results.EnterNewScope(); 10244 for (Preprocessor::macro_iterator M = SemaRef.PP.macro_begin(), 10245 MEnd = SemaRef.PP.macro_end(); 10246 M != MEnd; ++M) { 10247 Builder.AddTypedTextChunk( 10248 Builder.getAllocator().CopyString(M->first->getName())); 10249 Results.AddResult(CodeCompletionResult( 10250 Builder.TakeString(), CCP_CodePattern, CXCursor_MacroDefinition)); 10251 } 10252 Results.ExitScope(); 10253 } else if (IsDefinition) { 10254 // FIXME: Can we detect when the user just wrote an include guard above? 10255 } 10256 10257 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 10258 Results.getCompletionContext(), Results.data(), 10259 Results.size()); 10260 } 10261 10262 void SemaCodeCompletion::CodeCompletePreprocessorExpression() { 10263 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(), 10264 CodeCompleter->getCodeCompletionTUInfo(), 10265 CodeCompletionContext::CCC_PreprocessorExpression); 10266 10267 if (CodeCompleter->includeMacros()) 10268 AddMacroResults(SemaRef.PP, Results, CodeCompleter->loadExternal(), true); 10269 10270 // defined (<macro>) 10271 Results.EnterNewScope(); 10272 CodeCompletionBuilder Builder(Results.getAllocator(), 10273 Results.getCodeCompletionTUInfo()); 10274 Builder.AddTypedTextChunk("defined"); 10275 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 10276 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 10277 Builder.AddPlaceholderChunk("macro"); 10278 Builder.AddChunk(CodeCompletionString::CK_RightParen); 10279 Results.AddResult(Builder.TakeString()); 10280 Results.ExitScope(); 10281 10282 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 10283 Results.getCompletionContext(), Results.data(), 10284 Results.size()); 10285 } 10286 10287 void SemaCodeCompletion::CodeCompletePreprocessorMacroArgument( 10288 Scope *S, IdentifierInfo *Macro, MacroInfo *MacroInfo, unsigned Argument) { 10289 // FIXME: In the future, we could provide "overload" results, much like we 10290 // do for function calls. 10291 10292 // Now just ignore this. There will be another code-completion callback 10293 // for the expanded tokens. 10294 } 10295 10296 // This handles completion inside an #include filename, e.g. #include <foo/ba 10297 // We look for the directory "foo" under each directory on the include path, 10298 // list its files, and reassemble the appropriate #include. 10299 void SemaCodeCompletion::CodeCompleteIncludedFile(llvm::StringRef Dir, 10300 bool Angled) { 10301 // RelDir should use /, but unescaped \ is possible on windows! 10302 // Our completions will normalize to / for simplicity, this case is rare. 10303 std::string RelDir = llvm::sys::path::convert_to_slash(Dir); 10304 // We need the native slashes for the actual file system interactions. 10305 SmallString<128> NativeRelDir = StringRef(RelDir); 10306 llvm::sys::path::native(NativeRelDir); 10307 llvm::vfs::FileSystem &FS = 10308 SemaRef.getSourceManager().getFileManager().getVirtualFileSystem(); 10309 10310 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(), 10311 CodeCompleter->getCodeCompletionTUInfo(), 10312 CodeCompletionContext::CCC_IncludedFile); 10313 llvm::DenseSet<StringRef> SeenResults; // To deduplicate results. 10314 10315 // Helper: adds one file or directory completion result. 10316 auto AddCompletion = [&](StringRef Filename, bool IsDirectory) { 10317 SmallString<64> TypedChunk = Filename; 10318 // Directory completion is up to the slash, e.g. <sys/ 10319 TypedChunk.push_back(IsDirectory ? '/' : Angled ? '>' : '"'); 10320 auto R = SeenResults.insert(TypedChunk); 10321 if (R.second) { // New completion 10322 const char *InternedTyped = Results.getAllocator().CopyString(TypedChunk); 10323 *R.first = InternedTyped; // Avoid dangling StringRef. 10324 CodeCompletionBuilder Builder(CodeCompleter->getAllocator(), 10325 CodeCompleter->getCodeCompletionTUInfo()); 10326 Builder.AddTypedTextChunk(InternedTyped); 10327 // The result is a "Pattern", which is pretty opaque. 10328 // We may want to include the real filename to allow smart ranking. 10329 Results.AddResult(CodeCompletionResult(Builder.TakeString())); 10330 } 10331 }; 10332 10333 // Helper: scans IncludeDir for nice files, and adds results for each. 10334 auto AddFilesFromIncludeDir = [&](StringRef IncludeDir, 10335 bool IsSystem, 10336 DirectoryLookup::LookupType_t LookupType) { 10337 llvm::SmallString<128> Dir = IncludeDir; 10338 if (!NativeRelDir.empty()) { 10339 if (LookupType == DirectoryLookup::LT_Framework) { 10340 // For a framework dir, #include <Foo/Bar/> actually maps to 10341 // a path of Foo.framework/Headers/Bar/. 10342 auto Begin = llvm::sys::path::begin(NativeRelDir); 10343 auto End = llvm::sys::path::end(NativeRelDir); 10344 10345 llvm::sys::path::append(Dir, *Begin + ".framework", "Headers"); 10346 llvm::sys::path::append(Dir, ++Begin, End); 10347 } else { 10348 llvm::sys::path::append(Dir, NativeRelDir); 10349 } 10350 } 10351 10352 const StringRef &Dirname = llvm::sys::path::filename(Dir); 10353 const bool isQt = Dirname.starts_with("Qt") || Dirname == "ActiveQt"; 10354 const bool ExtensionlessHeaders = 10355 IsSystem || isQt || Dir.ends_with(".framework/Headers"); 10356 std::error_code EC; 10357 unsigned Count = 0; 10358 for (auto It = FS.dir_begin(Dir, EC); 10359 !EC && It != llvm::vfs::directory_iterator(); It.increment(EC)) { 10360 if (++Count == 2500) // If we happen to hit a huge directory, 10361 break; // bail out early so we're not too slow. 10362 StringRef Filename = llvm::sys::path::filename(It->path()); 10363 10364 // To know whether a symlink should be treated as file or a directory, we 10365 // have to stat it. This should be cheap enough as there shouldn't be many 10366 // symlinks. 10367 llvm::sys::fs::file_type Type = It->type(); 10368 if (Type == llvm::sys::fs::file_type::symlink_file) { 10369 if (auto FileStatus = FS.status(It->path())) 10370 Type = FileStatus->getType(); 10371 } 10372 switch (Type) { 10373 case llvm::sys::fs::file_type::directory_file: 10374 // All entries in a framework directory must have a ".framework" suffix, 10375 // but the suffix does not appear in the source code's include/import. 10376 if (LookupType == DirectoryLookup::LT_Framework && 10377 NativeRelDir.empty() && !Filename.consume_back(".framework")) 10378 break; 10379 10380 AddCompletion(Filename, /*IsDirectory=*/true); 10381 break; 10382 case llvm::sys::fs::file_type::regular_file: { 10383 // Only files that really look like headers. (Except in special dirs). 10384 const bool IsHeader = Filename.ends_with_insensitive(".h") || 10385 Filename.ends_with_insensitive(".hh") || 10386 Filename.ends_with_insensitive(".hpp") || 10387 Filename.ends_with_insensitive(".hxx") || 10388 Filename.ends_with_insensitive(".inc") || 10389 (ExtensionlessHeaders && !Filename.contains('.')); 10390 if (!IsHeader) 10391 break; 10392 AddCompletion(Filename, /*IsDirectory=*/false); 10393 break; 10394 } 10395 default: 10396 break; 10397 } 10398 } 10399 }; 10400 10401 // Helper: adds results relative to IncludeDir, if possible. 10402 auto AddFilesFromDirLookup = [&](const DirectoryLookup &IncludeDir, 10403 bool IsSystem) { 10404 switch (IncludeDir.getLookupType()) { 10405 case DirectoryLookup::LT_HeaderMap: 10406 // header maps are not (currently) enumerable. 10407 break; 10408 case DirectoryLookup::LT_NormalDir: 10409 AddFilesFromIncludeDir(IncludeDir.getDirRef()->getName(), IsSystem, 10410 DirectoryLookup::LT_NormalDir); 10411 break; 10412 case DirectoryLookup::LT_Framework: 10413 AddFilesFromIncludeDir(IncludeDir.getFrameworkDirRef()->getName(), 10414 IsSystem, DirectoryLookup::LT_Framework); 10415 break; 10416 } 10417 }; 10418 10419 // Finally with all our helpers, we can scan the include path. 10420 // Do this in standard order so deduplication keeps the right file. 10421 // (In case we decide to add more details to the results later). 10422 const auto &S = SemaRef.PP.getHeaderSearchInfo(); 10423 using llvm::make_range; 10424 if (!Angled) { 10425 // The current directory is on the include path for "quoted" includes. 10426 if (auto CurFile = SemaRef.PP.getCurrentFileLexer()->getFileEntry()) 10427 AddFilesFromIncludeDir(CurFile->getDir().getName(), false, 10428 DirectoryLookup::LT_NormalDir); 10429 for (const auto &D : make_range(S.quoted_dir_begin(), S.quoted_dir_end())) 10430 AddFilesFromDirLookup(D, false); 10431 } 10432 for (const auto &D : make_range(S.angled_dir_begin(), S.angled_dir_end())) 10433 AddFilesFromDirLookup(D, false); 10434 for (const auto &D : make_range(S.system_dir_begin(), S.system_dir_end())) 10435 AddFilesFromDirLookup(D, true); 10436 10437 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 10438 Results.getCompletionContext(), Results.data(), 10439 Results.size()); 10440 } 10441 10442 void SemaCodeCompletion::CodeCompleteNaturalLanguage() { 10443 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 10444 CodeCompletionContext::CCC_NaturalLanguage, nullptr, 10445 0); 10446 } 10447 10448 void SemaCodeCompletion::CodeCompleteAvailabilityPlatformName() { 10449 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(), 10450 CodeCompleter->getCodeCompletionTUInfo(), 10451 CodeCompletionContext::CCC_Other); 10452 Results.EnterNewScope(); 10453 static const char *Platforms[] = {"macOS", "iOS", "watchOS", "tvOS"}; 10454 for (const char *Platform : llvm::ArrayRef(Platforms)) { 10455 Results.AddResult(CodeCompletionResult(Platform)); 10456 Results.AddResult(CodeCompletionResult(Results.getAllocator().CopyString( 10457 Twine(Platform) + "ApplicationExtension"))); 10458 } 10459 Results.ExitScope(); 10460 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 10461 Results.getCompletionContext(), Results.data(), 10462 Results.size()); 10463 } 10464 10465 void SemaCodeCompletion::GatherGlobalCodeCompletions( 10466 CodeCompletionAllocator &Allocator, CodeCompletionTUInfo &CCTUInfo, 10467 SmallVectorImpl<CodeCompletionResult> &Results) { 10468 ResultBuilder Builder(SemaRef, Allocator, CCTUInfo, 10469 CodeCompletionContext::CCC_Recovery); 10470 if (!CodeCompleter || CodeCompleter->includeGlobals()) { 10471 CodeCompletionDeclConsumer Consumer( 10472 Builder, getASTContext().getTranslationUnitDecl()); 10473 SemaRef.LookupVisibleDecls(getASTContext().getTranslationUnitDecl(), 10474 Sema::LookupAnyName, Consumer, 10475 !CodeCompleter || CodeCompleter->loadExternal()); 10476 } 10477 10478 if (!CodeCompleter || CodeCompleter->includeMacros()) 10479 AddMacroResults(SemaRef.PP, Builder, 10480 !CodeCompleter || CodeCompleter->loadExternal(), true); 10481 10482 Results.clear(); 10483 Results.insert(Results.end(), Builder.data(), 10484 Builder.data() + Builder.size()); 10485 } 10486 10487 SemaCodeCompletion::SemaCodeCompletion(Sema &S, 10488 CodeCompleteConsumer *CompletionConsumer) 10489 : SemaBase(S), CodeCompleter(CompletionConsumer), 10490 Resolver(S.getASTContext()) {} 10491