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, {}, false, false, Results); 4571 } 4572 4573 // Note that we intentionally suppress macro results here, since we do not 4574 // encourage using macros to produce the names of entities. 4575 4576 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 4577 Results.getCompletionContext(), Results.data(), 4578 Results.size()); 4579 } 4580 4581 static const char *underscoreAttrScope(llvm::StringRef Scope) { 4582 if (Scope == "clang") 4583 return "_Clang"; 4584 if (Scope == "gnu") 4585 return "__gnu__"; 4586 return nullptr; 4587 } 4588 4589 static const char *noUnderscoreAttrScope(llvm::StringRef Scope) { 4590 if (Scope == "_Clang") 4591 return "clang"; 4592 if (Scope == "__gnu__") 4593 return "gnu"; 4594 return nullptr; 4595 } 4596 4597 void SemaCodeCompletion::CodeCompleteAttribute( 4598 AttributeCommonInfo::Syntax Syntax, AttributeCompletion Completion, 4599 const IdentifierInfo *InScope) { 4600 if (Completion == AttributeCompletion::None) 4601 return; 4602 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(), 4603 CodeCompleter->getCodeCompletionTUInfo(), 4604 CodeCompletionContext::CCC_Attribute); 4605 4606 // We're going to iterate over the normalized spellings of the attribute. 4607 // These don't include "underscore guarding": the normalized spelling is 4608 // clang::foo but you can also write _Clang::__foo__. 4609 // 4610 // (Clang supports a mix like clang::__foo__ but we won't suggest it: either 4611 // you care about clashing with macros or you don't). 4612 // 4613 // So if we're already in a scope, we determine its canonical spellings 4614 // (for comparison with normalized attr spelling) and remember whether it was 4615 // underscore-guarded (so we know how to spell contained attributes). 4616 llvm::StringRef InScopeName; 4617 bool InScopeUnderscore = false; 4618 if (InScope) { 4619 InScopeName = InScope->getName(); 4620 if (const char *NoUnderscore = noUnderscoreAttrScope(InScopeName)) { 4621 InScopeName = NoUnderscore; 4622 InScopeUnderscore = true; 4623 } 4624 } 4625 bool SyntaxSupportsGuards = Syntax == AttributeCommonInfo::AS_GNU || 4626 Syntax == AttributeCommonInfo::AS_CXX11 || 4627 Syntax == AttributeCommonInfo::AS_C23; 4628 4629 llvm::DenseSet<llvm::StringRef> FoundScopes; 4630 auto AddCompletions = [&](const ParsedAttrInfo &A) { 4631 if (A.IsTargetSpecific && 4632 !A.existsInTarget(getASTContext().getTargetInfo())) 4633 return; 4634 if (!A.acceptsLangOpts(getLangOpts())) 4635 return; 4636 for (const auto &S : A.Spellings) { 4637 if (S.Syntax != Syntax) 4638 continue; 4639 llvm::StringRef Name = S.NormalizedFullName; 4640 llvm::StringRef Scope; 4641 if ((Syntax == AttributeCommonInfo::AS_CXX11 || 4642 Syntax == AttributeCommonInfo::AS_C23)) { 4643 std::tie(Scope, Name) = Name.split("::"); 4644 if (Name.empty()) // oops, unscoped 4645 std::swap(Name, Scope); 4646 } 4647 4648 // Do we just want a list of scopes rather than attributes? 4649 if (Completion == AttributeCompletion::Scope) { 4650 // Make sure to emit each scope only once. 4651 if (!Scope.empty() && FoundScopes.insert(Scope).second) { 4652 Results.AddResult( 4653 CodeCompletionResult(Results.getAllocator().CopyString(Scope))); 4654 // Include alternate form (__gnu__ instead of gnu). 4655 if (const char *Scope2 = underscoreAttrScope(Scope)) 4656 Results.AddResult(CodeCompletionResult(Scope2)); 4657 } 4658 continue; 4659 } 4660 4661 // If a scope was specified, it must match but we don't need to print it. 4662 if (!InScopeName.empty()) { 4663 if (Scope != InScopeName) 4664 continue; 4665 Scope = ""; 4666 } 4667 4668 auto Add = [&](llvm::StringRef Scope, llvm::StringRef Name, 4669 bool Underscores) { 4670 CodeCompletionBuilder Builder(Results.getAllocator(), 4671 Results.getCodeCompletionTUInfo()); 4672 llvm::SmallString<32> Text; 4673 if (!Scope.empty()) { 4674 Text.append(Scope); 4675 Text.append("::"); 4676 } 4677 if (Underscores) 4678 Text.append("__"); 4679 Text.append(Name); 4680 if (Underscores) 4681 Text.append("__"); 4682 Builder.AddTypedTextChunk(Results.getAllocator().CopyString(Text)); 4683 4684 if (!A.ArgNames.empty()) { 4685 Builder.AddChunk(CodeCompletionString::CK_LeftParen, "("); 4686 bool First = true; 4687 for (const char *Arg : A.ArgNames) { 4688 if (!First) 4689 Builder.AddChunk(CodeCompletionString::CK_Comma, ", "); 4690 First = false; 4691 Builder.AddPlaceholderChunk(Arg); 4692 } 4693 Builder.AddChunk(CodeCompletionString::CK_RightParen, ")"); 4694 } 4695 4696 Results.AddResult(Builder.TakeString()); 4697 }; 4698 4699 // Generate the non-underscore-guarded result. 4700 // Note this is (a suffix of) the NormalizedFullName, no need to copy. 4701 // If an underscore-guarded scope was specified, only the 4702 // underscore-guarded attribute name is relevant. 4703 if (!InScopeUnderscore) 4704 Add(Scope, Name, /*Underscores=*/false); 4705 4706 // Generate the underscore-guarded version, for syntaxes that support it. 4707 // We skip this if the scope was already spelled and not guarded, or 4708 // we must spell it and can't guard it. 4709 if (!(InScope && !InScopeUnderscore) && SyntaxSupportsGuards) { 4710 llvm::SmallString<32> Guarded; 4711 if (Scope.empty()) { 4712 Add(Scope, Name, /*Underscores=*/true); 4713 } else { 4714 const char *GuardedScope = underscoreAttrScope(Scope); 4715 if (!GuardedScope) 4716 continue; 4717 Add(GuardedScope, Name, /*Underscores=*/true); 4718 } 4719 } 4720 4721 // It may be nice to include the Kind so we can look up the docs later. 4722 } 4723 }; 4724 4725 for (const auto *A : ParsedAttrInfo::getAllBuiltin()) 4726 AddCompletions(*A); 4727 for (const auto &Entry : ParsedAttrInfoRegistry::entries()) 4728 AddCompletions(*Entry.instantiate()); 4729 4730 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 4731 Results.getCompletionContext(), Results.data(), 4732 Results.size()); 4733 } 4734 4735 struct SemaCodeCompletion::CodeCompleteExpressionData { 4736 CodeCompleteExpressionData(QualType PreferredType = QualType(), 4737 bool IsParenthesized = false) 4738 : PreferredType(PreferredType), IntegralConstantExpression(false), 4739 ObjCCollection(false), IsParenthesized(IsParenthesized) {} 4740 4741 QualType PreferredType; 4742 bool IntegralConstantExpression; 4743 bool ObjCCollection; 4744 bool IsParenthesized; 4745 SmallVector<Decl *, 4> IgnoreDecls; 4746 }; 4747 4748 namespace { 4749 /// Information that allows to avoid completing redundant enumerators. 4750 struct CoveredEnumerators { 4751 llvm::SmallPtrSet<EnumConstantDecl *, 8> Seen; 4752 NestedNameSpecifier *SuggestedQualifier = nullptr; 4753 }; 4754 } // namespace 4755 4756 static void AddEnumerators(ResultBuilder &Results, ASTContext &Context, 4757 EnumDecl *Enum, DeclContext *CurContext, 4758 const CoveredEnumerators &Enumerators) { 4759 NestedNameSpecifier *Qualifier = Enumerators.SuggestedQualifier; 4760 if (Context.getLangOpts().CPlusPlus && !Qualifier && Enumerators.Seen.empty()) { 4761 // If there are no prior enumerators in C++, check whether we have to 4762 // qualify the names of the enumerators that we suggest, because they 4763 // may not be visible in this scope. 4764 Qualifier = getRequiredQualification(Context, CurContext, Enum); 4765 } 4766 4767 Results.EnterNewScope(); 4768 for (auto *E : Enum->enumerators()) { 4769 if (Enumerators.Seen.count(E)) 4770 continue; 4771 4772 CodeCompletionResult R(E, CCP_EnumInCase, Qualifier); 4773 Results.AddResult(R, CurContext, nullptr, false); 4774 } 4775 Results.ExitScope(); 4776 } 4777 4778 /// Try to find a corresponding FunctionProtoType for function-like types (e.g. 4779 /// function pointers, std::function, etc). 4780 static const FunctionProtoType *TryDeconstructFunctionLike(QualType T) { 4781 assert(!T.isNull()); 4782 // Try to extract first template argument from std::function<> and similar. 4783 // Note we only handle the sugared types, they closely match what users wrote. 4784 // We explicitly choose to not handle ClassTemplateSpecializationDecl. 4785 if (auto *Specialization = T->getAs<TemplateSpecializationType>()) { 4786 if (Specialization->template_arguments().size() != 1) 4787 return nullptr; 4788 const TemplateArgument &Argument = Specialization->template_arguments()[0]; 4789 if (Argument.getKind() != TemplateArgument::Type) 4790 return nullptr; 4791 return Argument.getAsType()->getAs<FunctionProtoType>(); 4792 } 4793 // Handle other cases. 4794 if (T->isPointerType()) 4795 T = T->getPointeeType(); 4796 return T->getAs<FunctionProtoType>(); 4797 } 4798 4799 /// Adds a pattern completion for a lambda expression with the specified 4800 /// parameter types and placeholders for parameter names. 4801 static void AddLambdaCompletion(ResultBuilder &Results, 4802 llvm::ArrayRef<QualType> Parameters, 4803 const LangOptions &LangOpts) { 4804 if (!Results.includeCodePatterns()) 4805 return; 4806 CodeCompletionBuilder Completion(Results.getAllocator(), 4807 Results.getCodeCompletionTUInfo()); 4808 // [](<parameters>) {} 4809 Completion.AddChunk(CodeCompletionString::CK_LeftBracket); 4810 Completion.AddPlaceholderChunk("="); 4811 Completion.AddChunk(CodeCompletionString::CK_RightBracket); 4812 if (!Parameters.empty()) { 4813 Completion.AddChunk(CodeCompletionString::CK_LeftParen); 4814 bool First = true; 4815 for (auto Parameter : Parameters) { 4816 if (!First) 4817 Completion.AddChunk(CodeCompletionString::ChunkKind::CK_Comma); 4818 else 4819 First = false; 4820 4821 constexpr llvm::StringLiteral NamePlaceholder = "!#!NAME_GOES_HERE!#!"; 4822 std::string Type = std::string(NamePlaceholder); 4823 Parameter.getAsStringInternal(Type, PrintingPolicy(LangOpts)); 4824 llvm::StringRef Prefix, Suffix; 4825 std::tie(Prefix, Suffix) = llvm::StringRef(Type).split(NamePlaceholder); 4826 Prefix = Prefix.rtrim(); 4827 Suffix = Suffix.ltrim(); 4828 4829 Completion.AddTextChunk(Completion.getAllocator().CopyString(Prefix)); 4830 Completion.AddChunk(CodeCompletionString::CK_HorizontalSpace); 4831 Completion.AddPlaceholderChunk("parameter"); 4832 Completion.AddTextChunk(Completion.getAllocator().CopyString(Suffix)); 4833 }; 4834 Completion.AddChunk(CodeCompletionString::CK_RightParen); 4835 } 4836 Completion.AddChunk(clang::CodeCompletionString::CK_HorizontalSpace); 4837 Completion.AddChunk(CodeCompletionString::CK_LeftBrace); 4838 Completion.AddChunk(CodeCompletionString::CK_HorizontalSpace); 4839 Completion.AddPlaceholderChunk("body"); 4840 Completion.AddChunk(CodeCompletionString::CK_HorizontalSpace); 4841 Completion.AddChunk(CodeCompletionString::CK_RightBrace); 4842 4843 Results.AddResult(Completion.TakeString()); 4844 } 4845 4846 /// Perform code-completion in an expression context when we know what 4847 /// type we're looking for. 4848 void SemaCodeCompletion::CodeCompleteExpression( 4849 Scope *S, const CodeCompleteExpressionData &Data) { 4850 ResultBuilder Results( 4851 SemaRef, CodeCompleter->getAllocator(), 4852 CodeCompleter->getCodeCompletionTUInfo(), 4853 CodeCompletionContext( 4854 Data.IsParenthesized 4855 ? CodeCompletionContext::CCC_ParenthesizedExpression 4856 : CodeCompletionContext::CCC_Expression, 4857 Data.PreferredType)); 4858 auto PCC = 4859 Data.IsParenthesized ? PCC_ParenthesizedExpression : PCC_Expression; 4860 if (Data.ObjCCollection) 4861 Results.setFilter(&ResultBuilder::IsObjCCollection); 4862 else if (Data.IntegralConstantExpression) 4863 Results.setFilter(&ResultBuilder::IsIntegralConstantValue); 4864 else if (WantTypesInContext(PCC, getLangOpts())) 4865 Results.setFilter(&ResultBuilder::IsOrdinaryName); 4866 else 4867 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName); 4868 4869 if (!Data.PreferredType.isNull()) 4870 Results.setPreferredType(Data.PreferredType.getNonReferenceType()); 4871 4872 // Ignore any declarations that we were told that we don't care about. 4873 for (unsigned I = 0, N = Data.IgnoreDecls.size(); I != N; ++I) 4874 Results.Ignore(Data.IgnoreDecls[I]); 4875 4876 CodeCompletionDeclConsumer Consumer(Results, SemaRef.CurContext); 4877 SemaRef.LookupVisibleDecls(S, Sema::LookupOrdinaryName, Consumer, 4878 CodeCompleter->includeGlobals(), 4879 CodeCompleter->loadExternal()); 4880 4881 Results.EnterNewScope(); 4882 AddOrdinaryNameResults(PCC, S, SemaRef, Results); 4883 Results.ExitScope(); 4884 4885 bool PreferredTypeIsPointer = false; 4886 if (!Data.PreferredType.isNull()) { 4887 PreferredTypeIsPointer = Data.PreferredType->isAnyPointerType() || 4888 Data.PreferredType->isMemberPointerType() || 4889 Data.PreferredType->isBlockPointerType(); 4890 if (Data.PreferredType->isEnumeralType()) { 4891 EnumDecl *Enum = Data.PreferredType->castAs<EnumType>()->getDecl(); 4892 if (auto *Def = Enum->getDefinition()) 4893 Enum = Def; 4894 // FIXME: collect covered enumerators in cases like: 4895 // if (x == my_enum::one) { ... } else if (x == ^) {} 4896 AddEnumerators(Results, getASTContext(), Enum, SemaRef.CurContext, 4897 CoveredEnumerators()); 4898 } 4899 } 4900 4901 if (S->getFnParent() && !Data.ObjCCollection && 4902 !Data.IntegralConstantExpression) 4903 AddPrettyFunctionResults(getLangOpts(), Results); 4904 4905 if (CodeCompleter->includeMacros()) 4906 AddMacroResults(SemaRef.PP, Results, CodeCompleter->loadExternal(), false, 4907 PreferredTypeIsPointer); 4908 4909 // Complete a lambda expression when preferred type is a function. 4910 if (!Data.PreferredType.isNull() && getLangOpts().CPlusPlus11) { 4911 if (const FunctionProtoType *F = 4912 TryDeconstructFunctionLike(Data.PreferredType)) 4913 AddLambdaCompletion(Results, F->getParamTypes(), getLangOpts()); 4914 } 4915 4916 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 4917 Results.getCompletionContext(), Results.data(), 4918 Results.size()); 4919 } 4920 4921 void SemaCodeCompletion::CodeCompleteExpression(Scope *S, 4922 QualType PreferredType, 4923 bool IsParenthesized) { 4924 return CodeCompleteExpression( 4925 S, CodeCompleteExpressionData(PreferredType, IsParenthesized)); 4926 } 4927 4928 void SemaCodeCompletion::CodeCompletePostfixExpression(Scope *S, ExprResult E, 4929 QualType PreferredType) { 4930 if (E.isInvalid()) 4931 CodeCompleteExpression(S, PreferredType); 4932 else if (getLangOpts().ObjC) 4933 CodeCompleteObjCInstanceMessage(S, E.get(), {}, false); 4934 } 4935 4936 /// The set of properties that have already been added, referenced by 4937 /// property name. 4938 typedef llvm::SmallPtrSet<const IdentifierInfo *, 16> AddedPropertiesSet; 4939 4940 /// Retrieve the container definition, if any? 4941 static ObjCContainerDecl *getContainerDef(ObjCContainerDecl *Container) { 4942 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) { 4943 if (Interface->hasDefinition()) 4944 return Interface->getDefinition(); 4945 4946 return Interface; 4947 } 4948 4949 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) { 4950 if (Protocol->hasDefinition()) 4951 return Protocol->getDefinition(); 4952 4953 return Protocol; 4954 } 4955 return Container; 4956 } 4957 4958 /// Adds a block invocation code completion result for the given block 4959 /// declaration \p BD. 4960 static void AddObjCBlockCall(ASTContext &Context, const PrintingPolicy &Policy, 4961 CodeCompletionBuilder &Builder, 4962 const NamedDecl *BD, 4963 const FunctionTypeLoc &BlockLoc, 4964 const FunctionProtoTypeLoc &BlockProtoLoc) { 4965 Builder.AddResultTypeChunk( 4966 GetCompletionTypeString(BlockLoc.getReturnLoc().getType(), Context, 4967 Policy, Builder.getAllocator())); 4968 4969 AddTypedNameChunk(Context, Policy, BD, Builder); 4970 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 4971 4972 if (BlockProtoLoc && BlockProtoLoc.getTypePtr()->isVariadic()) { 4973 Builder.AddPlaceholderChunk("..."); 4974 } else { 4975 for (unsigned I = 0, N = BlockLoc.getNumParams(); I != N; ++I) { 4976 if (I) 4977 Builder.AddChunk(CodeCompletionString::CK_Comma); 4978 4979 // Format the placeholder string. 4980 std::string PlaceholderStr = 4981 FormatFunctionParameter(Policy, BlockLoc.getParam(I)); 4982 4983 if (I == N - 1 && BlockProtoLoc && 4984 BlockProtoLoc.getTypePtr()->isVariadic()) 4985 PlaceholderStr += ", ..."; 4986 4987 // Add the placeholder string. 4988 Builder.AddPlaceholderChunk( 4989 Builder.getAllocator().CopyString(PlaceholderStr)); 4990 } 4991 } 4992 4993 Builder.AddChunk(CodeCompletionString::CK_RightParen); 4994 } 4995 4996 static void 4997 AddObjCProperties(const CodeCompletionContext &CCContext, 4998 ObjCContainerDecl *Container, bool AllowCategories, 4999 bool AllowNullaryMethods, DeclContext *CurContext, 5000 AddedPropertiesSet &AddedProperties, ResultBuilder &Results, 5001 bool IsBaseExprStatement = false, 5002 bool IsClassProperty = false, bool InOriginalClass = true) { 5003 typedef CodeCompletionResult Result; 5004 5005 // Retrieve the definition. 5006 Container = getContainerDef(Container); 5007 5008 // Add properties in this container. 5009 const auto AddProperty = [&](const ObjCPropertyDecl *P) { 5010 if (!AddedProperties.insert(P->getIdentifier()).second) 5011 return; 5012 5013 // FIXME: Provide block invocation completion for non-statement 5014 // expressions. 5015 if (!P->getType().getTypePtr()->isBlockPointerType() || 5016 !IsBaseExprStatement) { 5017 Result R = Result(P, Results.getBasePriority(P), nullptr); 5018 if (!InOriginalClass) 5019 setInBaseClass(R); 5020 Results.MaybeAddResult(R, CurContext); 5021 return; 5022 } 5023 5024 // Block setter and invocation completion is provided only when we are able 5025 // to find the FunctionProtoTypeLoc with parameter names for the block. 5026 FunctionTypeLoc BlockLoc; 5027 FunctionProtoTypeLoc BlockProtoLoc; 5028 findTypeLocationForBlockDecl(P->getTypeSourceInfo(), BlockLoc, 5029 BlockProtoLoc); 5030 if (!BlockLoc) { 5031 Result R = Result(P, Results.getBasePriority(P), nullptr); 5032 if (!InOriginalClass) 5033 setInBaseClass(R); 5034 Results.MaybeAddResult(R, CurContext); 5035 return; 5036 } 5037 5038 // The default completion result for block properties should be the block 5039 // invocation completion when the base expression is a statement. 5040 CodeCompletionBuilder Builder(Results.getAllocator(), 5041 Results.getCodeCompletionTUInfo()); 5042 AddObjCBlockCall(Container->getASTContext(), 5043 getCompletionPrintingPolicy(Results.getSema()), Builder, P, 5044 BlockLoc, BlockProtoLoc); 5045 Result R = Result(Builder.TakeString(), P, Results.getBasePriority(P)); 5046 if (!InOriginalClass) 5047 setInBaseClass(R); 5048 Results.MaybeAddResult(R, CurContext); 5049 5050 // Provide additional block setter completion iff the base expression is a 5051 // statement and the block property is mutable. 5052 if (!P->isReadOnly()) { 5053 CodeCompletionBuilder Builder(Results.getAllocator(), 5054 Results.getCodeCompletionTUInfo()); 5055 AddResultTypeChunk(Container->getASTContext(), 5056 getCompletionPrintingPolicy(Results.getSema()), P, 5057 CCContext.getBaseType(), Builder); 5058 Builder.AddTypedTextChunk( 5059 Results.getAllocator().CopyString(P->getName())); 5060 Builder.AddChunk(CodeCompletionString::CK_Equal); 5061 5062 std::string PlaceholderStr = formatBlockPlaceholder( 5063 getCompletionPrintingPolicy(Results.getSema()), P, BlockLoc, 5064 BlockProtoLoc, /*SuppressBlockName=*/true); 5065 // Add the placeholder string. 5066 Builder.AddPlaceholderChunk( 5067 Builder.getAllocator().CopyString(PlaceholderStr)); 5068 5069 // When completing blocks properties that return void the default 5070 // property completion result should show up before the setter, 5071 // otherwise the setter completion should show up before the default 5072 // property completion, as we normally want to use the result of the 5073 // call. 5074 Result R = 5075 Result(Builder.TakeString(), P, 5076 Results.getBasePriority(P) + 5077 (BlockLoc.getTypePtr()->getReturnType()->isVoidType() 5078 ? CCD_BlockPropertySetter 5079 : -CCD_BlockPropertySetter)); 5080 if (!InOriginalClass) 5081 setInBaseClass(R); 5082 Results.MaybeAddResult(R, CurContext); 5083 } 5084 }; 5085 5086 if (IsClassProperty) { 5087 for (const auto *P : Container->class_properties()) 5088 AddProperty(P); 5089 } else { 5090 for (const auto *P : Container->instance_properties()) 5091 AddProperty(P); 5092 } 5093 5094 // Add nullary methods or implicit class properties 5095 if (AllowNullaryMethods) { 5096 ASTContext &Context = Container->getASTContext(); 5097 PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema()); 5098 // Adds a method result 5099 const auto AddMethod = [&](const ObjCMethodDecl *M) { 5100 const IdentifierInfo *Name = M->getSelector().getIdentifierInfoForSlot(0); 5101 if (!Name) 5102 return; 5103 if (!AddedProperties.insert(Name).second) 5104 return; 5105 CodeCompletionBuilder Builder(Results.getAllocator(), 5106 Results.getCodeCompletionTUInfo()); 5107 AddResultTypeChunk(Context, Policy, M, CCContext.getBaseType(), Builder); 5108 Builder.AddTypedTextChunk( 5109 Results.getAllocator().CopyString(Name->getName())); 5110 Result R = Result(Builder.TakeString(), M, 5111 CCP_MemberDeclaration + CCD_MethodAsProperty); 5112 if (!InOriginalClass) 5113 setInBaseClass(R); 5114 Results.MaybeAddResult(R, CurContext); 5115 }; 5116 5117 if (IsClassProperty) { 5118 for (const auto *M : Container->methods()) { 5119 // Gather the class method that can be used as implicit property 5120 // getters. Methods with arguments or methods that return void aren't 5121 // added to the results as they can't be used as a getter. 5122 if (!M->getSelector().isUnarySelector() || 5123 M->getReturnType()->isVoidType() || M->isInstanceMethod()) 5124 continue; 5125 AddMethod(M); 5126 } 5127 } else { 5128 for (auto *M : Container->methods()) { 5129 if (M->getSelector().isUnarySelector()) 5130 AddMethod(M); 5131 } 5132 } 5133 } 5134 5135 // Add properties in referenced protocols. 5136 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) { 5137 for (auto *P : Protocol->protocols()) 5138 AddObjCProperties(CCContext, P, AllowCategories, AllowNullaryMethods, 5139 CurContext, AddedProperties, Results, 5140 IsBaseExprStatement, IsClassProperty, 5141 /*InOriginalClass*/ false); 5142 } else if (ObjCInterfaceDecl *IFace = 5143 dyn_cast<ObjCInterfaceDecl>(Container)) { 5144 if (AllowCategories) { 5145 // Look through categories. 5146 for (auto *Cat : IFace->known_categories()) 5147 AddObjCProperties(CCContext, Cat, AllowCategories, AllowNullaryMethods, 5148 CurContext, AddedProperties, Results, 5149 IsBaseExprStatement, IsClassProperty, 5150 InOriginalClass); 5151 } 5152 5153 // Look through protocols. 5154 for (auto *I : IFace->all_referenced_protocols()) 5155 AddObjCProperties(CCContext, I, AllowCategories, AllowNullaryMethods, 5156 CurContext, AddedProperties, Results, 5157 IsBaseExprStatement, IsClassProperty, 5158 /*InOriginalClass*/ false); 5159 5160 // Look in the superclass. 5161 if (IFace->getSuperClass()) 5162 AddObjCProperties(CCContext, IFace->getSuperClass(), AllowCategories, 5163 AllowNullaryMethods, CurContext, AddedProperties, 5164 Results, IsBaseExprStatement, IsClassProperty, 5165 /*InOriginalClass*/ false); 5166 } else if (const auto *Category = 5167 dyn_cast<ObjCCategoryDecl>(Container)) { 5168 // Look through protocols. 5169 for (auto *P : Category->protocols()) 5170 AddObjCProperties(CCContext, P, AllowCategories, AllowNullaryMethods, 5171 CurContext, AddedProperties, Results, 5172 IsBaseExprStatement, IsClassProperty, 5173 /*InOriginalClass*/ false); 5174 } 5175 } 5176 5177 static void 5178 AddRecordMembersCompletionResults(Sema &SemaRef, ResultBuilder &Results, 5179 Scope *S, QualType BaseType, 5180 ExprValueKind BaseKind, RecordDecl *RD, 5181 std::optional<FixItHint> AccessOpFixIt) { 5182 // Indicate that we are performing a member access, and the cv-qualifiers 5183 // for the base object type. 5184 Results.setObjectTypeQualifiers(BaseType.getQualifiers(), BaseKind); 5185 5186 // Access to a C/C++ class, struct, or union. 5187 Results.allowNestedNameSpecifiers(); 5188 std::vector<FixItHint> FixIts; 5189 if (AccessOpFixIt) 5190 FixIts.emplace_back(*AccessOpFixIt); 5191 CodeCompletionDeclConsumer Consumer(Results, RD, BaseType, std::move(FixIts)); 5192 SemaRef.LookupVisibleDecls( 5193 RD, Sema::LookupMemberName, Consumer, 5194 SemaRef.CodeCompletion().CodeCompleter->includeGlobals(), 5195 /*IncludeDependentBases=*/true, 5196 SemaRef.CodeCompletion().CodeCompleter->loadExternal()); 5197 5198 if (SemaRef.getLangOpts().CPlusPlus) { 5199 if (!Results.empty()) { 5200 // The "template" keyword can follow "->" or "." in the grammar. 5201 // However, we only want to suggest the template keyword if something 5202 // is dependent. 5203 bool IsDependent = BaseType->isDependentType(); 5204 if (!IsDependent) { 5205 for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent()) 5206 if (DeclContext *Ctx = DepScope->getEntity()) { 5207 IsDependent = Ctx->isDependentContext(); 5208 break; 5209 } 5210 } 5211 5212 if (IsDependent) 5213 Results.AddResult(CodeCompletionResult("template")); 5214 } 5215 } 5216 } 5217 5218 // Returns the RecordDecl inside the BaseType, falling back to primary template 5219 // in case of specializations. Since we might not have a decl for the 5220 // instantiation/specialization yet, e.g. dependent code. 5221 static RecordDecl *getAsRecordDecl(QualType BaseType) { 5222 BaseType = BaseType.getNonReferenceType(); 5223 if (auto *RD = BaseType->getAsRecordDecl()) { 5224 if (const auto *CTSD = 5225 llvm::dyn_cast<ClassTemplateSpecializationDecl>(RD)) { 5226 // Template might not be instantiated yet, fall back to primary template 5227 // in such cases. 5228 if (CTSD->getTemplateSpecializationKind() == TSK_Undeclared) 5229 RD = CTSD->getSpecializedTemplate()->getTemplatedDecl(); 5230 } 5231 return RD; 5232 } 5233 5234 if (const auto *TST = BaseType->getAs<TemplateSpecializationType>()) { 5235 if (const auto *TD = dyn_cast_or_null<ClassTemplateDecl>( 5236 TST->getTemplateName().getAsTemplateDecl())) { 5237 return TD->getTemplatedDecl(); 5238 } 5239 } 5240 5241 return nullptr; 5242 } 5243 5244 namespace { 5245 // Collects completion-relevant information about a concept-constrainted type T. 5246 // In particular, examines the constraint expressions to find members of T. 5247 // 5248 // The design is very simple: we walk down each constraint looking for 5249 // expressions of the form T.foo(). 5250 // If we're extra lucky, the return type is specified. 5251 // We don't do any clever handling of && or || in constraint expressions, we 5252 // take members from both branches. 5253 // 5254 // For example, given: 5255 // template <class T> concept X = requires (T t, string& s) { t.print(s); }; 5256 // template <X U> void foo(U u) { u.^ } 5257 // We want to suggest the inferred member function 'print(string)'. 5258 // We see that u has type U, so X<U> holds. 5259 // X<U> requires t.print(s) to be valid, where t has type U (substituted for T). 5260 // By looking at the CallExpr we find the signature of print(). 5261 // 5262 // While we tend to know in advance which kind of members (access via . -> ::) 5263 // we want, it's simpler just to gather them all and post-filter. 5264 // 5265 // FIXME: some of this machinery could be used for non-concept type-parms too, 5266 // enabling completion for type parameters based on other uses of that param. 5267 // 5268 // FIXME: there are other cases where a type can be constrained by a concept, 5269 // e.g. inside `if constexpr(ConceptSpecializationExpr) { ... }` 5270 class ConceptInfo { 5271 public: 5272 // Describes a likely member of a type, inferred by concept constraints. 5273 // Offered as a code completion for T. T-> and T:: contexts. 5274 struct Member { 5275 // Always non-null: we only handle members with ordinary identifier names. 5276 const IdentifierInfo *Name = nullptr; 5277 // Set for functions we've seen called. 5278 // We don't have the declared parameter types, only the actual types of 5279 // arguments we've seen. These are still valuable, as it's hard to render 5280 // a useful function completion with neither parameter types nor names! 5281 std::optional<SmallVector<QualType, 1>> ArgTypes; 5282 // Whether this is accessed as T.member, T->member, or T::member. 5283 enum AccessOperator { 5284 Colons, 5285 Arrow, 5286 Dot, 5287 } Operator = Dot; 5288 // What's known about the type of a variable or return type of a function. 5289 const TypeConstraint *ResultType = nullptr; 5290 // FIXME: also track: 5291 // - kind of entity (function/variable/type), to expose structured results 5292 // - template args kinds/types, as a proxy for template params 5293 5294 // For now we simply return these results as "pattern" strings. 5295 CodeCompletionString *render(Sema &S, CodeCompletionAllocator &Alloc, 5296 CodeCompletionTUInfo &Info) const { 5297 CodeCompletionBuilder B(Alloc, Info); 5298 // Result type 5299 if (ResultType) { 5300 std::string AsString; 5301 { 5302 llvm::raw_string_ostream OS(AsString); 5303 QualType ExactType = deduceType(*ResultType); 5304 if (!ExactType.isNull()) 5305 ExactType.print(OS, getCompletionPrintingPolicy(S)); 5306 else 5307 ResultType->print(OS, getCompletionPrintingPolicy(S)); 5308 } 5309 B.AddResultTypeChunk(Alloc.CopyString(AsString)); 5310 } 5311 // Member name 5312 B.AddTypedTextChunk(Alloc.CopyString(Name->getName())); 5313 // Function argument list 5314 if (ArgTypes) { 5315 B.AddChunk(clang::CodeCompletionString::CK_LeftParen); 5316 bool First = true; 5317 for (QualType Arg : *ArgTypes) { 5318 if (First) 5319 First = false; 5320 else { 5321 B.AddChunk(clang::CodeCompletionString::CK_Comma); 5322 B.AddChunk(clang::CodeCompletionString::CK_HorizontalSpace); 5323 } 5324 B.AddPlaceholderChunk(Alloc.CopyString( 5325 Arg.getAsString(getCompletionPrintingPolicy(S)))); 5326 } 5327 B.AddChunk(clang::CodeCompletionString::CK_RightParen); 5328 } 5329 return B.TakeString(); 5330 } 5331 }; 5332 5333 // BaseType is the type parameter T to infer members from. 5334 // T must be accessible within S, as we use it to find the template entity 5335 // that T is attached to in order to gather the relevant constraints. 5336 ConceptInfo(const TemplateTypeParmType &BaseType, Scope *S) { 5337 auto *TemplatedEntity = getTemplatedEntity(BaseType.getDecl(), S); 5338 for (const Expr *E : constraintsForTemplatedEntity(TemplatedEntity)) 5339 believe(E, &BaseType); 5340 } 5341 5342 std::vector<Member> members() { 5343 std::vector<Member> Results; 5344 for (const auto &E : this->Results) 5345 Results.push_back(E.second); 5346 llvm::sort(Results, [](const Member &L, const Member &R) { 5347 return L.Name->getName() < R.Name->getName(); 5348 }); 5349 return Results; 5350 } 5351 5352 private: 5353 // Infer members of T, given that the expression E (dependent on T) is true. 5354 void believe(const Expr *E, const TemplateTypeParmType *T) { 5355 if (!E || !T) 5356 return; 5357 if (auto *CSE = dyn_cast<ConceptSpecializationExpr>(E)) { 5358 // If the concept is 5359 // template <class A, class B> concept CD = f<A, B>(); 5360 // And the concept specialization is 5361 // CD<int, T> 5362 // Then we're substituting T for B, so we want to make f<A, B>() true 5363 // by adding members to B - i.e. believe(f<A, B>(), B); 5364 // 5365 // For simplicity: 5366 // - we don't attempt to substitute int for A 5367 // - when T is used in other ways (like CD<T*>) we ignore it 5368 ConceptDecl *CD = CSE->getNamedConcept(); 5369 TemplateParameterList *Params = CD->getTemplateParameters(); 5370 unsigned Index = 0; 5371 for (const auto &Arg : CSE->getTemplateArguments()) { 5372 if (Index >= Params->size()) 5373 break; // Won't happen in valid code. 5374 if (isApprox(Arg, T)) { 5375 auto *TTPD = dyn_cast<TemplateTypeParmDecl>(Params->getParam(Index)); 5376 if (!TTPD) 5377 continue; 5378 // T was used as an argument, and bound to the parameter TT. 5379 auto *TT = cast<TemplateTypeParmType>(TTPD->getTypeForDecl()); 5380 // So now we know the constraint as a function of TT is true. 5381 believe(CD->getConstraintExpr(), TT); 5382 // (concepts themselves have no associated constraints to require) 5383 } 5384 5385 ++Index; 5386 } 5387 } else if (auto *BO = dyn_cast<BinaryOperator>(E)) { 5388 // For A && B, we can infer members from both branches. 5389 // For A || B, the union is still more useful than the intersection. 5390 if (BO->getOpcode() == BO_LAnd || BO->getOpcode() == BO_LOr) { 5391 believe(BO->getLHS(), T); 5392 believe(BO->getRHS(), T); 5393 } 5394 } else if (auto *RE = dyn_cast<RequiresExpr>(E)) { 5395 // A requires(){...} lets us infer members from each requirement. 5396 for (const concepts::Requirement *Req : RE->getRequirements()) { 5397 if (!Req->isDependent()) 5398 continue; // Can't tell us anything about T. 5399 // Now Req cannot a substitution-error: those aren't dependent. 5400 5401 if (auto *TR = dyn_cast<concepts::TypeRequirement>(Req)) { 5402 // Do a full traversal so we get `foo` from `typename T::foo::bar`. 5403 QualType AssertedType = TR->getType()->getType(); 5404 ValidVisitor(this, T).TraverseType(AssertedType); 5405 } else if (auto *ER = dyn_cast<concepts::ExprRequirement>(Req)) { 5406 ValidVisitor Visitor(this, T); 5407 // If we have a type constraint on the value of the expression, 5408 // AND the whole outer expression describes a member, then we'll 5409 // be able to use the constraint to provide the return type. 5410 if (ER->getReturnTypeRequirement().isTypeConstraint()) { 5411 Visitor.OuterType = 5412 ER->getReturnTypeRequirement().getTypeConstraint(); 5413 Visitor.OuterExpr = ER->getExpr(); 5414 } 5415 Visitor.TraverseStmt(ER->getExpr()); 5416 } else if (auto *NR = dyn_cast<concepts::NestedRequirement>(Req)) { 5417 believe(NR->getConstraintExpr(), T); 5418 } 5419 } 5420 } 5421 } 5422 5423 // This visitor infers members of T based on traversing expressions/types 5424 // that involve T. It is invoked with code known to be valid for T. 5425 class ValidVisitor : public RecursiveASTVisitor<ValidVisitor> { 5426 ConceptInfo *Outer; 5427 const TemplateTypeParmType *T; 5428 5429 CallExpr *Caller = nullptr; 5430 Expr *Callee = nullptr; 5431 5432 public: 5433 // If set, OuterExpr is constrained by OuterType. 5434 Expr *OuterExpr = nullptr; 5435 const TypeConstraint *OuterType = nullptr; 5436 5437 ValidVisitor(ConceptInfo *Outer, const TemplateTypeParmType *T) 5438 : Outer(Outer), T(T) { 5439 assert(T); 5440 } 5441 5442 // In T.foo or T->foo, `foo` is a member function/variable. 5443 bool VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E) { 5444 const Type *Base = E->getBaseType().getTypePtr(); 5445 bool IsArrow = E->isArrow(); 5446 if (Base->isPointerType() && IsArrow) { 5447 IsArrow = false; 5448 Base = Base->getPointeeType().getTypePtr(); 5449 } 5450 if (isApprox(Base, T)) 5451 addValue(E, E->getMember(), IsArrow ? Member::Arrow : Member::Dot); 5452 return true; 5453 } 5454 5455 // In T::foo, `foo` is a static member function/variable. 5456 bool VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) { 5457 if (E->getQualifier() && isApprox(E->getQualifier()->getAsType(), T)) 5458 addValue(E, E->getDeclName(), Member::Colons); 5459 return true; 5460 } 5461 5462 // In T::typename foo, `foo` is a type. 5463 bool VisitDependentNameType(DependentNameType *DNT) { 5464 const auto *Q = DNT->getQualifier(); 5465 if (Q && isApprox(Q->getAsType(), T)) 5466 addType(DNT->getIdentifier()); 5467 return true; 5468 } 5469 5470 // In T::foo::bar, `foo` must be a type. 5471 // VisitNNS() doesn't exist, and TraverseNNS isn't always called :-( 5472 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNSL) { 5473 if (NNSL) { 5474 NestedNameSpecifier *NNS = NNSL.getNestedNameSpecifier(); 5475 const auto *Q = NNS->getPrefix(); 5476 if (Q && isApprox(Q->getAsType(), T)) 5477 addType(NNS->getAsIdentifier()); 5478 } 5479 // FIXME: also handle T::foo<X>::bar 5480 return RecursiveASTVisitor::TraverseNestedNameSpecifierLoc(NNSL); 5481 } 5482 5483 // FIXME also handle T::foo<X> 5484 5485 // Track the innermost caller/callee relationship so we can tell if a 5486 // nested expr is being called as a function. 5487 bool VisitCallExpr(CallExpr *CE) { 5488 Caller = CE; 5489 Callee = CE->getCallee(); 5490 return true; 5491 } 5492 5493 private: 5494 void addResult(Member &&M) { 5495 auto R = Outer->Results.try_emplace(M.Name); 5496 Member &O = R.first->second; 5497 // Overwrite existing if the new member has more info. 5498 // The preference of . vs :: vs -> is fairly arbitrary. 5499 if (/*Inserted*/ R.second || 5500 std::make_tuple(M.ArgTypes.has_value(), M.ResultType != nullptr, 5501 M.Operator) > std::make_tuple(O.ArgTypes.has_value(), 5502 O.ResultType != nullptr, 5503 O.Operator)) 5504 O = std::move(M); 5505 } 5506 5507 void addType(const IdentifierInfo *Name) { 5508 if (!Name) 5509 return; 5510 Member M; 5511 M.Name = Name; 5512 M.Operator = Member::Colons; 5513 addResult(std::move(M)); 5514 } 5515 5516 void addValue(Expr *E, DeclarationName Name, 5517 Member::AccessOperator Operator) { 5518 if (!Name.isIdentifier()) 5519 return; 5520 Member Result; 5521 Result.Name = Name.getAsIdentifierInfo(); 5522 Result.Operator = Operator; 5523 // If this is the callee of an immediately-enclosing CallExpr, then 5524 // treat it as a method, otherwise it's a variable. 5525 if (Caller != nullptr && Callee == E) { 5526 Result.ArgTypes.emplace(); 5527 for (const auto *Arg : Caller->arguments()) 5528 Result.ArgTypes->push_back(Arg->getType()); 5529 if (Caller == OuterExpr) { 5530 Result.ResultType = OuterType; 5531 } 5532 } else { 5533 if (E == OuterExpr) 5534 Result.ResultType = OuterType; 5535 } 5536 addResult(std::move(Result)); 5537 } 5538 }; 5539 5540 static bool isApprox(const TemplateArgument &Arg, const Type *T) { 5541 return Arg.getKind() == TemplateArgument::Type && 5542 isApprox(Arg.getAsType().getTypePtr(), T); 5543 } 5544 5545 static bool isApprox(const Type *T1, const Type *T2) { 5546 return T1 && T2 && 5547 T1->getCanonicalTypeUnqualified() == 5548 T2->getCanonicalTypeUnqualified(); 5549 } 5550 5551 // Returns the DeclContext immediately enclosed by the template parameter 5552 // scope. For primary templates, this is the templated (e.g.) CXXRecordDecl. 5553 // For specializations, this is e.g. ClassTemplatePartialSpecializationDecl. 5554 static DeclContext *getTemplatedEntity(const TemplateTypeParmDecl *D, 5555 Scope *S) { 5556 if (D == nullptr) 5557 return nullptr; 5558 Scope *Inner = nullptr; 5559 while (S) { 5560 if (S->isTemplateParamScope() && S->isDeclScope(D)) 5561 return Inner ? Inner->getEntity() : nullptr; 5562 Inner = S; 5563 S = S->getParent(); 5564 } 5565 return nullptr; 5566 } 5567 5568 // Gets all the type constraint expressions that might apply to the type 5569 // variables associated with DC (as returned by getTemplatedEntity()). 5570 static SmallVector<const Expr *, 1> 5571 constraintsForTemplatedEntity(DeclContext *DC) { 5572 SmallVector<const Expr *, 1> Result; 5573 if (DC == nullptr) 5574 return Result; 5575 // Primary templates can have constraints. 5576 if (const auto *TD = cast<Decl>(DC)->getDescribedTemplate()) 5577 TD->getAssociatedConstraints(Result); 5578 // Partial specializations may have constraints. 5579 if (const auto *CTPSD = 5580 dyn_cast<ClassTemplatePartialSpecializationDecl>(DC)) 5581 CTPSD->getAssociatedConstraints(Result); 5582 if (const auto *VTPSD = dyn_cast<VarTemplatePartialSpecializationDecl>(DC)) 5583 VTPSD->getAssociatedConstraints(Result); 5584 return Result; 5585 } 5586 5587 // Attempt to find the unique type satisfying a constraint. 5588 // This lets us show e.g. `int` instead of `std::same_as<int>`. 5589 static QualType deduceType(const TypeConstraint &T) { 5590 // Assume a same_as<T> return type constraint is std::same_as or equivalent. 5591 // In this case the return type is T. 5592 DeclarationName DN = T.getNamedConcept()->getDeclName(); 5593 if (DN.isIdentifier() && DN.getAsIdentifierInfo()->isStr("same_as")) 5594 if (const auto *Args = T.getTemplateArgsAsWritten()) 5595 if (Args->getNumTemplateArgs() == 1) { 5596 const auto &Arg = Args->arguments().front().getArgument(); 5597 if (Arg.getKind() == TemplateArgument::Type) 5598 return Arg.getAsType(); 5599 } 5600 return {}; 5601 } 5602 5603 llvm::DenseMap<const IdentifierInfo *, Member> Results; 5604 }; 5605 5606 // Returns a type for E that yields acceptable member completions. 5607 // In particular, when E->getType() is DependentTy, try to guess a likely type. 5608 // We accept some lossiness (like dropping parameters). 5609 // We only try to handle common expressions on the LHS of MemberExpr. 5610 QualType getApproximateType(const Expr *E) { 5611 if (E->getType().isNull()) 5612 return QualType(); 5613 E = E->IgnoreParenImpCasts(); 5614 QualType Unresolved = E->getType(); 5615 // We only resolve DependentTy, or undeduced autos (including auto* etc). 5616 if (!Unresolved->isSpecificBuiltinType(BuiltinType::Dependent)) { 5617 AutoType *Auto = Unresolved->getContainedAutoType(); 5618 if (!Auto || !Auto->isUndeducedAutoType()) 5619 return Unresolved; 5620 } 5621 // A call: approximate-resolve callee to a function type, get its return type 5622 if (const CallExpr *CE = llvm::dyn_cast<CallExpr>(E)) { 5623 QualType Callee = getApproximateType(CE->getCallee()); 5624 if (Callee.isNull() || 5625 Callee->isSpecificPlaceholderType(BuiltinType::BoundMember)) 5626 Callee = Expr::findBoundMemberType(CE->getCallee()); 5627 if (Callee.isNull()) 5628 return Unresolved; 5629 5630 if (const auto *FnTypePtr = Callee->getAs<PointerType>()) { 5631 Callee = FnTypePtr->getPointeeType(); 5632 } else if (const auto *BPT = Callee->getAs<BlockPointerType>()) { 5633 Callee = BPT->getPointeeType(); 5634 } 5635 if (const FunctionType *FnType = Callee->getAs<FunctionType>()) 5636 return FnType->getReturnType().getNonReferenceType(); 5637 5638 // Unresolved call: try to guess the return type. 5639 if (const auto *OE = llvm::dyn_cast<OverloadExpr>(CE->getCallee())) { 5640 // If all candidates have the same approximate return type, use it. 5641 // Discard references and const to allow more to be "the same". 5642 // (In particular, if there's one candidate + ADL, resolve it). 5643 const Type *Common = nullptr; 5644 for (const auto *D : OE->decls()) { 5645 QualType ReturnType; 5646 if (const auto *FD = llvm::dyn_cast<FunctionDecl>(D)) 5647 ReturnType = FD->getReturnType(); 5648 else if (const auto *FTD = llvm::dyn_cast<FunctionTemplateDecl>(D)) 5649 ReturnType = FTD->getTemplatedDecl()->getReturnType(); 5650 if (ReturnType.isNull()) 5651 continue; 5652 const Type *Candidate = 5653 ReturnType.getNonReferenceType().getCanonicalType().getTypePtr(); 5654 if (Common && Common != Candidate) 5655 return Unresolved; // Multiple candidates. 5656 Common = Candidate; 5657 } 5658 if (Common != nullptr) 5659 return QualType(Common, 0); 5660 } 5661 } 5662 // A dependent member: approximate-resolve the base, then lookup. 5663 if (const auto *CDSME = llvm::dyn_cast<CXXDependentScopeMemberExpr>(E)) { 5664 QualType Base = CDSME->isImplicitAccess() 5665 ? CDSME->getBaseType() 5666 : getApproximateType(CDSME->getBase()); 5667 if (CDSME->isArrow() && !Base.isNull()) 5668 Base = Base->getPointeeType(); // could handle unique_ptr etc here? 5669 auto *RD = 5670 Base.isNull() 5671 ? nullptr 5672 : llvm::dyn_cast_or_null<CXXRecordDecl>(getAsRecordDecl(Base)); 5673 if (RD && RD->isCompleteDefinition()) { 5674 // Look up member heuristically, including in bases. 5675 for (const auto *Member : RD->lookupDependentName( 5676 CDSME->getMember(), [](const NamedDecl *Member) { 5677 return llvm::isa<ValueDecl>(Member); 5678 })) { 5679 return llvm::cast<ValueDecl>(Member)->getType().getNonReferenceType(); 5680 } 5681 } 5682 } 5683 // A reference to an `auto` variable: approximate-resolve its initializer. 5684 if (const auto *DRE = llvm::dyn_cast<DeclRefExpr>(E)) { 5685 if (const auto *VD = llvm::dyn_cast<VarDecl>(DRE->getDecl())) { 5686 if (VD->hasInit()) 5687 return getApproximateType(VD->getInit()); 5688 } 5689 } 5690 if (const auto *UO = llvm::dyn_cast<UnaryOperator>(E)) { 5691 if (UO->getOpcode() == UnaryOperatorKind::UO_Deref) { 5692 // We recurse into the subexpression because it could be of dependent 5693 // type. 5694 if (auto Pointee = getApproximateType(UO->getSubExpr())->getPointeeType(); 5695 !Pointee.isNull()) 5696 return Pointee; 5697 // Our caller expects a non-null result, even though the SubType is 5698 // supposed to have a pointee. Fall through to Unresolved anyway. 5699 } 5700 } 5701 return Unresolved; 5702 } 5703 5704 // If \p Base is ParenListExpr, assume a chain of comma operators and pick the 5705 // last expr. We expect other ParenListExprs to be resolved to e.g. constructor 5706 // calls before here. (So the ParenListExpr should be nonempty, but check just 5707 // in case) 5708 Expr *unwrapParenList(Expr *Base) { 5709 if (auto *PLE = llvm::dyn_cast_or_null<ParenListExpr>(Base)) { 5710 if (PLE->getNumExprs() == 0) 5711 return nullptr; 5712 Base = PLE->getExpr(PLE->getNumExprs() - 1); 5713 } 5714 return Base; 5715 } 5716 5717 } // namespace 5718 5719 void SemaCodeCompletion::CodeCompleteMemberReferenceExpr( 5720 Scope *S, Expr *Base, Expr *OtherOpBase, SourceLocation OpLoc, bool IsArrow, 5721 bool IsBaseExprStatement, QualType PreferredType) { 5722 Base = unwrapParenList(Base); 5723 OtherOpBase = unwrapParenList(OtherOpBase); 5724 if (!Base || !CodeCompleter) 5725 return; 5726 5727 ExprResult ConvertedBase = 5728 SemaRef.PerformMemberExprBaseConversion(Base, IsArrow); 5729 if (ConvertedBase.isInvalid()) 5730 return; 5731 QualType ConvertedBaseType = getApproximateType(ConvertedBase.get()); 5732 5733 enum CodeCompletionContext::Kind contextKind; 5734 5735 if (IsArrow) { 5736 if (const auto *Ptr = ConvertedBaseType->getAs<PointerType>()) 5737 ConvertedBaseType = Ptr->getPointeeType(); 5738 } 5739 5740 if (IsArrow) { 5741 contextKind = CodeCompletionContext::CCC_ArrowMemberAccess; 5742 } else { 5743 if (ConvertedBaseType->isObjCObjectPointerType() || 5744 ConvertedBaseType->isObjCObjectOrInterfaceType()) { 5745 contextKind = CodeCompletionContext::CCC_ObjCPropertyAccess; 5746 } else { 5747 contextKind = CodeCompletionContext::CCC_DotMemberAccess; 5748 } 5749 } 5750 5751 CodeCompletionContext CCContext(contextKind, ConvertedBaseType); 5752 CCContext.setPreferredType(PreferredType); 5753 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(), 5754 CodeCompleter->getCodeCompletionTUInfo(), CCContext, 5755 &ResultBuilder::IsMember); 5756 5757 auto DoCompletion = [&](Expr *Base, bool IsArrow, 5758 std::optional<FixItHint> AccessOpFixIt) -> bool { 5759 if (!Base) 5760 return false; 5761 5762 ExprResult ConvertedBase = 5763 SemaRef.PerformMemberExprBaseConversion(Base, IsArrow); 5764 if (ConvertedBase.isInvalid()) 5765 return false; 5766 Base = ConvertedBase.get(); 5767 5768 QualType BaseType = getApproximateType(Base); 5769 if (BaseType.isNull()) 5770 return false; 5771 ExprValueKind BaseKind = Base->getValueKind(); 5772 5773 if (IsArrow) { 5774 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 5775 BaseType = Ptr->getPointeeType(); 5776 BaseKind = VK_LValue; 5777 } else if (BaseType->isObjCObjectPointerType() || 5778 BaseType->isTemplateTypeParmType()) { 5779 // Both cases (dot/arrow) handled below. 5780 } else { 5781 return false; 5782 } 5783 } 5784 5785 if (RecordDecl *RD = getAsRecordDecl(BaseType)) { 5786 AddRecordMembersCompletionResults(SemaRef, Results, S, BaseType, BaseKind, 5787 RD, std::move(AccessOpFixIt)); 5788 } else if (const auto *TTPT = 5789 dyn_cast<TemplateTypeParmType>(BaseType.getTypePtr())) { 5790 auto Operator = 5791 IsArrow ? ConceptInfo::Member::Arrow : ConceptInfo::Member::Dot; 5792 for (const auto &R : ConceptInfo(*TTPT, S).members()) { 5793 if (R.Operator != Operator) 5794 continue; 5795 CodeCompletionResult Result( 5796 R.render(SemaRef, CodeCompleter->getAllocator(), 5797 CodeCompleter->getCodeCompletionTUInfo())); 5798 if (AccessOpFixIt) 5799 Result.FixIts.push_back(*AccessOpFixIt); 5800 Results.AddResult(std::move(Result)); 5801 } 5802 } else if (!IsArrow && BaseType->isObjCObjectPointerType()) { 5803 // Objective-C property reference. Bail if we're performing fix-it code 5804 // completion since Objective-C properties are normally backed by ivars, 5805 // most Objective-C fix-its here would have little value. 5806 if (AccessOpFixIt) { 5807 return false; 5808 } 5809 AddedPropertiesSet AddedProperties; 5810 5811 if (const ObjCObjectPointerType *ObjCPtr = 5812 BaseType->getAsObjCInterfacePointerType()) { 5813 // Add property results based on our interface. 5814 assert(ObjCPtr && "Non-NULL pointer guaranteed above!"); 5815 AddObjCProperties(CCContext, ObjCPtr->getInterfaceDecl(), true, 5816 /*AllowNullaryMethods=*/true, SemaRef.CurContext, 5817 AddedProperties, Results, IsBaseExprStatement); 5818 } 5819 5820 // Add properties from the protocols in a qualified interface. 5821 for (auto *I : BaseType->castAs<ObjCObjectPointerType>()->quals()) 5822 AddObjCProperties(CCContext, I, true, /*AllowNullaryMethods=*/true, 5823 SemaRef.CurContext, AddedProperties, Results, 5824 IsBaseExprStatement, /*IsClassProperty*/ false, 5825 /*InOriginalClass*/ false); 5826 } else if ((IsArrow && BaseType->isObjCObjectPointerType()) || 5827 (!IsArrow && BaseType->isObjCObjectType())) { 5828 // Objective-C instance variable access. Bail if we're performing fix-it 5829 // code completion since Objective-C properties are normally backed by 5830 // ivars, most Objective-C fix-its here would have little value. 5831 if (AccessOpFixIt) { 5832 return false; 5833 } 5834 ObjCInterfaceDecl *Class = nullptr; 5835 if (const ObjCObjectPointerType *ObjCPtr = 5836 BaseType->getAs<ObjCObjectPointerType>()) 5837 Class = ObjCPtr->getInterfaceDecl(); 5838 else 5839 Class = BaseType->castAs<ObjCObjectType>()->getInterface(); 5840 5841 // Add all ivars from this class and its superclasses. 5842 if (Class) { 5843 CodeCompletionDeclConsumer Consumer(Results, Class, BaseType); 5844 Results.setFilter(&ResultBuilder::IsObjCIvar); 5845 SemaRef.LookupVisibleDecls(Class, Sema::LookupMemberName, Consumer, 5846 CodeCompleter->includeGlobals(), 5847 /*IncludeDependentBases=*/false, 5848 CodeCompleter->loadExternal()); 5849 } 5850 } 5851 5852 // FIXME: How do we cope with isa? 5853 return true; 5854 }; 5855 5856 Results.EnterNewScope(); 5857 5858 bool CompletionSucceded = DoCompletion(Base, IsArrow, std::nullopt); 5859 if (CodeCompleter->includeFixIts()) { 5860 const CharSourceRange OpRange = 5861 CharSourceRange::getTokenRange(OpLoc, OpLoc); 5862 CompletionSucceded |= DoCompletion( 5863 OtherOpBase, !IsArrow, 5864 FixItHint::CreateReplacement(OpRange, IsArrow ? "." : "->")); 5865 } 5866 5867 Results.ExitScope(); 5868 5869 if (!CompletionSucceded) 5870 return; 5871 5872 // Hand off the results found for code completion. 5873 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 5874 Results.getCompletionContext(), Results.data(), 5875 Results.size()); 5876 } 5877 5878 void SemaCodeCompletion::CodeCompleteObjCClassPropertyRefExpr( 5879 Scope *S, const IdentifierInfo &ClassName, SourceLocation ClassNameLoc, 5880 bool IsBaseExprStatement) { 5881 const IdentifierInfo *ClassNamePtr = &ClassName; 5882 ObjCInterfaceDecl *IFace = 5883 SemaRef.ObjC().getObjCInterfaceDecl(ClassNamePtr, ClassNameLoc); 5884 if (!IFace) 5885 return; 5886 CodeCompletionContext CCContext( 5887 CodeCompletionContext::CCC_ObjCPropertyAccess); 5888 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(), 5889 CodeCompleter->getCodeCompletionTUInfo(), CCContext, 5890 &ResultBuilder::IsMember); 5891 Results.EnterNewScope(); 5892 AddedPropertiesSet AddedProperties; 5893 AddObjCProperties(CCContext, IFace, true, 5894 /*AllowNullaryMethods=*/true, SemaRef.CurContext, 5895 AddedProperties, Results, IsBaseExprStatement, 5896 /*IsClassProperty=*/true); 5897 Results.ExitScope(); 5898 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 5899 Results.getCompletionContext(), Results.data(), 5900 Results.size()); 5901 } 5902 5903 void SemaCodeCompletion::CodeCompleteTag(Scope *S, unsigned TagSpec) { 5904 if (!CodeCompleter) 5905 return; 5906 5907 ResultBuilder::LookupFilter Filter = nullptr; 5908 enum CodeCompletionContext::Kind ContextKind = 5909 CodeCompletionContext::CCC_Other; 5910 switch ((DeclSpec::TST)TagSpec) { 5911 case DeclSpec::TST_enum: 5912 Filter = &ResultBuilder::IsEnum; 5913 ContextKind = CodeCompletionContext::CCC_EnumTag; 5914 break; 5915 5916 case DeclSpec::TST_union: 5917 Filter = &ResultBuilder::IsUnion; 5918 ContextKind = CodeCompletionContext::CCC_UnionTag; 5919 break; 5920 5921 case DeclSpec::TST_struct: 5922 case DeclSpec::TST_class: 5923 case DeclSpec::TST_interface: 5924 Filter = &ResultBuilder::IsClassOrStruct; 5925 ContextKind = CodeCompletionContext::CCC_ClassOrStructTag; 5926 break; 5927 5928 default: 5929 llvm_unreachable("Unknown type specifier kind in CodeCompleteTag"); 5930 } 5931 5932 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(), 5933 CodeCompleter->getCodeCompletionTUInfo(), ContextKind); 5934 CodeCompletionDeclConsumer Consumer(Results, SemaRef.CurContext); 5935 5936 // First pass: look for tags. 5937 Results.setFilter(Filter); 5938 SemaRef.LookupVisibleDecls(S, Sema::LookupTagName, Consumer, 5939 CodeCompleter->includeGlobals(), 5940 CodeCompleter->loadExternal()); 5941 5942 if (CodeCompleter->includeGlobals()) { 5943 // Second pass: look for nested name specifiers. 5944 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier); 5945 SemaRef.LookupVisibleDecls(S, Sema::LookupNestedNameSpecifierName, Consumer, 5946 CodeCompleter->includeGlobals(), 5947 CodeCompleter->loadExternal()); 5948 } 5949 5950 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 5951 Results.getCompletionContext(), Results.data(), 5952 Results.size()); 5953 } 5954 5955 static void AddTypeQualifierResults(DeclSpec &DS, ResultBuilder &Results, 5956 const LangOptions &LangOpts) { 5957 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_const)) 5958 Results.AddResult("const"); 5959 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_volatile)) 5960 Results.AddResult("volatile"); 5961 if (LangOpts.C99 && !(DS.getTypeQualifiers() & DeclSpec::TQ_restrict)) 5962 Results.AddResult("restrict"); 5963 if (LangOpts.C11 && !(DS.getTypeQualifiers() & DeclSpec::TQ_atomic)) 5964 Results.AddResult("_Atomic"); 5965 if (LangOpts.MSVCCompat && !(DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)) 5966 Results.AddResult("__unaligned"); 5967 } 5968 5969 void SemaCodeCompletion::CodeCompleteTypeQualifiers(DeclSpec &DS) { 5970 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(), 5971 CodeCompleter->getCodeCompletionTUInfo(), 5972 CodeCompletionContext::CCC_TypeQualifiers); 5973 Results.EnterNewScope(); 5974 AddTypeQualifierResults(DS, Results, getLangOpts()); 5975 Results.ExitScope(); 5976 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 5977 Results.getCompletionContext(), Results.data(), 5978 Results.size()); 5979 } 5980 5981 void SemaCodeCompletion::CodeCompleteFunctionQualifiers( 5982 DeclSpec &DS, Declarator &D, const VirtSpecifiers *VS) { 5983 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(), 5984 CodeCompleter->getCodeCompletionTUInfo(), 5985 CodeCompletionContext::CCC_TypeQualifiers); 5986 Results.EnterNewScope(); 5987 AddTypeQualifierResults(DS, Results, getLangOpts()); 5988 if (getLangOpts().CPlusPlus11) { 5989 Results.AddResult("noexcept"); 5990 if (D.getContext() == DeclaratorContext::Member && !D.isCtorOrDtor() && 5991 !D.isStaticMember()) { 5992 if (!VS || !VS->isFinalSpecified()) 5993 Results.AddResult("final"); 5994 if (!VS || !VS->isOverrideSpecified()) 5995 Results.AddResult("override"); 5996 } 5997 } 5998 Results.ExitScope(); 5999 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 6000 Results.getCompletionContext(), Results.data(), 6001 Results.size()); 6002 } 6003 6004 void SemaCodeCompletion::CodeCompleteBracketDeclarator(Scope *S) { 6005 CodeCompleteExpression(S, QualType(getASTContext().getSizeType())); 6006 } 6007 6008 void SemaCodeCompletion::CodeCompleteCase(Scope *S) { 6009 if (SemaRef.getCurFunction()->SwitchStack.empty() || !CodeCompleter) 6010 return; 6011 6012 SwitchStmt *Switch = 6013 SemaRef.getCurFunction()->SwitchStack.back().getPointer(); 6014 // Condition expression might be invalid, do not continue in this case. 6015 if (!Switch->getCond()) 6016 return; 6017 QualType type = Switch->getCond()->IgnoreImplicit()->getType(); 6018 if (!type->isEnumeralType()) { 6019 CodeCompleteExpressionData Data(type); 6020 Data.IntegralConstantExpression = true; 6021 CodeCompleteExpression(S, Data); 6022 return; 6023 } 6024 6025 // Code-complete the cases of a switch statement over an enumeration type 6026 // by providing the list of 6027 EnumDecl *Enum = type->castAs<EnumType>()->getDecl(); 6028 if (EnumDecl *Def = Enum->getDefinition()) 6029 Enum = Def; 6030 6031 // Determine which enumerators we have already seen in the switch statement. 6032 // FIXME: Ideally, we would also be able to look *past* the code-completion 6033 // token, in case we are code-completing in the middle of the switch and not 6034 // at the end. However, we aren't able to do so at the moment. 6035 CoveredEnumerators Enumerators; 6036 for (SwitchCase *SC = Switch->getSwitchCaseList(); SC; 6037 SC = SC->getNextSwitchCase()) { 6038 CaseStmt *Case = dyn_cast<CaseStmt>(SC); 6039 if (!Case) 6040 continue; 6041 6042 Expr *CaseVal = Case->getLHS()->IgnoreParenCasts(); 6043 if (auto *DRE = dyn_cast<DeclRefExpr>(CaseVal)) 6044 if (auto *Enumerator = 6045 dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 6046 // We look into the AST of the case statement to determine which 6047 // enumerator was named. Alternatively, we could compute the value of 6048 // the integral constant expression, then compare it against the 6049 // values of each enumerator. However, value-based approach would not 6050 // work as well with C++ templates where enumerators declared within a 6051 // template are type- and value-dependent. 6052 Enumerators.Seen.insert(Enumerator); 6053 6054 // If this is a qualified-id, keep track of the nested-name-specifier 6055 // so that we can reproduce it as part of code completion, e.g., 6056 // 6057 // switch (TagD.getKind()) { 6058 // case TagDecl::TK_enum: 6059 // break; 6060 // case XXX 6061 // 6062 // At the XXX, our completions are TagDecl::TK_union, 6063 // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union, 6064 // TK_struct, and TK_class. 6065 Enumerators.SuggestedQualifier = DRE->getQualifier(); 6066 } 6067 } 6068 6069 // Add any enumerators that have not yet been mentioned. 6070 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(), 6071 CodeCompleter->getCodeCompletionTUInfo(), 6072 CodeCompletionContext::CCC_Expression); 6073 AddEnumerators(Results, getASTContext(), Enum, SemaRef.CurContext, 6074 Enumerators); 6075 6076 if (CodeCompleter->includeMacros()) { 6077 AddMacroResults(SemaRef.PP, Results, CodeCompleter->loadExternal(), false); 6078 } 6079 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 6080 Results.getCompletionContext(), Results.data(), 6081 Results.size()); 6082 } 6083 6084 static bool anyNullArguments(ArrayRef<Expr *> Args) { 6085 if (Args.size() && !Args.data()) 6086 return true; 6087 6088 for (unsigned I = 0; I != Args.size(); ++I) 6089 if (!Args[I]) 6090 return true; 6091 6092 return false; 6093 } 6094 6095 typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate; 6096 6097 static void mergeCandidatesWithResults( 6098 Sema &SemaRef, SmallVectorImpl<ResultCandidate> &Results, 6099 OverloadCandidateSet &CandidateSet, SourceLocation Loc, size_t ArgSize) { 6100 // Sort the overload candidate set by placing the best overloads first. 6101 llvm::stable_sort(CandidateSet, [&](const OverloadCandidate &X, 6102 const OverloadCandidate &Y) { 6103 return isBetterOverloadCandidate(SemaRef, X, Y, Loc, 6104 CandidateSet.getKind()); 6105 }); 6106 6107 // Add the remaining viable overload candidates as code-completion results. 6108 for (OverloadCandidate &Candidate : CandidateSet) { 6109 if (Candidate.Function) { 6110 if (Candidate.Function->isDeleted()) 6111 continue; 6112 if (shouldEnforceArgLimit(/*PartialOverloading=*/true, 6113 Candidate.Function) && 6114 Candidate.Function->getNumParams() <= ArgSize && 6115 // Having zero args is annoying, normally we don't surface a function 6116 // with 2 params, if you already have 2 params, because you are 6117 // inserting the 3rd now. But with zero, it helps the user to figure 6118 // out there are no overloads that take any arguments. Hence we are 6119 // keeping the overload. 6120 ArgSize > 0) 6121 continue; 6122 } 6123 if (Candidate.Viable) 6124 Results.push_back(ResultCandidate(Candidate.Function)); 6125 } 6126 } 6127 6128 /// Get the type of the Nth parameter from a given set of overload 6129 /// candidates. 6130 static QualType getParamType(Sema &SemaRef, 6131 ArrayRef<ResultCandidate> Candidates, unsigned N) { 6132 6133 // Given the overloads 'Candidates' for a function call matching all arguments 6134 // up to N, return the type of the Nth parameter if it is the same for all 6135 // overload candidates. 6136 QualType ParamType; 6137 for (auto &Candidate : Candidates) { 6138 QualType CandidateParamType = Candidate.getParamType(N); 6139 if (CandidateParamType.isNull()) 6140 continue; 6141 if (ParamType.isNull()) { 6142 ParamType = CandidateParamType; 6143 continue; 6144 } 6145 if (!SemaRef.Context.hasSameUnqualifiedType( 6146 ParamType.getNonReferenceType(), 6147 CandidateParamType.getNonReferenceType())) 6148 // Two conflicting types, give up. 6149 return QualType(); 6150 } 6151 6152 return ParamType; 6153 } 6154 6155 static QualType 6156 ProduceSignatureHelp(Sema &SemaRef, MutableArrayRef<ResultCandidate> Candidates, 6157 unsigned CurrentArg, SourceLocation OpenParLoc, 6158 bool Braced) { 6159 if (Candidates.empty()) 6160 return QualType(); 6161 if (SemaRef.getPreprocessor().isCodeCompletionReached()) 6162 SemaRef.CodeCompletion().CodeCompleter->ProcessOverloadCandidates( 6163 SemaRef, CurrentArg, Candidates.data(), Candidates.size(), OpenParLoc, 6164 Braced); 6165 return getParamType(SemaRef, Candidates, CurrentArg); 6166 } 6167 6168 // Given a callee expression `Fn`, if the call is through a function pointer, 6169 // try to find the declaration of the corresponding function pointer type, 6170 // so that we can recover argument names from it. 6171 static FunctionProtoTypeLoc GetPrototypeLoc(Expr *Fn) { 6172 TypeLoc Target; 6173 6174 if (const auto *T = Fn->getType().getTypePtr()->getAs<TypedefType>()) { 6175 Target = T->getDecl()->getTypeSourceInfo()->getTypeLoc(); 6176 6177 } else if (const auto *DR = dyn_cast<DeclRefExpr>(Fn)) { 6178 const auto *D = DR->getDecl(); 6179 if (const auto *const VD = dyn_cast<VarDecl>(D)) { 6180 Target = VD->getTypeSourceInfo()->getTypeLoc(); 6181 } 6182 } else if (const auto *ME = dyn_cast<MemberExpr>(Fn)) { 6183 const auto *MD = ME->getMemberDecl(); 6184 if (const auto *FD = dyn_cast<FieldDecl>(MD)) { 6185 Target = FD->getTypeSourceInfo()->getTypeLoc(); 6186 } 6187 } 6188 6189 if (!Target) 6190 return {}; 6191 6192 // Unwrap types that may be wrapping the function type 6193 while (true) { 6194 if (auto P = Target.getAs<PointerTypeLoc>()) { 6195 Target = P.getPointeeLoc(); 6196 continue; 6197 } 6198 if (auto A = Target.getAs<AttributedTypeLoc>()) { 6199 Target = A.getModifiedLoc(); 6200 continue; 6201 } 6202 if (auto P = Target.getAs<ParenTypeLoc>()) { 6203 Target = P.getInnerLoc(); 6204 continue; 6205 } 6206 break; 6207 } 6208 6209 if (auto F = Target.getAs<FunctionProtoTypeLoc>()) { 6210 return F; 6211 } 6212 6213 return {}; 6214 } 6215 6216 QualType 6217 SemaCodeCompletion::ProduceCallSignatureHelp(Expr *Fn, ArrayRef<Expr *> Args, 6218 SourceLocation OpenParLoc) { 6219 Fn = unwrapParenList(Fn); 6220 if (!CodeCompleter || !Fn) 6221 return QualType(); 6222 6223 // FIXME: Provide support for variadic template functions. 6224 // Ignore type-dependent call expressions entirely. 6225 if (Fn->isTypeDependent() || anyNullArguments(Args)) 6226 return QualType(); 6227 // In presence of dependent args we surface all possible signatures using the 6228 // non-dependent args in the prefix. Afterwards we do a post filtering to make 6229 // sure provided candidates satisfy parameter count restrictions. 6230 auto ArgsWithoutDependentTypes = 6231 Args.take_while([](Expr *Arg) { return !Arg->isTypeDependent(); }); 6232 6233 SmallVector<ResultCandidate, 8> Results; 6234 6235 Expr *NakedFn = Fn->IgnoreParenCasts(); 6236 // Build an overload candidate set based on the functions we find. 6237 SourceLocation Loc = Fn->getExprLoc(); 6238 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); 6239 6240 if (auto ULE = dyn_cast<UnresolvedLookupExpr>(NakedFn)) { 6241 SemaRef.AddOverloadedCallCandidates(ULE, ArgsWithoutDependentTypes, 6242 CandidateSet, 6243 /*PartialOverloading=*/true); 6244 } else if (auto UME = dyn_cast<UnresolvedMemberExpr>(NakedFn)) { 6245 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 6246 if (UME->hasExplicitTemplateArgs()) { 6247 UME->copyTemplateArgumentsInto(TemplateArgsBuffer); 6248 TemplateArgs = &TemplateArgsBuffer; 6249 } 6250 6251 // Add the base as first argument (use a nullptr if the base is implicit). 6252 SmallVector<Expr *, 12> ArgExprs( 6253 1, UME->isImplicitAccess() ? nullptr : UME->getBase()); 6254 ArgExprs.append(ArgsWithoutDependentTypes.begin(), 6255 ArgsWithoutDependentTypes.end()); 6256 UnresolvedSet<8> Decls; 6257 Decls.append(UME->decls_begin(), UME->decls_end()); 6258 const bool FirstArgumentIsBase = !UME->isImplicitAccess() && UME->getBase(); 6259 SemaRef.AddFunctionCandidates(Decls, ArgExprs, CandidateSet, TemplateArgs, 6260 /*SuppressUserConversions=*/false, 6261 /*PartialOverloading=*/true, 6262 FirstArgumentIsBase); 6263 } else { 6264 FunctionDecl *FD = nullptr; 6265 if (auto *MCE = dyn_cast<MemberExpr>(NakedFn)) 6266 FD = dyn_cast<FunctionDecl>(MCE->getMemberDecl()); 6267 else if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) 6268 FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 6269 if (FD) { // We check whether it's a resolved function declaration. 6270 if (!getLangOpts().CPlusPlus || 6271 !FD->getType()->getAs<FunctionProtoType>()) 6272 Results.push_back(ResultCandidate(FD)); 6273 else 6274 SemaRef.AddOverloadCandidate(FD, 6275 DeclAccessPair::make(FD, FD->getAccess()), 6276 ArgsWithoutDependentTypes, CandidateSet, 6277 /*SuppressUserConversions=*/false, 6278 /*PartialOverloading=*/true); 6279 6280 } else if (auto DC = NakedFn->getType()->getAsCXXRecordDecl()) { 6281 // If expression's type is CXXRecordDecl, it may overload the function 6282 // call operator, so we check if it does and add them as candidates. 6283 // A complete type is needed to lookup for member function call operators. 6284 if (SemaRef.isCompleteType(Loc, NakedFn->getType())) { 6285 DeclarationName OpName = 6286 getASTContext().DeclarationNames.getCXXOperatorName(OO_Call); 6287 LookupResult R(SemaRef, OpName, Loc, Sema::LookupOrdinaryName); 6288 SemaRef.LookupQualifiedName(R, DC); 6289 R.suppressDiagnostics(); 6290 SmallVector<Expr *, 12> ArgExprs(1, NakedFn); 6291 ArgExprs.append(ArgsWithoutDependentTypes.begin(), 6292 ArgsWithoutDependentTypes.end()); 6293 SemaRef.AddFunctionCandidates(R.asUnresolvedSet(), ArgExprs, 6294 CandidateSet, 6295 /*ExplicitArgs=*/nullptr, 6296 /*SuppressUserConversions=*/false, 6297 /*PartialOverloading=*/true); 6298 } 6299 } else { 6300 // Lastly we check whether expression's type is function pointer or 6301 // function. 6302 6303 FunctionProtoTypeLoc P = GetPrototypeLoc(NakedFn); 6304 QualType T = NakedFn->getType(); 6305 if (!T->getPointeeType().isNull()) 6306 T = T->getPointeeType(); 6307 6308 if (auto FP = T->getAs<FunctionProtoType>()) { 6309 if (!SemaRef.TooManyArguments(FP->getNumParams(), 6310 ArgsWithoutDependentTypes.size(), 6311 /*PartialOverloading=*/true) || 6312 FP->isVariadic()) { 6313 if (P) { 6314 Results.push_back(ResultCandidate(P)); 6315 } else { 6316 Results.push_back(ResultCandidate(FP)); 6317 } 6318 } 6319 } else if (auto FT = T->getAs<FunctionType>()) 6320 // No prototype and declaration, it may be a K & R style function. 6321 Results.push_back(ResultCandidate(FT)); 6322 } 6323 } 6324 mergeCandidatesWithResults(SemaRef, Results, CandidateSet, Loc, Args.size()); 6325 QualType ParamType = ProduceSignatureHelp(SemaRef, Results, Args.size(), 6326 OpenParLoc, /*Braced=*/false); 6327 return !CandidateSet.empty() ? ParamType : QualType(); 6328 } 6329 6330 // Determine which param to continue aggregate initialization from after 6331 // a designated initializer. 6332 // 6333 // Given struct S { int a,b,c,d,e; }: 6334 // after `S{.b=1,` we want to suggest c to continue 6335 // after `S{.b=1, 2,` we continue with d (this is legal C and ext in C++) 6336 // after `S{.b=1, .a=2,` we continue with b (this is legal C and ext in C++) 6337 // 6338 // Possible outcomes: 6339 // - we saw a designator for a field, and continue from the returned index. 6340 // Only aggregate initialization is allowed. 6341 // - we saw a designator, but it was complex or we couldn't find the field. 6342 // Only aggregate initialization is possible, but we can't assist with it. 6343 // Returns an out-of-range index. 6344 // - we saw no designators, just positional arguments. 6345 // Returns std::nullopt. 6346 static std::optional<unsigned> 6347 getNextAggregateIndexAfterDesignatedInit(const ResultCandidate &Aggregate, 6348 ArrayRef<Expr *> Args) { 6349 static constexpr unsigned Invalid = std::numeric_limits<unsigned>::max(); 6350 assert(Aggregate.getKind() == ResultCandidate::CK_Aggregate); 6351 6352 // Look for designated initializers. 6353 // They're in their syntactic form, not yet resolved to fields. 6354 const IdentifierInfo *DesignatedFieldName = nullptr; 6355 unsigned ArgsAfterDesignator = 0; 6356 for (const Expr *Arg : Args) { 6357 if (const auto *DIE = dyn_cast<DesignatedInitExpr>(Arg)) { 6358 if (DIE->size() == 1 && DIE->getDesignator(0)->isFieldDesignator()) { 6359 DesignatedFieldName = DIE->getDesignator(0)->getFieldName(); 6360 ArgsAfterDesignator = 0; 6361 } else { 6362 return Invalid; // Complicated designator. 6363 } 6364 } else if (isa<DesignatedInitUpdateExpr>(Arg)) { 6365 return Invalid; // Unsupported. 6366 } else { 6367 ++ArgsAfterDesignator; 6368 } 6369 } 6370 if (!DesignatedFieldName) 6371 return std::nullopt; 6372 6373 // Find the index within the class's fields. 6374 // (Probing getParamDecl() directly would be quadratic in number of fields). 6375 unsigned DesignatedIndex = 0; 6376 const FieldDecl *DesignatedField = nullptr; 6377 for (const auto *Field : Aggregate.getAggregate()->fields()) { 6378 if (Field->getIdentifier() == DesignatedFieldName) { 6379 DesignatedField = Field; 6380 break; 6381 } 6382 ++DesignatedIndex; 6383 } 6384 if (!DesignatedField) 6385 return Invalid; // Designator referred to a missing field, give up. 6386 6387 // Find the index within the aggregate (which may have leading bases). 6388 unsigned AggregateSize = Aggregate.getNumParams(); 6389 while (DesignatedIndex < AggregateSize && 6390 Aggregate.getParamDecl(DesignatedIndex) != DesignatedField) 6391 ++DesignatedIndex; 6392 6393 // Continue from the index after the last named field. 6394 return DesignatedIndex + ArgsAfterDesignator + 1; 6395 } 6396 6397 QualType SemaCodeCompletion::ProduceConstructorSignatureHelp( 6398 QualType Type, SourceLocation Loc, ArrayRef<Expr *> Args, 6399 SourceLocation OpenParLoc, bool Braced) { 6400 if (!CodeCompleter) 6401 return QualType(); 6402 SmallVector<ResultCandidate, 8> Results; 6403 6404 // A complete type is needed to lookup for constructors. 6405 RecordDecl *RD = 6406 SemaRef.isCompleteType(Loc, Type) ? Type->getAsRecordDecl() : nullptr; 6407 if (!RD) 6408 return Type; 6409 CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD); 6410 6411 // Consider aggregate initialization. 6412 // We don't check that types so far are correct. 6413 // We also don't handle C99/C++17 brace-elision, we assume init-list elements 6414 // are 1:1 with fields. 6415 // FIXME: it would be nice to support "unwrapping" aggregates that contain 6416 // a single subaggregate, like std::array<T, N> -> T __elements[N]. 6417 if (Braced && !RD->isUnion() && 6418 (!getLangOpts().CPlusPlus || (CRD && CRD->isAggregate()))) { 6419 ResultCandidate AggregateSig(RD); 6420 unsigned AggregateSize = AggregateSig.getNumParams(); 6421 6422 if (auto NextIndex = 6423 getNextAggregateIndexAfterDesignatedInit(AggregateSig, Args)) { 6424 // A designator was used, only aggregate init is possible. 6425 if (*NextIndex >= AggregateSize) 6426 return Type; 6427 Results.push_back(AggregateSig); 6428 return ProduceSignatureHelp(SemaRef, Results, *NextIndex, OpenParLoc, 6429 Braced); 6430 } 6431 6432 // Describe aggregate initialization, but also constructors below. 6433 if (Args.size() < AggregateSize) 6434 Results.push_back(AggregateSig); 6435 } 6436 6437 // FIXME: Provide support for member initializers. 6438 // FIXME: Provide support for variadic template constructors. 6439 6440 if (CRD) { 6441 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); 6442 for (NamedDecl *C : SemaRef.LookupConstructors(CRD)) { 6443 if (auto *FD = dyn_cast<FunctionDecl>(C)) { 6444 // FIXME: we can't yet provide correct signature help for initializer 6445 // list constructors, so skip them entirely. 6446 if (Braced && getLangOpts().CPlusPlus && 6447 SemaRef.isInitListConstructor(FD)) 6448 continue; 6449 SemaRef.AddOverloadCandidate( 6450 FD, DeclAccessPair::make(FD, C->getAccess()), Args, CandidateSet, 6451 /*SuppressUserConversions=*/false, 6452 /*PartialOverloading=*/true, 6453 /*AllowExplicit*/ true); 6454 } else if (auto *FTD = dyn_cast<FunctionTemplateDecl>(C)) { 6455 if (Braced && getLangOpts().CPlusPlus && 6456 SemaRef.isInitListConstructor(FTD->getTemplatedDecl())) 6457 continue; 6458 6459 SemaRef.AddTemplateOverloadCandidate( 6460 FTD, DeclAccessPair::make(FTD, C->getAccess()), 6461 /*ExplicitTemplateArgs=*/nullptr, Args, CandidateSet, 6462 /*SuppressUserConversions=*/false, 6463 /*PartialOverloading=*/true); 6464 } 6465 } 6466 mergeCandidatesWithResults(SemaRef, Results, CandidateSet, Loc, 6467 Args.size()); 6468 } 6469 6470 return ProduceSignatureHelp(SemaRef, Results, Args.size(), OpenParLoc, 6471 Braced); 6472 } 6473 6474 QualType SemaCodeCompletion::ProduceCtorInitMemberSignatureHelp( 6475 Decl *ConstructorDecl, CXXScopeSpec SS, ParsedType TemplateTypeTy, 6476 ArrayRef<Expr *> ArgExprs, IdentifierInfo *II, SourceLocation OpenParLoc, 6477 bool Braced) { 6478 if (!CodeCompleter) 6479 return QualType(); 6480 6481 CXXConstructorDecl *Constructor = 6482 dyn_cast<CXXConstructorDecl>(ConstructorDecl); 6483 if (!Constructor) 6484 return QualType(); 6485 // FIXME: Add support for Base class constructors as well. 6486 if (ValueDecl *MemberDecl = SemaRef.tryLookupCtorInitMemberDecl( 6487 Constructor->getParent(), SS, TemplateTypeTy, II)) 6488 return ProduceConstructorSignatureHelp(MemberDecl->getType(), 6489 MemberDecl->getLocation(), ArgExprs, 6490 OpenParLoc, Braced); 6491 return QualType(); 6492 } 6493 6494 static bool argMatchesTemplateParams(const ParsedTemplateArgument &Arg, 6495 unsigned Index, 6496 const TemplateParameterList &Params) { 6497 const NamedDecl *Param; 6498 if (Index < Params.size()) 6499 Param = Params.getParam(Index); 6500 else if (Params.hasParameterPack()) 6501 Param = Params.asArray().back(); 6502 else 6503 return false; // too many args 6504 6505 switch (Arg.getKind()) { 6506 case ParsedTemplateArgument::Type: 6507 return llvm::isa<TemplateTypeParmDecl>(Param); // constraints not checked 6508 case ParsedTemplateArgument::NonType: 6509 return llvm::isa<NonTypeTemplateParmDecl>(Param); // type not checked 6510 case ParsedTemplateArgument::Template: 6511 return llvm::isa<TemplateTemplateParmDecl>(Param); // signature not checked 6512 } 6513 llvm_unreachable("Unhandled switch case"); 6514 } 6515 6516 QualType SemaCodeCompletion::ProduceTemplateArgumentSignatureHelp( 6517 TemplateTy ParsedTemplate, ArrayRef<ParsedTemplateArgument> Args, 6518 SourceLocation LAngleLoc) { 6519 if (!CodeCompleter || !ParsedTemplate) 6520 return QualType(); 6521 6522 SmallVector<ResultCandidate, 8> Results; 6523 auto Consider = [&](const TemplateDecl *TD) { 6524 // Only add if the existing args are compatible with the template. 6525 bool Matches = true; 6526 for (unsigned I = 0; I < Args.size(); ++I) { 6527 if (!argMatchesTemplateParams(Args[I], I, *TD->getTemplateParameters())) { 6528 Matches = false; 6529 break; 6530 } 6531 } 6532 if (Matches) 6533 Results.emplace_back(TD); 6534 }; 6535 6536 TemplateName Template = ParsedTemplate.get(); 6537 if (const auto *TD = Template.getAsTemplateDecl()) { 6538 Consider(TD); 6539 } else if (const auto *OTS = Template.getAsOverloadedTemplate()) { 6540 for (const NamedDecl *ND : *OTS) 6541 if (const auto *TD = llvm::dyn_cast<TemplateDecl>(ND)) 6542 Consider(TD); 6543 } 6544 return ProduceSignatureHelp(SemaRef, Results, Args.size(), LAngleLoc, 6545 /*Braced=*/false); 6546 } 6547 6548 static QualType getDesignatedType(QualType BaseType, const Designation &Desig) { 6549 for (unsigned I = 0; I < Desig.getNumDesignators(); ++I) { 6550 if (BaseType.isNull()) 6551 break; 6552 QualType NextType; 6553 const auto &D = Desig.getDesignator(I); 6554 if (D.isArrayDesignator() || D.isArrayRangeDesignator()) { 6555 if (BaseType->isArrayType()) 6556 NextType = BaseType->getAsArrayTypeUnsafe()->getElementType(); 6557 } else { 6558 assert(D.isFieldDesignator()); 6559 auto *RD = getAsRecordDecl(BaseType); 6560 if (RD && RD->isCompleteDefinition()) { 6561 for (const auto *Member : RD->lookup(D.getFieldDecl())) 6562 if (const FieldDecl *FD = llvm::dyn_cast<FieldDecl>(Member)) { 6563 NextType = FD->getType(); 6564 break; 6565 } 6566 } 6567 } 6568 BaseType = NextType; 6569 } 6570 return BaseType; 6571 } 6572 6573 void SemaCodeCompletion::CodeCompleteDesignator( 6574 QualType BaseType, llvm::ArrayRef<Expr *> InitExprs, const Designation &D) { 6575 BaseType = getDesignatedType(BaseType, D); 6576 if (BaseType.isNull()) 6577 return; 6578 const auto *RD = getAsRecordDecl(BaseType); 6579 if (!RD || RD->fields().empty()) 6580 return; 6581 6582 CodeCompletionContext CCC(CodeCompletionContext::CCC_DotMemberAccess, 6583 BaseType); 6584 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(), 6585 CodeCompleter->getCodeCompletionTUInfo(), CCC); 6586 6587 Results.EnterNewScope(); 6588 for (const Decl *D : RD->decls()) { 6589 const FieldDecl *FD; 6590 if (auto *IFD = dyn_cast<IndirectFieldDecl>(D)) 6591 FD = IFD->getAnonField(); 6592 else if (auto *DFD = dyn_cast<FieldDecl>(D)) 6593 FD = DFD; 6594 else 6595 continue; 6596 6597 // FIXME: Make use of previous designators to mark any fields before those 6598 // inaccessible, and also compute the next initializer priority. 6599 ResultBuilder::Result Result(FD, Results.getBasePriority(FD)); 6600 Results.AddResult(Result, SemaRef.CurContext, /*Hiding=*/nullptr); 6601 } 6602 Results.ExitScope(); 6603 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 6604 Results.getCompletionContext(), Results.data(), 6605 Results.size()); 6606 } 6607 6608 void SemaCodeCompletion::CodeCompleteInitializer(Scope *S, Decl *D) { 6609 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D); 6610 if (!VD) { 6611 CodeCompleteOrdinaryName(S, PCC_Expression); 6612 return; 6613 } 6614 6615 CodeCompleteExpressionData Data; 6616 Data.PreferredType = VD->getType(); 6617 // Ignore VD to avoid completing the variable itself, e.g. in 'int foo = ^'. 6618 Data.IgnoreDecls.push_back(VD); 6619 6620 CodeCompleteExpression(S, Data); 6621 } 6622 6623 void SemaCodeCompletion::CodeCompleteAfterIf(Scope *S, bool IsBracedThen) { 6624 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(), 6625 CodeCompleter->getCodeCompletionTUInfo(), 6626 mapCodeCompletionContext(SemaRef, PCC_Statement)); 6627 Results.setFilter(&ResultBuilder::IsOrdinaryName); 6628 Results.EnterNewScope(); 6629 6630 CodeCompletionDeclConsumer Consumer(Results, SemaRef.CurContext); 6631 SemaRef.LookupVisibleDecls(S, Sema::LookupOrdinaryName, Consumer, 6632 CodeCompleter->includeGlobals(), 6633 CodeCompleter->loadExternal()); 6634 6635 AddOrdinaryNameResults(PCC_Statement, S, SemaRef, Results); 6636 6637 // "else" block 6638 CodeCompletionBuilder Builder(Results.getAllocator(), 6639 Results.getCodeCompletionTUInfo()); 6640 6641 auto AddElseBodyPattern = [&] { 6642 if (IsBracedThen) { 6643 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 6644 Builder.AddChunk(CodeCompletionString::CK_LeftBrace); 6645 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); 6646 Builder.AddPlaceholderChunk("statements"); 6647 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); 6648 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 6649 } else { 6650 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); 6651 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 6652 Builder.AddPlaceholderChunk("statement"); 6653 Builder.AddChunk(CodeCompletionString::CK_SemiColon); 6654 } 6655 }; 6656 Builder.AddTypedTextChunk("else"); 6657 if (Results.includeCodePatterns()) 6658 AddElseBodyPattern(); 6659 Results.AddResult(Builder.TakeString()); 6660 6661 // "else if" block 6662 Builder.AddTypedTextChunk("else if"); 6663 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 6664 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 6665 if (getLangOpts().CPlusPlus) 6666 Builder.AddPlaceholderChunk("condition"); 6667 else 6668 Builder.AddPlaceholderChunk("expression"); 6669 Builder.AddChunk(CodeCompletionString::CK_RightParen); 6670 if (Results.includeCodePatterns()) { 6671 AddElseBodyPattern(); 6672 } 6673 Results.AddResult(Builder.TakeString()); 6674 6675 Results.ExitScope(); 6676 6677 if (S->getFnParent()) 6678 AddPrettyFunctionResults(getLangOpts(), Results); 6679 6680 if (CodeCompleter->includeMacros()) 6681 AddMacroResults(SemaRef.PP, Results, CodeCompleter->loadExternal(), false); 6682 6683 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 6684 Results.getCompletionContext(), Results.data(), 6685 Results.size()); 6686 } 6687 6688 void SemaCodeCompletion::CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS, 6689 bool EnteringContext, 6690 bool IsUsingDeclaration, 6691 QualType BaseType, 6692 QualType PreferredType) { 6693 if (SS.isEmpty() || !CodeCompleter) 6694 return; 6695 6696 CodeCompletionContext CC(CodeCompletionContext::CCC_Symbol, PreferredType); 6697 CC.setIsUsingDeclaration(IsUsingDeclaration); 6698 CC.setCXXScopeSpecifier(SS); 6699 6700 // We want to keep the scope specifier even if it's invalid (e.g. the scope 6701 // "a::b::" is not corresponding to any context/namespace in the AST), since 6702 // it can be useful for global code completion which have information about 6703 // contexts/symbols that are not in the AST. 6704 if (SS.isInvalid()) { 6705 // As SS is invalid, we try to collect accessible contexts from the current 6706 // scope with a dummy lookup so that the completion consumer can try to 6707 // guess what the specified scope is. 6708 ResultBuilder DummyResults(SemaRef, CodeCompleter->getAllocator(), 6709 CodeCompleter->getCodeCompletionTUInfo(), CC); 6710 if (!PreferredType.isNull()) 6711 DummyResults.setPreferredType(PreferredType); 6712 if (S->getEntity()) { 6713 CodeCompletionDeclConsumer Consumer(DummyResults, S->getEntity(), 6714 BaseType); 6715 SemaRef.LookupVisibleDecls(S, Sema::LookupOrdinaryName, Consumer, 6716 /*IncludeGlobalScope=*/false, 6717 /*LoadExternal=*/false); 6718 } 6719 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 6720 DummyResults.getCompletionContext(), nullptr, 0); 6721 return; 6722 } 6723 // Always pretend to enter a context to ensure that a dependent type 6724 // resolves to a dependent record. 6725 DeclContext *Ctx = SemaRef.computeDeclContext(SS, /*EnteringContext=*/true); 6726 6727 // Try to instantiate any non-dependent declaration contexts before 6728 // we look in them. Bail out if we fail. 6729 NestedNameSpecifier *NNS = SS.getScopeRep(); 6730 if (NNS != nullptr && SS.isValid() && !NNS->isDependent()) { 6731 if (Ctx == nullptr || SemaRef.RequireCompleteDeclContext(SS, Ctx)) 6732 return; 6733 } 6734 6735 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(), 6736 CodeCompleter->getCodeCompletionTUInfo(), CC); 6737 if (!PreferredType.isNull()) 6738 Results.setPreferredType(PreferredType); 6739 Results.EnterNewScope(); 6740 6741 // The "template" keyword can follow "::" in the grammar, but only 6742 // put it into the grammar if the nested-name-specifier is dependent. 6743 // FIXME: results is always empty, this appears to be dead. 6744 if (!Results.empty() && NNS && NNS->isDependent()) 6745 Results.AddResult("template"); 6746 6747 // If the scope is a concept-constrained type parameter, infer nested 6748 // members based on the constraints. 6749 if (NNS) { 6750 if (const auto *TTPT = 6751 dyn_cast_or_null<TemplateTypeParmType>(NNS->getAsType())) { 6752 for (const auto &R : ConceptInfo(*TTPT, S).members()) { 6753 if (R.Operator != ConceptInfo::Member::Colons) 6754 continue; 6755 Results.AddResult(CodeCompletionResult( 6756 R.render(SemaRef, CodeCompleter->getAllocator(), 6757 CodeCompleter->getCodeCompletionTUInfo()))); 6758 } 6759 } 6760 } 6761 6762 // Add calls to overridden virtual functions, if there are any. 6763 // 6764 // FIXME: This isn't wonderful, because we don't know whether we're actually 6765 // in a context that permits expressions. This is a general issue with 6766 // qualified-id completions. 6767 if (Ctx && !EnteringContext) 6768 MaybeAddOverrideCalls(SemaRef, Ctx, Results); 6769 Results.ExitScope(); 6770 6771 if (Ctx && 6772 (CodeCompleter->includeNamespaceLevelDecls() || !Ctx->isFileContext())) { 6773 CodeCompletionDeclConsumer Consumer(Results, Ctx, BaseType); 6774 SemaRef.LookupVisibleDecls(Ctx, Sema::LookupOrdinaryName, Consumer, 6775 /*IncludeGlobalScope=*/true, 6776 /*IncludeDependentBases=*/true, 6777 CodeCompleter->loadExternal()); 6778 } 6779 6780 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 6781 Results.getCompletionContext(), Results.data(), 6782 Results.size()); 6783 } 6784 6785 void SemaCodeCompletion::CodeCompleteUsing(Scope *S) { 6786 if (!CodeCompleter) 6787 return; 6788 6789 // This can be both a using alias or using declaration, in the former we 6790 // expect a new name and a symbol in the latter case. 6791 CodeCompletionContext Context(CodeCompletionContext::CCC_SymbolOrNewName); 6792 Context.setIsUsingDeclaration(true); 6793 6794 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(), 6795 CodeCompleter->getCodeCompletionTUInfo(), Context, 6796 &ResultBuilder::IsNestedNameSpecifier); 6797 Results.EnterNewScope(); 6798 6799 // If we aren't in class scope, we could see the "namespace" keyword. 6800 if (!S->isClassScope()) 6801 Results.AddResult(CodeCompletionResult("namespace")); 6802 6803 // After "using", we can see anything that would start a 6804 // nested-name-specifier. 6805 CodeCompletionDeclConsumer Consumer(Results, SemaRef.CurContext); 6806 SemaRef.LookupVisibleDecls(S, Sema::LookupOrdinaryName, Consumer, 6807 CodeCompleter->includeGlobals(), 6808 CodeCompleter->loadExternal()); 6809 Results.ExitScope(); 6810 6811 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 6812 Results.getCompletionContext(), Results.data(), 6813 Results.size()); 6814 } 6815 6816 void SemaCodeCompletion::CodeCompleteUsingDirective(Scope *S) { 6817 if (!CodeCompleter) 6818 return; 6819 6820 // After "using namespace", we expect to see a namespace name or namespace 6821 // alias. 6822 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(), 6823 CodeCompleter->getCodeCompletionTUInfo(), 6824 CodeCompletionContext::CCC_Namespace, 6825 &ResultBuilder::IsNamespaceOrAlias); 6826 Results.EnterNewScope(); 6827 CodeCompletionDeclConsumer Consumer(Results, SemaRef.CurContext); 6828 SemaRef.LookupVisibleDecls(S, Sema::LookupOrdinaryName, Consumer, 6829 CodeCompleter->includeGlobals(), 6830 CodeCompleter->loadExternal()); 6831 Results.ExitScope(); 6832 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 6833 Results.getCompletionContext(), Results.data(), 6834 Results.size()); 6835 } 6836 6837 void SemaCodeCompletion::CodeCompleteNamespaceDecl(Scope *S) { 6838 if (!CodeCompleter) 6839 return; 6840 6841 DeclContext *Ctx = S->getEntity(); 6842 if (!S->getParent()) 6843 Ctx = getASTContext().getTranslationUnitDecl(); 6844 6845 bool SuppressedGlobalResults = 6846 Ctx && !CodeCompleter->includeGlobals() && isa<TranslationUnitDecl>(Ctx); 6847 6848 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(), 6849 CodeCompleter->getCodeCompletionTUInfo(), 6850 SuppressedGlobalResults 6851 ? CodeCompletionContext::CCC_Namespace 6852 : CodeCompletionContext::CCC_Other, 6853 &ResultBuilder::IsNamespace); 6854 6855 if (Ctx && Ctx->isFileContext() && !SuppressedGlobalResults) { 6856 // We only want to see those namespaces that have already been defined 6857 // within this scope, because its likely that the user is creating an 6858 // extended namespace declaration. Keep track of the most recent 6859 // definition of each namespace. 6860 std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest; 6861 for (DeclContext::specific_decl_iterator<NamespaceDecl> 6862 NS(Ctx->decls_begin()), 6863 NSEnd(Ctx->decls_end()); 6864 NS != NSEnd; ++NS) 6865 OrigToLatest[NS->getFirstDecl()] = *NS; 6866 6867 // Add the most recent definition (or extended definition) of each 6868 // namespace to the list of results. 6869 Results.EnterNewScope(); 6870 for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator 6871 NS = OrigToLatest.begin(), 6872 NSEnd = OrigToLatest.end(); 6873 NS != NSEnd; ++NS) 6874 Results.AddResult( 6875 CodeCompletionResult(NS->second, Results.getBasePriority(NS->second), 6876 nullptr), 6877 SemaRef.CurContext, nullptr, false); 6878 Results.ExitScope(); 6879 } 6880 6881 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 6882 Results.getCompletionContext(), Results.data(), 6883 Results.size()); 6884 } 6885 6886 void SemaCodeCompletion::CodeCompleteNamespaceAliasDecl(Scope *S) { 6887 if (!CodeCompleter) 6888 return; 6889 6890 // After "namespace", we expect to see a namespace or alias. 6891 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(), 6892 CodeCompleter->getCodeCompletionTUInfo(), 6893 CodeCompletionContext::CCC_Namespace, 6894 &ResultBuilder::IsNamespaceOrAlias); 6895 CodeCompletionDeclConsumer Consumer(Results, SemaRef.CurContext); 6896 SemaRef.LookupVisibleDecls(S, Sema::LookupOrdinaryName, Consumer, 6897 CodeCompleter->includeGlobals(), 6898 CodeCompleter->loadExternal()); 6899 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 6900 Results.getCompletionContext(), Results.data(), 6901 Results.size()); 6902 } 6903 6904 void SemaCodeCompletion::CodeCompleteOperatorName(Scope *S) { 6905 if (!CodeCompleter) 6906 return; 6907 6908 typedef CodeCompletionResult Result; 6909 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(), 6910 CodeCompleter->getCodeCompletionTUInfo(), 6911 CodeCompletionContext::CCC_Type, 6912 &ResultBuilder::IsType); 6913 Results.EnterNewScope(); 6914 6915 // Add the names of overloadable operators. Note that OO_Conditional is not 6916 // actually overloadable. 6917 #define OVERLOADED_OPERATOR(Name, Spelling, Token, Unary, Binary, MemberOnly) \ 6918 if (OO_##Name != OO_Conditional) \ 6919 Results.AddResult(Result(Spelling)); 6920 #include "clang/Basic/OperatorKinds.def" 6921 6922 // Add any type names visible from the current scope 6923 Results.allowNestedNameSpecifiers(); 6924 CodeCompletionDeclConsumer Consumer(Results, SemaRef.CurContext); 6925 SemaRef.LookupVisibleDecls(S, Sema::LookupOrdinaryName, Consumer, 6926 CodeCompleter->includeGlobals(), 6927 CodeCompleter->loadExternal()); 6928 6929 // Add any type specifiers 6930 AddTypeSpecifierResults(getLangOpts(), Results); 6931 Results.ExitScope(); 6932 6933 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 6934 Results.getCompletionContext(), Results.data(), 6935 Results.size()); 6936 } 6937 6938 void SemaCodeCompletion::CodeCompleteConstructorInitializer( 6939 Decl *ConstructorD, ArrayRef<CXXCtorInitializer *> Initializers) { 6940 if (!ConstructorD) 6941 return; 6942 6943 SemaRef.AdjustDeclIfTemplate(ConstructorD); 6944 6945 auto *Constructor = dyn_cast<CXXConstructorDecl>(ConstructorD); 6946 if (!Constructor) 6947 return; 6948 6949 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(), 6950 CodeCompleter->getCodeCompletionTUInfo(), 6951 CodeCompletionContext::CCC_Symbol); 6952 Results.EnterNewScope(); 6953 6954 // Fill in any already-initialized fields or base classes. 6955 llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields; 6956 llvm::SmallPtrSet<CanQualType, 4> InitializedBases; 6957 for (unsigned I = 0, E = Initializers.size(); I != E; ++I) { 6958 if (Initializers[I]->isBaseInitializer()) 6959 InitializedBases.insert(getASTContext().getCanonicalType( 6960 QualType(Initializers[I]->getBaseClass(), 0))); 6961 else 6962 InitializedFields.insert( 6963 cast<FieldDecl>(Initializers[I]->getAnyMember())); 6964 } 6965 6966 // Add completions for base classes. 6967 PrintingPolicy Policy = getCompletionPrintingPolicy(SemaRef); 6968 bool SawLastInitializer = Initializers.empty(); 6969 CXXRecordDecl *ClassDecl = Constructor->getParent(); 6970 6971 auto GenerateCCS = [&](const NamedDecl *ND, const char *Name) { 6972 CodeCompletionBuilder Builder(Results.getAllocator(), 6973 Results.getCodeCompletionTUInfo()); 6974 Builder.AddTypedTextChunk(Name); 6975 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 6976 if (const auto *Function = dyn_cast<FunctionDecl>(ND)) 6977 AddFunctionParameterChunks(SemaRef.PP, Policy, Function, Builder); 6978 else if (const auto *FunTemplDecl = dyn_cast<FunctionTemplateDecl>(ND)) 6979 AddFunctionParameterChunks(SemaRef.PP, Policy, 6980 FunTemplDecl->getTemplatedDecl(), Builder); 6981 Builder.AddChunk(CodeCompletionString::CK_RightParen); 6982 return Builder.TakeString(); 6983 }; 6984 auto AddDefaultCtorInit = [&](const char *Name, const char *Type, 6985 const NamedDecl *ND) { 6986 CodeCompletionBuilder Builder(Results.getAllocator(), 6987 Results.getCodeCompletionTUInfo()); 6988 Builder.AddTypedTextChunk(Name); 6989 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 6990 Builder.AddPlaceholderChunk(Type); 6991 Builder.AddChunk(CodeCompletionString::CK_RightParen); 6992 if (ND) { 6993 auto CCR = CodeCompletionResult( 6994 Builder.TakeString(), ND, 6995 SawLastInitializer ? CCP_NextInitializer : CCP_MemberDeclaration); 6996 if (isa<FieldDecl>(ND)) 6997 CCR.CursorKind = CXCursor_MemberRef; 6998 return Results.AddResult(CCR); 6999 } 7000 return Results.AddResult(CodeCompletionResult( 7001 Builder.TakeString(), 7002 SawLastInitializer ? CCP_NextInitializer : CCP_MemberDeclaration)); 7003 }; 7004 auto AddCtorsWithName = [&](const CXXRecordDecl *RD, unsigned int Priority, 7005 const char *Name, const FieldDecl *FD) { 7006 if (!RD) 7007 return AddDefaultCtorInit(Name, 7008 FD ? Results.getAllocator().CopyString( 7009 FD->getType().getAsString(Policy)) 7010 : Name, 7011 FD); 7012 auto Ctors = getConstructors(getASTContext(), RD); 7013 if (Ctors.begin() == Ctors.end()) 7014 return AddDefaultCtorInit(Name, Name, RD); 7015 for (const NamedDecl *Ctor : Ctors) { 7016 auto CCR = CodeCompletionResult(GenerateCCS(Ctor, Name), RD, Priority); 7017 CCR.CursorKind = getCursorKindForDecl(Ctor); 7018 Results.AddResult(CCR); 7019 } 7020 }; 7021 auto AddBase = [&](const CXXBaseSpecifier &Base) { 7022 const char *BaseName = 7023 Results.getAllocator().CopyString(Base.getType().getAsString(Policy)); 7024 const auto *RD = Base.getType()->getAsCXXRecordDecl(); 7025 AddCtorsWithName( 7026 RD, SawLastInitializer ? CCP_NextInitializer : CCP_MemberDeclaration, 7027 BaseName, nullptr); 7028 }; 7029 auto AddField = [&](const FieldDecl *FD) { 7030 const char *FieldName = 7031 Results.getAllocator().CopyString(FD->getIdentifier()->getName()); 7032 const CXXRecordDecl *RD = FD->getType()->getAsCXXRecordDecl(); 7033 AddCtorsWithName( 7034 RD, SawLastInitializer ? CCP_NextInitializer : CCP_MemberDeclaration, 7035 FieldName, FD); 7036 }; 7037 7038 for (const auto &Base : ClassDecl->bases()) { 7039 if (!InitializedBases 7040 .insert(getASTContext().getCanonicalType(Base.getType())) 7041 .second) { 7042 SawLastInitializer = 7043 !Initializers.empty() && Initializers.back()->isBaseInitializer() && 7044 getASTContext().hasSameUnqualifiedType( 7045 Base.getType(), QualType(Initializers.back()->getBaseClass(), 0)); 7046 continue; 7047 } 7048 7049 AddBase(Base); 7050 SawLastInitializer = false; 7051 } 7052 7053 // Add completions for virtual base classes. 7054 for (const auto &Base : ClassDecl->vbases()) { 7055 if (!InitializedBases 7056 .insert(getASTContext().getCanonicalType(Base.getType())) 7057 .second) { 7058 SawLastInitializer = 7059 !Initializers.empty() && Initializers.back()->isBaseInitializer() && 7060 getASTContext().hasSameUnqualifiedType( 7061 Base.getType(), QualType(Initializers.back()->getBaseClass(), 0)); 7062 continue; 7063 } 7064 7065 AddBase(Base); 7066 SawLastInitializer = false; 7067 } 7068 7069 // Add completions for members. 7070 for (auto *Field : ClassDecl->fields()) { 7071 if (!InitializedFields.insert(cast<FieldDecl>(Field->getCanonicalDecl())) 7072 .second) { 7073 SawLastInitializer = !Initializers.empty() && 7074 Initializers.back()->isAnyMemberInitializer() && 7075 Initializers.back()->getAnyMember() == Field; 7076 continue; 7077 } 7078 7079 if (!Field->getDeclName()) 7080 continue; 7081 7082 AddField(Field); 7083 SawLastInitializer = false; 7084 } 7085 Results.ExitScope(); 7086 7087 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 7088 Results.getCompletionContext(), Results.data(), 7089 Results.size()); 7090 } 7091 7092 /// Determine whether this scope denotes a namespace. 7093 static bool isNamespaceScope(Scope *S) { 7094 DeclContext *DC = S->getEntity(); 7095 if (!DC) 7096 return false; 7097 7098 return DC->isFileContext(); 7099 } 7100 7101 void SemaCodeCompletion::CodeCompleteLambdaIntroducer(Scope *S, 7102 LambdaIntroducer &Intro, 7103 bool AfterAmpersand) { 7104 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(), 7105 CodeCompleter->getCodeCompletionTUInfo(), 7106 CodeCompletionContext::CCC_Other); 7107 Results.EnterNewScope(); 7108 7109 // Note what has already been captured. 7110 llvm::SmallPtrSet<IdentifierInfo *, 4> Known; 7111 bool IncludedThis = false; 7112 for (const auto &C : Intro.Captures) { 7113 if (C.Kind == LCK_This) { 7114 IncludedThis = true; 7115 continue; 7116 } 7117 7118 Known.insert(C.Id); 7119 } 7120 7121 // Look for other capturable variables. 7122 for (; S && !isNamespaceScope(S); S = S->getParent()) { 7123 for (const auto *D : S->decls()) { 7124 const auto *Var = dyn_cast<VarDecl>(D); 7125 if (!Var || !Var->hasLocalStorage() || Var->hasAttr<BlocksAttr>()) 7126 continue; 7127 7128 if (Known.insert(Var->getIdentifier()).second) 7129 Results.AddResult(CodeCompletionResult(Var, CCP_LocalDeclaration), 7130 SemaRef.CurContext, nullptr, false); 7131 } 7132 } 7133 7134 // Add 'this', if it would be valid. 7135 if (!IncludedThis && !AfterAmpersand && Intro.Default != LCD_ByCopy) 7136 addThisCompletion(SemaRef, Results); 7137 7138 Results.ExitScope(); 7139 7140 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 7141 Results.getCompletionContext(), Results.data(), 7142 Results.size()); 7143 } 7144 7145 void SemaCodeCompletion::CodeCompleteAfterFunctionEquals(Declarator &D) { 7146 if (!getLangOpts().CPlusPlus11) 7147 return; 7148 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(), 7149 CodeCompleter->getCodeCompletionTUInfo(), 7150 CodeCompletionContext::CCC_Other); 7151 auto ShouldAddDefault = [&D, this]() { 7152 if (!D.isFunctionDeclarator()) 7153 return false; 7154 auto &Id = D.getName(); 7155 if (Id.getKind() == UnqualifiedIdKind::IK_DestructorName) 7156 return true; 7157 // FIXME(liuhui): Ideally, we should check the constructor parameter list to 7158 // verify that it is the default, copy or move constructor? 7159 if (Id.getKind() == UnqualifiedIdKind::IK_ConstructorName && 7160 D.getFunctionTypeInfo().NumParams <= 1) 7161 return true; 7162 if (Id.getKind() == UnqualifiedIdKind::IK_OperatorFunctionId) { 7163 auto Op = Id.OperatorFunctionId.Operator; 7164 // FIXME(liuhui): Ideally, we should check the function parameter list to 7165 // verify that it is the copy or move assignment? 7166 if (Op == OverloadedOperatorKind::OO_Equal) 7167 return true; 7168 if (getLangOpts().CPlusPlus20 && 7169 (Op == OverloadedOperatorKind::OO_EqualEqual || 7170 Op == OverloadedOperatorKind::OO_ExclaimEqual || 7171 Op == OverloadedOperatorKind::OO_Less || 7172 Op == OverloadedOperatorKind::OO_LessEqual || 7173 Op == OverloadedOperatorKind::OO_Greater || 7174 Op == OverloadedOperatorKind::OO_GreaterEqual || 7175 Op == OverloadedOperatorKind::OO_Spaceship)) 7176 return true; 7177 } 7178 return false; 7179 }; 7180 7181 Results.EnterNewScope(); 7182 if (ShouldAddDefault()) 7183 Results.AddResult("default"); 7184 // FIXME(liuhui): Ideally, we should only provide `delete` completion for the 7185 // first function declaration. 7186 Results.AddResult("delete"); 7187 Results.ExitScope(); 7188 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 7189 Results.getCompletionContext(), Results.data(), 7190 Results.size()); 7191 } 7192 7193 /// Macro that optionally prepends an "@" to the string literal passed in via 7194 /// Keyword, depending on whether NeedAt is true or false. 7195 #define OBJC_AT_KEYWORD_NAME(NeedAt, Keyword) ((NeedAt) ? "@" Keyword : Keyword) 7196 7197 static void AddObjCImplementationResults(const LangOptions &LangOpts, 7198 ResultBuilder &Results, bool NeedAt) { 7199 typedef CodeCompletionResult Result; 7200 // Since we have an implementation, we can end it. 7201 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "end"))); 7202 7203 CodeCompletionBuilder Builder(Results.getAllocator(), 7204 Results.getCodeCompletionTUInfo()); 7205 if (LangOpts.ObjC) { 7206 // @dynamic 7207 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "dynamic")); 7208 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7209 Builder.AddPlaceholderChunk("property"); 7210 Results.AddResult(Result(Builder.TakeString())); 7211 7212 // @synthesize 7213 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "synthesize")); 7214 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7215 Builder.AddPlaceholderChunk("property"); 7216 Results.AddResult(Result(Builder.TakeString())); 7217 } 7218 } 7219 7220 static void AddObjCInterfaceResults(const LangOptions &LangOpts, 7221 ResultBuilder &Results, bool NeedAt) { 7222 typedef CodeCompletionResult Result; 7223 7224 // Since we have an interface or protocol, we can end it. 7225 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "end"))); 7226 7227 if (LangOpts.ObjC) { 7228 // @property 7229 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "property"))); 7230 7231 // @required 7232 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "required"))); 7233 7234 // @optional 7235 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "optional"))); 7236 } 7237 } 7238 7239 static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt) { 7240 typedef CodeCompletionResult Result; 7241 CodeCompletionBuilder Builder(Results.getAllocator(), 7242 Results.getCodeCompletionTUInfo()); 7243 7244 // @class name ; 7245 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "class")); 7246 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7247 Builder.AddPlaceholderChunk("name"); 7248 Results.AddResult(Result(Builder.TakeString())); 7249 7250 if (Results.includeCodePatterns()) { 7251 // @interface name 7252 // FIXME: Could introduce the whole pattern, including superclasses and 7253 // such. 7254 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "interface")); 7255 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7256 Builder.AddPlaceholderChunk("class"); 7257 Results.AddResult(Result(Builder.TakeString())); 7258 7259 // @protocol name 7260 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "protocol")); 7261 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7262 Builder.AddPlaceholderChunk("protocol"); 7263 Results.AddResult(Result(Builder.TakeString())); 7264 7265 // @implementation name 7266 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "implementation")); 7267 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7268 Builder.AddPlaceholderChunk("class"); 7269 Results.AddResult(Result(Builder.TakeString())); 7270 } 7271 7272 // @compatibility_alias name 7273 Builder.AddTypedTextChunk( 7274 OBJC_AT_KEYWORD_NAME(NeedAt, "compatibility_alias")); 7275 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7276 Builder.AddPlaceholderChunk("alias"); 7277 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7278 Builder.AddPlaceholderChunk("class"); 7279 Results.AddResult(Result(Builder.TakeString())); 7280 7281 if (Results.getSema().getLangOpts().Modules) { 7282 // @import name 7283 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "import")); 7284 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7285 Builder.AddPlaceholderChunk("module"); 7286 Results.AddResult(Result(Builder.TakeString())); 7287 } 7288 } 7289 7290 void SemaCodeCompletion::CodeCompleteObjCAtDirective(Scope *S) { 7291 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(), 7292 CodeCompleter->getCodeCompletionTUInfo(), 7293 CodeCompletionContext::CCC_Other); 7294 Results.EnterNewScope(); 7295 if (isa<ObjCImplDecl>(SemaRef.CurContext)) 7296 AddObjCImplementationResults(getLangOpts(), Results, false); 7297 else if (SemaRef.CurContext->isObjCContainer()) 7298 AddObjCInterfaceResults(getLangOpts(), Results, false); 7299 else 7300 AddObjCTopLevelResults(Results, false); 7301 Results.ExitScope(); 7302 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 7303 Results.getCompletionContext(), Results.data(), 7304 Results.size()); 7305 } 7306 7307 static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt) { 7308 typedef CodeCompletionResult Result; 7309 CodeCompletionBuilder Builder(Results.getAllocator(), 7310 Results.getCodeCompletionTUInfo()); 7311 7312 // @encode ( type-name ) 7313 const char *EncodeType = "char[]"; 7314 if (Results.getSema().getLangOpts().CPlusPlus || 7315 Results.getSema().getLangOpts().ConstStrings) 7316 EncodeType = "const char[]"; 7317 Builder.AddResultTypeChunk(EncodeType); 7318 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "encode")); 7319 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7320 Builder.AddPlaceholderChunk("type-name"); 7321 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7322 Results.AddResult(Result(Builder.TakeString())); 7323 7324 // @protocol ( protocol-name ) 7325 Builder.AddResultTypeChunk("Protocol *"); 7326 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "protocol")); 7327 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7328 Builder.AddPlaceholderChunk("protocol-name"); 7329 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7330 Results.AddResult(Result(Builder.TakeString())); 7331 7332 // @selector ( selector ) 7333 Builder.AddResultTypeChunk("SEL"); 7334 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "selector")); 7335 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7336 Builder.AddPlaceholderChunk("selector"); 7337 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7338 Results.AddResult(Result(Builder.TakeString())); 7339 7340 // @"string" 7341 Builder.AddResultTypeChunk("NSString *"); 7342 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "\"")); 7343 Builder.AddPlaceholderChunk("string"); 7344 Builder.AddTextChunk("\""); 7345 Results.AddResult(Result(Builder.TakeString())); 7346 7347 // @[objects, ...] 7348 Builder.AddResultTypeChunk("NSArray *"); 7349 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "[")); 7350 Builder.AddPlaceholderChunk("objects, ..."); 7351 Builder.AddChunk(CodeCompletionString::CK_RightBracket); 7352 Results.AddResult(Result(Builder.TakeString())); 7353 7354 // @{key : object, ...} 7355 Builder.AddResultTypeChunk("NSDictionary *"); 7356 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "{")); 7357 Builder.AddPlaceholderChunk("key"); 7358 Builder.AddChunk(CodeCompletionString::CK_Colon); 7359 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7360 Builder.AddPlaceholderChunk("object, ..."); 7361 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 7362 Results.AddResult(Result(Builder.TakeString())); 7363 7364 // @(expression) 7365 Builder.AddResultTypeChunk("id"); 7366 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "(")); 7367 Builder.AddPlaceholderChunk("expression"); 7368 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7369 Results.AddResult(Result(Builder.TakeString())); 7370 } 7371 7372 static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt) { 7373 typedef CodeCompletionResult Result; 7374 CodeCompletionBuilder Builder(Results.getAllocator(), 7375 Results.getCodeCompletionTUInfo()); 7376 7377 if (Results.includeCodePatterns()) { 7378 // @try { statements } @catch ( declaration ) { statements } @finally 7379 // { statements } 7380 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "try")); 7381 Builder.AddChunk(CodeCompletionString::CK_LeftBrace); 7382 Builder.AddPlaceholderChunk("statements"); 7383 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 7384 Builder.AddTextChunk("@catch"); 7385 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7386 Builder.AddPlaceholderChunk("parameter"); 7387 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7388 Builder.AddChunk(CodeCompletionString::CK_LeftBrace); 7389 Builder.AddPlaceholderChunk("statements"); 7390 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 7391 Builder.AddTextChunk("@finally"); 7392 Builder.AddChunk(CodeCompletionString::CK_LeftBrace); 7393 Builder.AddPlaceholderChunk("statements"); 7394 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 7395 Results.AddResult(Result(Builder.TakeString())); 7396 } 7397 7398 // @throw 7399 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "throw")); 7400 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7401 Builder.AddPlaceholderChunk("expression"); 7402 Results.AddResult(Result(Builder.TakeString())); 7403 7404 if (Results.includeCodePatterns()) { 7405 // @synchronized ( expression ) { statements } 7406 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "synchronized")); 7407 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7408 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7409 Builder.AddPlaceholderChunk("expression"); 7410 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7411 Builder.AddChunk(CodeCompletionString::CK_LeftBrace); 7412 Builder.AddPlaceholderChunk("statements"); 7413 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 7414 Results.AddResult(Result(Builder.TakeString())); 7415 } 7416 } 7417 7418 static void AddObjCVisibilityResults(const LangOptions &LangOpts, 7419 ResultBuilder &Results, bool NeedAt) { 7420 typedef CodeCompletionResult Result; 7421 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "private"))); 7422 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "protected"))); 7423 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "public"))); 7424 if (LangOpts.ObjC) 7425 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "package"))); 7426 } 7427 7428 void SemaCodeCompletion::CodeCompleteObjCAtVisibility(Scope *S) { 7429 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(), 7430 CodeCompleter->getCodeCompletionTUInfo(), 7431 CodeCompletionContext::CCC_Other); 7432 Results.EnterNewScope(); 7433 AddObjCVisibilityResults(getLangOpts(), Results, false); 7434 Results.ExitScope(); 7435 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 7436 Results.getCompletionContext(), Results.data(), 7437 Results.size()); 7438 } 7439 7440 void SemaCodeCompletion::CodeCompleteObjCAtStatement(Scope *S) { 7441 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(), 7442 CodeCompleter->getCodeCompletionTUInfo(), 7443 CodeCompletionContext::CCC_Other); 7444 Results.EnterNewScope(); 7445 AddObjCStatementResults(Results, false); 7446 AddObjCExpressionResults(Results, false); 7447 Results.ExitScope(); 7448 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 7449 Results.getCompletionContext(), Results.data(), 7450 Results.size()); 7451 } 7452 7453 void SemaCodeCompletion::CodeCompleteObjCAtExpression(Scope *S) { 7454 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(), 7455 CodeCompleter->getCodeCompletionTUInfo(), 7456 CodeCompletionContext::CCC_Other); 7457 Results.EnterNewScope(); 7458 AddObjCExpressionResults(Results, false); 7459 Results.ExitScope(); 7460 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 7461 Results.getCompletionContext(), Results.data(), 7462 Results.size()); 7463 } 7464 7465 /// Determine whether the addition of the given flag to an Objective-C 7466 /// property's attributes will cause a conflict. 7467 static bool ObjCPropertyFlagConflicts(unsigned Attributes, unsigned NewFlag) { 7468 // Check if we've already added this flag. 7469 if (Attributes & NewFlag) 7470 return true; 7471 7472 Attributes |= NewFlag; 7473 7474 // Check for collisions with "readonly". 7475 if ((Attributes & ObjCPropertyAttribute::kind_readonly) && 7476 (Attributes & ObjCPropertyAttribute::kind_readwrite)) 7477 return true; 7478 7479 // Check for more than one of { assign, copy, retain, strong, weak }. 7480 unsigned AssignCopyRetMask = 7481 Attributes & 7482 (ObjCPropertyAttribute::kind_assign | 7483 ObjCPropertyAttribute::kind_unsafe_unretained | 7484 ObjCPropertyAttribute::kind_copy | ObjCPropertyAttribute::kind_retain | 7485 ObjCPropertyAttribute::kind_strong | ObjCPropertyAttribute::kind_weak); 7486 if (AssignCopyRetMask && 7487 AssignCopyRetMask != ObjCPropertyAttribute::kind_assign && 7488 AssignCopyRetMask != ObjCPropertyAttribute::kind_unsafe_unretained && 7489 AssignCopyRetMask != ObjCPropertyAttribute::kind_copy && 7490 AssignCopyRetMask != ObjCPropertyAttribute::kind_retain && 7491 AssignCopyRetMask != ObjCPropertyAttribute::kind_strong && 7492 AssignCopyRetMask != ObjCPropertyAttribute::kind_weak) 7493 return true; 7494 7495 return false; 7496 } 7497 7498 void SemaCodeCompletion::CodeCompleteObjCPropertyFlags(Scope *S, 7499 ObjCDeclSpec &ODS) { 7500 if (!CodeCompleter) 7501 return; 7502 7503 unsigned Attributes = ODS.getPropertyAttributes(); 7504 7505 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(), 7506 CodeCompleter->getCodeCompletionTUInfo(), 7507 CodeCompletionContext::CCC_Other); 7508 Results.EnterNewScope(); 7509 if (!ObjCPropertyFlagConflicts(Attributes, 7510 ObjCPropertyAttribute::kind_readonly)) 7511 Results.AddResult(CodeCompletionResult("readonly")); 7512 if (!ObjCPropertyFlagConflicts(Attributes, 7513 ObjCPropertyAttribute::kind_assign)) 7514 Results.AddResult(CodeCompletionResult("assign")); 7515 if (!ObjCPropertyFlagConflicts(Attributes, 7516 ObjCPropertyAttribute::kind_unsafe_unretained)) 7517 Results.AddResult(CodeCompletionResult("unsafe_unretained")); 7518 if (!ObjCPropertyFlagConflicts(Attributes, 7519 ObjCPropertyAttribute::kind_readwrite)) 7520 Results.AddResult(CodeCompletionResult("readwrite")); 7521 if (!ObjCPropertyFlagConflicts(Attributes, 7522 ObjCPropertyAttribute::kind_retain)) 7523 Results.AddResult(CodeCompletionResult("retain")); 7524 if (!ObjCPropertyFlagConflicts(Attributes, 7525 ObjCPropertyAttribute::kind_strong)) 7526 Results.AddResult(CodeCompletionResult("strong")); 7527 if (!ObjCPropertyFlagConflicts(Attributes, ObjCPropertyAttribute::kind_copy)) 7528 Results.AddResult(CodeCompletionResult("copy")); 7529 if (!ObjCPropertyFlagConflicts(Attributes, 7530 ObjCPropertyAttribute::kind_nonatomic)) 7531 Results.AddResult(CodeCompletionResult("nonatomic")); 7532 if (!ObjCPropertyFlagConflicts(Attributes, 7533 ObjCPropertyAttribute::kind_atomic)) 7534 Results.AddResult(CodeCompletionResult("atomic")); 7535 7536 // Only suggest "weak" if we're compiling for ARC-with-weak-references or GC. 7537 if (getLangOpts().ObjCWeak || getLangOpts().getGC() != LangOptions::NonGC) 7538 if (!ObjCPropertyFlagConflicts(Attributes, 7539 ObjCPropertyAttribute::kind_weak)) 7540 Results.AddResult(CodeCompletionResult("weak")); 7541 7542 if (!ObjCPropertyFlagConflicts(Attributes, 7543 ObjCPropertyAttribute::kind_setter)) { 7544 CodeCompletionBuilder Setter(Results.getAllocator(), 7545 Results.getCodeCompletionTUInfo()); 7546 Setter.AddTypedTextChunk("setter"); 7547 Setter.AddTextChunk("="); 7548 Setter.AddPlaceholderChunk("method"); 7549 Results.AddResult(CodeCompletionResult(Setter.TakeString())); 7550 } 7551 if (!ObjCPropertyFlagConflicts(Attributes, 7552 ObjCPropertyAttribute::kind_getter)) { 7553 CodeCompletionBuilder Getter(Results.getAllocator(), 7554 Results.getCodeCompletionTUInfo()); 7555 Getter.AddTypedTextChunk("getter"); 7556 Getter.AddTextChunk("="); 7557 Getter.AddPlaceholderChunk("method"); 7558 Results.AddResult(CodeCompletionResult(Getter.TakeString())); 7559 } 7560 if (!ObjCPropertyFlagConflicts(Attributes, 7561 ObjCPropertyAttribute::kind_nullability)) { 7562 Results.AddResult(CodeCompletionResult("nonnull")); 7563 Results.AddResult(CodeCompletionResult("nullable")); 7564 Results.AddResult(CodeCompletionResult("null_unspecified")); 7565 Results.AddResult(CodeCompletionResult("null_resettable")); 7566 } 7567 Results.ExitScope(); 7568 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 7569 Results.getCompletionContext(), Results.data(), 7570 Results.size()); 7571 } 7572 7573 /// Describes the kind of Objective-C method that we want to find 7574 /// via code completion. 7575 enum ObjCMethodKind { 7576 MK_Any, ///< Any kind of method, provided it means other specified criteria. 7577 MK_ZeroArgSelector, ///< Zero-argument (unary) selector. 7578 MK_OneArgSelector ///< One-argument selector. 7579 }; 7580 7581 static bool isAcceptableObjCSelector(Selector Sel, ObjCMethodKind WantKind, 7582 ArrayRef<const IdentifierInfo *> SelIdents, 7583 bool AllowSameLength = true) { 7584 unsigned NumSelIdents = SelIdents.size(); 7585 if (NumSelIdents > Sel.getNumArgs()) 7586 return false; 7587 7588 switch (WantKind) { 7589 case MK_Any: 7590 break; 7591 case MK_ZeroArgSelector: 7592 return Sel.isUnarySelector(); 7593 case MK_OneArgSelector: 7594 return Sel.getNumArgs() == 1; 7595 } 7596 7597 if (!AllowSameLength && NumSelIdents && NumSelIdents == Sel.getNumArgs()) 7598 return false; 7599 7600 for (unsigned I = 0; I != NumSelIdents; ++I) 7601 if (SelIdents[I] != Sel.getIdentifierInfoForSlot(I)) 7602 return false; 7603 7604 return true; 7605 } 7606 7607 static bool isAcceptableObjCMethod(ObjCMethodDecl *Method, 7608 ObjCMethodKind WantKind, 7609 ArrayRef<const IdentifierInfo *> SelIdents, 7610 bool AllowSameLength = true) { 7611 return isAcceptableObjCSelector(Method->getSelector(), WantKind, SelIdents, 7612 AllowSameLength); 7613 } 7614 7615 /// A set of selectors, which is used to avoid introducing multiple 7616 /// completions with the same selector into the result set. 7617 typedef llvm::SmallPtrSet<Selector, 16> VisitedSelectorSet; 7618 7619 /// Add all of the Objective-C methods in the given Objective-C 7620 /// container to the set of results. 7621 /// 7622 /// The container will be a class, protocol, category, or implementation of 7623 /// any of the above. This mether will recurse to include methods from 7624 /// the superclasses of classes along with their categories, protocols, and 7625 /// implementations. 7626 /// 7627 /// \param Container the container in which we'll look to find methods. 7628 /// 7629 /// \param WantInstanceMethods Whether to add instance methods (only); if 7630 /// false, this routine will add factory methods (only). 7631 /// 7632 /// \param CurContext the context in which we're performing the lookup that 7633 /// finds methods. 7634 /// 7635 /// \param AllowSameLength Whether we allow a method to be added to the list 7636 /// when it has the same number of parameters as we have selector identifiers. 7637 /// 7638 /// \param Results the structure into which we'll add results. 7639 static void AddObjCMethods(ObjCContainerDecl *Container, 7640 bool WantInstanceMethods, ObjCMethodKind WantKind, 7641 ArrayRef<const IdentifierInfo *> SelIdents, 7642 DeclContext *CurContext, 7643 VisitedSelectorSet &Selectors, bool AllowSameLength, 7644 ResultBuilder &Results, bool InOriginalClass = true, 7645 bool IsRootClass = false) { 7646 typedef CodeCompletionResult Result; 7647 Container = getContainerDef(Container); 7648 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container); 7649 IsRootClass = IsRootClass || (IFace && !IFace->getSuperClass()); 7650 for (ObjCMethodDecl *M : Container->methods()) { 7651 // The instance methods on the root class can be messaged via the 7652 // metaclass. 7653 if (M->isInstanceMethod() == WantInstanceMethods || 7654 (IsRootClass && !WantInstanceMethods)) { 7655 // Check whether the selector identifiers we've been given are a 7656 // subset of the identifiers for this particular method. 7657 if (!isAcceptableObjCMethod(M, WantKind, SelIdents, AllowSameLength)) 7658 continue; 7659 7660 if (!Selectors.insert(M->getSelector()).second) 7661 continue; 7662 7663 Result R = Result(M, Results.getBasePriority(M), nullptr); 7664 R.StartParameter = SelIdents.size(); 7665 R.AllParametersAreInformative = (WantKind != MK_Any); 7666 if (!InOriginalClass) 7667 setInBaseClass(R); 7668 Results.MaybeAddResult(R, CurContext); 7669 } 7670 } 7671 7672 // Visit the protocols of protocols. 7673 if (const auto *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) { 7674 if (Protocol->hasDefinition()) { 7675 const ObjCList<ObjCProtocolDecl> &Protocols = 7676 Protocol->getReferencedProtocols(); 7677 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(), 7678 E = Protocols.end(); 7679 I != E; ++I) 7680 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, CurContext, 7681 Selectors, AllowSameLength, Results, false, IsRootClass); 7682 } 7683 } 7684 7685 if (!IFace || !IFace->hasDefinition()) 7686 return; 7687 7688 // Add methods in protocols. 7689 for (ObjCProtocolDecl *I : IFace->protocols()) 7690 AddObjCMethods(I, WantInstanceMethods, WantKind, SelIdents, CurContext, 7691 Selectors, AllowSameLength, Results, false, IsRootClass); 7692 7693 // Add methods in categories. 7694 for (ObjCCategoryDecl *CatDecl : IFace->known_categories()) { 7695 AddObjCMethods(CatDecl, WantInstanceMethods, WantKind, SelIdents, 7696 CurContext, Selectors, AllowSameLength, Results, 7697 InOriginalClass, IsRootClass); 7698 7699 // Add a categories protocol methods. 7700 const ObjCList<ObjCProtocolDecl> &Protocols = 7701 CatDecl->getReferencedProtocols(); 7702 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(), 7703 E = Protocols.end(); 7704 I != E; ++I) 7705 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, CurContext, 7706 Selectors, AllowSameLength, Results, false, IsRootClass); 7707 7708 // Add methods in category implementations. 7709 if (ObjCCategoryImplDecl *Impl = CatDecl->getImplementation()) 7710 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents, CurContext, 7711 Selectors, AllowSameLength, Results, InOriginalClass, 7712 IsRootClass); 7713 } 7714 7715 // Add methods in superclass. 7716 // Avoid passing in IsRootClass since root classes won't have super classes. 7717 if (IFace->getSuperClass()) 7718 AddObjCMethods(IFace->getSuperClass(), WantInstanceMethods, WantKind, 7719 SelIdents, CurContext, Selectors, AllowSameLength, Results, 7720 /*IsRootClass=*/false); 7721 7722 // Add methods in our implementation, if any. 7723 if (ObjCImplementationDecl *Impl = IFace->getImplementation()) 7724 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents, CurContext, 7725 Selectors, AllowSameLength, Results, InOriginalClass, 7726 IsRootClass); 7727 } 7728 7729 void SemaCodeCompletion::CodeCompleteObjCPropertyGetter(Scope *S) { 7730 // Try to find the interface where getters might live. 7731 ObjCInterfaceDecl *Class = 7732 dyn_cast_or_null<ObjCInterfaceDecl>(SemaRef.CurContext); 7733 if (!Class) { 7734 if (ObjCCategoryDecl *Category = 7735 dyn_cast_or_null<ObjCCategoryDecl>(SemaRef.CurContext)) 7736 Class = Category->getClassInterface(); 7737 7738 if (!Class) 7739 return; 7740 } 7741 7742 // Find all of the potential getters. 7743 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(), 7744 CodeCompleter->getCodeCompletionTUInfo(), 7745 CodeCompletionContext::CCC_Other); 7746 Results.EnterNewScope(); 7747 7748 VisitedSelectorSet Selectors; 7749 AddObjCMethods(Class, true, MK_ZeroArgSelector, {}, SemaRef.CurContext, 7750 Selectors, 7751 /*AllowSameLength=*/true, Results); 7752 Results.ExitScope(); 7753 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 7754 Results.getCompletionContext(), Results.data(), 7755 Results.size()); 7756 } 7757 7758 void SemaCodeCompletion::CodeCompleteObjCPropertySetter(Scope *S) { 7759 // Try to find the interface where setters might live. 7760 ObjCInterfaceDecl *Class = 7761 dyn_cast_or_null<ObjCInterfaceDecl>(SemaRef.CurContext); 7762 if (!Class) { 7763 if (ObjCCategoryDecl *Category = 7764 dyn_cast_or_null<ObjCCategoryDecl>(SemaRef.CurContext)) 7765 Class = Category->getClassInterface(); 7766 7767 if (!Class) 7768 return; 7769 } 7770 7771 // Find all of the potential getters. 7772 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(), 7773 CodeCompleter->getCodeCompletionTUInfo(), 7774 CodeCompletionContext::CCC_Other); 7775 Results.EnterNewScope(); 7776 7777 VisitedSelectorSet Selectors; 7778 AddObjCMethods(Class, true, MK_OneArgSelector, {}, SemaRef.CurContext, 7779 Selectors, 7780 /*AllowSameLength=*/true, Results); 7781 7782 Results.ExitScope(); 7783 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 7784 Results.getCompletionContext(), Results.data(), 7785 Results.size()); 7786 } 7787 7788 void SemaCodeCompletion::CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS, 7789 bool IsParameter) { 7790 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(), 7791 CodeCompleter->getCodeCompletionTUInfo(), 7792 CodeCompletionContext::CCC_Type); 7793 Results.EnterNewScope(); 7794 7795 // Add context-sensitive, Objective-C parameter-passing keywords. 7796 bool AddedInOut = false; 7797 if ((DS.getObjCDeclQualifier() & 7798 (ObjCDeclSpec::DQ_In | ObjCDeclSpec::DQ_Inout)) == 0) { 7799 Results.AddResult("in"); 7800 Results.AddResult("inout"); 7801 AddedInOut = true; 7802 } 7803 if ((DS.getObjCDeclQualifier() & 7804 (ObjCDeclSpec::DQ_Out | ObjCDeclSpec::DQ_Inout)) == 0) { 7805 Results.AddResult("out"); 7806 if (!AddedInOut) 7807 Results.AddResult("inout"); 7808 } 7809 if ((DS.getObjCDeclQualifier() & 7810 (ObjCDeclSpec::DQ_Bycopy | ObjCDeclSpec::DQ_Byref | 7811 ObjCDeclSpec::DQ_Oneway)) == 0) { 7812 Results.AddResult("bycopy"); 7813 Results.AddResult("byref"); 7814 Results.AddResult("oneway"); 7815 } 7816 if ((DS.getObjCDeclQualifier() & ObjCDeclSpec::DQ_CSNullability) == 0) { 7817 Results.AddResult("nonnull"); 7818 Results.AddResult("nullable"); 7819 Results.AddResult("null_unspecified"); 7820 } 7821 7822 // If we're completing the return type of an Objective-C method and the 7823 // identifier IBAction refers to a macro, provide a completion item for 7824 // an action, e.g., 7825 // IBAction)<#selector#>:(id)sender 7826 if (DS.getObjCDeclQualifier() == 0 && !IsParameter && 7827 SemaRef.PP.isMacroDefined("IBAction")) { 7828 CodeCompletionBuilder Builder(Results.getAllocator(), 7829 Results.getCodeCompletionTUInfo(), 7830 CCP_CodePattern, CXAvailability_Available); 7831 Builder.AddTypedTextChunk("IBAction"); 7832 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7833 Builder.AddPlaceholderChunk("selector"); 7834 Builder.AddChunk(CodeCompletionString::CK_Colon); 7835 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 7836 Builder.AddTextChunk("id"); 7837 Builder.AddChunk(CodeCompletionString::CK_RightParen); 7838 Builder.AddTextChunk("sender"); 7839 Results.AddResult(CodeCompletionResult(Builder.TakeString())); 7840 } 7841 7842 // If we're completing the return type, provide 'instancetype'. 7843 if (!IsParameter) { 7844 Results.AddResult(CodeCompletionResult("instancetype")); 7845 } 7846 7847 // Add various builtin type names and specifiers. 7848 AddOrdinaryNameResults(PCC_Type, S, SemaRef, Results); 7849 Results.ExitScope(); 7850 7851 // Add the various type names 7852 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName); 7853 CodeCompletionDeclConsumer Consumer(Results, SemaRef.CurContext); 7854 SemaRef.LookupVisibleDecls(S, Sema::LookupOrdinaryName, Consumer, 7855 CodeCompleter->includeGlobals(), 7856 CodeCompleter->loadExternal()); 7857 7858 if (CodeCompleter->includeMacros()) 7859 AddMacroResults(SemaRef.PP, Results, CodeCompleter->loadExternal(), false); 7860 7861 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 7862 Results.getCompletionContext(), Results.data(), 7863 Results.size()); 7864 } 7865 7866 /// When we have an expression with type "id", we may assume 7867 /// that it has some more-specific class type based on knowledge of 7868 /// common uses of Objective-C. This routine returns that class type, 7869 /// or NULL if no better result could be determined. 7870 static ObjCInterfaceDecl *GetAssumedMessageSendExprType(Expr *E) { 7871 auto *Msg = dyn_cast_or_null<ObjCMessageExpr>(E); 7872 if (!Msg) 7873 return nullptr; 7874 7875 Selector Sel = Msg->getSelector(); 7876 if (Sel.isNull()) 7877 return nullptr; 7878 7879 const IdentifierInfo *Id = Sel.getIdentifierInfoForSlot(0); 7880 if (!Id) 7881 return nullptr; 7882 7883 ObjCMethodDecl *Method = Msg->getMethodDecl(); 7884 if (!Method) 7885 return nullptr; 7886 7887 // Determine the class that we're sending the message to. 7888 ObjCInterfaceDecl *IFace = nullptr; 7889 switch (Msg->getReceiverKind()) { 7890 case ObjCMessageExpr::Class: 7891 if (const ObjCObjectType *ObjType = 7892 Msg->getClassReceiver()->getAs<ObjCObjectType>()) 7893 IFace = ObjType->getInterface(); 7894 break; 7895 7896 case ObjCMessageExpr::Instance: { 7897 QualType T = Msg->getInstanceReceiver()->getType(); 7898 if (const ObjCObjectPointerType *Ptr = T->getAs<ObjCObjectPointerType>()) 7899 IFace = Ptr->getInterfaceDecl(); 7900 break; 7901 } 7902 7903 case ObjCMessageExpr::SuperInstance: 7904 case ObjCMessageExpr::SuperClass: 7905 break; 7906 } 7907 7908 if (!IFace) 7909 return nullptr; 7910 7911 ObjCInterfaceDecl *Super = IFace->getSuperClass(); 7912 if (Method->isInstanceMethod()) 7913 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName()) 7914 .Case("retain", IFace) 7915 .Case("strong", IFace) 7916 .Case("autorelease", IFace) 7917 .Case("copy", IFace) 7918 .Case("copyWithZone", IFace) 7919 .Case("mutableCopy", IFace) 7920 .Case("mutableCopyWithZone", IFace) 7921 .Case("awakeFromCoder", IFace) 7922 .Case("replacementObjectFromCoder", IFace) 7923 .Case("class", IFace) 7924 .Case("classForCoder", IFace) 7925 .Case("superclass", Super) 7926 .Default(nullptr); 7927 7928 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName()) 7929 .Case("new", IFace) 7930 .Case("alloc", IFace) 7931 .Case("allocWithZone", IFace) 7932 .Case("class", IFace) 7933 .Case("superclass", Super) 7934 .Default(nullptr); 7935 } 7936 7937 // Add a special completion for a message send to "super", which fills in the 7938 // most likely case of forwarding all of our arguments to the superclass 7939 // function. 7940 /// 7941 /// \param S The semantic analysis object. 7942 /// 7943 /// \param NeedSuperKeyword Whether we need to prefix this completion with 7944 /// the "super" keyword. Otherwise, we just need to provide the arguments. 7945 /// 7946 /// \param SelIdents The identifiers in the selector that have already been 7947 /// provided as arguments for a send to "super". 7948 /// 7949 /// \param Results The set of results to augment. 7950 /// 7951 /// \returns the Objective-C method declaration that would be invoked by 7952 /// this "super" completion. If NULL, no completion was added. 7953 static ObjCMethodDecl * 7954 AddSuperSendCompletion(Sema &S, bool NeedSuperKeyword, 7955 ArrayRef<const IdentifierInfo *> SelIdents, 7956 ResultBuilder &Results) { 7957 ObjCMethodDecl *CurMethod = S.getCurMethodDecl(); 7958 if (!CurMethod) 7959 return nullptr; 7960 7961 ObjCInterfaceDecl *Class = CurMethod->getClassInterface(); 7962 if (!Class) 7963 return nullptr; 7964 7965 // Try to find a superclass method with the same selector. 7966 ObjCMethodDecl *SuperMethod = nullptr; 7967 while ((Class = Class->getSuperClass()) && !SuperMethod) { 7968 // Check in the class 7969 SuperMethod = Class->getMethod(CurMethod->getSelector(), 7970 CurMethod->isInstanceMethod()); 7971 7972 // Check in categories or class extensions. 7973 if (!SuperMethod) { 7974 for (const auto *Cat : Class->known_categories()) { 7975 if ((SuperMethod = Cat->getMethod(CurMethod->getSelector(), 7976 CurMethod->isInstanceMethod()))) 7977 break; 7978 } 7979 } 7980 } 7981 7982 if (!SuperMethod) 7983 return nullptr; 7984 7985 // Check whether the superclass method has the same signature. 7986 if (CurMethod->param_size() != SuperMethod->param_size() || 7987 CurMethod->isVariadic() != SuperMethod->isVariadic()) 7988 return nullptr; 7989 7990 for (ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin(), 7991 CurPEnd = CurMethod->param_end(), 7992 SuperP = SuperMethod->param_begin(); 7993 CurP != CurPEnd; ++CurP, ++SuperP) { 7994 // Make sure the parameter types are compatible. 7995 if (!S.Context.hasSameUnqualifiedType((*CurP)->getType(), 7996 (*SuperP)->getType())) 7997 return nullptr; 7998 7999 // Make sure we have a parameter name to forward! 8000 if (!(*CurP)->getIdentifier()) 8001 return nullptr; 8002 } 8003 8004 // We have a superclass method. Now, form the send-to-super completion. 8005 CodeCompletionBuilder Builder(Results.getAllocator(), 8006 Results.getCodeCompletionTUInfo()); 8007 8008 // Give this completion a return type. 8009 AddResultTypeChunk(S.Context, getCompletionPrintingPolicy(S), SuperMethod, 8010 Results.getCompletionContext().getBaseType(), Builder); 8011 8012 // If we need the "super" keyword, add it (plus some spacing). 8013 if (NeedSuperKeyword) { 8014 Builder.AddTypedTextChunk("super"); 8015 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 8016 } 8017 8018 Selector Sel = CurMethod->getSelector(); 8019 if (Sel.isUnarySelector()) { 8020 if (NeedSuperKeyword) 8021 Builder.AddTextChunk( 8022 Builder.getAllocator().CopyString(Sel.getNameForSlot(0))); 8023 else 8024 Builder.AddTypedTextChunk( 8025 Builder.getAllocator().CopyString(Sel.getNameForSlot(0))); 8026 } else { 8027 ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin(); 8028 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I, ++CurP) { 8029 if (I > SelIdents.size()) 8030 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 8031 8032 if (I < SelIdents.size()) 8033 Builder.AddInformativeChunk( 8034 Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":")); 8035 else if (NeedSuperKeyword || I > SelIdents.size()) { 8036 Builder.AddTextChunk( 8037 Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":")); 8038 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString( 8039 (*CurP)->getIdentifier()->getName())); 8040 } else { 8041 Builder.AddTypedTextChunk( 8042 Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":")); 8043 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString( 8044 (*CurP)->getIdentifier()->getName())); 8045 } 8046 } 8047 } 8048 8049 Results.AddResult(CodeCompletionResult(Builder.TakeString(), SuperMethod, 8050 CCP_SuperCompletion)); 8051 return SuperMethod; 8052 } 8053 8054 void SemaCodeCompletion::CodeCompleteObjCMessageReceiver(Scope *S) { 8055 typedef CodeCompletionResult Result; 8056 ResultBuilder Results( 8057 SemaRef, CodeCompleter->getAllocator(), 8058 CodeCompleter->getCodeCompletionTUInfo(), 8059 CodeCompletionContext::CCC_ObjCMessageReceiver, 8060 getLangOpts().CPlusPlus11 8061 ? &ResultBuilder::IsObjCMessageReceiverOrLambdaCapture 8062 : &ResultBuilder::IsObjCMessageReceiver); 8063 8064 CodeCompletionDeclConsumer Consumer(Results, SemaRef.CurContext); 8065 Results.EnterNewScope(); 8066 SemaRef.LookupVisibleDecls(S, Sema::LookupOrdinaryName, Consumer, 8067 CodeCompleter->includeGlobals(), 8068 CodeCompleter->loadExternal()); 8069 8070 // If we are in an Objective-C method inside a class that has a superclass, 8071 // add "super" as an option. 8072 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) 8073 if (ObjCInterfaceDecl *Iface = Method->getClassInterface()) 8074 if (Iface->getSuperClass()) { 8075 Results.AddResult(Result("super")); 8076 8077 AddSuperSendCompletion(SemaRef, /*NeedSuperKeyword=*/true, {}, Results); 8078 } 8079 8080 if (getLangOpts().CPlusPlus11) 8081 addThisCompletion(SemaRef, Results); 8082 8083 Results.ExitScope(); 8084 8085 if (CodeCompleter->includeMacros()) 8086 AddMacroResults(SemaRef.PP, Results, CodeCompleter->loadExternal(), false); 8087 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 8088 Results.getCompletionContext(), Results.data(), 8089 Results.size()); 8090 } 8091 8092 void SemaCodeCompletion::CodeCompleteObjCSuperMessage( 8093 Scope *S, SourceLocation SuperLoc, 8094 ArrayRef<const IdentifierInfo *> SelIdents, bool AtArgumentExpression) { 8095 ObjCInterfaceDecl *CDecl = nullptr; 8096 if (ObjCMethodDecl *CurMethod = SemaRef.getCurMethodDecl()) { 8097 // Figure out which interface we're in. 8098 CDecl = CurMethod->getClassInterface(); 8099 if (!CDecl) 8100 return; 8101 8102 // Find the superclass of this class. 8103 CDecl = CDecl->getSuperClass(); 8104 if (!CDecl) 8105 return; 8106 8107 if (CurMethod->isInstanceMethod()) { 8108 // We are inside an instance method, which means that the message 8109 // send [super ...] is actually calling an instance method on the 8110 // current object. 8111 return CodeCompleteObjCInstanceMessage(S, nullptr, SelIdents, 8112 AtArgumentExpression, CDecl); 8113 } 8114 8115 // Fall through to send to the superclass in CDecl. 8116 } else { 8117 // "super" may be the name of a type or variable. Figure out which 8118 // it is. 8119 const IdentifierInfo *Super = SemaRef.getSuperIdentifier(); 8120 NamedDecl *ND = 8121 SemaRef.LookupSingleName(S, Super, SuperLoc, Sema::LookupOrdinaryName); 8122 if ((CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(ND))) { 8123 // "super" names an interface. Use it. 8124 } else if (TypeDecl *TD = dyn_cast_or_null<TypeDecl>(ND)) { 8125 if (const ObjCObjectType *Iface = 8126 getASTContext().getTypeDeclType(TD)->getAs<ObjCObjectType>()) 8127 CDecl = Iface->getInterface(); 8128 } else if (ND && isa<UnresolvedUsingTypenameDecl>(ND)) { 8129 // "super" names an unresolved type; we can't be more specific. 8130 } else { 8131 // Assume that "super" names some kind of value and parse that way. 8132 CXXScopeSpec SS; 8133 SourceLocation TemplateKWLoc; 8134 UnqualifiedId id; 8135 id.setIdentifier(Super, SuperLoc); 8136 ExprResult SuperExpr = 8137 SemaRef.ActOnIdExpression(S, SS, TemplateKWLoc, id, 8138 /*HasTrailingLParen=*/false, 8139 /*IsAddressOfOperand=*/false); 8140 return CodeCompleteObjCInstanceMessage(S, (Expr *)SuperExpr.get(), 8141 SelIdents, AtArgumentExpression); 8142 } 8143 8144 // Fall through 8145 } 8146 8147 ParsedType Receiver; 8148 if (CDecl) 8149 Receiver = ParsedType::make(getASTContext().getObjCInterfaceType(CDecl)); 8150 return CodeCompleteObjCClassMessage(S, Receiver, SelIdents, 8151 AtArgumentExpression, 8152 /*IsSuper=*/true); 8153 } 8154 8155 /// Given a set of code-completion results for the argument of a message 8156 /// send, determine the preferred type (if any) for that argument expression. 8157 static QualType getPreferredArgumentTypeForMessageSend(ResultBuilder &Results, 8158 unsigned NumSelIdents) { 8159 typedef CodeCompletionResult Result; 8160 ASTContext &Context = Results.getSema().Context; 8161 8162 QualType PreferredType; 8163 unsigned BestPriority = CCP_Unlikely * 2; 8164 Result *ResultsData = Results.data(); 8165 for (unsigned I = 0, N = Results.size(); I != N; ++I) { 8166 Result &R = ResultsData[I]; 8167 if (R.Kind == Result::RK_Declaration && 8168 isa<ObjCMethodDecl>(R.Declaration)) { 8169 if (R.Priority <= BestPriority) { 8170 const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(R.Declaration); 8171 if (NumSelIdents <= Method->param_size()) { 8172 QualType MyPreferredType = 8173 Method->parameters()[NumSelIdents - 1]->getType(); 8174 if (R.Priority < BestPriority || PreferredType.isNull()) { 8175 BestPriority = R.Priority; 8176 PreferredType = MyPreferredType; 8177 } else if (!Context.hasSameUnqualifiedType(PreferredType, 8178 MyPreferredType)) { 8179 PreferredType = QualType(); 8180 } 8181 } 8182 } 8183 } 8184 } 8185 8186 return PreferredType; 8187 } 8188 8189 static void 8190 AddClassMessageCompletions(Sema &SemaRef, Scope *S, ParsedType Receiver, 8191 ArrayRef<const IdentifierInfo *> SelIdents, 8192 bool AtArgumentExpression, bool IsSuper, 8193 ResultBuilder &Results) { 8194 typedef CodeCompletionResult Result; 8195 ObjCInterfaceDecl *CDecl = nullptr; 8196 8197 // If the given name refers to an interface type, retrieve the 8198 // corresponding declaration. 8199 if (Receiver) { 8200 QualType T = SemaRef.GetTypeFromParser(Receiver, nullptr); 8201 if (!T.isNull()) 8202 if (const ObjCObjectType *Interface = T->getAs<ObjCObjectType>()) 8203 CDecl = Interface->getInterface(); 8204 } 8205 8206 // Add all of the factory methods in this Objective-C class, its protocols, 8207 // superclasses, categories, implementation, etc. 8208 Results.EnterNewScope(); 8209 8210 // If this is a send-to-super, try to add the special "super" send 8211 // completion. 8212 if (IsSuper) { 8213 if (ObjCMethodDecl *SuperMethod = 8214 AddSuperSendCompletion(SemaRef, false, SelIdents, Results)) 8215 Results.Ignore(SuperMethod); 8216 } 8217 8218 // If we're inside an Objective-C method definition, prefer its selector to 8219 // others. 8220 if (ObjCMethodDecl *CurMethod = SemaRef.getCurMethodDecl()) 8221 Results.setPreferredSelector(CurMethod->getSelector()); 8222 8223 VisitedSelectorSet Selectors; 8224 if (CDecl) 8225 AddObjCMethods(CDecl, false, MK_Any, SelIdents, SemaRef.CurContext, 8226 Selectors, AtArgumentExpression, Results); 8227 else { 8228 // We're messaging "id" as a type; provide all class/factory methods. 8229 8230 // If we have an external source, load the entire class method 8231 // pool from the AST file. 8232 if (SemaRef.getExternalSource()) { 8233 for (uint32_t I = 0, 8234 N = SemaRef.getExternalSource()->GetNumExternalSelectors(); 8235 I != N; ++I) { 8236 Selector Sel = SemaRef.getExternalSource()->GetExternalSelector(I); 8237 if (Sel.isNull() || SemaRef.ObjC().MethodPool.count(Sel)) 8238 continue; 8239 8240 SemaRef.ObjC().ReadMethodPool(Sel); 8241 } 8242 } 8243 8244 for (SemaObjC::GlobalMethodPool::iterator 8245 M = SemaRef.ObjC().MethodPool.begin(), 8246 MEnd = SemaRef.ObjC().MethodPool.end(); 8247 M != MEnd; ++M) { 8248 for (ObjCMethodList *MethList = &M->second.second; 8249 MethList && MethList->getMethod(); MethList = MethList->getNext()) { 8250 if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents)) 8251 continue; 8252 8253 Result R(MethList->getMethod(), 8254 Results.getBasePriority(MethList->getMethod()), nullptr); 8255 R.StartParameter = SelIdents.size(); 8256 R.AllParametersAreInformative = false; 8257 Results.MaybeAddResult(R, SemaRef.CurContext); 8258 } 8259 } 8260 } 8261 8262 Results.ExitScope(); 8263 } 8264 8265 void SemaCodeCompletion::CodeCompleteObjCClassMessage( 8266 Scope *S, ParsedType Receiver, ArrayRef<const IdentifierInfo *> SelIdents, 8267 bool AtArgumentExpression, bool IsSuper) { 8268 8269 QualType T = SemaRef.GetTypeFromParser(Receiver); 8270 8271 ResultBuilder Results( 8272 SemaRef, CodeCompleter->getAllocator(), 8273 CodeCompleter->getCodeCompletionTUInfo(), 8274 CodeCompletionContext(CodeCompletionContext::CCC_ObjCClassMessage, T, 8275 SelIdents)); 8276 8277 AddClassMessageCompletions(SemaRef, S, Receiver, SelIdents, 8278 AtArgumentExpression, IsSuper, Results); 8279 8280 // If we're actually at the argument expression (rather than prior to the 8281 // selector), we're actually performing code completion for an expression. 8282 // Determine whether we have a single, best method. If so, we can 8283 // code-complete the expression using the corresponding parameter type as 8284 // our preferred type, improving completion results. 8285 if (AtArgumentExpression) { 8286 QualType PreferredType = 8287 getPreferredArgumentTypeForMessageSend(Results, SelIdents.size()); 8288 if (PreferredType.isNull()) 8289 CodeCompleteOrdinaryName(S, PCC_Expression); 8290 else 8291 CodeCompleteExpression(S, PreferredType); 8292 return; 8293 } 8294 8295 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 8296 Results.getCompletionContext(), Results.data(), 8297 Results.size()); 8298 } 8299 8300 void SemaCodeCompletion::CodeCompleteObjCInstanceMessage( 8301 Scope *S, Expr *Receiver, ArrayRef<const IdentifierInfo *> SelIdents, 8302 bool AtArgumentExpression, ObjCInterfaceDecl *Super) { 8303 typedef CodeCompletionResult Result; 8304 ASTContext &Context = getASTContext(); 8305 8306 Expr *RecExpr = static_cast<Expr *>(Receiver); 8307 8308 // If necessary, apply function/array conversion to the receiver. 8309 // C99 6.7.5.3p[7,8]. 8310 if (RecExpr) { 8311 ExprResult Conv = SemaRef.DefaultFunctionArrayLvalueConversion(RecExpr); 8312 if (Conv.isInvalid()) // conversion failed. bail. 8313 return; 8314 RecExpr = Conv.get(); 8315 } 8316 QualType ReceiverType = RecExpr 8317 ? RecExpr->getType() 8318 : Super ? Context.getObjCObjectPointerType( 8319 Context.getObjCInterfaceType(Super)) 8320 : Context.getObjCIdType(); 8321 8322 // If we're messaging an expression with type "id" or "Class", check 8323 // whether we know something special about the receiver that allows 8324 // us to assume a more-specific receiver type. 8325 if (ReceiverType->isObjCIdType() || ReceiverType->isObjCClassType()) { 8326 if (ObjCInterfaceDecl *IFace = GetAssumedMessageSendExprType(RecExpr)) { 8327 if (ReceiverType->isObjCClassType()) 8328 return CodeCompleteObjCClassMessage( 8329 S, ParsedType::make(Context.getObjCInterfaceType(IFace)), SelIdents, 8330 AtArgumentExpression, Super); 8331 8332 ReceiverType = 8333 Context.getObjCObjectPointerType(Context.getObjCInterfaceType(IFace)); 8334 } 8335 } else if (RecExpr && getLangOpts().CPlusPlus) { 8336 ExprResult Conv = SemaRef.PerformContextuallyConvertToObjCPointer(RecExpr); 8337 if (Conv.isUsable()) { 8338 RecExpr = Conv.get(); 8339 ReceiverType = RecExpr->getType(); 8340 } 8341 } 8342 8343 // Build the set of methods we can see. 8344 ResultBuilder Results( 8345 SemaRef, CodeCompleter->getAllocator(), 8346 CodeCompleter->getCodeCompletionTUInfo(), 8347 CodeCompletionContext(CodeCompletionContext::CCC_ObjCInstanceMessage, 8348 ReceiverType, SelIdents)); 8349 8350 Results.EnterNewScope(); 8351 8352 // If this is a send-to-super, try to add the special "super" send 8353 // completion. 8354 if (Super) { 8355 if (ObjCMethodDecl *SuperMethod = 8356 AddSuperSendCompletion(SemaRef, false, SelIdents, Results)) 8357 Results.Ignore(SuperMethod); 8358 } 8359 8360 // If we're inside an Objective-C method definition, prefer its selector to 8361 // others. 8362 if (ObjCMethodDecl *CurMethod = SemaRef.getCurMethodDecl()) 8363 Results.setPreferredSelector(CurMethod->getSelector()); 8364 8365 // Keep track of the selectors we've already added. 8366 VisitedSelectorSet Selectors; 8367 8368 // Handle messages to Class. This really isn't a message to an instance 8369 // method, so we treat it the same way we would treat a message send to a 8370 // class method. 8371 if (ReceiverType->isObjCClassType() || 8372 ReceiverType->isObjCQualifiedClassType()) { 8373 if (ObjCMethodDecl *CurMethod = SemaRef.getCurMethodDecl()) { 8374 if (ObjCInterfaceDecl *ClassDecl = CurMethod->getClassInterface()) 8375 AddObjCMethods(ClassDecl, false, MK_Any, SelIdents, SemaRef.CurContext, 8376 Selectors, AtArgumentExpression, Results); 8377 } 8378 } 8379 // Handle messages to a qualified ID ("id<foo>"). 8380 else if (const ObjCObjectPointerType *QualID = 8381 ReceiverType->getAsObjCQualifiedIdType()) { 8382 // Search protocols for instance methods. 8383 for (auto *I : QualID->quals()) 8384 AddObjCMethods(I, true, MK_Any, SelIdents, SemaRef.CurContext, Selectors, 8385 AtArgumentExpression, Results); 8386 } 8387 // Handle messages to a pointer to interface type. 8388 else if (const ObjCObjectPointerType *IFacePtr = 8389 ReceiverType->getAsObjCInterfacePointerType()) { 8390 // Search the class, its superclasses, etc., for instance methods. 8391 AddObjCMethods(IFacePtr->getInterfaceDecl(), true, MK_Any, SelIdents, 8392 SemaRef.CurContext, Selectors, AtArgumentExpression, 8393 Results); 8394 8395 // Search protocols for instance methods. 8396 for (auto *I : IFacePtr->quals()) 8397 AddObjCMethods(I, true, MK_Any, SelIdents, SemaRef.CurContext, Selectors, 8398 AtArgumentExpression, Results); 8399 } 8400 // Handle messages to "id". 8401 else if (ReceiverType->isObjCIdType()) { 8402 // We're messaging "id", so provide all instance methods we know 8403 // about as code-completion results. 8404 8405 // If we have an external source, load the entire class method 8406 // pool from the AST file. 8407 if (SemaRef.ExternalSource) { 8408 for (uint32_t I = 0, 8409 N = SemaRef.ExternalSource->GetNumExternalSelectors(); 8410 I != N; ++I) { 8411 Selector Sel = SemaRef.ExternalSource->GetExternalSelector(I); 8412 if (Sel.isNull() || SemaRef.ObjC().MethodPool.count(Sel)) 8413 continue; 8414 8415 SemaRef.ObjC().ReadMethodPool(Sel); 8416 } 8417 } 8418 8419 for (SemaObjC::GlobalMethodPool::iterator 8420 M = SemaRef.ObjC().MethodPool.begin(), 8421 MEnd = SemaRef.ObjC().MethodPool.end(); 8422 M != MEnd; ++M) { 8423 for (ObjCMethodList *MethList = &M->second.first; 8424 MethList && MethList->getMethod(); MethList = MethList->getNext()) { 8425 if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents)) 8426 continue; 8427 8428 if (!Selectors.insert(MethList->getMethod()->getSelector()).second) 8429 continue; 8430 8431 Result R(MethList->getMethod(), 8432 Results.getBasePriority(MethList->getMethod()), nullptr); 8433 R.StartParameter = SelIdents.size(); 8434 R.AllParametersAreInformative = false; 8435 Results.MaybeAddResult(R, SemaRef.CurContext); 8436 } 8437 } 8438 } 8439 Results.ExitScope(); 8440 8441 // If we're actually at the argument expression (rather than prior to the 8442 // selector), we're actually performing code completion for an expression. 8443 // Determine whether we have a single, best method. If so, we can 8444 // code-complete the expression using the corresponding parameter type as 8445 // our preferred type, improving completion results. 8446 if (AtArgumentExpression) { 8447 QualType PreferredType = 8448 getPreferredArgumentTypeForMessageSend(Results, SelIdents.size()); 8449 if (PreferredType.isNull()) 8450 CodeCompleteOrdinaryName(S, PCC_Expression); 8451 else 8452 CodeCompleteExpression(S, PreferredType); 8453 return; 8454 } 8455 8456 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 8457 Results.getCompletionContext(), Results.data(), 8458 Results.size()); 8459 } 8460 8461 void SemaCodeCompletion::CodeCompleteObjCForCollection( 8462 Scope *S, DeclGroupPtrTy IterationVar) { 8463 CodeCompleteExpressionData Data; 8464 Data.ObjCCollection = true; 8465 8466 if (IterationVar.getAsOpaquePtr()) { 8467 DeclGroupRef DG = IterationVar.get(); 8468 for (DeclGroupRef::iterator I = DG.begin(), End = DG.end(); I != End; ++I) { 8469 if (*I) 8470 Data.IgnoreDecls.push_back(*I); 8471 } 8472 } 8473 8474 CodeCompleteExpression(S, Data); 8475 } 8476 8477 void SemaCodeCompletion::CodeCompleteObjCSelector( 8478 Scope *S, ArrayRef<const IdentifierInfo *> SelIdents) { 8479 // If we have an external source, load the entire class method 8480 // pool from the AST file. 8481 if (SemaRef.ExternalSource) { 8482 for (uint32_t I = 0, N = SemaRef.ExternalSource->GetNumExternalSelectors(); 8483 I != N; ++I) { 8484 Selector Sel = SemaRef.ExternalSource->GetExternalSelector(I); 8485 if (Sel.isNull() || SemaRef.ObjC().MethodPool.count(Sel)) 8486 continue; 8487 8488 SemaRef.ObjC().ReadMethodPool(Sel); 8489 } 8490 } 8491 8492 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(), 8493 CodeCompleter->getCodeCompletionTUInfo(), 8494 CodeCompletionContext::CCC_SelectorName); 8495 Results.EnterNewScope(); 8496 for (SemaObjC::GlobalMethodPool::iterator 8497 M = SemaRef.ObjC().MethodPool.begin(), 8498 MEnd = SemaRef.ObjC().MethodPool.end(); 8499 M != MEnd; ++M) { 8500 8501 Selector Sel = M->first; 8502 if (!isAcceptableObjCSelector(Sel, MK_Any, SelIdents)) 8503 continue; 8504 8505 CodeCompletionBuilder Builder(Results.getAllocator(), 8506 Results.getCodeCompletionTUInfo()); 8507 if (Sel.isUnarySelector()) { 8508 Builder.AddTypedTextChunk( 8509 Builder.getAllocator().CopyString(Sel.getNameForSlot(0))); 8510 Results.AddResult(Builder.TakeString()); 8511 continue; 8512 } 8513 8514 std::string Accumulator; 8515 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I) { 8516 if (I == SelIdents.size()) { 8517 if (!Accumulator.empty()) { 8518 Builder.AddInformativeChunk( 8519 Builder.getAllocator().CopyString(Accumulator)); 8520 Accumulator.clear(); 8521 } 8522 } 8523 8524 Accumulator += Sel.getNameForSlot(I); 8525 Accumulator += ':'; 8526 } 8527 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(Accumulator)); 8528 Results.AddResult(Builder.TakeString()); 8529 } 8530 Results.ExitScope(); 8531 8532 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 8533 Results.getCompletionContext(), Results.data(), 8534 Results.size()); 8535 } 8536 8537 /// Add all of the protocol declarations that we find in the given 8538 /// (translation unit) context. 8539 static void AddProtocolResults(DeclContext *Ctx, DeclContext *CurContext, 8540 bool OnlyForwardDeclarations, 8541 ResultBuilder &Results) { 8542 typedef CodeCompletionResult Result; 8543 8544 for (const auto *D : Ctx->decls()) { 8545 // Record any protocols we find. 8546 if (const auto *Proto = dyn_cast<ObjCProtocolDecl>(D)) 8547 if (!OnlyForwardDeclarations || !Proto->hasDefinition()) 8548 Results.AddResult( 8549 Result(Proto, Results.getBasePriority(Proto), nullptr), CurContext, 8550 nullptr, false); 8551 } 8552 } 8553 8554 void SemaCodeCompletion::CodeCompleteObjCProtocolReferences( 8555 ArrayRef<IdentifierLocPair> Protocols) { 8556 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(), 8557 CodeCompleter->getCodeCompletionTUInfo(), 8558 CodeCompletionContext::CCC_ObjCProtocolName); 8559 8560 if (CodeCompleter->includeGlobals()) { 8561 Results.EnterNewScope(); 8562 8563 // Tell the result set to ignore all of the protocols we have 8564 // already seen. 8565 // FIXME: This doesn't work when caching code-completion results. 8566 for (const IdentifierLocPair &Pair : Protocols) 8567 if (ObjCProtocolDecl *Protocol = 8568 SemaRef.ObjC().LookupProtocol(Pair.first, Pair.second)) 8569 Results.Ignore(Protocol); 8570 8571 // Add all protocols. 8572 AddProtocolResults(getASTContext().getTranslationUnitDecl(), 8573 SemaRef.CurContext, false, Results); 8574 8575 Results.ExitScope(); 8576 } 8577 8578 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 8579 Results.getCompletionContext(), Results.data(), 8580 Results.size()); 8581 } 8582 8583 void SemaCodeCompletion::CodeCompleteObjCProtocolDecl(Scope *) { 8584 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(), 8585 CodeCompleter->getCodeCompletionTUInfo(), 8586 CodeCompletionContext::CCC_ObjCProtocolName); 8587 8588 if (CodeCompleter->includeGlobals()) { 8589 Results.EnterNewScope(); 8590 8591 // Add all protocols. 8592 AddProtocolResults(getASTContext().getTranslationUnitDecl(), 8593 SemaRef.CurContext, true, Results); 8594 8595 Results.ExitScope(); 8596 } 8597 8598 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 8599 Results.getCompletionContext(), Results.data(), 8600 Results.size()); 8601 } 8602 8603 /// Add all of the Objective-C interface declarations that we find in 8604 /// the given (translation unit) context. 8605 static void AddInterfaceResults(DeclContext *Ctx, DeclContext *CurContext, 8606 bool OnlyForwardDeclarations, 8607 bool OnlyUnimplemented, 8608 ResultBuilder &Results) { 8609 typedef CodeCompletionResult Result; 8610 8611 for (const auto *D : Ctx->decls()) { 8612 // Record any interfaces we find. 8613 if (const auto *Class = dyn_cast<ObjCInterfaceDecl>(D)) 8614 if ((!OnlyForwardDeclarations || !Class->hasDefinition()) && 8615 (!OnlyUnimplemented || !Class->getImplementation())) 8616 Results.AddResult( 8617 Result(Class, Results.getBasePriority(Class), nullptr), CurContext, 8618 nullptr, false); 8619 } 8620 } 8621 8622 void SemaCodeCompletion::CodeCompleteObjCInterfaceDecl(Scope *S) { 8623 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(), 8624 CodeCompleter->getCodeCompletionTUInfo(), 8625 CodeCompletionContext::CCC_ObjCInterfaceName); 8626 Results.EnterNewScope(); 8627 8628 if (CodeCompleter->includeGlobals()) { 8629 // Add all classes. 8630 AddInterfaceResults(getASTContext().getTranslationUnitDecl(), 8631 SemaRef.CurContext, false, false, Results); 8632 } 8633 8634 Results.ExitScope(); 8635 8636 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 8637 Results.getCompletionContext(), Results.data(), 8638 Results.size()); 8639 } 8640 8641 void SemaCodeCompletion::CodeCompleteObjCClassForwardDecl(Scope *S) { 8642 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(), 8643 CodeCompleter->getCodeCompletionTUInfo(), 8644 CodeCompletionContext::CCC_ObjCClassForwardDecl); 8645 Results.EnterNewScope(); 8646 8647 if (CodeCompleter->includeGlobals()) { 8648 // Add all classes. 8649 AddInterfaceResults(getASTContext().getTranslationUnitDecl(), 8650 SemaRef.CurContext, false, false, Results); 8651 } 8652 8653 Results.ExitScope(); 8654 8655 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 8656 Results.getCompletionContext(), Results.data(), 8657 Results.size()); 8658 } 8659 8660 void SemaCodeCompletion::CodeCompleteObjCSuperclass( 8661 Scope *S, IdentifierInfo *ClassName, SourceLocation ClassNameLoc) { 8662 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(), 8663 CodeCompleter->getCodeCompletionTUInfo(), 8664 CodeCompletionContext::CCC_ObjCInterfaceName); 8665 Results.EnterNewScope(); 8666 8667 // Make sure that we ignore the class we're currently defining. 8668 NamedDecl *CurClass = SemaRef.LookupSingleName( 8669 SemaRef.TUScope, ClassName, ClassNameLoc, Sema::LookupOrdinaryName); 8670 if (CurClass && isa<ObjCInterfaceDecl>(CurClass)) 8671 Results.Ignore(CurClass); 8672 8673 if (CodeCompleter->includeGlobals()) { 8674 // Add all classes. 8675 AddInterfaceResults(getASTContext().getTranslationUnitDecl(), 8676 SemaRef.CurContext, false, false, Results); 8677 } 8678 8679 Results.ExitScope(); 8680 8681 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 8682 Results.getCompletionContext(), Results.data(), 8683 Results.size()); 8684 } 8685 8686 void SemaCodeCompletion::CodeCompleteObjCImplementationDecl(Scope *S) { 8687 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(), 8688 CodeCompleter->getCodeCompletionTUInfo(), 8689 CodeCompletionContext::CCC_ObjCImplementation); 8690 Results.EnterNewScope(); 8691 8692 if (CodeCompleter->includeGlobals()) { 8693 // Add all unimplemented classes. 8694 AddInterfaceResults(getASTContext().getTranslationUnitDecl(), 8695 SemaRef.CurContext, false, true, Results); 8696 } 8697 8698 Results.ExitScope(); 8699 8700 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 8701 Results.getCompletionContext(), Results.data(), 8702 Results.size()); 8703 } 8704 8705 void SemaCodeCompletion::CodeCompleteObjCInterfaceCategory( 8706 Scope *S, IdentifierInfo *ClassName, SourceLocation ClassNameLoc) { 8707 typedef CodeCompletionResult Result; 8708 8709 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(), 8710 CodeCompleter->getCodeCompletionTUInfo(), 8711 CodeCompletionContext::CCC_ObjCCategoryName); 8712 8713 // Ignore any categories we find that have already been implemented by this 8714 // interface. 8715 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames; 8716 NamedDecl *CurClass = SemaRef.LookupSingleName( 8717 SemaRef.TUScope, ClassName, ClassNameLoc, Sema::LookupOrdinaryName); 8718 if (ObjCInterfaceDecl *Class = 8719 dyn_cast_or_null<ObjCInterfaceDecl>(CurClass)) { 8720 for (const auto *Cat : Class->visible_categories()) 8721 CategoryNames.insert(Cat->getIdentifier()); 8722 } 8723 8724 // Add all of the categories we know about. 8725 Results.EnterNewScope(); 8726 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 8727 for (const auto *D : TU->decls()) 8728 if (const auto *Category = dyn_cast<ObjCCategoryDecl>(D)) 8729 if (CategoryNames.insert(Category->getIdentifier()).second) 8730 Results.AddResult( 8731 Result(Category, Results.getBasePriority(Category), nullptr), 8732 SemaRef.CurContext, nullptr, false); 8733 Results.ExitScope(); 8734 8735 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 8736 Results.getCompletionContext(), Results.data(), 8737 Results.size()); 8738 } 8739 8740 void SemaCodeCompletion::CodeCompleteObjCImplementationCategory( 8741 Scope *S, IdentifierInfo *ClassName, SourceLocation ClassNameLoc) { 8742 typedef CodeCompletionResult Result; 8743 8744 // Find the corresponding interface. If we couldn't find the interface, the 8745 // program itself is ill-formed. However, we'll try to be helpful still by 8746 // providing the list of all of the categories we know about. 8747 NamedDecl *CurClass = SemaRef.LookupSingleName( 8748 SemaRef.TUScope, ClassName, ClassNameLoc, Sema::LookupOrdinaryName); 8749 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass); 8750 if (!Class) 8751 return CodeCompleteObjCInterfaceCategory(S, ClassName, ClassNameLoc); 8752 8753 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(), 8754 CodeCompleter->getCodeCompletionTUInfo(), 8755 CodeCompletionContext::CCC_ObjCCategoryName); 8756 8757 // Add all of the categories that have corresponding interface 8758 // declarations in this class and any of its superclasses, except for 8759 // already-implemented categories in the class itself. 8760 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames; 8761 Results.EnterNewScope(); 8762 bool IgnoreImplemented = true; 8763 while (Class) { 8764 for (const auto *Cat : Class->visible_categories()) { 8765 if ((!IgnoreImplemented || !Cat->getImplementation()) && 8766 CategoryNames.insert(Cat->getIdentifier()).second) 8767 Results.AddResult(Result(Cat, Results.getBasePriority(Cat), nullptr), 8768 SemaRef.CurContext, nullptr, false); 8769 } 8770 8771 Class = Class->getSuperClass(); 8772 IgnoreImplemented = false; 8773 } 8774 Results.ExitScope(); 8775 8776 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 8777 Results.getCompletionContext(), Results.data(), 8778 Results.size()); 8779 } 8780 8781 void SemaCodeCompletion::CodeCompleteObjCPropertyDefinition(Scope *S) { 8782 CodeCompletionContext CCContext(CodeCompletionContext::CCC_Other); 8783 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(), 8784 CodeCompleter->getCodeCompletionTUInfo(), CCContext); 8785 8786 // Figure out where this @synthesize lives. 8787 ObjCContainerDecl *Container = 8788 dyn_cast_or_null<ObjCContainerDecl>(SemaRef.CurContext); 8789 if (!Container || (!isa<ObjCImplementationDecl>(Container) && 8790 !isa<ObjCCategoryImplDecl>(Container))) 8791 return; 8792 8793 // Ignore any properties that have already been implemented. 8794 Container = getContainerDef(Container); 8795 for (const auto *D : Container->decls()) 8796 if (const auto *PropertyImpl = dyn_cast<ObjCPropertyImplDecl>(D)) 8797 Results.Ignore(PropertyImpl->getPropertyDecl()); 8798 8799 // Add any properties that we find. 8800 AddedPropertiesSet AddedProperties; 8801 Results.EnterNewScope(); 8802 if (ObjCImplementationDecl *ClassImpl = 8803 dyn_cast<ObjCImplementationDecl>(Container)) 8804 AddObjCProperties(CCContext, ClassImpl->getClassInterface(), false, 8805 /*AllowNullaryMethods=*/false, SemaRef.CurContext, 8806 AddedProperties, Results); 8807 else 8808 AddObjCProperties(CCContext, 8809 cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl(), 8810 false, /*AllowNullaryMethods=*/false, SemaRef.CurContext, 8811 AddedProperties, Results); 8812 Results.ExitScope(); 8813 8814 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 8815 Results.getCompletionContext(), Results.data(), 8816 Results.size()); 8817 } 8818 8819 void SemaCodeCompletion::CodeCompleteObjCPropertySynthesizeIvar( 8820 Scope *S, IdentifierInfo *PropertyName) { 8821 typedef CodeCompletionResult Result; 8822 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(), 8823 CodeCompleter->getCodeCompletionTUInfo(), 8824 CodeCompletionContext::CCC_Other); 8825 8826 // Figure out where this @synthesize lives. 8827 ObjCContainerDecl *Container = 8828 dyn_cast_or_null<ObjCContainerDecl>(SemaRef.CurContext); 8829 if (!Container || (!isa<ObjCImplementationDecl>(Container) && 8830 !isa<ObjCCategoryImplDecl>(Container))) 8831 return; 8832 8833 // Figure out which interface we're looking into. 8834 ObjCInterfaceDecl *Class = nullptr; 8835 if (ObjCImplementationDecl *ClassImpl = 8836 dyn_cast<ObjCImplementationDecl>(Container)) 8837 Class = ClassImpl->getClassInterface(); 8838 else 8839 Class = cast<ObjCCategoryImplDecl>(Container) 8840 ->getCategoryDecl() 8841 ->getClassInterface(); 8842 8843 // Determine the type of the property we're synthesizing. 8844 QualType PropertyType = getASTContext().getObjCIdType(); 8845 if (Class) { 8846 if (ObjCPropertyDecl *Property = Class->FindPropertyDeclaration( 8847 PropertyName, ObjCPropertyQueryKind::OBJC_PR_query_instance)) { 8848 PropertyType = 8849 Property->getType().getNonReferenceType().getUnqualifiedType(); 8850 8851 // Give preference to ivars 8852 Results.setPreferredType(PropertyType); 8853 } 8854 } 8855 8856 // Add all of the instance variables in this class and its superclasses. 8857 Results.EnterNewScope(); 8858 bool SawSimilarlyNamedIvar = false; 8859 std::string NameWithPrefix; 8860 NameWithPrefix += '_'; 8861 NameWithPrefix += PropertyName->getName(); 8862 std::string NameWithSuffix = PropertyName->getName().str(); 8863 NameWithSuffix += '_'; 8864 for (; Class; Class = Class->getSuperClass()) { 8865 for (ObjCIvarDecl *Ivar = Class->all_declared_ivar_begin(); Ivar; 8866 Ivar = Ivar->getNextIvar()) { 8867 Results.AddResult(Result(Ivar, Results.getBasePriority(Ivar), nullptr), 8868 SemaRef.CurContext, nullptr, false); 8869 8870 // Determine whether we've seen an ivar with a name similar to the 8871 // property. 8872 if ((PropertyName == Ivar->getIdentifier() || 8873 NameWithPrefix == Ivar->getName() || 8874 NameWithSuffix == Ivar->getName())) { 8875 SawSimilarlyNamedIvar = true; 8876 8877 // Reduce the priority of this result by one, to give it a slight 8878 // advantage over other results whose names don't match so closely. 8879 if (Results.size() && 8880 Results.data()[Results.size() - 1].Kind == 8881 CodeCompletionResult::RK_Declaration && 8882 Results.data()[Results.size() - 1].Declaration == Ivar) 8883 Results.data()[Results.size() - 1].Priority--; 8884 } 8885 } 8886 } 8887 8888 if (!SawSimilarlyNamedIvar) { 8889 // Create ivar result _propName, that the user can use to synthesize 8890 // an ivar of the appropriate type. 8891 unsigned Priority = CCP_MemberDeclaration + 1; 8892 typedef CodeCompletionResult Result; 8893 CodeCompletionAllocator &Allocator = Results.getAllocator(); 8894 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo(), 8895 Priority, CXAvailability_Available); 8896 8897 PrintingPolicy Policy = getCompletionPrintingPolicy(SemaRef); 8898 Builder.AddResultTypeChunk(GetCompletionTypeString( 8899 PropertyType, getASTContext(), Policy, Allocator)); 8900 Builder.AddTypedTextChunk(Allocator.CopyString(NameWithPrefix)); 8901 Results.AddResult( 8902 Result(Builder.TakeString(), Priority, CXCursor_ObjCIvarDecl)); 8903 } 8904 8905 Results.ExitScope(); 8906 8907 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 8908 Results.getCompletionContext(), Results.data(), 8909 Results.size()); 8910 } 8911 8912 // Mapping from selectors to the methods that implement that selector, along 8913 // with the "in original class" flag. 8914 typedef llvm::DenseMap<Selector, 8915 llvm::PointerIntPair<ObjCMethodDecl *, 1, bool>> 8916 KnownMethodsMap; 8917 8918 /// Find all of the methods that reside in the given container 8919 /// (and its superclasses, protocols, etc.) that meet the given 8920 /// criteria. Insert those methods into the map of known methods, 8921 /// indexed by selector so they can be easily found. 8922 static void FindImplementableMethods(ASTContext &Context, 8923 ObjCContainerDecl *Container, 8924 std::optional<bool> WantInstanceMethods, 8925 QualType ReturnType, 8926 KnownMethodsMap &KnownMethods, 8927 bool InOriginalClass = true) { 8928 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)) { 8929 // Make sure we have a definition; that's what we'll walk. 8930 if (!IFace->hasDefinition()) 8931 return; 8932 8933 IFace = IFace->getDefinition(); 8934 Container = IFace; 8935 8936 const ObjCList<ObjCProtocolDecl> &Protocols = 8937 IFace->getReferencedProtocols(); 8938 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(), 8939 E = Protocols.end(); 8940 I != E; ++I) 8941 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType, 8942 KnownMethods, InOriginalClass); 8943 8944 // Add methods from any class extensions and categories. 8945 for (auto *Cat : IFace->visible_categories()) { 8946 FindImplementableMethods(Context, Cat, WantInstanceMethods, ReturnType, 8947 KnownMethods, false); 8948 } 8949 8950 // Visit the superclass. 8951 if (IFace->getSuperClass()) 8952 FindImplementableMethods(Context, IFace->getSuperClass(), 8953 WantInstanceMethods, ReturnType, KnownMethods, 8954 false); 8955 } 8956 8957 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) { 8958 // Recurse into protocols. 8959 const ObjCList<ObjCProtocolDecl> &Protocols = 8960 Category->getReferencedProtocols(); 8961 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(), 8962 E = Protocols.end(); 8963 I != E; ++I) 8964 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType, 8965 KnownMethods, InOriginalClass); 8966 8967 // If this category is the original class, jump to the interface. 8968 if (InOriginalClass && Category->getClassInterface()) 8969 FindImplementableMethods(Context, Category->getClassInterface(), 8970 WantInstanceMethods, ReturnType, KnownMethods, 8971 false); 8972 } 8973 8974 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) { 8975 // Make sure we have a definition; that's what we'll walk. 8976 if (!Protocol->hasDefinition()) 8977 return; 8978 Protocol = Protocol->getDefinition(); 8979 Container = Protocol; 8980 8981 // Recurse into protocols. 8982 const ObjCList<ObjCProtocolDecl> &Protocols = 8983 Protocol->getReferencedProtocols(); 8984 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(), 8985 E = Protocols.end(); 8986 I != E; ++I) 8987 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType, 8988 KnownMethods, false); 8989 } 8990 8991 // Add methods in this container. This operation occurs last because 8992 // we want the methods from this container to override any methods 8993 // we've previously seen with the same selector. 8994 for (auto *M : Container->methods()) { 8995 if (!WantInstanceMethods || M->isInstanceMethod() == *WantInstanceMethods) { 8996 if (!ReturnType.isNull() && 8997 !Context.hasSameUnqualifiedType(ReturnType, M->getReturnType())) 8998 continue; 8999 9000 KnownMethods[M->getSelector()] = 9001 KnownMethodsMap::mapped_type(M, InOriginalClass); 9002 } 9003 } 9004 } 9005 9006 /// Add the parenthesized return or parameter type chunk to a code 9007 /// completion string. 9008 static void AddObjCPassingTypeChunk(QualType Type, unsigned ObjCDeclQuals, 9009 ASTContext &Context, 9010 const PrintingPolicy &Policy, 9011 CodeCompletionBuilder &Builder) { 9012 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 9013 std::string Quals = formatObjCParamQualifiers(ObjCDeclQuals, Type); 9014 if (!Quals.empty()) 9015 Builder.AddTextChunk(Builder.getAllocator().CopyString(Quals)); 9016 Builder.AddTextChunk( 9017 GetCompletionTypeString(Type, Context, Policy, Builder.getAllocator())); 9018 Builder.AddChunk(CodeCompletionString::CK_RightParen); 9019 } 9020 9021 /// Determine whether the given class is or inherits from a class by 9022 /// the given name. 9023 static bool InheritsFromClassNamed(ObjCInterfaceDecl *Class, StringRef Name) { 9024 if (!Class) 9025 return false; 9026 9027 if (Class->getIdentifier() && Class->getIdentifier()->getName() == Name) 9028 return true; 9029 9030 return InheritsFromClassNamed(Class->getSuperClass(), Name); 9031 } 9032 9033 /// Add code completions for Objective-C Key-Value Coding (KVC) and 9034 /// Key-Value Observing (KVO). 9035 static void AddObjCKeyValueCompletions(ObjCPropertyDecl *Property, 9036 bool IsInstanceMethod, 9037 QualType ReturnType, ASTContext &Context, 9038 VisitedSelectorSet &KnownSelectors, 9039 ResultBuilder &Results) { 9040 IdentifierInfo *PropName = Property->getIdentifier(); 9041 if (!PropName || PropName->getLength() == 0) 9042 return; 9043 9044 PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema()); 9045 9046 // Builder that will create each code completion. 9047 typedef CodeCompletionResult Result; 9048 CodeCompletionAllocator &Allocator = Results.getAllocator(); 9049 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo()); 9050 9051 // The selector table. 9052 SelectorTable &Selectors = Context.Selectors; 9053 9054 // The property name, copied into the code completion allocation region 9055 // on demand. 9056 struct KeyHolder { 9057 CodeCompletionAllocator &Allocator; 9058 StringRef Key; 9059 const char *CopiedKey; 9060 9061 KeyHolder(CodeCompletionAllocator &Allocator, StringRef Key) 9062 : Allocator(Allocator), Key(Key), CopiedKey(nullptr) {} 9063 9064 operator const char *() { 9065 if (CopiedKey) 9066 return CopiedKey; 9067 9068 return CopiedKey = Allocator.CopyString(Key); 9069 } 9070 } Key(Allocator, PropName->getName()); 9071 9072 // The uppercased name of the property name. 9073 std::string UpperKey = std::string(PropName->getName()); 9074 if (!UpperKey.empty()) 9075 UpperKey[0] = toUppercase(UpperKey[0]); 9076 9077 bool ReturnTypeMatchesProperty = 9078 ReturnType.isNull() || 9079 Context.hasSameUnqualifiedType(ReturnType.getNonReferenceType(), 9080 Property->getType()); 9081 bool ReturnTypeMatchesVoid = ReturnType.isNull() || ReturnType->isVoidType(); 9082 9083 // Add the normal accessor -(type)key. 9084 if (IsInstanceMethod && 9085 KnownSelectors.insert(Selectors.getNullarySelector(PropName)).second && 9086 ReturnTypeMatchesProperty && !Property->getGetterMethodDecl()) { 9087 if (ReturnType.isNull()) 9088 AddObjCPassingTypeChunk(Property->getType(), /*Quals=*/0, Context, Policy, 9089 Builder); 9090 9091 Builder.AddTypedTextChunk(Key); 9092 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern, 9093 CXCursor_ObjCInstanceMethodDecl)); 9094 } 9095 9096 // If we have an integral or boolean property (or the user has provided 9097 // an integral or boolean return type), add the accessor -(type)isKey. 9098 if (IsInstanceMethod && 9099 ((!ReturnType.isNull() && 9100 (ReturnType->isIntegerType() || ReturnType->isBooleanType())) || 9101 (ReturnType.isNull() && (Property->getType()->isIntegerType() || 9102 Property->getType()->isBooleanType())))) { 9103 std::string SelectorName = (Twine("is") + UpperKey).str(); 9104 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 9105 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId)) 9106 .second) { 9107 if (ReturnType.isNull()) { 9108 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 9109 Builder.AddTextChunk("BOOL"); 9110 Builder.AddChunk(CodeCompletionString::CK_RightParen); 9111 } 9112 9113 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorId->getName())); 9114 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern, 9115 CXCursor_ObjCInstanceMethodDecl)); 9116 } 9117 } 9118 9119 // Add the normal mutator. 9120 if (IsInstanceMethod && ReturnTypeMatchesVoid && 9121 !Property->getSetterMethodDecl()) { 9122 std::string SelectorName = (Twine("set") + UpperKey).str(); 9123 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 9124 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 9125 if (ReturnType.isNull()) { 9126 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 9127 Builder.AddTextChunk("void"); 9128 Builder.AddChunk(CodeCompletionString::CK_RightParen); 9129 } 9130 9131 Builder.AddTypedTextChunk( 9132 Allocator.CopyString(SelectorId->getName() + ":")); 9133 AddObjCPassingTypeChunk(Property->getType(), /*Quals=*/0, Context, Policy, 9134 Builder); 9135 Builder.AddTextChunk(Key); 9136 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern, 9137 CXCursor_ObjCInstanceMethodDecl)); 9138 } 9139 } 9140 9141 // Indexed and unordered accessors 9142 unsigned IndexedGetterPriority = CCP_CodePattern; 9143 unsigned IndexedSetterPriority = CCP_CodePattern; 9144 unsigned UnorderedGetterPriority = CCP_CodePattern; 9145 unsigned UnorderedSetterPriority = CCP_CodePattern; 9146 if (const auto *ObjCPointer = 9147 Property->getType()->getAs<ObjCObjectPointerType>()) { 9148 if (ObjCInterfaceDecl *IFace = ObjCPointer->getInterfaceDecl()) { 9149 // If this interface type is not provably derived from a known 9150 // collection, penalize the corresponding completions. 9151 if (!InheritsFromClassNamed(IFace, "NSMutableArray")) { 9152 IndexedSetterPriority += CCD_ProbablyNotObjCCollection; 9153 if (!InheritsFromClassNamed(IFace, "NSArray")) 9154 IndexedGetterPriority += CCD_ProbablyNotObjCCollection; 9155 } 9156 9157 if (!InheritsFromClassNamed(IFace, "NSMutableSet")) { 9158 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection; 9159 if (!InheritsFromClassNamed(IFace, "NSSet")) 9160 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection; 9161 } 9162 } 9163 } else { 9164 IndexedGetterPriority += CCD_ProbablyNotObjCCollection; 9165 IndexedSetterPriority += CCD_ProbablyNotObjCCollection; 9166 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection; 9167 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection; 9168 } 9169 9170 // Add -(NSUInteger)countOf<key> 9171 if (IsInstanceMethod && 9172 (ReturnType.isNull() || ReturnType->isIntegerType())) { 9173 std::string SelectorName = (Twine("countOf") + UpperKey).str(); 9174 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 9175 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId)) 9176 .second) { 9177 if (ReturnType.isNull()) { 9178 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 9179 Builder.AddTextChunk("NSUInteger"); 9180 Builder.AddChunk(CodeCompletionString::CK_RightParen); 9181 } 9182 9183 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorId->getName())); 9184 Results.AddResult( 9185 Result(Builder.TakeString(), 9186 std::min(IndexedGetterPriority, UnorderedGetterPriority), 9187 CXCursor_ObjCInstanceMethodDecl)); 9188 } 9189 } 9190 9191 // Indexed getters 9192 // Add -(id)objectInKeyAtIndex:(NSUInteger)index 9193 if (IsInstanceMethod && 9194 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) { 9195 std::string SelectorName = (Twine("objectIn") + UpperKey + "AtIndex").str(); 9196 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 9197 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 9198 if (ReturnType.isNull()) { 9199 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 9200 Builder.AddTextChunk("id"); 9201 Builder.AddChunk(CodeCompletionString::CK_RightParen); 9202 } 9203 9204 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 9205 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 9206 Builder.AddTextChunk("NSUInteger"); 9207 Builder.AddChunk(CodeCompletionString::CK_RightParen); 9208 Builder.AddTextChunk("index"); 9209 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority, 9210 CXCursor_ObjCInstanceMethodDecl)); 9211 } 9212 } 9213 9214 // Add -(NSArray *)keyAtIndexes:(NSIndexSet *)indexes 9215 if (IsInstanceMethod && 9216 (ReturnType.isNull() || 9217 (ReturnType->isObjCObjectPointerType() && 9218 ReturnType->castAs<ObjCObjectPointerType>()->getInterfaceDecl() && 9219 ReturnType->castAs<ObjCObjectPointerType>() 9220 ->getInterfaceDecl() 9221 ->getName() == "NSArray"))) { 9222 std::string SelectorName = (Twine(Property->getName()) + "AtIndexes").str(); 9223 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 9224 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 9225 if (ReturnType.isNull()) { 9226 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 9227 Builder.AddTextChunk("NSArray *"); 9228 Builder.AddChunk(CodeCompletionString::CK_RightParen); 9229 } 9230 9231 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 9232 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 9233 Builder.AddTextChunk("NSIndexSet *"); 9234 Builder.AddChunk(CodeCompletionString::CK_RightParen); 9235 Builder.AddTextChunk("indexes"); 9236 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority, 9237 CXCursor_ObjCInstanceMethodDecl)); 9238 } 9239 } 9240 9241 // Add -(void)getKey:(type **)buffer range:(NSRange)inRange 9242 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 9243 std::string SelectorName = (Twine("get") + UpperKey).str(); 9244 const IdentifierInfo *SelectorIds[2] = {&Context.Idents.get(SelectorName), 9245 &Context.Idents.get("range")}; 9246 9247 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) { 9248 if (ReturnType.isNull()) { 9249 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 9250 Builder.AddTextChunk("void"); 9251 Builder.AddChunk(CodeCompletionString::CK_RightParen); 9252 } 9253 9254 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 9255 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 9256 Builder.AddPlaceholderChunk("object-type"); 9257 Builder.AddTextChunk(" **"); 9258 Builder.AddChunk(CodeCompletionString::CK_RightParen); 9259 Builder.AddTextChunk("buffer"); 9260 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 9261 Builder.AddTypedTextChunk("range:"); 9262 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 9263 Builder.AddTextChunk("NSRange"); 9264 Builder.AddChunk(CodeCompletionString::CK_RightParen); 9265 Builder.AddTextChunk("inRange"); 9266 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority, 9267 CXCursor_ObjCInstanceMethodDecl)); 9268 } 9269 } 9270 9271 // Mutable indexed accessors 9272 9273 // - (void)insertObject:(type *)object inKeyAtIndex:(NSUInteger)index 9274 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 9275 std::string SelectorName = (Twine("in") + UpperKey + "AtIndex").str(); 9276 const IdentifierInfo *SelectorIds[2] = {&Context.Idents.get("insertObject"), 9277 &Context.Idents.get(SelectorName)}; 9278 9279 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) { 9280 if (ReturnType.isNull()) { 9281 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 9282 Builder.AddTextChunk("void"); 9283 Builder.AddChunk(CodeCompletionString::CK_RightParen); 9284 } 9285 9286 Builder.AddTypedTextChunk("insertObject:"); 9287 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 9288 Builder.AddPlaceholderChunk("object-type"); 9289 Builder.AddTextChunk(" *"); 9290 Builder.AddChunk(CodeCompletionString::CK_RightParen); 9291 Builder.AddTextChunk("object"); 9292 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 9293 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 9294 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 9295 Builder.AddPlaceholderChunk("NSUInteger"); 9296 Builder.AddChunk(CodeCompletionString::CK_RightParen); 9297 Builder.AddTextChunk("index"); 9298 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority, 9299 CXCursor_ObjCInstanceMethodDecl)); 9300 } 9301 } 9302 9303 // - (void)insertKey:(NSArray *)array atIndexes:(NSIndexSet *)indexes 9304 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 9305 std::string SelectorName = (Twine("insert") + UpperKey).str(); 9306 const IdentifierInfo *SelectorIds[2] = {&Context.Idents.get(SelectorName), 9307 &Context.Idents.get("atIndexes")}; 9308 9309 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) { 9310 if (ReturnType.isNull()) { 9311 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 9312 Builder.AddTextChunk("void"); 9313 Builder.AddChunk(CodeCompletionString::CK_RightParen); 9314 } 9315 9316 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 9317 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 9318 Builder.AddTextChunk("NSArray *"); 9319 Builder.AddChunk(CodeCompletionString::CK_RightParen); 9320 Builder.AddTextChunk("array"); 9321 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 9322 Builder.AddTypedTextChunk("atIndexes:"); 9323 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 9324 Builder.AddPlaceholderChunk("NSIndexSet *"); 9325 Builder.AddChunk(CodeCompletionString::CK_RightParen); 9326 Builder.AddTextChunk("indexes"); 9327 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority, 9328 CXCursor_ObjCInstanceMethodDecl)); 9329 } 9330 } 9331 9332 // -(void)removeObjectFromKeyAtIndex:(NSUInteger)index 9333 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 9334 std::string SelectorName = 9335 (Twine("removeObjectFrom") + UpperKey + "AtIndex").str(); 9336 const IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 9337 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 9338 if (ReturnType.isNull()) { 9339 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 9340 Builder.AddTextChunk("void"); 9341 Builder.AddChunk(CodeCompletionString::CK_RightParen); 9342 } 9343 9344 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 9345 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 9346 Builder.AddTextChunk("NSUInteger"); 9347 Builder.AddChunk(CodeCompletionString::CK_RightParen); 9348 Builder.AddTextChunk("index"); 9349 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority, 9350 CXCursor_ObjCInstanceMethodDecl)); 9351 } 9352 } 9353 9354 // -(void)removeKeyAtIndexes:(NSIndexSet *)indexes 9355 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 9356 std::string SelectorName = (Twine("remove") + UpperKey + "AtIndexes").str(); 9357 const IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 9358 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 9359 if (ReturnType.isNull()) { 9360 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 9361 Builder.AddTextChunk("void"); 9362 Builder.AddChunk(CodeCompletionString::CK_RightParen); 9363 } 9364 9365 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 9366 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 9367 Builder.AddTextChunk("NSIndexSet *"); 9368 Builder.AddChunk(CodeCompletionString::CK_RightParen); 9369 Builder.AddTextChunk("indexes"); 9370 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority, 9371 CXCursor_ObjCInstanceMethodDecl)); 9372 } 9373 } 9374 9375 // - (void)replaceObjectInKeyAtIndex:(NSUInteger)index withObject:(id)object 9376 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 9377 std::string SelectorName = 9378 (Twine("replaceObjectIn") + UpperKey + "AtIndex").str(); 9379 const IdentifierInfo *SelectorIds[2] = {&Context.Idents.get(SelectorName), 9380 &Context.Idents.get("withObject")}; 9381 9382 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) { 9383 if (ReturnType.isNull()) { 9384 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 9385 Builder.AddTextChunk("void"); 9386 Builder.AddChunk(CodeCompletionString::CK_RightParen); 9387 } 9388 9389 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 9390 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 9391 Builder.AddPlaceholderChunk("NSUInteger"); 9392 Builder.AddChunk(CodeCompletionString::CK_RightParen); 9393 Builder.AddTextChunk("index"); 9394 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 9395 Builder.AddTypedTextChunk("withObject:"); 9396 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 9397 Builder.AddTextChunk("id"); 9398 Builder.AddChunk(CodeCompletionString::CK_RightParen); 9399 Builder.AddTextChunk("object"); 9400 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority, 9401 CXCursor_ObjCInstanceMethodDecl)); 9402 } 9403 } 9404 9405 // - (void)replaceKeyAtIndexes:(NSIndexSet *)indexes withKey:(NSArray *)array 9406 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 9407 std::string SelectorName1 = 9408 (Twine("replace") + UpperKey + "AtIndexes").str(); 9409 std::string SelectorName2 = (Twine("with") + UpperKey).str(); 9410 const IdentifierInfo *SelectorIds[2] = {&Context.Idents.get(SelectorName1), 9411 &Context.Idents.get(SelectorName2)}; 9412 9413 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) { 9414 if (ReturnType.isNull()) { 9415 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 9416 Builder.AddTextChunk("void"); 9417 Builder.AddChunk(CodeCompletionString::CK_RightParen); 9418 } 9419 9420 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName1 + ":")); 9421 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 9422 Builder.AddPlaceholderChunk("NSIndexSet *"); 9423 Builder.AddChunk(CodeCompletionString::CK_RightParen); 9424 Builder.AddTextChunk("indexes"); 9425 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 9426 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName2 + ":")); 9427 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 9428 Builder.AddTextChunk("NSArray *"); 9429 Builder.AddChunk(CodeCompletionString::CK_RightParen); 9430 Builder.AddTextChunk("array"); 9431 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority, 9432 CXCursor_ObjCInstanceMethodDecl)); 9433 } 9434 } 9435 9436 // Unordered getters 9437 // - (NSEnumerator *)enumeratorOfKey 9438 if (IsInstanceMethod && 9439 (ReturnType.isNull() || 9440 (ReturnType->isObjCObjectPointerType() && 9441 ReturnType->castAs<ObjCObjectPointerType>()->getInterfaceDecl() && 9442 ReturnType->castAs<ObjCObjectPointerType>() 9443 ->getInterfaceDecl() 9444 ->getName() == "NSEnumerator"))) { 9445 std::string SelectorName = (Twine("enumeratorOf") + UpperKey).str(); 9446 const IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 9447 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId)) 9448 .second) { 9449 if (ReturnType.isNull()) { 9450 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 9451 Builder.AddTextChunk("NSEnumerator *"); 9452 Builder.AddChunk(CodeCompletionString::CK_RightParen); 9453 } 9454 9455 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName)); 9456 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority, 9457 CXCursor_ObjCInstanceMethodDecl)); 9458 } 9459 } 9460 9461 // - (type *)memberOfKey:(type *)object 9462 if (IsInstanceMethod && 9463 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) { 9464 std::string SelectorName = (Twine("memberOf") + UpperKey).str(); 9465 const IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 9466 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 9467 if (ReturnType.isNull()) { 9468 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 9469 Builder.AddPlaceholderChunk("object-type"); 9470 Builder.AddTextChunk(" *"); 9471 Builder.AddChunk(CodeCompletionString::CK_RightParen); 9472 } 9473 9474 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 9475 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 9476 if (ReturnType.isNull()) { 9477 Builder.AddPlaceholderChunk("object-type"); 9478 Builder.AddTextChunk(" *"); 9479 } else { 9480 Builder.AddTextChunk(GetCompletionTypeString( 9481 ReturnType, Context, Policy, Builder.getAllocator())); 9482 } 9483 Builder.AddChunk(CodeCompletionString::CK_RightParen); 9484 Builder.AddTextChunk("object"); 9485 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority, 9486 CXCursor_ObjCInstanceMethodDecl)); 9487 } 9488 } 9489 9490 // Mutable unordered accessors 9491 // - (void)addKeyObject:(type *)object 9492 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 9493 std::string SelectorName = 9494 (Twine("add") + UpperKey + Twine("Object")).str(); 9495 const IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 9496 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 9497 if (ReturnType.isNull()) { 9498 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 9499 Builder.AddTextChunk("void"); 9500 Builder.AddChunk(CodeCompletionString::CK_RightParen); 9501 } 9502 9503 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 9504 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 9505 Builder.AddPlaceholderChunk("object-type"); 9506 Builder.AddTextChunk(" *"); 9507 Builder.AddChunk(CodeCompletionString::CK_RightParen); 9508 Builder.AddTextChunk("object"); 9509 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority, 9510 CXCursor_ObjCInstanceMethodDecl)); 9511 } 9512 } 9513 9514 // - (void)addKey:(NSSet *)objects 9515 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 9516 std::string SelectorName = (Twine("add") + UpperKey).str(); 9517 const IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 9518 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 9519 if (ReturnType.isNull()) { 9520 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 9521 Builder.AddTextChunk("void"); 9522 Builder.AddChunk(CodeCompletionString::CK_RightParen); 9523 } 9524 9525 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 9526 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 9527 Builder.AddTextChunk("NSSet *"); 9528 Builder.AddChunk(CodeCompletionString::CK_RightParen); 9529 Builder.AddTextChunk("objects"); 9530 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority, 9531 CXCursor_ObjCInstanceMethodDecl)); 9532 } 9533 } 9534 9535 // - (void)removeKeyObject:(type *)object 9536 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 9537 std::string SelectorName = 9538 (Twine("remove") + UpperKey + Twine("Object")).str(); 9539 const IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 9540 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 9541 if (ReturnType.isNull()) { 9542 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 9543 Builder.AddTextChunk("void"); 9544 Builder.AddChunk(CodeCompletionString::CK_RightParen); 9545 } 9546 9547 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 9548 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 9549 Builder.AddPlaceholderChunk("object-type"); 9550 Builder.AddTextChunk(" *"); 9551 Builder.AddChunk(CodeCompletionString::CK_RightParen); 9552 Builder.AddTextChunk("object"); 9553 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority, 9554 CXCursor_ObjCInstanceMethodDecl)); 9555 } 9556 } 9557 9558 // - (void)removeKey:(NSSet *)objects 9559 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 9560 std::string SelectorName = (Twine("remove") + UpperKey).str(); 9561 const IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 9562 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 9563 if (ReturnType.isNull()) { 9564 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 9565 Builder.AddTextChunk("void"); 9566 Builder.AddChunk(CodeCompletionString::CK_RightParen); 9567 } 9568 9569 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 9570 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 9571 Builder.AddTextChunk("NSSet *"); 9572 Builder.AddChunk(CodeCompletionString::CK_RightParen); 9573 Builder.AddTextChunk("objects"); 9574 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority, 9575 CXCursor_ObjCInstanceMethodDecl)); 9576 } 9577 } 9578 9579 // - (void)intersectKey:(NSSet *)objects 9580 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 9581 std::string SelectorName = (Twine("intersect") + UpperKey).str(); 9582 const IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 9583 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 9584 if (ReturnType.isNull()) { 9585 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 9586 Builder.AddTextChunk("void"); 9587 Builder.AddChunk(CodeCompletionString::CK_RightParen); 9588 } 9589 9590 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 9591 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 9592 Builder.AddTextChunk("NSSet *"); 9593 Builder.AddChunk(CodeCompletionString::CK_RightParen); 9594 Builder.AddTextChunk("objects"); 9595 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority, 9596 CXCursor_ObjCInstanceMethodDecl)); 9597 } 9598 } 9599 9600 // Key-Value Observing 9601 // + (NSSet *)keyPathsForValuesAffectingKey 9602 if (!IsInstanceMethod && 9603 (ReturnType.isNull() || 9604 (ReturnType->isObjCObjectPointerType() && 9605 ReturnType->castAs<ObjCObjectPointerType>()->getInterfaceDecl() && 9606 ReturnType->castAs<ObjCObjectPointerType>() 9607 ->getInterfaceDecl() 9608 ->getName() == "NSSet"))) { 9609 std::string SelectorName = 9610 (Twine("keyPathsForValuesAffecting") + UpperKey).str(); 9611 const IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 9612 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId)) 9613 .second) { 9614 if (ReturnType.isNull()) { 9615 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 9616 Builder.AddTextChunk("NSSet<NSString *> *"); 9617 Builder.AddChunk(CodeCompletionString::CK_RightParen); 9618 } 9619 9620 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName)); 9621 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern, 9622 CXCursor_ObjCClassMethodDecl)); 9623 } 9624 } 9625 9626 // + (BOOL)automaticallyNotifiesObserversForKey 9627 if (!IsInstanceMethod && 9628 (ReturnType.isNull() || ReturnType->isIntegerType() || 9629 ReturnType->isBooleanType())) { 9630 std::string SelectorName = 9631 (Twine("automaticallyNotifiesObserversOf") + UpperKey).str(); 9632 const IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 9633 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId)) 9634 .second) { 9635 if (ReturnType.isNull()) { 9636 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 9637 Builder.AddTextChunk("BOOL"); 9638 Builder.AddChunk(CodeCompletionString::CK_RightParen); 9639 } 9640 9641 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName)); 9642 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern, 9643 CXCursor_ObjCClassMethodDecl)); 9644 } 9645 } 9646 } 9647 9648 void SemaCodeCompletion::CodeCompleteObjCMethodDecl( 9649 Scope *S, std::optional<bool> IsInstanceMethod, ParsedType ReturnTy) { 9650 ASTContext &Context = getASTContext(); 9651 // Determine the return type of the method we're declaring, if 9652 // provided. 9653 QualType ReturnType = SemaRef.GetTypeFromParser(ReturnTy); 9654 Decl *IDecl = nullptr; 9655 if (SemaRef.CurContext->isObjCContainer()) { 9656 ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(SemaRef.CurContext); 9657 IDecl = OCD; 9658 } 9659 // Determine where we should start searching for methods. 9660 ObjCContainerDecl *SearchDecl = nullptr; 9661 bool IsInImplementation = false; 9662 if (Decl *D = IDecl) { 9663 if (ObjCImplementationDecl *Impl = dyn_cast<ObjCImplementationDecl>(D)) { 9664 SearchDecl = Impl->getClassInterface(); 9665 IsInImplementation = true; 9666 } else if (ObjCCategoryImplDecl *CatImpl = 9667 dyn_cast<ObjCCategoryImplDecl>(D)) { 9668 SearchDecl = CatImpl->getCategoryDecl(); 9669 IsInImplementation = true; 9670 } else 9671 SearchDecl = dyn_cast<ObjCContainerDecl>(D); 9672 } 9673 9674 if (!SearchDecl && S) { 9675 if (DeclContext *DC = S->getEntity()) 9676 SearchDecl = dyn_cast<ObjCContainerDecl>(DC); 9677 } 9678 9679 if (!SearchDecl) { 9680 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 9681 CodeCompletionContext::CCC_Other, nullptr, 0); 9682 return; 9683 } 9684 9685 // Find all of the methods that we could declare/implement here. 9686 KnownMethodsMap KnownMethods; 9687 FindImplementableMethods(Context, SearchDecl, IsInstanceMethod, ReturnType, 9688 KnownMethods); 9689 9690 // Add declarations or definitions for each of the known methods. 9691 typedef CodeCompletionResult Result; 9692 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(), 9693 CodeCompleter->getCodeCompletionTUInfo(), 9694 CodeCompletionContext::CCC_Other); 9695 Results.EnterNewScope(); 9696 PrintingPolicy Policy = getCompletionPrintingPolicy(SemaRef); 9697 for (KnownMethodsMap::iterator M = KnownMethods.begin(), 9698 MEnd = KnownMethods.end(); 9699 M != MEnd; ++M) { 9700 ObjCMethodDecl *Method = M->second.getPointer(); 9701 CodeCompletionBuilder Builder(Results.getAllocator(), 9702 Results.getCodeCompletionTUInfo()); 9703 9704 // Add the '-'/'+' prefix if it wasn't provided yet. 9705 if (!IsInstanceMethod) { 9706 Builder.AddTextChunk(Method->isInstanceMethod() ? "-" : "+"); 9707 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 9708 } 9709 9710 // If the result type was not already provided, add it to the 9711 // pattern as (type). 9712 if (ReturnType.isNull()) { 9713 QualType ResTy = Method->getSendResultType().stripObjCKindOfType(Context); 9714 AttributedType::stripOuterNullability(ResTy); 9715 AddObjCPassingTypeChunk(ResTy, Method->getObjCDeclQualifier(), Context, 9716 Policy, Builder); 9717 } 9718 9719 Selector Sel = Method->getSelector(); 9720 9721 if (Sel.isUnarySelector()) { 9722 // Unary selectors have no arguments. 9723 Builder.AddTypedTextChunk( 9724 Builder.getAllocator().CopyString(Sel.getNameForSlot(0))); 9725 } else { 9726 // Add all parameters to the pattern. 9727 unsigned I = 0; 9728 for (ObjCMethodDecl::param_iterator P = Method->param_begin(), 9729 PEnd = Method->param_end(); 9730 P != PEnd; (void)++P, ++I) { 9731 // Add the part of the selector name. 9732 if (I == 0) 9733 Builder.AddTypedTextChunk( 9734 Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":")); 9735 else if (I < Sel.getNumArgs()) { 9736 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 9737 Builder.AddTypedTextChunk( 9738 Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":")); 9739 } else 9740 break; 9741 9742 // Add the parameter type. 9743 QualType ParamType; 9744 if ((*P)->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 9745 ParamType = (*P)->getType(); 9746 else 9747 ParamType = (*P)->getOriginalType(); 9748 ParamType = ParamType.substObjCTypeArgs( 9749 Context, {}, ObjCSubstitutionContext::Parameter); 9750 AttributedType::stripOuterNullability(ParamType); 9751 AddObjCPassingTypeChunk(ParamType, (*P)->getObjCDeclQualifier(), 9752 Context, Policy, Builder); 9753 9754 if (IdentifierInfo *Id = (*P)->getIdentifier()) 9755 Builder.AddTextChunk( 9756 Builder.getAllocator().CopyString(Id->getName())); 9757 } 9758 } 9759 9760 if (Method->isVariadic()) { 9761 if (Method->param_size() > 0) 9762 Builder.AddChunk(CodeCompletionString::CK_Comma); 9763 Builder.AddTextChunk("..."); 9764 } 9765 9766 if (IsInImplementation && Results.includeCodePatterns()) { 9767 // We will be defining the method here, so add a compound statement. 9768 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 9769 Builder.AddChunk(CodeCompletionString::CK_LeftBrace); 9770 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); 9771 if (!Method->getReturnType()->isVoidType()) { 9772 // If the result type is not void, add a return clause. 9773 Builder.AddTextChunk("return"); 9774 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 9775 Builder.AddPlaceholderChunk("expression"); 9776 Builder.AddChunk(CodeCompletionString::CK_SemiColon); 9777 } else 9778 Builder.AddPlaceholderChunk("statements"); 9779 9780 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); 9781 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 9782 } 9783 9784 unsigned Priority = CCP_CodePattern; 9785 auto R = Result(Builder.TakeString(), Method, Priority); 9786 if (!M->second.getInt()) 9787 setInBaseClass(R); 9788 Results.AddResult(std::move(R)); 9789 } 9790 9791 // Add Key-Value-Coding and Key-Value-Observing accessor methods for all of 9792 // the properties in this class and its categories. 9793 if (Context.getLangOpts().ObjC) { 9794 SmallVector<ObjCContainerDecl *, 4> Containers; 9795 Containers.push_back(SearchDecl); 9796 9797 VisitedSelectorSet KnownSelectors; 9798 for (KnownMethodsMap::iterator M = KnownMethods.begin(), 9799 MEnd = KnownMethods.end(); 9800 M != MEnd; ++M) 9801 KnownSelectors.insert(M->first); 9802 9803 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(SearchDecl); 9804 if (!IFace) 9805 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(SearchDecl)) 9806 IFace = Category->getClassInterface(); 9807 9808 if (IFace) 9809 llvm::append_range(Containers, IFace->visible_categories()); 9810 9811 if (IsInstanceMethod) { 9812 for (unsigned I = 0, N = Containers.size(); I != N; ++I) 9813 for (auto *P : Containers[I]->instance_properties()) 9814 AddObjCKeyValueCompletions(P, *IsInstanceMethod, ReturnType, Context, 9815 KnownSelectors, Results); 9816 } 9817 } 9818 9819 Results.ExitScope(); 9820 9821 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 9822 Results.getCompletionContext(), Results.data(), 9823 Results.size()); 9824 } 9825 9826 void SemaCodeCompletion::CodeCompleteObjCMethodDeclSelector( 9827 Scope *S, bool IsInstanceMethod, bool AtParameterName, ParsedType ReturnTy, 9828 ArrayRef<const IdentifierInfo *> SelIdents) { 9829 // If we have an external source, load the entire class method 9830 // pool from the AST file. 9831 if (SemaRef.ExternalSource) { 9832 for (uint32_t I = 0, N = SemaRef.ExternalSource->GetNumExternalSelectors(); 9833 I != N; ++I) { 9834 Selector Sel = SemaRef.ExternalSource->GetExternalSelector(I); 9835 if (Sel.isNull() || SemaRef.ObjC().MethodPool.count(Sel)) 9836 continue; 9837 9838 SemaRef.ObjC().ReadMethodPool(Sel); 9839 } 9840 } 9841 9842 // Build the set of methods we can see. 9843 typedef CodeCompletionResult Result; 9844 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(), 9845 CodeCompleter->getCodeCompletionTUInfo(), 9846 CodeCompletionContext::CCC_Other); 9847 9848 if (ReturnTy) 9849 Results.setPreferredType( 9850 SemaRef.GetTypeFromParser(ReturnTy).getNonReferenceType()); 9851 9852 Results.EnterNewScope(); 9853 for (SemaObjC::GlobalMethodPool::iterator 9854 M = SemaRef.ObjC().MethodPool.begin(), 9855 MEnd = SemaRef.ObjC().MethodPool.end(); 9856 M != MEnd; ++M) { 9857 for (ObjCMethodList *MethList = IsInstanceMethod ? &M->second.first 9858 : &M->second.second; 9859 MethList && MethList->getMethod(); MethList = MethList->getNext()) { 9860 if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents)) 9861 continue; 9862 9863 if (AtParameterName) { 9864 // Suggest parameter names we've seen before. 9865 unsigned NumSelIdents = SelIdents.size(); 9866 if (NumSelIdents && 9867 NumSelIdents <= MethList->getMethod()->param_size()) { 9868 ParmVarDecl *Param = 9869 MethList->getMethod()->parameters()[NumSelIdents - 1]; 9870 if (Param->getIdentifier()) { 9871 CodeCompletionBuilder Builder(Results.getAllocator(), 9872 Results.getCodeCompletionTUInfo()); 9873 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString( 9874 Param->getIdentifier()->getName())); 9875 Results.AddResult(Builder.TakeString()); 9876 } 9877 } 9878 9879 continue; 9880 } 9881 9882 Result R(MethList->getMethod(), 9883 Results.getBasePriority(MethList->getMethod()), nullptr); 9884 R.StartParameter = SelIdents.size(); 9885 R.AllParametersAreInformative = false; 9886 R.DeclaringEntity = true; 9887 Results.MaybeAddResult(R, SemaRef.CurContext); 9888 } 9889 } 9890 9891 Results.ExitScope(); 9892 9893 if (!AtParameterName && !SelIdents.empty() && 9894 SelIdents.front()->getName().starts_with("init")) { 9895 for (const auto &M : SemaRef.PP.macros()) { 9896 if (M.first->getName() != "NS_DESIGNATED_INITIALIZER") 9897 continue; 9898 Results.EnterNewScope(); 9899 CodeCompletionBuilder Builder(Results.getAllocator(), 9900 Results.getCodeCompletionTUInfo()); 9901 Builder.AddTypedTextChunk( 9902 Builder.getAllocator().CopyString(M.first->getName())); 9903 Results.AddResult(CodeCompletionResult(Builder.TakeString(), CCP_Macro, 9904 CXCursor_MacroDefinition)); 9905 Results.ExitScope(); 9906 } 9907 } 9908 9909 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 9910 Results.getCompletionContext(), Results.data(), 9911 Results.size()); 9912 } 9913 9914 void SemaCodeCompletion::CodeCompletePreprocessorDirective(bool InConditional) { 9915 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(), 9916 CodeCompleter->getCodeCompletionTUInfo(), 9917 CodeCompletionContext::CCC_PreprocessorDirective); 9918 Results.EnterNewScope(); 9919 9920 // #if <condition> 9921 CodeCompletionBuilder Builder(Results.getAllocator(), 9922 Results.getCodeCompletionTUInfo()); 9923 Builder.AddTypedTextChunk("if"); 9924 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 9925 Builder.AddPlaceholderChunk("condition"); 9926 Results.AddResult(Builder.TakeString()); 9927 9928 // #ifdef <macro> 9929 Builder.AddTypedTextChunk("ifdef"); 9930 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 9931 Builder.AddPlaceholderChunk("macro"); 9932 Results.AddResult(Builder.TakeString()); 9933 9934 // #ifndef <macro> 9935 Builder.AddTypedTextChunk("ifndef"); 9936 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 9937 Builder.AddPlaceholderChunk("macro"); 9938 Results.AddResult(Builder.TakeString()); 9939 9940 if (InConditional) { 9941 // #elif <condition> 9942 Builder.AddTypedTextChunk("elif"); 9943 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 9944 Builder.AddPlaceholderChunk("condition"); 9945 Results.AddResult(Builder.TakeString()); 9946 9947 // #elifdef <macro> 9948 Builder.AddTypedTextChunk("elifdef"); 9949 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 9950 Builder.AddPlaceholderChunk("macro"); 9951 Results.AddResult(Builder.TakeString()); 9952 9953 // #elifndef <macro> 9954 Builder.AddTypedTextChunk("elifndef"); 9955 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 9956 Builder.AddPlaceholderChunk("macro"); 9957 Results.AddResult(Builder.TakeString()); 9958 9959 // #else 9960 Builder.AddTypedTextChunk("else"); 9961 Results.AddResult(Builder.TakeString()); 9962 9963 // #endif 9964 Builder.AddTypedTextChunk("endif"); 9965 Results.AddResult(Builder.TakeString()); 9966 } 9967 9968 // #include "header" 9969 Builder.AddTypedTextChunk("include"); 9970 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 9971 Builder.AddTextChunk("\""); 9972 Builder.AddPlaceholderChunk("header"); 9973 Builder.AddTextChunk("\""); 9974 Results.AddResult(Builder.TakeString()); 9975 9976 // #include <header> 9977 Builder.AddTypedTextChunk("include"); 9978 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 9979 Builder.AddTextChunk("<"); 9980 Builder.AddPlaceholderChunk("header"); 9981 Builder.AddTextChunk(">"); 9982 Results.AddResult(Builder.TakeString()); 9983 9984 // #define <macro> 9985 Builder.AddTypedTextChunk("define"); 9986 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 9987 Builder.AddPlaceholderChunk("macro"); 9988 Results.AddResult(Builder.TakeString()); 9989 9990 // #define <macro>(<args>) 9991 Builder.AddTypedTextChunk("define"); 9992 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 9993 Builder.AddPlaceholderChunk("macro"); 9994 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 9995 Builder.AddPlaceholderChunk("args"); 9996 Builder.AddChunk(CodeCompletionString::CK_RightParen); 9997 Results.AddResult(Builder.TakeString()); 9998 9999 // #undef <macro> 10000 Builder.AddTypedTextChunk("undef"); 10001 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 10002 Builder.AddPlaceholderChunk("macro"); 10003 Results.AddResult(Builder.TakeString()); 10004 10005 // #line <number> 10006 Builder.AddTypedTextChunk("line"); 10007 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 10008 Builder.AddPlaceholderChunk("number"); 10009 Results.AddResult(Builder.TakeString()); 10010 10011 // #line <number> "filename" 10012 Builder.AddTypedTextChunk("line"); 10013 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 10014 Builder.AddPlaceholderChunk("number"); 10015 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 10016 Builder.AddTextChunk("\""); 10017 Builder.AddPlaceholderChunk("filename"); 10018 Builder.AddTextChunk("\""); 10019 Results.AddResult(Builder.TakeString()); 10020 10021 // #error <message> 10022 Builder.AddTypedTextChunk("error"); 10023 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 10024 Builder.AddPlaceholderChunk("message"); 10025 Results.AddResult(Builder.TakeString()); 10026 10027 // #pragma <arguments> 10028 Builder.AddTypedTextChunk("pragma"); 10029 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 10030 Builder.AddPlaceholderChunk("arguments"); 10031 Results.AddResult(Builder.TakeString()); 10032 10033 if (getLangOpts().ObjC) { 10034 // #import "header" 10035 Builder.AddTypedTextChunk("import"); 10036 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 10037 Builder.AddTextChunk("\""); 10038 Builder.AddPlaceholderChunk("header"); 10039 Builder.AddTextChunk("\""); 10040 Results.AddResult(Builder.TakeString()); 10041 10042 // #import <header> 10043 Builder.AddTypedTextChunk("import"); 10044 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 10045 Builder.AddTextChunk("<"); 10046 Builder.AddPlaceholderChunk("header"); 10047 Builder.AddTextChunk(">"); 10048 Results.AddResult(Builder.TakeString()); 10049 } 10050 10051 // #include_next "header" 10052 Builder.AddTypedTextChunk("include_next"); 10053 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 10054 Builder.AddTextChunk("\""); 10055 Builder.AddPlaceholderChunk("header"); 10056 Builder.AddTextChunk("\""); 10057 Results.AddResult(Builder.TakeString()); 10058 10059 // #include_next <header> 10060 Builder.AddTypedTextChunk("include_next"); 10061 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 10062 Builder.AddTextChunk("<"); 10063 Builder.AddPlaceholderChunk("header"); 10064 Builder.AddTextChunk(">"); 10065 Results.AddResult(Builder.TakeString()); 10066 10067 // #warning <message> 10068 Builder.AddTypedTextChunk("warning"); 10069 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 10070 Builder.AddPlaceholderChunk("message"); 10071 Results.AddResult(Builder.TakeString()); 10072 10073 // Note: #ident and #sccs are such crazy anachronisms that we don't provide 10074 // completions for them. And __include_macros is a Clang-internal extension 10075 // that we don't want to encourage anyone to use. 10076 10077 // FIXME: we don't support #assert or #unassert, so don't suggest them. 10078 Results.ExitScope(); 10079 10080 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 10081 Results.getCompletionContext(), Results.data(), 10082 Results.size()); 10083 } 10084 10085 void SemaCodeCompletion::CodeCompleteInPreprocessorConditionalExclusion( 10086 Scope *S) { 10087 CodeCompleteOrdinaryName(S, S->getFnParent() 10088 ? SemaCodeCompletion::PCC_RecoveryInFunction 10089 : SemaCodeCompletion::PCC_Namespace); 10090 } 10091 10092 void SemaCodeCompletion::CodeCompletePreprocessorMacroName(bool IsDefinition) { 10093 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(), 10094 CodeCompleter->getCodeCompletionTUInfo(), 10095 IsDefinition ? CodeCompletionContext::CCC_MacroName 10096 : CodeCompletionContext::CCC_MacroNameUse); 10097 if (!IsDefinition && CodeCompleter->includeMacros()) { 10098 // Add just the names of macros, not their arguments. 10099 CodeCompletionBuilder Builder(Results.getAllocator(), 10100 Results.getCodeCompletionTUInfo()); 10101 Results.EnterNewScope(); 10102 for (Preprocessor::macro_iterator M = SemaRef.PP.macro_begin(), 10103 MEnd = SemaRef.PP.macro_end(); 10104 M != MEnd; ++M) { 10105 Builder.AddTypedTextChunk( 10106 Builder.getAllocator().CopyString(M->first->getName())); 10107 Results.AddResult(CodeCompletionResult( 10108 Builder.TakeString(), CCP_CodePattern, CXCursor_MacroDefinition)); 10109 } 10110 Results.ExitScope(); 10111 } else if (IsDefinition) { 10112 // FIXME: Can we detect when the user just wrote an include guard above? 10113 } 10114 10115 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 10116 Results.getCompletionContext(), Results.data(), 10117 Results.size()); 10118 } 10119 10120 void SemaCodeCompletion::CodeCompletePreprocessorExpression() { 10121 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(), 10122 CodeCompleter->getCodeCompletionTUInfo(), 10123 CodeCompletionContext::CCC_PreprocessorExpression); 10124 10125 if (CodeCompleter->includeMacros()) 10126 AddMacroResults(SemaRef.PP, Results, CodeCompleter->loadExternal(), true); 10127 10128 // defined (<macro>) 10129 Results.EnterNewScope(); 10130 CodeCompletionBuilder Builder(Results.getAllocator(), 10131 Results.getCodeCompletionTUInfo()); 10132 Builder.AddTypedTextChunk("defined"); 10133 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 10134 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 10135 Builder.AddPlaceholderChunk("macro"); 10136 Builder.AddChunk(CodeCompletionString::CK_RightParen); 10137 Results.AddResult(Builder.TakeString()); 10138 Results.ExitScope(); 10139 10140 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 10141 Results.getCompletionContext(), Results.data(), 10142 Results.size()); 10143 } 10144 10145 void SemaCodeCompletion::CodeCompletePreprocessorMacroArgument( 10146 Scope *S, IdentifierInfo *Macro, MacroInfo *MacroInfo, unsigned Argument) { 10147 // FIXME: In the future, we could provide "overload" results, much like we 10148 // do for function calls. 10149 10150 // Now just ignore this. There will be another code-completion callback 10151 // for the expanded tokens. 10152 } 10153 10154 // This handles completion inside an #include filename, e.g. #include <foo/ba 10155 // We look for the directory "foo" under each directory on the include path, 10156 // list its files, and reassemble the appropriate #include. 10157 void SemaCodeCompletion::CodeCompleteIncludedFile(llvm::StringRef Dir, 10158 bool Angled) { 10159 // RelDir should use /, but unescaped \ is possible on windows! 10160 // Our completions will normalize to / for simplicity, this case is rare. 10161 std::string RelDir = llvm::sys::path::convert_to_slash(Dir); 10162 // We need the native slashes for the actual file system interactions. 10163 SmallString<128> NativeRelDir = StringRef(RelDir); 10164 llvm::sys::path::native(NativeRelDir); 10165 llvm::vfs::FileSystem &FS = 10166 SemaRef.getSourceManager().getFileManager().getVirtualFileSystem(); 10167 10168 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(), 10169 CodeCompleter->getCodeCompletionTUInfo(), 10170 CodeCompletionContext::CCC_IncludedFile); 10171 llvm::DenseSet<StringRef> SeenResults; // To deduplicate results. 10172 10173 // Helper: adds one file or directory completion result. 10174 auto AddCompletion = [&](StringRef Filename, bool IsDirectory) { 10175 SmallString<64> TypedChunk = Filename; 10176 // Directory completion is up to the slash, e.g. <sys/ 10177 TypedChunk.push_back(IsDirectory ? '/' : Angled ? '>' : '"'); 10178 auto R = SeenResults.insert(TypedChunk); 10179 if (R.second) { // New completion 10180 const char *InternedTyped = Results.getAllocator().CopyString(TypedChunk); 10181 *R.first = InternedTyped; // Avoid dangling StringRef. 10182 CodeCompletionBuilder Builder(CodeCompleter->getAllocator(), 10183 CodeCompleter->getCodeCompletionTUInfo()); 10184 Builder.AddTypedTextChunk(InternedTyped); 10185 // The result is a "Pattern", which is pretty opaque. 10186 // We may want to include the real filename to allow smart ranking. 10187 Results.AddResult(CodeCompletionResult(Builder.TakeString())); 10188 } 10189 }; 10190 10191 // Helper: scans IncludeDir for nice files, and adds results for each. 10192 auto AddFilesFromIncludeDir = [&](StringRef IncludeDir, 10193 bool IsSystem, 10194 DirectoryLookup::LookupType_t LookupType) { 10195 llvm::SmallString<128> Dir = IncludeDir; 10196 if (!NativeRelDir.empty()) { 10197 if (LookupType == DirectoryLookup::LT_Framework) { 10198 // For a framework dir, #include <Foo/Bar/> actually maps to 10199 // a path of Foo.framework/Headers/Bar/. 10200 auto Begin = llvm::sys::path::begin(NativeRelDir); 10201 auto End = llvm::sys::path::end(NativeRelDir); 10202 10203 llvm::sys::path::append(Dir, *Begin + ".framework", "Headers"); 10204 llvm::sys::path::append(Dir, ++Begin, End); 10205 } else { 10206 llvm::sys::path::append(Dir, NativeRelDir); 10207 } 10208 } 10209 10210 const StringRef &Dirname = llvm::sys::path::filename(Dir); 10211 const bool isQt = Dirname.starts_with("Qt") || Dirname == "ActiveQt"; 10212 const bool ExtensionlessHeaders = 10213 IsSystem || isQt || Dir.ends_with(".framework/Headers"); 10214 std::error_code EC; 10215 unsigned Count = 0; 10216 for (auto It = FS.dir_begin(Dir, EC); 10217 !EC && It != llvm::vfs::directory_iterator(); It.increment(EC)) { 10218 if (++Count == 2500) // If we happen to hit a huge directory, 10219 break; // bail out early so we're not too slow. 10220 StringRef Filename = llvm::sys::path::filename(It->path()); 10221 10222 // To know whether a symlink should be treated as file or a directory, we 10223 // have to stat it. This should be cheap enough as there shouldn't be many 10224 // symlinks. 10225 llvm::sys::fs::file_type Type = It->type(); 10226 if (Type == llvm::sys::fs::file_type::symlink_file) { 10227 if (auto FileStatus = FS.status(It->path())) 10228 Type = FileStatus->getType(); 10229 } 10230 switch (Type) { 10231 case llvm::sys::fs::file_type::directory_file: 10232 // All entries in a framework directory must have a ".framework" suffix, 10233 // but the suffix does not appear in the source code's include/import. 10234 if (LookupType == DirectoryLookup::LT_Framework && 10235 NativeRelDir.empty() && !Filename.consume_back(".framework")) 10236 break; 10237 10238 AddCompletion(Filename, /*IsDirectory=*/true); 10239 break; 10240 case llvm::sys::fs::file_type::regular_file: { 10241 // Only files that really look like headers. (Except in special dirs). 10242 const bool IsHeader = Filename.ends_with_insensitive(".h") || 10243 Filename.ends_with_insensitive(".hh") || 10244 Filename.ends_with_insensitive(".hpp") || 10245 Filename.ends_with_insensitive(".hxx") || 10246 Filename.ends_with_insensitive(".inc") || 10247 (ExtensionlessHeaders && !Filename.contains('.')); 10248 if (!IsHeader) 10249 break; 10250 AddCompletion(Filename, /*IsDirectory=*/false); 10251 break; 10252 } 10253 default: 10254 break; 10255 } 10256 } 10257 }; 10258 10259 // Helper: adds results relative to IncludeDir, if possible. 10260 auto AddFilesFromDirLookup = [&](const DirectoryLookup &IncludeDir, 10261 bool IsSystem) { 10262 switch (IncludeDir.getLookupType()) { 10263 case DirectoryLookup::LT_HeaderMap: 10264 // header maps are not (currently) enumerable. 10265 break; 10266 case DirectoryLookup::LT_NormalDir: 10267 AddFilesFromIncludeDir(IncludeDir.getDirRef()->getName(), IsSystem, 10268 DirectoryLookup::LT_NormalDir); 10269 break; 10270 case DirectoryLookup::LT_Framework: 10271 AddFilesFromIncludeDir(IncludeDir.getFrameworkDirRef()->getName(), 10272 IsSystem, DirectoryLookup::LT_Framework); 10273 break; 10274 } 10275 }; 10276 10277 // Finally with all our helpers, we can scan the include path. 10278 // Do this in standard order so deduplication keeps the right file. 10279 // (In case we decide to add more details to the results later). 10280 const auto &S = SemaRef.PP.getHeaderSearchInfo(); 10281 using llvm::make_range; 10282 if (!Angled) { 10283 // The current directory is on the include path for "quoted" includes. 10284 if (auto CurFile = SemaRef.PP.getCurrentFileLexer()->getFileEntry()) 10285 AddFilesFromIncludeDir(CurFile->getDir().getName(), false, 10286 DirectoryLookup::LT_NormalDir); 10287 for (const auto &D : make_range(S.quoted_dir_begin(), S.quoted_dir_end())) 10288 AddFilesFromDirLookup(D, false); 10289 } 10290 for (const auto &D : make_range(S.angled_dir_begin(), S.angled_dir_end())) 10291 AddFilesFromDirLookup(D, false); 10292 for (const auto &D : make_range(S.system_dir_begin(), S.system_dir_end())) 10293 AddFilesFromDirLookup(D, true); 10294 10295 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 10296 Results.getCompletionContext(), Results.data(), 10297 Results.size()); 10298 } 10299 10300 void SemaCodeCompletion::CodeCompleteNaturalLanguage() { 10301 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 10302 CodeCompletionContext::CCC_NaturalLanguage, nullptr, 10303 0); 10304 } 10305 10306 void SemaCodeCompletion::CodeCompleteAvailabilityPlatformName() { 10307 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(), 10308 CodeCompleter->getCodeCompletionTUInfo(), 10309 CodeCompletionContext::CCC_Other); 10310 Results.EnterNewScope(); 10311 static const char *Platforms[] = {"macOS", "iOS", "watchOS", "tvOS"}; 10312 for (const char *Platform : llvm::ArrayRef(Platforms)) { 10313 Results.AddResult(CodeCompletionResult(Platform)); 10314 Results.AddResult(CodeCompletionResult(Results.getAllocator().CopyString( 10315 Twine(Platform) + "ApplicationExtension"))); 10316 } 10317 Results.ExitScope(); 10318 HandleCodeCompleteResults(&SemaRef, CodeCompleter, 10319 Results.getCompletionContext(), Results.data(), 10320 Results.size()); 10321 } 10322 10323 void SemaCodeCompletion::GatherGlobalCodeCompletions( 10324 CodeCompletionAllocator &Allocator, CodeCompletionTUInfo &CCTUInfo, 10325 SmallVectorImpl<CodeCompletionResult> &Results) { 10326 ResultBuilder Builder(SemaRef, Allocator, CCTUInfo, 10327 CodeCompletionContext::CCC_Recovery); 10328 if (!CodeCompleter || CodeCompleter->includeGlobals()) { 10329 CodeCompletionDeclConsumer Consumer( 10330 Builder, getASTContext().getTranslationUnitDecl()); 10331 SemaRef.LookupVisibleDecls(getASTContext().getTranslationUnitDecl(), 10332 Sema::LookupAnyName, Consumer, 10333 !CodeCompleter || CodeCompleter->loadExternal()); 10334 } 10335 10336 if (!CodeCompleter || CodeCompleter->includeMacros()) 10337 AddMacroResults(SemaRef.PP, Builder, 10338 !CodeCompleter || CodeCompleter->loadExternal(), true); 10339 10340 Results.clear(); 10341 Results.insert(Results.end(), Builder.data(), 10342 Builder.data() + Builder.size()); 10343 } 10344 10345 SemaCodeCompletion::SemaCodeCompletion(Sema &S, 10346 CodeCompleteConsumer *CompletionConsumer) 10347 : SemaBase(S), CodeCompleter(CompletionConsumer) {} 10348