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