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