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