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