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