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) { 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 && Candidate.Function->isDeleted()) 5514 continue; 5515 if (Candidate.Viable) 5516 Results.push_back(ResultCandidate(Candidate.Function)); 5517 } 5518 } 5519 5520 /// Get the type of the Nth parameter from a given set of overload 5521 /// candidates. 5522 static QualType getParamType(Sema &SemaRef, 5523 ArrayRef<ResultCandidate> Candidates, unsigned N) { 5524 5525 // Given the overloads 'Candidates' for a function call matching all arguments 5526 // up to N, return the type of the Nth parameter if it is the same for all 5527 // overload candidates. 5528 QualType ParamType; 5529 for (auto &Candidate : Candidates) { 5530 if (const auto *FType = Candidate.getFunctionType()) 5531 if (const auto *Proto = dyn_cast<FunctionProtoType>(FType)) 5532 if (N < Proto->getNumParams()) { 5533 if (ParamType.isNull()) 5534 ParamType = Proto->getParamType(N); 5535 else if (!SemaRef.Context.hasSameUnqualifiedType( 5536 ParamType.getNonReferenceType(), 5537 Proto->getParamType(N).getNonReferenceType())) 5538 // Otherwise return a default-constructed QualType. 5539 return QualType(); 5540 } 5541 } 5542 5543 return ParamType; 5544 } 5545 5546 static QualType 5547 ProduceSignatureHelp(Sema &SemaRef, Scope *S, 5548 MutableArrayRef<ResultCandidate> Candidates, 5549 unsigned CurrentArg, SourceLocation OpenParLoc) { 5550 if (Candidates.empty()) 5551 return QualType(); 5552 SemaRef.CodeCompleter->ProcessOverloadCandidates( 5553 SemaRef, CurrentArg, Candidates.data(), Candidates.size(), OpenParLoc); 5554 return getParamType(SemaRef, Candidates, CurrentArg); 5555 } 5556 5557 QualType Sema::ProduceCallSignatureHelp(Scope *S, Expr *Fn, 5558 ArrayRef<Expr *> Args, 5559 SourceLocation OpenParLoc) { 5560 if (!CodeCompleter) 5561 return QualType(); 5562 5563 // FIXME: Provide support for variadic template functions. 5564 // Ignore type-dependent call expressions entirely. 5565 if (!Fn || Fn->isTypeDependent() || anyNullArguments(Args) || 5566 Expr::hasAnyTypeDependentArguments(Args)) { 5567 return QualType(); 5568 } 5569 5570 // Build an overload candidate set based on the functions we find. 5571 SourceLocation Loc = Fn->getExprLoc(); 5572 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); 5573 5574 SmallVector<ResultCandidate, 8> Results; 5575 5576 Expr *NakedFn = Fn->IgnoreParenCasts(); 5577 if (auto ULE = dyn_cast<UnresolvedLookupExpr>(NakedFn)) 5578 AddOverloadedCallCandidates(ULE, Args, CandidateSet, 5579 /*PartialOverloading=*/true); 5580 else if (auto UME = dyn_cast<UnresolvedMemberExpr>(NakedFn)) { 5581 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 5582 if (UME->hasExplicitTemplateArgs()) { 5583 UME->copyTemplateArgumentsInto(TemplateArgsBuffer); 5584 TemplateArgs = &TemplateArgsBuffer; 5585 } 5586 5587 // Add the base as first argument (use a nullptr if the base is implicit). 5588 SmallVector<Expr *, 12> ArgExprs( 5589 1, UME->isImplicitAccess() ? nullptr : UME->getBase()); 5590 ArgExprs.append(Args.begin(), Args.end()); 5591 UnresolvedSet<8> Decls; 5592 Decls.append(UME->decls_begin(), UME->decls_end()); 5593 const bool FirstArgumentIsBase = !UME->isImplicitAccess() && UME->getBase(); 5594 AddFunctionCandidates(Decls, ArgExprs, CandidateSet, TemplateArgs, 5595 /*SuppressUserConversions=*/false, 5596 /*PartialOverloading=*/true, FirstArgumentIsBase); 5597 } else { 5598 FunctionDecl *FD = nullptr; 5599 if (auto *MCE = dyn_cast<MemberExpr>(NakedFn)) 5600 FD = dyn_cast<FunctionDecl>(MCE->getMemberDecl()); 5601 else if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) 5602 FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 5603 if (FD) { // We check whether it's a resolved function declaration. 5604 if (!getLangOpts().CPlusPlus || 5605 !FD->getType()->getAs<FunctionProtoType>()) 5606 Results.push_back(ResultCandidate(FD)); 5607 else 5608 AddOverloadCandidate(FD, DeclAccessPair::make(FD, FD->getAccess()), 5609 Args, CandidateSet, 5610 /*SuppressUserConversions=*/false, 5611 /*PartialOverloading=*/true); 5612 5613 } else if (auto DC = NakedFn->getType()->getAsCXXRecordDecl()) { 5614 // If expression's type is CXXRecordDecl, it may overload the function 5615 // call operator, so we check if it does and add them as candidates. 5616 // A complete type is needed to lookup for member function call operators. 5617 if (isCompleteType(Loc, NakedFn->getType())) { 5618 DeclarationName OpName = 5619 Context.DeclarationNames.getCXXOperatorName(OO_Call); 5620 LookupResult R(*this, OpName, Loc, LookupOrdinaryName); 5621 LookupQualifiedName(R, DC); 5622 R.suppressDiagnostics(); 5623 SmallVector<Expr *, 12> ArgExprs(1, NakedFn); 5624 ArgExprs.append(Args.begin(), Args.end()); 5625 AddFunctionCandidates(R.asUnresolvedSet(), ArgExprs, CandidateSet, 5626 /*ExplicitArgs=*/nullptr, 5627 /*SuppressUserConversions=*/false, 5628 /*PartialOverloading=*/true); 5629 } 5630 } else { 5631 // Lastly we check whether expression's type is function pointer or 5632 // function. 5633 QualType T = NakedFn->getType(); 5634 if (!T->getPointeeType().isNull()) 5635 T = T->getPointeeType(); 5636 5637 if (auto FP = T->getAs<FunctionProtoType>()) { 5638 if (!TooManyArguments(FP->getNumParams(), Args.size(), 5639 /*PartialOverloading=*/true) || 5640 FP->isVariadic()) 5641 Results.push_back(ResultCandidate(FP)); 5642 } else if (auto FT = T->getAs<FunctionType>()) 5643 // No prototype and declaration, it may be a K & R style function. 5644 Results.push_back(ResultCandidate(FT)); 5645 } 5646 } 5647 mergeCandidatesWithResults(*this, Results, CandidateSet, Loc); 5648 QualType ParamType = 5649 ProduceSignatureHelp(*this, S, Results, Args.size(), OpenParLoc); 5650 return !CandidateSet.empty() ? ParamType : QualType(); 5651 } 5652 5653 QualType Sema::ProduceConstructorSignatureHelp(Scope *S, QualType Type, 5654 SourceLocation Loc, 5655 ArrayRef<Expr *> Args, 5656 SourceLocation OpenParLoc) { 5657 if (!CodeCompleter) 5658 return QualType(); 5659 5660 // A complete type is needed to lookup for constructors. 5661 CXXRecordDecl *RD = 5662 isCompleteType(Loc, Type) ? Type->getAsCXXRecordDecl() : nullptr; 5663 if (!RD) 5664 return Type; 5665 5666 // FIXME: Provide support for member initializers. 5667 // FIXME: Provide support for variadic template constructors. 5668 5669 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); 5670 5671 for (NamedDecl *C : LookupConstructors(RD)) { 5672 if (auto *FD = dyn_cast<FunctionDecl>(C)) { 5673 AddOverloadCandidate(FD, DeclAccessPair::make(FD, C->getAccess()), Args, 5674 CandidateSet, 5675 /*SuppressUserConversions=*/false, 5676 /*PartialOverloading=*/true, 5677 /*AllowExplicit*/ true); 5678 } else if (auto *FTD = dyn_cast<FunctionTemplateDecl>(C)) { 5679 AddTemplateOverloadCandidate( 5680 FTD, DeclAccessPair::make(FTD, C->getAccess()), 5681 /*ExplicitTemplateArgs=*/nullptr, Args, CandidateSet, 5682 /*SuppressUserConversions=*/false, 5683 /*PartialOverloading=*/true); 5684 } 5685 } 5686 5687 SmallVector<ResultCandidate, 8> Results; 5688 mergeCandidatesWithResults(*this, Results, CandidateSet, Loc); 5689 return ProduceSignatureHelp(*this, S, Results, Args.size(), OpenParLoc); 5690 } 5691 5692 QualType Sema::ProduceCtorInitMemberSignatureHelp( 5693 Scope *S, Decl *ConstructorDecl, CXXScopeSpec SS, ParsedType TemplateTypeTy, 5694 ArrayRef<Expr *> ArgExprs, IdentifierInfo *II, SourceLocation OpenParLoc) { 5695 if (!CodeCompleter) 5696 return QualType(); 5697 5698 CXXConstructorDecl *Constructor = 5699 dyn_cast<CXXConstructorDecl>(ConstructorDecl); 5700 if (!Constructor) 5701 return QualType(); 5702 // FIXME: Add support for Base class constructors as well. 5703 if (ValueDecl *MemberDecl = tryLookupCtorInitMemberDecl( 5704 Constructor->getParent(), SS, TemplateTypeTy, II)) 5705 return ProduceConstructorSignatureHelp(getCurScope(), MemberDecl->getType(), 5706 MemberDecl->getLocation(), ArgExprs, 5707 OpenParLoc); 5708 return QualType(); 5709 } 5710 5711 void Sema::CodeCompleteDesignator(const QualType BaseType, 5712 llvm::ArrayRef<Expr *> InitExprs, 5713 const Designation &D) { 5714 if (BaseType.isNull()) 5715 return; 5716 // FIXME: Handle nested designations, e.g. : .x.^ 5717 if (!D.empty()) 5718 return; 5719 5720 const auto *RD = getAsRecordDecl(BaseType); 5721 if (!RD) 5722 return; 5723 if (const auto *CTSD = llvm::dyn_cast<ClassTemplateSpecializationDecl>(RD)) { 5724 // Template might not be instantiated yet, fall back to primary template in 5725 // such cases. 5726 if (CTSD->getTemplateSpecializationKind() == TSK_Undeclared) 5727 RD = CTSD->getSpecializedTemplate()->getTemplatedDecl(); 5728 } 5729 if (RD->fields().empty()) 5730 return; 5731 5732 CodeCompletionContext CCC(CodeCompletionContext::CCC_DotMemberAccess, 5733 BaseType); 5734 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5735 CodeCompleter->getCodeCompletionTUInfo(), CCC); 5736 5737 Results.EnterNewScope(); 5738 for (const auto *FD : RD->fields()) { 5739 // FIXME: Make use of previous designators to mark any fields before those 5740 // inaccessible, and also compute the next initializer priority. 5741 ResultBuilder::Result Result(FD, Results.getBasePriority(FD)); 5742 Results.AddResult(Result, CurContext, /*Hiding=*/nullptr); 5743 } 5744 Results.ExitScope(); 5745 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 5746 Results.data(), Results.size()); 5747 } 5748 5749 void Sema::CodeCompleteInitializer(Scope *S, Decl *D) { 5750 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D); 5751 if (!VD) { 5752 CodeCompleteOrdinaryName(S, PCC_Expression); 5753 return; 5754 } 5755 5756 CodeCompleteExpressionData Data; 5757 Data.PreferredType = VD->getType(); 5758 // Ignore VD to avoid completing the variable itself, e.g. in 'int foo = ^'. 5759 Data.IgnoreDecls.push_back(VD); 5760 5761 CodeCompleteExpression(S, Data); 5762 } 5763 5764 void Sema::CodeCompleteAfterIf(Scope *S, bool IsBracedThen) { 5765 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5766 CodeCompleter->getCodeCompletionTUInfo(), 5767 mapCodeCompletionContext(*this, PCC_Statement)); 5768 Results.setFilter(&ResultBuilder::IsOrdinaryName); 5769 Results.EnterNewScope(); 5770 5771 CodeCompletionDeclConsumer Consumer(Results, CurContext); 5772 LookupVisibleDecls(S, LookupOrdinaryName, Consumer, 5773 CodeCompleter->includeGlobals(), 5774 CodeCompleter->loadExternal()); 5775 5776 AddOrdinaryNameResults(PCC_Statement, S, *this, Results); 5777 5778 // "else" block 5779 CodeCompletionBuilder Builder(Results.getAllocator(), 5780 Results.getCodeCompletionTUInfo()); 5781 5782 auto AddElseBodyPattern = [&] { 5783 if (IsBracedThen) { 5784 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 5785 Builder.AddChunk(CodeCompletionString::CK_LeftBrace); 5786 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); 5787 Builder.AddPlaceholderChunk("statements"); 5788 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); 5789 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 5790 } else { 5791 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); 5792 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 5793 Builder.AddPlaceholderChunk("statement"); 5794 Builder.AddChunk(CodeCompletionString::CK_SemiColon); 5795 } 5796 }; 5797 Builder.AddTypedTextChunk("else"); 5798 if (Results.includeCodePatterns()) 5799 AddElseBodyPattern(); 5800 Results.AddResult(Builder.TakeString()); 5801 5802 // "else if" block 5803 Builder.AddTypedTextChunk("else if"); 5804 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 5805 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 5806 if (getLangOpts().CPlusPlus) 5807 Builder.AddPlaceholderChunk("condition"); 5808 else 5809 Builder.AddPlaceholderChunk("expression"); 5810 Builder.AddChunk(CodeCompletionString::CK_RightParen); 5811 if (Results.includeCodePatterns()) { 5812 AddElseBodyPattern(); 5813 } 5814 Results.AddResult(Builder.TakeString()); 5815 5816 Results.ExitScope(); 5817 5818 if (S->getFnParent()) 5819 AddPrettyFunctionResults(getLangOpts(), Results); 5820 5821 if (CodeCompleter->includeMacros()) 5822 AddMacroResults(PP, Results, CodeCompleter->loadExternal(), false); 5823 5824 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 5825 Results.data(), Results.size()); 5826 } 5827 5828 void Sema::CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS, 5829 bool EnteringContext, 5830 bool IsUsingDeclaration, QualType BaseType, 5831 QualType PreferredType) { 5832 if (SS.isEmpty() || !CodeCompleter) 5833 return; 5834 5835 CodeCompletionContext CC(CodeCompletionContext::CCC_Symbol, PreferredType); 5836 CC.setIsUsingDeclaration(IsUsingDeclaration); 5837 CC.setCXXScopeSpecifier(SS); 5838 5839 // We want to keep the scope specifier even if it's invalid (e.g. the scope 5840 // "a::b::" is not corresponding to any context/namespace in the AST), since 5841 // it can be useful for global code completion which have information about 5842 // contexts/symbols that are not in the AST. 5843 if (SS.isInvalid()) { 5844 // As SS is invalid, we try to collect accessible contexts from the current 5845 // scope with a dummy lookup so that the completion consumer can try to 5846 // guess what the specified scope is. 5847 ResultBuilder DummyResults(*this, CodeCompleter->getAllocator(), 5848 CodeCompleter->getCodeCompletionTUInfo(), CC); 5849 if (!PreferredType.isNull()) 5850 DummyResults.setPreferredType(PreferredType); 5851 if (S->getEntity()) { 5852 CodeCompletionDeclConsumer Consumer(DummyResults, S->getEntity(), 5853 BaseType); 5854 LookupVisibleDecls(S, LookupOrdinaryName, Consumer, 5855 /*IncludeGlobalScope=*/false, 5856 /*LoadExternal=*/false); 5857 } 5858 HandleCodeCompleteResults(this, CodeCompleter, 5859 DummyResults.getCompletionContext(), nullptr, 0); 5860 return; 5861 } 5862 // Always pretend to enter a context to ensure that a dependent type 5863 // resolves to a dependent record. 5864 DeclContext *Ctx = computeDeclContext(SS, /*EnteringContext=*/true); 5865 5866 // Try to instantiate any non-dependent declaration contexts before 5867 // we look in them. Bail out if we fail. 5868 NestedNameSpecifier *NNS = SS.getScopeRep(); 5869 if (NNS != nullptr && SS.isValid() && !NNS->isDependent()) { 5870 if (Ctx == nullptr || RequireCompleteDeclContext(SS, Ctx)) 5871 return; 5872 } 5873 5874 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5875 CodeCompleter->getCodeCompletionTUInfo(), CC); 5876 if (!PreferredType.isNull()) 5877 Results.setPreferredType(PreferredType); 5878 Results.EnterNewScope(); 5879 5880 // The "template" keyword can follow "::" in the grammar, but only 5881 // put it into the grammar if the nested-name-specifier is dependent. 5882 // FIXME: results is always empty, this appears to be dead. 5883 if (!Results.empty() && NNS->isDependent()) 5884 Results.AddResult("template"); 5885 5886 // If the scope is a concept-constrained type parameter, infer nested 5887 // members based on the constraints. 5888 if (const auto *TTPT = 5889 dyn_cast_or_null<TemplateTypeParmType>(NNS->getAsType())) { 5890 for (const auto &R : ConceptInfo(*TTPT, S).members()) { 5891 if (R.Operator != ConceptInfo::Member::Colons) 5892 continue; 5893 Results.AddResult(CodeCompletionResult( 5894 R.render(*this, CodeCompleter->getAllocator(), 5895 CodeCompleter->getCodeCompletionTUInfo()))); 5896 } 5897 } 5898 5899 // Add calls to overridden virtual functions, if there are any. 5900 // 5901 // FIXME: This isn't wonderful, because we don't know whether we're actually 5902 // in a context that permits expressions. This is a general issue with 5903 // qualified-id completions. 5904 if (Ctx && !EnteringContext) 5905 MaybeAddOverrideCalls(*this, Ctx, Results); 5906 Results.ExitScope(); 5907 5908 if (Ctx && 5909 (CodeCompleter->includeNamespaceLevelDecls() || !Ctx->isFileContext())) { 5910 CodeCompletionDeclConsumer Consumer(Results, Ctx, BaseType); 5911 LookupVisibleDecls(Ctx, LookupOrdinaryName, Consumer, 5912 /*IncludeGlobalScope=*/true, 5913 /*IncludeDependentBases=*/true, 5914 CodeCompleter->loadExternal()); 5915 } 5916 5917 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 5918 Results.data(), Results.size()); 5919 } 5920 5921 void Sema::CodeCompleteUsing(Scope *S) { 5922 if (!CodeCompleter) 5923 return; 5924 5925 // This can be both a using alias or using declaration, in the former we 5926 // expect a new name and a symbol in the latter case. 5927 CodeCompletionContext Context(CodeCompletionContext::CCC_SymbolOrNewName); 5928 Context.setIsUsingDeclaration(true); 5929 5930 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5931 CodeCompleter->getCodeCompletionTUInfo(), Context, 5932 &ResultBuilder::IsNestedNameSpecifier); 5933 Results.EnterNewScope(); 5934 5935 // If we aren't in class scope, we could see the "namespace" keyword. 5936 if (!S->isClassScope()) 5937 Results.AddResult(CodeCompletionResult("namespace")); 5938 5939 // After "using", we can see anything that would start a 5940 // nested-name-specifier. 5941 CodeCompletionDeclConsumer Consumer(Results, CurContext); 5942 LookupVisibleDecls(S, LookupOrdinaryName, Consumer, 5943 CodeCompleter->includeGlobals(), 5944 CodeCompleter->loadExternal()); 5945 Results.ExitScope(); 5946 5947 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 5948 Results.data(), Results.size()); 5949 } 5950 5951 void Sema::CodeCompleteUsingDirective(Scope *S) { 5952 if (!CodeCompleter) 5953 return; 5954 5955 // After "using namespace", we expect to see a namespace name or namespace 5956 // alias. 5957 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5958 CodeCompleter->getCodeCompletionTUInfo(), 5959 CodeCompletionContext::CCC_Namespace, 5960 &ResultBuilder::IsNamespaceOrAlias); 5961 Results.EnterNewScope(); 5962 CodeCompletionDeclConsumer Consumer(Results, CurContext); 5963 LookupVisibleDecls(S, LookupOrdinaryName, Consumer, 5964 CodeCompleter->includeGlobals(), 5965 CodeCompleter->loadExternal()); 5966 Results.ExitScope(); 5967 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 5968 Results.data(), Results.size()); 5969 } 5970 5971 void Sema::CodeCompleteNamespaceDecl(Scope *S) { 5972 if (!CodeCompleter) 5973 return; 5974 5975 DeclContext *Ctx = S->getEntity(); 5976 if (!S->getParent()) 5977 Ctx = Context.getTranslationUnitDecl(); 5978 5979 bool SuppressedGlobalResults = 5980 Ctx && !CodeCompleter->includeGlobals() && isa<TranslationUnitDecl>(Ctx); 5981 5982 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5983 CodeCompleter->getCodeCompletionTUInfo(), 5984 SuppressedGlobalResults 5985 ? CodeCompletionContext::CCC_Namespace 5986 : CodeCompletionContext::CCC_Other, 5987 &ResultBuilder::IsNamespace); 5988 5989 if (Ctx && Ctx->isFileContext() && !SuppressedGlobalResults) { 5990 // We only want to see those namespaces that have already been defined 5991 // within this scope, because its likely that the user is creating an 5992 // extended namespace declaration. Keep track of the most recent 5993 // definition of each namespace. 5994 std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest; 5995 for (DeclContext::specific_decl_iterator<NamespaceDecl> 5996 NS(Ctx->decls_begin()), 5997 NSEnd(Ctx->decls_end()); 5998 NS != NSEnd; ++NS) 5999 OrigToLatest[NS->getOriginalNamespace()] = *NS; 6000 6001 // Add the most recent definition (or extended definition) of each 6002 // namespace to the list of results. 6003 Results.EnterNewScope(); 6004 for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator 6005 NS = OrigToLatest.begin(), 6006 NSEnd = OrigToLatest.end(); 6007 NS != NSEnd; ++NS) 6008 Results.AddResult( 6009 CodeCompletionResult(NS->second, Results.getBasePriority(NS->second), 6010 nullptr), 6011 CurContext, nullptr, false); 6012 Results.ExitScope(); 6013 } 6014 6015 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 6016 Results.data(), Results.size()); 6017 } 6018 6019 void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) { 6020 if (!CodeCompleter) 6021 return; 6022 6023 // After "namespace", we expect to see a namespace or alias. 6024 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 6025 CodeCompleter->getCodeCompletionTUInfo(), 6026 CodeCompletionContext::CCC_Namespace, 6027 &ResultBuilder::IsNamespaceOrAlias); 6028 CodeCompletionDeclConsumer Consumer(Results, CurContext); 6029 LookupVisibleDecls(S, LookupOrdinaryName, Consumer, 6030 CodeCompleter->includeGlobals(), 6031 CodeCompleter->loadExternal()); 6032 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 6033 Results.data(), Results.size()); 6034 } 6035 6036 void Sema::CodeCompleteOperatorName(Scope *S) { 6037 if (!CodeCompleter) 6038 return; 6039 6040 typedef CodeCompletionResult Result; 6041 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 6042 CodeCompleter->getCodeCompletionTUInfo(), 6043 CodeCompletionContext::CCC_Type, 6044 &ResultBuilder::IsType); 6045 Results.EnterNewScope(); 6046 6047 // Add the names of overloadable operators. Note that OO_Conditional is not 6048 // actually overloadable. 6049 #define OVERLOADED_OPERATOR(Name, Spelling, Token, Unary, Binary, MemberOnly) \ 6050 if (OO_##Name != OO_Conditional) \ 6051 Results.AddResult(Result(Spelling)); 6052 #include "clang/Basic/OperatorKinds.def" 6053 6054 // Add any type names visible from the current scope 6055 Results.allowNestedNameSpecifiers(); 6056 CodeCompletionDeclConsumer Consumer(Results, CurContext); 6057 LookupVisibleDecls(S, LookupOrdinaryName, Consumer, 6058 CodeCompleter->includeGlobals(), 6059 CodeCompleter->loadExternal()); 6060 6061 // Add any type specifiers 6062 AddTypeSpecifierResults(getLangOpts(), Results); 6063 Results.ExitScope(); 6064 6065 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 6066 Results.data(), Results.size()); 6067 } 6068 6069 void Sema::CodeCompleteConstructorInitializer( 6070 Decl *ConstructorD, ArrayRef<CXXCtorInitializer *> Initializers) { 6071 if (!ConstructorD) 6072 return; 6073 6074 AdjustDeclIfTemplate(ConstructorD); 6075 6076 auto *Constructor = dyn_cast<CXXConstructorDecl>(ConstructorD); 6077 if (!Constructor) 6078 return; 6079 6080 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 6081 CodeCompleter->getCodeCompletionTUInfo(), 6082 CodeCompletionContext::CCC_Symbol); 6083 Results.EnterNewScope(); 6084 6085 // Fill in any already-initialized fields or base classes. 6086 llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields; 6087 llvm::SmallPtrSet<CanQualType, 4> InitializedBases; 6088 for (unsigned I = 0, E = Initializers.size(); I != E; ++I) { 6089 if (Initializers[I]->isBaseInitializer()) 6090 InitializedBases.insert(Context.getCanonicalType( 6091 QualType(Initializers[I]->getBaseClass(), 0))); 6092 else 6093 InitializedFields.insert( 6094 cast<FieldDecl>(Initializers[I]->getAnyMember())); 6095 } 6096 6097 // Add completions for base classes. 6098 PrintingPolicy Policy = getCompletionPrintingPolicy(*this); 6099 bool SawLastInitializer = Initializers.empty(); 6100 CXXRecordDecl *ClassDecl = Constructor->getParent(); 6101 6102 auto GenerateCCS = [&](const NamedDecl *ND, const char *Name) { 6103 CodeCompletionBuilder Builder(Results.getAllocator(), 6104 Results.getCodeCompletionTUInfo()); 6105 Builder.AddTypedTextChunk(Name); 6106 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 6107 if (const auto *Function = dyn_cast<FunctionDecl>(ND)) 6108 AddFunctionParameterChunks(PP, Policy, Function, Builder); 6109 else if (const auto *FunTemplDecl = dyn_cast<FunctionTemplateDecl>(ND)) 6110 AddFunctionParameterChunks(PP, Policy, FunTemplDecl->getTemplatedDecl(), 6111 Builder); 6112 Builder.AddChunk(CodeCompletionString::CK_RightParen); 6113 return Builder.TakeString(); 6114 }; 6115 auto AddDefaultCtorInit = [&](const char *Name, const char *Type, 6116 const NamedDecl *ND) { 6117 CodeCompletionBuilder Builder(Results.getAllocator(), 6118 Results.getCodeCompletionTUInfo()); 6119 Builder.AddTypedTextChunk(Name); 6120 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 6121 Builder.AddPlaceholderChunk(Type); 6122 Builder.AddChunk(CodeCompletionString::CK_RightParen); 6123 if (ND) { 6124 auto CCR = CodeCompletionResult( 6125 Builder.TakeString(), ND, 6126 SawLastInitializer ? CCP_NextInitializer : CCP_MemberDeclaration); 6127 if (isa<FieldDecl>(ND)) 6128 CCR.CursorKind = CXCursor_MemberRef; 6129 return Results.AddResult(CCR); 6130 } 6131 return Results.AddResult(CodeCompletionResult( 6132 Builder.TakeString(), 6133 SawLastInitializer ? CCP_NextInitializer : CCP_MemberDeclaration)); 6134 }; 6135 auto AddCtorsWithName = [&](const CXXRecordDecl *RD, unsigned int Priority, 6136 const char *Name, const FieldDecl *FD) { 6137 if (!RD) 6138 return AddDefaultCtorInit(Name, 6139 FD ? Results.getAllocator().CopyString( 6140 FD->getType().getAsString(Policy)) 6141 : Name, 6142 FD); 6143 auto Ctors = getConstructors(Context, RD); 6144 if (Ctors.begin() == Ctors.end()) 6145 return AddDefaultCtorInit(Name, Name, RD); 6146 for (const NamedDecl *Ctor : Ctors) { 6147 auto CCR = CodeCompletionResult(GenerateCCS(Ctor, Name), RD, Priority); 6148 CCR.CursorKind = getCursorKindForDecl(Ctor); 6149 Results.AddResult(CCR); 6150 } 6151 }; 6152 auto AddBase = [&](const CXXBaseSpecifier &Base) { 6153 const char *BaseName = 6154 Results.getAllocator().CopyString(Base.getType().getAsString(Policy)); 6155 const auto *RD = Base.getType()->getAsCXXRecordDecl(); 6156 AddCtorsWithName( 6157 RD, SawLastInitializer ? CCP_NextInitializer : CCP_MemberDeclaration, 6158 BaseName, nullptr); 6159 }; 6160 auto AddField = [&](const FieldDecl *FD) { 6161 const char *FieldName = 6162 Results.getAllocator().CopyString(FD->getIdentifier()->getName()); 6163 const CXXRecordDecl *RD = FD->getType()->getAsCXXRecordDecl(); 6164 AddCtorsWithName( 6165 RD, SawLastInitializer ? CCP_NextInitializer : CCP_MemberDeclaration, 6166 FieldName, FD); 6167 }; 6168 6169 for (const auto &Base : ClassDecl->bases()) { 6170 if (!InitializedBases.insert(Context.getCanonicalType(Base.getType())) 6171 .second) { 6172 SawLastInitializer = 6173 !Initializers.empty() && Initializers.back()->isBaseInitializer() && 6174 Context.hasSameUnqualifiedType( 6175 Base.getType(), QualType(Initializers.back()->getBaseClass(), 0)); 6176 continue; 6177 } 6178 6179 AddBase(Base); 6180 SawLastInitializer = false; 6181 } 6182 6183 // Add completions for virtual base classes. 6184 for (const auto &Base : ClassDecl->vbases()) { 6185 if (!InitializedBases.insert(Context.getCanonicalType(Base.getType())) 6186 .second) { 6187 SawLastInitializer = 6188 !Initializers.empty() && Initializers.back()->isBaseInitializer() && 6189 Context.hasSameUnqualifiedType( 6190 Base.getType(), QualType(Initializers.back()->getBaseClass(), 0)); 6191 continue; 6192 } 6193 6194 AddBase(Base); 6195 SawLastInitializer = false; 6196 } 6197 6198 // Add completions for members. 6199 for (auto *Field : ClassDecl->fields()) { 6200 if (!InitializedFields.insert(cast<FieldDecl>(Field->getCanonicalDecl())) 6201 .second) { 6202 SawLastInitializer = !Initializers.empty() && 6203 Initializers.back()->isAnyMemberInitializer() && 6204 Initializers.back()->getAnyMember() == Field; 6205 continue; 6206 } 6207 6208 if (!Field->getDeclName()) 6209 continue; 6210 6211 AddField(Field); 6212 SawLastInitializer = false; 6213 } 6214 Results.ExitScope(); 6215 6216 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 6217 Results.data(), Results.size()); 6218 } 6219 6220 /// Determine whether this scope denotes a namespace. 6221 static bool isNamespaceScope(Scope *S) { 6222 DeclContext *DC = S->getEntity(); 6223 if (!DC) 6224 return false; 6225 6226 return DC->isFileContext(); 6227 } 6228 6229 void Sema::CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro, 6230 bool AfterAmpersand) { 6231 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 6232 CodeCompleter->getCodeCompletionTUInfo(), 6233 CodeCompletionContext::CCC_Other); 6234 Results.EnterNewScope(); 6235 6236 // Note what has already been captured. 6237 llvm::SmallPtrSet<IdentifierInfo *, 4> Known; 6238 bool IncludedThis = false; 6239 for (const auto &C : Intro.Captures) { 6240 if (C.Kind == LCK_This) { 6241 IncludedThis = true; 6242 continue; 6243 } 6244 6245 Known.insert(C.Id); 6246 } 6247 6248 // Look for other capturable variables. 6249 for (; S && !isNamespaceScope(S); S = S->getParent()) { 6250 for (const auto *D : S->decls()) { 6251 const auto *Var = dyn_cast<VarDecl>(D); 6252 if (!Var || !Var->hasLocalStorage() || Var->hasAttr<BlocksAttr>()) 6253 continue; 6254 6255 if (Known.insert(Var->getIdentifier()).second) 6256 Results.AddResult(CodeCompletionResult(Var, CCP_LocalDeclaration), 6257 CurContext, nullptr, false); 6258 } 6259 } 6260 6261 // Add 'this', if it would be valid. 6262 if (!IncludedThis && !AfterAmpersand && Intro.Default != LCD_ByCopy) 6263 addThisCompletion(*this, Results); 6264 6265 Results.ExitScope(); 6266 6267 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 6268 Results.data(), Results.size()); 6269 } 6270 6271 void Sema::CodeCompleteAfterFunctionEquals(Declarator &D) { 6272 if (!LangOpts.CPlusPlus11) 6273 return; 6274 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 6275 CodeCompleter->getCodeCompletionTUInfo(), 6276 CodeCompletionContext::CCC_Other); 6277 auto ShouldAddDefault = [&D, this]() { 6278 if (!D.isFunctionDeclarator()) 6279 return false; 6280 auto &Id = D.getName(); 6281 if (Id.getKind() == UnqualifiedIdKind::IK_DestructorName) 6282 return true; 6283 // FIXME(liuhui): Ideally, we should check the constructor parameter list to 6284 // verify that it is the default, copy or move constructor? 6285 if (Id.getKind() == UnqualifiedIdKind::IK_ConstructorName && 6286 D.getFunctionTypeInfo().NumParams <= 1) 6287 return true; 6288 if (Id.getKind() == UnqualifiedIdKind::IK_OperatorFunctionId) { 6289 auto Op = Id.OperatorFunctionId.Operator; 6290 // FIXME(liuhui): Ideally, we should check the function parameter list to 6291 // verify that it is the copy or move assignment? 6292 if (Op == OverloadedOperatorKind::OO_Equal) 6293 return true; 6294 if (LangOpts.CPlusPlus20 && 6295 (Op == OverloadedOperatorKind::OO_EqualEqual || 6296 Op == OverloadedOperatorKind::OO_ExclaimEqual || 6297 Op == OverloadedOperatorKind::OO_Less || 6298 Op == OverloadedOperatorKind::OO_LessEqual || 6299 Op == OverloadedOperatorKind::OO_Greater || 6300 Op == OverloadedOperatorKind::OO_GreaterEqual || 6301 Op == OverloadedOperatorKind::OO_Spaceship)) 6302 return true; 6303 } 6304 return false; 6305 }; 6306 6307 Results.EnterNewScope(); 6308 if (ShouldAddDefault()) 6309 Results.AddResult("default"); 6310 // FIXME(liuhui): Ideally, we should only provide `delete` completion for the 6311 // first function declaration. 6312 Results.AddResult("delete"); 6313 Results.ExitScope(); 6314 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 6315 Results.data(), Results.size()); 6316 } 6317 6318 /// Macro that optionally prepends an "@" to the string literal passed in via 6319 /// Keyword, depending on whether NeedAt is true or false. 6320 #define OBJC_AT_KEYWORD_NAME(NeedAt, Keyword) ((NeedAt) ? "@" Keyword : Keyword) 6321 6322 static void AddObjCImplementationResults(const LangOptions &LangOpts, 6323 ResultBuilder &Results, bool NeedAt) { 6324 typedef CodeCompletionResult Result; 6325 // Since we have an implementation, we can end it. 6326 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "end"))); 6327 6328 CodeCompletionBuilder Builder(Results.getAllocator(), 6329 Results.getCodeCompletionTUInfo()); 6330 if (LangOpts.ObjC) { 6331 // @dynamic 6332 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "dynamic")); 6333 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 6334 Builder.AddPlaceholderChunk("property"); 6335 Results.AddResult(Result(Builder.TakeString())); 6336 6337 // @synthesize 6338 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "synthesize")); 6339 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 6340 Builder.AddPlaceholderChunk("property"); 6341 Results.AddResult(Result(Builder.TakeString())); 6342 } 6343 } 6344 6345 static void AddObjCInterfaceResults(const LangOptions &LangOpts, 6346 ResultBuilder &Results, bool NeedAt) { 6347 typedef CodeCompletionResult Result; 6348 6349 // Since we have an interface or protocol, we can end it. 6350 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "end"))); 6351 6352 if (LangOpts.ObjC) { 6353 // @property 6354 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "property"))); 6355 6356 // @required 6357 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "required"))); 6358 6359 // @optional 6360 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "optional"))); 6361 } 6362 } 6363 6364 static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt) { 6365 typedef CodeCompletionResult Result; 6366 CodeCompletionBuilder Builder(Results.getAllocator(), 6367 Results.getCodeCompletionTUInfo()); 6368 6369 // @class name ; 6370 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "class")); 6371 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 6372 Builder.AddPlaceholderChunk("name"); 6373 Results.AddResult(Result(Builder.TakeString())); 6374 6375 if (Results.includeCodePatterns()) { 6376 // @interface name 6377 // FIXME: Could introduce the whole pattern, including superclasses and 6378 // such. 6379 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "interface")); 6380 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 6381 Builder.AddPlaceholderChunk("class"); 6382 Results.AddResult(Result(Builder.TakeString())); 6383 6384 // @protocol name 6385 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "protocol")); 6386 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 6387 Builder.AddPlaceholderChunk("protocol"); 6388 Results.AddResult(Result(Builder.TakeString())); 6389 6390 // @implementation name 6391 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "implementation")); 6392 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 6393 Builder.AddPlaceholderChunk("class"); 6394 Results.AddResult(Result(Builder.TakeString())); 6395 } 6396 6397 // @compatibility_alias name 6398 Builder.AddTypedTextChunk( 6399 OBJC_AT_KEYWORD_NAME(NeedAt, "compatibility_alias")); 6400 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 6401 Builder.AddPlaceholderChunk("alias"); 6402 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 6403 Builder.AddPlaceholderChunk("class"); 6404 Results.AddResult(Result(Builder.TakeString())); 6405 6406 if (Results.getSema().getLangOpts().Modules) { 6407 // @import name 6408 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "import")); 6409 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 6410 Builder.AddPlaceholderChunk("module"); 6411 Results.AddResult(Result(Builder.TakeString())); 6412 } 6413 } 6414 6415 void Sema::CodeCompleteObjCAtDirective(Scope *S) { 6416 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 6417 CodeCompleter->getCodeCompletionTUInfo(), 6418 CodeCompletionContext::CCC_Other); 6419 Results.EnterNewScope(); 6420 if (isa<ObjCImplDecl>(CurContext)) 6421 AddObjCImplementationResults(getLangOpts(), Results, false); 6422 else if (CurContext->isObjCContainer()) 6423 AddObjCInterfaceResults(getLangOpts(), Results, false); 6424 else 6425 AddObjCTopLevelResults(Results, false); 6426 Results.ExitScope(); 6427 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 6428 Results.data(), Results.size()); 6429 } 6430 6431 static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt) { 6432 typedef CodeCompletionResult Result; 6433 CodeCompletionBuilder Builder(Results.getAllocator(), 6434 Results.getCodeCompletionTUInfo()); 6435 6436 // @encode ( type-name ) 6437 const char *EncodeType = "char[]"; 6438 if (Results.getSema().getLangOpts().CPlusPlus || 6439 Results.getSema().getLangOpts().ConstStrings) 6440 EncodeType = "const char[]"; 6441 Builder.AddResultTypeChunk(EncodeType); 6442 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "encode")); 6443 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 6444 Builder.AddPlaceholderChunk("type-name"); 6445 Builder.AddChunk(CodeCompletionString::CK_RightParen); 6446 Results.AddResult(Result(Builder.TakeString())); 6447 6448 // @protocol ( protocol-name ) 6449 Builder.AddResultTypeChunk("Protocol *"); 6450 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "protocol")); 6451 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 6452 Builder.AddPlaceholderChunk("protocol-name"); 6453 Builder.AddChunk(CodeCompletionString::CK_RightParen); 6454 Results.AddResult(Result(Builder.TakeString())); 6455 6456 // @selector ( selector ) 6457 Builder.AddResultTypeChunk("SEL"); 6458 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "selector")); 6459 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 6460 Builder.AddPlaceholderChunk("selector"); 6461 Builder.AddChunk(CodeCompletionString::CK_RightParen); 6462 Results.AddResult(Result(Builder.TakeString())); 6463 6464 // @"string" 6465 Builder.AddResultTypeChunk("NSString *"); 6466 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "\"")); 6467 Builder.AddPlaceholderChunk("string"); 6468 Builder.AddTextChunk("\""); 6469 Results.AddResult(Result(Builder.TakeString())); 6470 6471 // @[objects, ...] 6472 Builder.AddResultTypeChunk("NSArray *"); 6473 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "[")); 6474 Builder.AddPlaceholderChunk("objects, ..."); 6475 Builder.AddChunk(CodeCompletionString::CK_RightBracket); 6476 Results.AddResult(Result(Builder.TakeString())); 6477 6478 // @{key : object, ...} 6479 Builder.AddResultTypeChunk("NSDictionary *"); 6480 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "{")); 6481 Builder.AddPlaceholderChunk("key"); 6482 Builder.AddChunk(CodeCompletionString::CK_Colon); 6483 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 6484 Builder.AddPlaceholderChunk("object, ..."); 6485 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 6486 Results.AddResult(Result(Builder.TakeString())); 6487 6488 // @(expression) 6489 Builder.AddResultTypeChunk("id"); 6490 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "(")); 6491 Builder.AddPlaceholderChunk("expression"); 6492 Builder.AddChunk(CodeCompletionString::CK_RightParen); 6493 Results.AddResult(Result(Builder.TakeString())); 6494 } 6495 6496 static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt) { 6497 typedef CodeCompletionResult Result; 6498 CodeCompletionBuilder Builder(Results.getAllocator(), 6499 Results.getCodeCompletionTUInfo()); 6500 6501 if (Results.includeCodePatterns()) { 6502 // @try { statements } @catch ( declaration ) { statements } @finally 6503 // { statements } 6504 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "try")); 6505 Builder.AddChunk(CodeCompletionString::CK_LeftBrace); 6506 Builder.AddPlaceholderChunk("statements"); 6507 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 6508 Builder.AddTextChunk("@catch"); 6509 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 6510 Builder.AddPlaceholderChunk("parameter"); 6511 Builder.AddChunk(CodeCompletionString::CK_RightParen); 6512 Builder.AddChunk(CodeCompletionString::CK_LeftBrace); 6513 Builder.AddPlaceholderChunk("statements"); 6514 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 6515 Builder.AddTextChunk("@finally"); 6516 Builder.AddChunk(CodeCompletionString::CK_LeftBrace); 6517 Builder.AddPlaceholderChunk("statements"); 6518 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 6519 Results.AddResult(Result(Builder.TakeString())); 6520 } 6521 6522 // @throw 6523 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "throw")); 6524 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 6525 Builder.AddPlaceholderChunk("expression"); 6526 Results.AddResult(Result(Builder.TakeString())); 6527 6528 if (Results.includeCodePatterns()) { 6529 // @synchronized ( expression ) { statements } 6530 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "synchronized")); 6531 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 6532 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 6533 Builder.AddPlaceholderChunk("expression"); 6534 Builder.AddChunk(CodeCompletionString::CK_RightParen); 6535 Builder.AddChunk(CodeCompletionString::CK_LeftBrace); 6536 Builder.AddPlaceholderChunk("statements"); 6537 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 6538 Results.AddResult(Result(Builder.TakeString())); 6539 } 6540 } 6541 6542 static void AddObjCVisibilityResults(const LangOptions &LangOpts, 6543 ResultBuilder &Results, bool NeedAt) { 6544 typedef CodeCompletionResult Result; 6545 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "private"))); 6546 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "protected"))); 6547 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "public"))); 6548 if (LangOpts.ObjC) 6549 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "package"))); 6550 } 6551 6552 void Sema::CodeCompleteObjCAtVisibility(Scope *S) { 6553 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 6554 CodeCompleter->getCodeCompletionTUInfo(), 6555 CodeCompletionContext::CCC_Other); 6556 Results.EnterNewScope(); 6557 AddObjCVisibilityResults(getLangOpts(), Results, false); 6558 Results.ExitScope(); 6559 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 6560 Results.data(), Results.size()); 6561 } 6562 6563 void Sema::CodeCompleteObjCAtStatement(Scope *S) { 6564 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 6565 CodeCompleter->getCodeCompletionTUInfo(), 6566 CodeCompletionContext::CCC_Other); 6567 Results.EnterNewScope(); 6568 AddObjCStatementResults(Results, false); 6569 AddObjCExpressionResults(Results, false); 6570 Results.ExitScope(); 6571 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 6572 Results.data(), Results.size()); 6573 } 6574 6575 void Sema::CodeCompleteObjCAtExpression(Scope *S) { 6576 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 6577 CodeCompleter->getCodeCompletionTUInfo(), 6578 CodeCompletionContext::CCC_Other); 6579 Results.EnterNewScope(); 6580 AddObjCExpressionResults(Results, false); 6581 Results.ExitScope(); 6582 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 6583 Results.data(), Results.size()); 6584 } 6585 6586 /// Determine whether the addition of the given flag to an Objective-C 6587 /// property's attributes will cause a conflict. 6588 static bool ObjCPropertyFlagConflicts(unsigned Attributes, unsigned NewFlag) { 6589 // Check if we've already added this flag. 6590 if (Attributes & NewFlag) 6591 return true; 6592 6593 Attributes |= NewFlag; 6594 6595 // Check for collisions with "readonly". 6596 if ((Attributes & ObjCPropertyAttribute::kind_readonly) && 6597 (Attributes & ObjCPropertyAttribute::kind_readwrite)) 6598 return true; 6599 6600 // Check for more than one of { assign, copy, retain, strong, weak }. 6601 unsigned AssignCopyRetMask = 6602 Attributes & 6603 (ObjCPropertyAttribute::kind_assign | 6604 ObjCPropertyAttribute::kind_unsafe_unretained | 6605 ObjCPropertyAttribute::kind_copy | ObjCPropertyAttribute::kind_retain | 6606 ObjCPropertyAttribute::kind_strong | ObjCPropertyAttribute::kind_weak); 6607 if (AssignCopyRetMask && 6608 AssignCopyRetMask != ObjCPropertyAttribute::kind_assign && 6609 AssignCopyRetMask != ObjCPropertyAttribute::kind_unsafe_unretained && 6610 AssignCopyRetMask != ObjCPropertyAttribute::kind_copy && 6611 AssignCopyRetMask != ObjCPropertyAttribute::kind_retain && 6612 AssignCopyRetMask != ObjCPropertyAttribute::kind_strong && 6613 AssignCopyRetMask != ObjCPropertyAttribute::kind_weak) 6614 return true; 6615 6616 return false; 6617 } 6618 6619 void Sema::CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS) { 6620 if (!CodeCompleter) 6621 return; 6622 6623 unsigned Attributes = ODS.getPropertyAttributes(); 6624 6625 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 6626 CodeCompleter->getCodeCompletionTUInfo(), 6627 CodeCompletionContext::CCC_Other); 6628 Results.EnterNewScope(); 6629 if (!ObjCPropertyFlagConflicts(Attributes, 6630 ObjCPropertyAttribute::kind_readonly)) 6631 Results.AddResult(CodeCompletionResult("readonly")); 6632 if (!ObjCPropertyFlagConflicts(Attributes, 6633 ObjCPropertyAttribute::kind_assign)) 6634 Results.AddResult(CodeCompletionResult("assign")); 6635 if (!ObjCPropertyFlagConflicts(Attributes, 6636 ObjCPropertyAttribute::kind_unsafe_unretained)) 6637 Results.AddResult(CodeCompletionResult("unsafe_unretained")); 6638 if (!ObjCPropertyFlagConflicts(Attributes, 6639 ObjCPropertyAttribute::kind_readwrite)) 6640 Results.AddResult(CodeCompletionResult("readwrite")); 6641 if (!ObjCPropertyFlagConflicts(Attributes, 6642 ObjCPropertyAttribute::kind_retain)) 6643 Results.AddResult(CodeCompletionResult("retain")); 6644 if (!ObjCPropertyFlagConflicts(Attributes, 6645 ObjCPropertyAttribute::kind_strong)) 6646 Results.AddResult(CodeCompletionResult("strong")); 6647 if (!ObjCPropertyFlagConflicts(Attributes, ObjCPropertyAttribute::kind_copy)) 6648 Results.AddResult(CodeCompletionResult("copy")); 6649 if (!ObjCPropertyFlagConflicts(Attributes, 6650 ObjCPropertyAttribute::kind_nonatomic)) 6651 Results.AddResult(CodeCompletionResult("nonatomic")); 6652 if (!ObjCPropertyFlagConflicts(Attributes, 6653 ObjCPropertyAttribute::kind_atomic)) 6654 Results.AddResult(CodeCompletionResult("atomic")); 6655 6656 // Only suggest "weak" if we're compiling for ARC-with-weak-references or GC. 6657 if (getLangOpts().ObjCWeak || getLangOpts().getGC() != LangOptions::NonGC) 6658 if (!ObjCPropertyFlagConflicts(Attributes, 6659 ObjCPropertyAttribute::kind_weak)) 6660 Results.AddResult(CodeCompletionResult("weak")); 6661 6662 if (!ObjCPropertyFlagConflicts(Attributes, 6663 ObjCPropertyAttribute::kind_setter)) { 6664 CodeCompletionBuilder Setter(Results.getAllocator(), 6665 Results.getCodeCompletionTUInfo()); 6666 Setter.AddTypedTextChunk("setter"); 6667 Setter.AddTextChunk("="); 6668 Setter.AddPlaceholderChunk("method"); 6669 Results.AddResult(CodeCompletionResult(Setter.TakeString())); 6670 } 6671 if (!ObjCPropertyFlagConflicts(Attributes, 6672 ObjCPropertyAttribute::kind_getter)) { 6673 CodeCompletionBuilder Getter(Results.getAllocator(), 6674 Results.getCodeCompletionTUInfo()); 6675 Getter.AddTypedTextChunk("getter"); 6676 Getter.AddTextChunk("="); 6677 Getter.AddPlaceholderChunk("method"); 6678 Results.AddResult(CodeCompletionResult(Getter.TakeString())); 6679 } 6680 if (!ObjCPropertyFlagConflicts(Attributes, 6681 ObjCPropertyAttribute::kind_nullability)) { 6682 Results.AddResult(CodeCompletionResult("nonnull")); 6683 Results.AddResult(CodeCompletionResult("nullable")); 6684 Results.AddResult(CodeCompletionResult("null_unspecified")); 6685 Results.AddResult(CodeCompletionResult("null_resettable")); 6686 } 6687 Results.ExitScope(); 6688 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 6689 Results.data(), Results.size()); 6690 } 6691 6692 /// Describes the kind of Objective-C method that we want to find 6693 /// via code completion. 6694 enum ObjCMethodKind { 6695 MK_Any, ///< Any kind of method, provided it means other specified criteria. 6696 MK_ZeroArgSelector, ///< Zero-argument (unary) selector. 6697 MK_OneArgSelector ///< One-argument selector. 6698 }; 6699 6700 static bool isAcceptableObjCSelector(Selector Sel, ObjCMethodKind WantKind, 6701 ArrayRef<IdentifierInfo *> SelIdents, 6702 bool AllowSameLength = true) { 6703 unsigned NumSelIdents = SelIdents.size(); 6704 if (NumSelIdents > Sel.getNumArgs()) 6705 return false; 6706 6707 switch (WantKind) { 6708 case MK_Any: 6709 break; 6710 case MK_ZeroArgSelector: 6711 return Sel.isUnarySelector(); 6712 case MK_OneArgSelector: 6713 return Sel.getNumArgs() == 1; 6714 } 6715 6716 if (!AllowSameLength && NumSelIdents && NumSelIdents == Sel.getNumArgs()) 6717 return false; 6718 6719 for (unsigned I = 0; I != NumSelIdents; ++I) 6720 if (SelIdents[I] != Sel.getIdentifierInfoForSlot(I)) 6721 return false; 6722 6723 return true; 6724 } 6725 6726 static bool isAcceptableObjCMethod(ObjCMethodDecl *Method, 6727 ObjCMethodKind WantKind, 6728 ArrayRef<IdentifierInfo *> SelIdents, 6729 bool AllowSameLength = true) { 6730 return isAcceptableObjCSelector(Method->getSelector(), WantKind, SelIdents, 6731 AllowSameLength); 6732 } 6733 6734 /// A set of selectors, which is used to avoid introducing multiple 6735 /// completions with the same selector into the result set. 6736 typedef llvm::SmallPtrSet<Selector, 16> VisitedSelectorSet; 6737 6738 /// Add all of the Objective-C methods in the given Objective-C 6739 /// container to the set of results. 6740 /// 6741 /// The container will be a class, protocol, category, or implementation of 6742 /// any of the above. This mether will recurse to include methods from 6743 /// the superclasses of classes along with their categories, protocols, and 6744 /// implementations. 6745 /// 6746 /// \param Container the container in which we'll look to find methods. 6747 /// 6748 /// \param WantInstanceMethods Whether to add instance methods (only); if 6749 /// false, this routine will add factory methods (only). 6750 /// 6751 /// \param CurContext the context in which we're performing the lookup that 6752 /// finds methods. 6753 /// 6754 /// \param AllowSameLength Whether we allow a method to be added to the list 6755 /// when it has the same number of parameters as we have selector identifiers. 6756 /// 6757 /// \param Results the structure into which we'll add results. 6758 static void AddObjCMethods(ObjCContainerDecl *Container, 6759 bool WantInstanceMethods, ObjCMethodKind WantKind, 6760 ArrayRef<IdentifierInfo *> SelIdents, 6761 DeclContext *CurContext, 6762 VisitedSelectorSet &Selectors, bool AllowSameLength, 6763 ResultBuilder &Results, bool InOriginalClass = true, 6764 bool IsRootClass = false) { 6765 typedef CodeCompletionResult Result; 6766 Container = getContainerDef(Container); 6767 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container); 6768 IsRootClass = IsRootClass || (IFace && !IFace->getSuperClass()); 6769 for (ObjCMethodDecl *M : Container->methods()) { 6770 // The instance methods on the root class can be messaged via the 6771 // metaclass. 6772 if (M->isInstanceMethod() == WantInstanceMethods || 6773 (IsRootClass && !WantInstanceMethods)) { 6774 // Check whether the selector identifiers we've been given are a 6775 // subset of the identifiers for this particular method. 6776 if (!isAcceptableObjCMethod(M, WantKind, SelIdents, AllowSameLength)) 6777 continue; 6778 6779 if (!Selectors.insert(M->getSelector()).second) 6780 continue; 6781 6782 Result R = Result(M, Results.getBasePriority(M), nullptr); 6783 R.StartParameter = SelIdents.size(); 6784 R.AllParametersAreInformative = (WantKind != MK_Any); 6785 if (!InOriginalClass) 6786 setInBaseClass(R); 6787 Results.MaybeAddResult(R, CurContext); 6788 } 6789 } 6790 6791 // Visit the protocols of protocols. 6792 if (const auto *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) { 6793 if (Protocol->hasDefinition()) { 6794 const ObjCList<ObjCProtocolDecl> &Protocols = 6795 Protocol->getReferencedProtocols(); 6796 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(), 6797 E = Protocols.end(); 6798 I != E; ++I) 6799 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, CurContext, 6800 Selectors, AllowSameLength, Results, false, IsRootClass); 6801 } 6802 } 6803 6804 if (!IFace || !IFace->hasDefinition()) 6805 return; 6806 6807 // Add methods in protocols. 6808 for (ObjCProtocolDecl *I : IFace->protocols()) 6809 AddObjCMethods(I, WantInstanceMethods, WantKind, SelIdents, CurContext, 6810 Selectors, AllowSameLength, Results, false, IsRootClass); 6811 6812 // Add methods in categories. 6813 for (ObjCCategoryDecl *CatDecl : IFace->known_categories()) { 6814 AddObjCMethods(CatDecl, WantInstanceMethods, WantKind, SelIdents, 6815 CurContext, Selectors, AllowSameLength, Results, 6816 InOriginalClass, IsRootClass); 6817 6818 // Add a categories protocol methods. 6819 const ObjCList<ObjCProtocolDecl> &Protocols = 6820 CatDecl->getReferencedProtocols(); 6821 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(), 6822 E = Protocols.end(); 6823 I != E; ++I) 6824 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, CurContext, 6825 Selectors, AllowSameLength, Results, false, IsRootClass); 6826 6827 // Add methods in category implementations. 6828 if (ObjCCategoryImplDecl *Impl = CatDecl->getImplementation()) 6829 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents, CurContext, 6830 Selectors, AllowSameLength, Results, InOriginalClass, 6831 IsRootClass); 6832 } 6833 6834 // Add methods in superclass. 6835 // Avoid passing in IsRootClass since root classes won't have super classes. 6836 if (IFace->getSuperClass()) 6837 AddObjCMethods(IFace->getSuperClass(), WantInstanceMethods, WantKind, 6838 SelIdents, CurContext, Selectors, AllowSameLength, Results, 6839 /*IsRootClass=*/false); 6840 6841 // Add methods in our implementation, if any. 6842 if (ObjCImplementationDecl *Impl = IFace->getImplementation()) 6843 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents, CurContext, 6844 Selectors, AllowSameLength, Results, InOriginalClass, 6845 IsRootClass); 6846 } 6847 6848 void Sema::CodeCompleteObjCPropertyGetter(Scope *S) { 6849 // Try to find the interface where getters might live. 6850 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext); 6851 if (!Class) { 6852 if (ObjCCategoryDecl *Category = 6853 dyn_cast_or_null<ObjCCategoryDecl>(CurContext)) 6854 Class = Category->getClassInterface(); 6855 6856 if (!Class) 6857 return; 6858 } 6859 6860 // Find all of the potential getters. 6861 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 6862 CodeCompleter->getCodeCompletionTUInfo(), 6863 CodeCompletionContext::CCC_Other); 6864 Results.EnterNewScope(); 6865 6866 VisitedSelectorSet Selectors; 6867 AddObjCMethods(Class, true, MK_ZeroArgSelector, None, CurContext, Selectors, 6868 /*AllowSameLength=*/true, Results); 6869 Results.ExitScope(); 6870 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 6871 Results.data(), Results.size()); 6872 } 6873 6874 void Sema::CodeCompleteObjCPropertySetter(Scope *S) { 6875 // Try to find the interface where setters might live. 6876 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext); 6877 if (!Class) { 6878 if (ObjCCategoryDecl *Category = 6879 dyn_cast_or_null<ObjCCategoryDecl>(CurContext)) 6880 Class = Category->getClassInterface(); 6881 6882 if (!Class) 6883 return; 6884 } 6885 6886 // Find all of the potential getters. 6887 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 6888 CodeCompleter->getCodeCompletionTUInfo(), 6889 CodeCompletionContext::CCC_Other); 6890 Results.EnterNewScope(); 6891 6892 VisitedSelectorSet Selectors; 6893 AddObjCMethods(Class, true, MK_OneArgSelector, None, CurContext, Selectors, 6894 /*AllowSameLength=*/true, Results); 6895 6896 Results.ExitScope(); 6897 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 6898 Results.data(), Results.size()); 6899 } 6900 6901 void Sema::CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS, 6902 bool IsParameter) { 6903 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 6904 CodeCompleter->getCodeCompletionTUInfo(), 6905 CodeCompletionContext::CCC_Type); 6906 Results.EnterNewScope(); 6907 6908 // Add context-sensitive, Objective-C parameter-passing keywords. 6909 bool AddedInOut = false; 6910 if ((DS.getObjCDeclQualifier() & 6911 (ObjCDeclSpec::DQ_In | ObjCDeclSpec::DQ_Inout)) == 0) { 6912 Results.AddResult("in"); 6913 Results.AddResult("inout"); 6914 AddedInOut = true; 6915 } 6916 if ((DS.getObjCDeclQualifier() & 6917 (ObjCDeclSpec::DQ_Out | ObjCDeclSpec::DQ_Inout)) == 0) { 6918 Results.AddResult("out"); 6919 if (!AddedInOut) 6920 Results.AddResult("inout"); 6921 } 6922 if ((DS.getObjCDeclQualifier() & 6923 (ObjCDeclSpec::DQ_Bycopy | ObjCDeclSpec::DQ_Byref | 6924 ObjCDeclSpec::DQ_Oneway)) == 0) { 6925 Results.AddResult("bycopy"); 6926 Results.AddResult("byref"); 6927 Results.AddResult("oneway"); 6928 } 6929 if ((DS.getObjCDeclQualifier() & ObjCDeclSpec::DQ_CSNullability) == 0) { 6930 Results.AddResult("nonnull"); 6931 Results.AddResult("nullable"); 6932 Results.AddResult("null_unspecified"); 6933 } 6934 6935 // If we're completing the return type of an Objective-C method and the 6936 // identifier IBAction refers to a macro, provide a completion item for 6937 // an action, e.g., 6938 // IBAction)<#selector#>:(id)sender 6939 if (DS.getObjCDeclQualifier() == 0 && !IsParameter && 6940 PP.isMacroDefined("IBAction")) { 6941 CodeCompletionBuilder Builder(Results.getAllocator(), 6942 Results.getCodeCompletionTUInfo(), 6943 CCP_CodePattern, CXAvailability_Available); 6944 Builder.AddTypedTextChunk("IBAction"); 6945 Builder.AddChunk(CodeCompletionString::CK_RightParen); 6946 Builder.AddPlaceholderChunk("selector"); 6947 Builder.AddChunk(CodeCompletionString::CK_Colon); 6948 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 6949 Builder.AddTextChunk("id"); 6950 Builder.AddChunk(CodeCompletionString::CK_RightParen); 6951 Builder.AddTextChunk("sender"); 6952 Results.AddResult(CodeCompletionResult(Builder.TakeString())); 6953 } 6954 6955 // If we're completing the return type, provide 'instancetype'. 6956 if (!IsParameter) { 6957 Results.AddResult(CodeCompletionResult("instancetype")); 6958 } 6959 6960 // Add various builtin type names and specifiers. 6961 AddOrdinaryNameResults(PCC_Type, S, *this, Results); 6962 Results.ExitScope(); 6963 6964 // Add the various type names 6965 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName); 6966 CodeCompletionDeclConsumer Consumer(Results, CurContext); 6967 LookupVisibleDecls(S, LookupOrdinaryName, Consumer, 6968 CodeCompleter->includeGlobals(), 6969 CodeCompleter->loadExternal()); 6970 6971 if (CodeCompleter->includeMacros()) 6972 AddMacroResults(PP, Results, CodeCompleter->loadExternal(), false); 6973 6974 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 6975 Results.data(), Results.size()); 6976 } 6977 6978 /// When we have an expression with type "id", we may assume 6979 /// that it has some more-specific class type based on knowledge of 6980 /// common uses of Objective-C. This routine returns that class type, 6981 /// or NULL if no better result could be determined. 6982 static ObjCInterfaceDecl *GetAssumedMessageSendExprType(Expr *E) { 6983 auto *Msg = dyn_cast_or_null<ObjCMessageExpr>(E); 6984 if (!Msg) 6985 return nullptr; 6986 6987 Selector Sel = Msg->getSelector(); 6988 if (Sel.isNull()) 6989 return nullptr; 6990 6991 IdentifierInfo *Id = Sel.getIdentifierInfoForSlot(0); 6992 if (!Id) 6993 return nullptr; 6994 6995 ObjCMethodDecl *Method = Msg->getMethodDecl(); 6996 if (!Method) 6997 return nullptr; 6998 6999 // Determine the class that we're sending the message to. 7000 ObjCInterfaceDecl *IFace = nullptr; 7001 switch (Msg->getReceiverKind()) { 7002 case ObjCMessageExpr::Class: 7003 if (const ObjCObjectType *ObjType = 7004 Msg->getClassReceiver()->getAs<ObjCObjectType>()) 7005 IFace = ObjType->getInterface(); 7006 break; 7007 7008 case ObjCMessageExpr::Instance: { 7009 QualType T = Msg->getInstanceReceiver()->getType(); 7010 if (const ObjCObjectPointerType *Ptr = T->getAs<ObjCObjectPointerType>()) 7011 IFace = Ptr->getInterfaceDecl(); 7012 break; 7013 } 7014 7015 case ObjCMessageExpr::SuperInstance: 7016 case ObjCMessageExpr::SuperClass: 7017 break; 7018 } 7019 7020 if (!IFace) 7021 return nullptr; 7022 7023 ObjCInterfaceDecl *Super = IFace->getSuperClass(); 7024 if (Method->isInstanceMethod()) 7025 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName()) 7026 .Case("retain", IFace) 7027 .Case("strong", IFace) 7028 .Case("autorelease", IFace) 7029 .Case("copy", IFace) 7030 .Case("copyWithZone", IFace) 7031 .Case("mutableCopy", IFace) 7032 .Case("mutableCopyWithZone", IFace) 7033 .Case("awakeFromCoder", IFace) 7034 .Case("replacementObjectFromCoder", IFace) 7035 .Case("class", IFace) 7036 .Case("classForCoder", IFace) 7037 .Case("superclass", Super) 7038 .Default(nullptr); 7039 7040 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName()) 7041 .Case("new", IFace) 7042 .Case("alloc", IFace) 7043 .Case("allocWithZone", IFace) 7044 .Case("class", IFace) 7045 .Case("superclass", Super) 7046 .Default(nullptr); 7047 } 7048 7049 // Add a special completion for a message send to "super", which fills in the 7050 // most likely case of forwarding all of our arguments to the superclass 7051 // function. 7052 /// 7053 /// \param S The semantic analysis object. 7054 /// 7055 /// \param NeedSuperKeyword Whether we need to prefix this completion with 7056 /// the "super" keyword. Otherwise, we just need to provide the arguments. 7057 /// 7058 /// \param SelIdents The identifiers in the selector that have already been 7059 /// provided as arguments for a send to "super". 7060 /// 7061 /// \param Results The set of results to augment. 7062 /// 7063 /// \returns the Objective-C method declaration that would be invoked by 7064 /// this "super" completion. If NULL, no completion was added. 7065 static ObjCMethodDecl * 7066 AddSuperSendCompletion(Sema &S, bool NeedSuperKeyword, 7067 ArrayRef<IdentifierInfo *> SelIdents, 7068 ResultBuilder &Results) { 7069 ObjCMethodDecl *CurMethod = S.getCurMethodDecl(); 7070 if (!CurMethod) 7071 return nullptr; 7072 7073 ObjCInterfaceDecl *Class = CurMethod->getClassInterface(); 7074 if (!Class) 7075 return nullptr; 7076 7077 // Try to find a superclass method with the same selector. 7078 ObjCMethodDecl *SuperMethod = nullptr; 7079 while ((Class = Class->getSuperClass()) && !SuperMethod) { 7080 // Check in the class 7081 SuperMethod = Class->getMethod(CurMethod->getSelector(), 7082 CurMethod->isInstanceMethod()); 7083 7084 // Check in categories or class extensions. 7085 if (!SuperMethod) { 7086 for (const auto *Cat : Class->known_categories()) { 7087 if ((SuperMethod = Cat->getMethod(CurMethod->getSelector(), 7088 CurMethod->isInstanceMethod()))) 7089 break; 7090 } 7091 } 7092 } 7093 7094 if (!SuperMethod) 7095 return nullptr; 7096 7097 // Check whether the superclass method has the same signature. 7098 if (CurMethod->param_size() != SuperMethod->param_size() || 7099 CurMethod->isVariadic() != SuperMethod->isVariadic()) 7100 return nullptr; 7101 7102 for (ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin(), 7103 CurPEnd = CurMethod->param_end(), 7104 SuperP = SuperMethod->param_begin(); 7105 CurP != CurPEnd; ++CurP, ++SuperP) { 7106 // Make sure the parameter types are compatible. 7107 if (!S.Context.hasSameUnqualifiedType((*CurP)->getType(), 7108 (*SuperP)->getType())) 7109 return nullptr; 7110 7111 // Make sure we have a parameter name to forward! 7112 if (!(*CurP)->getIdentifier()) 7113 return nullptr; 7114 } 7115 7116 // We have a superclass method. Now, form the send-to-super completion. 7117 CodeCompletionBuilder Builder(Results.getAllocator(), 7118 Results.getCodeCompletionTUInfo()); 7119 7120 // Give this completion a return type. 7121 AddResultTypeChunk(S.Context, getCompletionPrintingPolicy(S), SuperMethod, 7122 Results.getCompletionContext().getBaseType(), Builder); 7123 7124 // If we need the "super" keyword, add it (plus some spacing). 7125 if (NeedSuperKeyword) { 7126 Builder.AddTypedTextChunk("super"); 7127 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7128 } 7129 7130 Selector Sel = CurMethod->getSelector(); 7131 if (Sel.isUnarySelector()) { 7132 if (NeedSuperKeyword) 7133 Builder.AddTextChunk( 7134 Builder.getAllocator().CopyString(Sel.getNameForSlot(0))); 7135 else 7136 Builder.AddTypedTextChunk( 7137 Builder.getAllocator().CopyString(Sel.getNameForSlot(0))); 7138 } else { 7139 ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin(); 7140 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I, ++CurP) { 7141 if (I > SelIdents.size()) 7142 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7143 7144 if (I < SelIdents.size()) 7145 Builder.AddInformativeChunk( 7146 Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":")); 7147 else if (NeedSuperKeyword || I > SelIdents.size()) { 7148 Builder.AddTextChunk( 7149 Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":")); 7150 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString( 7151 (*CurP)->getIdentifier()->getName())); 7152 } else { 7153 Builder.AddTypedTextChunk( 7154 Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":")); 7155 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString( 7156 (*CurP)->getIdentifier()->getName())); 7157 } 7158 } 7159 } 7160 7161 Results.AddResult(CodeCompletionResult(Builder.TakeString(), SuperMethod, 7162 CCP_SuperCompletion)); 7163 return SuperMethod; 7164 } 7165 7166 void Sema::CodeCompleteObjCMessageReceiver(Scope *S) { 7167 typedef CodeCompletionResult Result; 7168 ResultBuilder Results( 7169 *this, CodeCompleter->getAllocator(), 7170 CodeCompleter->getCodeCompletionTUInfo(), 7171 CodeCompletionContext::CCC_ObjCMessageReceiver, 7172 getLangOpts().CPlusPlus11 7173 ? &ResultBuilder::IsObjCMessageReceiverOrLambdaCapture 7174 : &ResultBuilder::IsObjCMessageReceiver); 7175 7176 CodeCompletionDeclConsumer Consumer(Results, CurContext); 7177 Results.EnterNewScope(); 7178 LookupVisibleDecls(S, LookupOrdinaryName, Consumer, 7179 CodeCompleter->includeGlobals(), 7180 CodeCompleter->loadExternal()); 7181 7182 // If we are in an Objective-C method inside a class that has a superclass, 7183 // add "super" as an option. 7184 if (ObjCMethodDecl *Method = getCurMethodDecl()) 7185 if (ObjCInterfaceDecl *Iface = Method->getClassInterface()) 7186 if (Iface->getSuperClass()) { 7187 Results.AddResult(Result("super")); 7188 7189 AddSuperSendCompletion(*this, /*NeedSuperKeyword=*/true, None, Results); 7190 } 7191 7192 if (getLangOpts().CPlusPlus11) 7193 addThisCompletion(*this, Results); 7194 7195 Results.ExitScope(); 7196 7197 if (CodeCompleter->includeMacros()) 7198 AddMacroResults(PP, Results, CodeCompleter->loadExternal(), false); 7199 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 7200 Results.data(), Results.size()); 7201 } 7202 7203 void Sema::CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc, 7204 ArrayRef<IdentifierInfo *> SelIdents, 7205 bool AtArgumentExpression) { 7206 ObjCInterfaceDecl *CDecl = nullptr; 7207 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) { 7208 // Figure out which interface we're in. 7209 CDecl = CurMethod->getClassInterface(); 7210 if (!CDecl) 7211 return; 7212 7213 // Find the superclass of this class. 7214 CDecl = CDecl->getSuperClass(); 7215 if (!CDecl) 7216 return; 7217 7218 if (CurMethod->isInstanceMethod()) { 7219 // We are inside an instance method, which means that the message 7220 // send [super ...] is actually calling an instance method on the 7221 // current object. 7222 return CodeCompleteObjCInstanceMessage(S, nullptr, SelIdents, 7223 AtArgumentExpression, CDecl); 7224 } 7225 7226 // Fall through to send to the superclass in CDecl. 7227 } else { 7228 // "super" may be the name of a type or variable. Figure out which 7229 // it is. 7230 IdentifierInfo *Super = getSuperIdentifier(); 7231 NamedDecl *ND = LookupSingleName(S, Super, SuperLoc, LookupOrdinaryName); 7232 if ((CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(ND))) { 7233 // "super" names an interface. Use it. 7234 } else if (TypeDecl *TD = dyn_cast_or_null<TypeDecl>(ND)) { 7235 if (const ObjCObjectType *Iface = 7236 Context.getTypeDeclType(TD)->getAs<ObjCObjectType>()) 7237 CDecl = Iface->getInterface(); 7238 } else if (ND && isa<UnresolvedUsingTypenameDecl>(ND)) { 7239 // "super" names an unresolved type; we can't be more specific. 7240 } else { 7241 // Assume that "super" names some kind of value and parse that way. 7242 CXXScopeSpec SS; 7243 SourceLocation TemplateKWLoc; 7244 UnqualifiedId id; 7245 id.setIdentifier(Super, SuperLoc); 7246 ExprResult SuperExpr = ActOnIdExpression(S, SS, TemplateKWLoc, id, 7247 /*HasTrailingLParen=*/false, 7248 /*IsAddressOfOperand=*/false); 7249 return CodeCompleteObjCInstanceMessage(S, (Expr *)SuperExpr.get(), 7250 SelIdents, AtArgumentExpression); 7251 } 7252 7253 // Fall through 7254 } 7255 7256 ParsedType Receiver; 7257 if (CDecl) 7258 Receiver = ParsedType::make(Context.getObjCInterfaceType(CDecl)); 7259 return CodeCompleteObjCClassMessage(S, Receiver, SelIdents, 7260 AtArgumentExpression, 7261 /*IsSuper=*/true); 7262 } 7263 7264 /// Given a set of code-completion results for the argument of a message 7265 /// send, determine the preferred type (if any) for that argument expression. 7266 static QualType getPreferredArgumentTypeForMessageSend(ResultBuilder &Results, 7267 unsigned NumSelIdents) { 7268 typedef CodeCompletionResult Result; 7269 ASTContext &Context = Results.getSema().Context; 7270 7271 QualType PreferredType; 7272 unsigned BestPriority = CCP_Unlikely * 2; 7273 Result *ResultsData = Results.data(); 7274 for (unsigned I = 0, N = Results.size(); I != N; ++I) { 7275 Result &R = ResultsData[I]; 7276 if (R.Kind == Result::RK_Declaration && 7277 isa<ObjCMethodDecl>(R.Declaration)) { 7278 if (R.Priority <= BestPriority) { 7279 const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(R.Declaration); 7280 if (NumSelIdents <= Method->param_size()) { 7281 QualType MyPreferredType = 7282 Method->parameters()[NumSelIdents - 1]->getType(); 7283 if (R.Priority < BestPriority || PreferredType.isNull()) { 7284 BestPriority = R.Priority; 7285 PreferredType = MyPreferredType; 7286 } else if (!Context.hasSameUnqualifiedType(PreferredType, 7287 MyPreferredType)) { 7288 PreferredType = QualType(); 7289 } 7290 } 7291 } 7292 } 7293 } 7294 7295 return PreferredType; 7296 } 7297 7298 static void AddClassMessageCompletions(Sema &SemaRef, Scope *S, 7299 ParsedType Receiver, 7300 ArrayRef<IdentifierInfo *> SelIdents, 7301 bool AtArgumentExpression, bool IsSuper, 7302 ResultBuilder &Results) { 7303 typedef CodeCompletionResult Result; 7304 ObjCInterfaceDecl *CDecl = nullptr; 7305 7306 // If the given name refers to an interface type, retrieve the 7307 // corresponding declaration. 7308 if (Receiver) { 7309 QualType T = SemaRef.GetTypeFromParser(Receiver, nullptr); 7310 if (!T.isNull()) 7311 if (const ObjCObjectType *Interface = T->getAs<ObjCObjectType>()) 7312 CDecl = Interface->getInterface(); 7313 } 7314 7315 // Add all of the factory methods in this Objective-C class, its protocols, 7316 // superclasses, categories, implementation, etc. 7317 Results.EnterNewScope(); 7318 7319 // If this is a send-to-super, try to add the special "super" send 7320 // completion. 7321 if (IsSuper) { 7322 if (ObjCMethodDecl *SuperMethod = 7323 AddSuperSendCompletion(SemaRef, false, SelIdents, Results)) 7324 Results.Ignore(SuperMethod); 7325 } 7326 7327 // If we're inside an Objective-C method definition, prefer its selector to 7328 // others. 7329 if (ObjCMethodDecl *CurMethod = SemaRef.getCurMethodDecl()) 7330 Results.setPreferredSelector(CurMethod->getSelector()); 7331 7332 VisitedSelectorSet Selectors; 7333 if (CDecl) 7334 AddObjCMethods(CDecl, false, MK_Any, SelIdents, SemaRef.CurContext, 7335 Selectors, AtArgumentExpression, Results); 7336 else { 7337 // We're messaging "id" as a type; provide all class/factory methods. 7338 7339 // If we have an external source, load the entire class method 7340 // pool from the AST file. 7341 if (SemaRef.getExternalSource()) { 7342 for (uint32_t I = 0, 7343 N = SemaRef.getExternalSource()->GetNumExternalSelectors(); 7344 I != N; ++I) { 7345 Selector Sel = SemaRef.getExternalSource()->GetExternalSelector(I); 7346 if (Sel.isNull() || SemaRef.MethodPool.count(Sel)) 7347 continue; 7348 7349 SemaRef.ReadMethodPool(Sel); 7350 } 7351 } 7352 7353 for (Sema::GlobalMethodPool::iterator M = SemaRef.MethodPool.begin(), 7354 MEnd = SemaRef.MethodPool.end(); 7355 M != MEnd; ++M) { 7356 for (ObjCMethodList *MethList = &M->second.second; 7357 MethList && MethList->getMethod(); MethList = MethList->getNext()) { 7358 if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents)) 7359 continue; 7360 7361 Result R(MethList->getMethod(), 7362 Results.getBasePriority(MethList->getMethod()), nullptr); 7363 R.StartParameter = SelIdents.size(); 7364 R.AllParametersAreInformative = false; 7365 Results.MaybeAddResult(R, SemaRef.CurContext); 7366 } 7367 } 7368 } 7369 7370 Results.ExitScope(); 7371 } 7372 7373 void Sema::CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver, 7374 ArrayRef<IdentifierInfo *> SelIdents, 7375 bool AtArgumentExpression, 7376 bool IsSuper) { 7377 7378 QualType T = this->GetTypeFromParser(Receiver); 7379 7380 ResultBuilder Results( 7381 *this, CodeCompleter->getAllocator(), 7382 CodeCompleter->getCodeCompletionTUInfo(), 7383 CodeCompletionContext(CodeCompletionContext::CCC_ObjCClassMessage, T, 7384 SelIdents)); 7385 7386 AddClassMessageCompletions(*this, S, Receiver, SelIdents, 7387 AtArgumentExpression, IsSuper, Results); 7388 7389 // If we're actually at the argument expression (rather than prior to the 7390 // selector), we're actually performing code completion for an expression. 7391 // Determine whether we have a single, best method. If so, we can 7392 // code-complete the expression using the corresponding parameter type as 7393 // our preferred type, improving completion results. 7394 if (AtArgumentExpression) { 7395 QualType PreferredType = 7396 getPreferredArgumentTypeForMessageSend(Results, SelIdents.size()); 7397 if (PreferredType.isNull()) 7398 CodeCompleteOrdinaryName(S, PCC_Expression); 7399 else 7400 CodeCompleteExpression(S, PreferredType); 7401 return; 7402 } 7403 7404 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 7405 Results.data(), Results.size()); 7406 } 7407 7408 void Sema::CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver, 7409 ArrayRef<IdentifierInfo *> SelIdents, 7410 bool AtArgumentExpression, 7411 ObjCInterfaceDecl *Super) { 7412 typedef CodeCompletionResult Result; 7413 7414 Expr *RecExpr = static_cast<Expr *>(Receiver); 7415 7416 // If necessary, apply function/array conversion to the receiver. 7417 // C99 6.7.5.3p[7,8]. 7418 if (RecExpr) { 7419 ExprResult Conv = DefaultFunctionArrayLvalueConversion(RecExpr); 7420 if (Conv.isInvalid()) // conversion failed. bail. 7421 return; 7422 RecExpr = Conv.get(); 7423 } 7424 QualType ReceiverType = RecExpr 7425 ? RecExpr->getType() 7426 : Super ? Context.getObjCObjectPointerType( 7427 Context.getObjCInterfaceType(Super)) 7428 : Context.getObjCIdType(); 7429 7430 // If we're messaging an expression with type "id" or "Class", check 7431 // whether we know something special about the receiver that allows 7432 // us to assume a more-specific receiver type. 7433 if (ReceiverType->isObjCIdType() || ReceiverType->isObjCClassType()) { 7434 if (ObjCInterfaceDecl *IFace = GetAssumedMessageSendExprType(RecExpr)) { 7435 if (ReceiverType->isObjCClassType()) 7436 return CodeCompleteObjCClassMessage( 7437 S, ParsedType::make(Context.getObjCInterfaceType(IFace)), SelIdents, 7438 AtArgumentExpression, Super); 7439 7440 ReceiverType = 7441 Context.getObjCObjectPointerType(Context.getObjCInterfaceType(IFace)); 7442 } 7443 } else if (RecExpr && getLangOpts().CPlusPlus) { 7444 ExprResult Conv = PerformContextuallyConvertToObjCPointer(RecExpr); 7445 if (Conv.isUsable()) { 7446 RecExpr = Conv.get(); 7447 ReceiverType = RecExpr->getType(); 7448 } 7449 } 7450 7451 // Build the set of methods we can see. 7452 ResultBuilder Results( 7453 *this, CodeCompleter->getAllocator(), 7454 CodeCompleter->getCodeCompletionTUInfo(), 7455 CodeCompletionContext(CodeCompletionContext::CCC_ObjCInstanceMessage, 7456 ReceiverType, SelIdents)); 7457 7458 Results.EnterNewScope(); 7459 7460 // If this is a send-to-super, try to add the special "super" send 7461 // completion. 7462 if (Super) { 7463 if (ObjCMethodDecl *SuperMethod = 7464 AddSuperSendCompletion(*this, false, SelIdents, Results)) 7465 Results.Ignore(SuperMethod); 7466 } 7467 7468 // If we're inside an Objective-C method definition, prefer its selector to 7469 // others. 7470 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) 7471 Results.setPreferredSelector(CurMethod->getSelector()); 7472 7473 // Keep track of the selectors we've already added. 7474 VisitedSelectorSet Selectors; 7475 7476 // Handle messages to Class. This really isn't a message to an instance 7477 // method, so we treat it the same way we would treat a message send to a 7478 // class method. 7479 if (ReceiverType->isObjCClassType() || 7480 ReceiverType->isObjCQualifiedClassType()) { 7481 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) { 7482 if (ObjCInterfaceDecl *ClassDecl = CurMethod->getClassInterface()) 7483 AddObjCMethods(ClassDecl, false, MK_Any, SelIdents, CurContext, 7484 Selectors, AtArgumentExpression, Results); 7485 } 7486 } 7487 // Handle messages to a qualified ID ("id<foo>"). 7488 else if (const ObjCObjectPointerType *QualID = 7489 ReceiverType->getAsObjCQualifiedIdType()) { 7490 // Search protocols for instance methods. 7491 for (auto *I : QualID->quals()) 7492 AddObjCMethods(I, true, MK_Any, SelIdents, CurContext, Selectors, 7493 AtArgumentExpression, Results); 7494 } 7495 // Handle messages to a pointer to interface type. 7496 else if (const ObjCObjectPointerType *IFacePtr = 7497 ReceiverType->getAsObjCInterfacePointerType()) { 7498 // Search the class, its superclasses, etc., for instance methods. 7499 AddObjCMethods(IFacePtr->getInterfaceDecl(), true, MK_Any, SelIdents, 7500 CurContext, Selectors, AtArgumentExpression, Results); 7501 7502 // Search protocols for instance methods. 7503 for (auto *I : IFacePtr->quals()) 7504 AddObjCMethods(I, true, MK_Any, SelIdents, CurContext, Selectors, 7505 AtArgumentExpression, Results); 7506 } 7507 // Handle messages to "id". 7508 else if (ReceiverType->isObjCIdType()) { 7509 // We're messaging "id", so provide all instance methods we know 7510 // about as code-completion results. 7511 7512 // If we have an external source, load the entire class method 7513 // pool from the AST file. 7514 if (ExternalSource) { 7515 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors(); 7516 I != N; ++I) { 7517 Selector Sel = ExternalSource->GetExternalSelector(I); 7518 if (Sel.isNull() || MethodPool.count(Sel)) 7519 continue; 7520 7521 ReadMethodPool(Sel); 7522 } 7523 } 7524 7525 for (GlobalMethodPool::iterator M = MethodPool.begin(), 7526 MEnd = MethodPool.end(); 7527 M != MEnd; ++M) { 7528 for (ObjCMethodList *MethList = &M->second.first; 7529 MethList && MethList->getMethod(); MethList = MethList->getNext()) { 7530 if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents)) 7531 continue; 7532 7533 if (!Selectors.insert(MethList->getMethod()->getSelector()).second) 7534 continue; 7535 7536 Result R(MethList->getMethod(), 7537 Results.getBasePriority(MethList->getMethod()), nullptr); 7538 R.StartParameter = SelIdents.size(); 7539 R.AllParametersAreInformative = false; 7540 Results.MaybeAddResult(R, CurContext); 7541 } 7542 } 7543 } 7544 Results.ExitScope(); 7545 7546 // If we're actually at the argument expression (rather than prior to the 7547 // selector), we're actually performing code completion for an expression. 7548 // Determine whether we have a single, best method. If so, we can 7549 // code-complete the expression using the corresponding parameter type as 7550 // our preferred type, improving completion results. 7551 if (AtArgumentExpression) { 7552 QualType PreferredType = 7553 getPreferredArgumentTypeForMessageSend(Results, SelIdents.size()); 7554 if (PreferredType.isNull()) 7555 CodeCompleteOrdinaryName(S, PCC_Expression); 7556 else 7557 CodeCompleteExpression(S, PreferredType); 7558 return; 7559 } 7560 7561 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 7562 Results.data(), Results.size()); 7563 } 7564 7565 void Sema::CodeCompleteObjCForCollection(Scope *S, 7566 DeclGroupPtrTy IterationVar) { 7567 CodeCompleteExpressionData Data; 7568 Data.ObjCCollection = true; 7569 7570 if (IterationVar.getAsOpaquePtr()) { 7571 DeclGroupRef DG = IterationVar.get(); 7572 for (DeclGroupRef::iterator I = DG.begin(), End = DG.end(); I != End; ++I) { 7573 if (*I) 7574 Data.IgnoreDecls.push_back(*I); 7575 } 7576 } 7577 7578 CodeCompleteExpression(S, Data); 7579 } 7580 7581 void Sema::CodeCompleteObjCSelector(Scope *S, 7582 ArrayRef<IdentifierInfo *> SelIdents) { 7583 // If we have an external source, load the entire class method 7584 // pool from the AST file. 7585 if (ExternalSource) { 7586 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors(); I != N; 7587 ++I) { 7588 Selector Sel = ExternalSource->GetExternalSelector(I); 7589 if (Sel.isNull() || MethodPool.count(Sel)) 7590 continue; 7591 7592 ReadMethodPool(Sel); 7593 } 7594 } 7595 7596 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 7597 CodeCompleter->getCodeCompletionTUInfo(), 7598 CodeCompletionContext::CCC_SelectorName); 7599 Results.EnterNewScope(); 7600 for (GlobalMethodPool::iterator M = MethodPool.begin(), 7601 MEnd = MethodPool.end(); 7602 M != MEnd; ++M) { 7603 7604 Selector Sel = M->first; 7605 if (!isAcceptableObjCSelector(Sel, MK_Any, SelIdents)) 7606 continue; 7607 7608 CodeCompletionBuilder Builder(Results.getAllocator(), 7609 Results.getCodeCompletionTUInfo()); 7610 if (Sel.isUnarySelector()) { 7611 Builder.AddTypedTextChunk( 7612 Builder.getAllocator().CopyString(Sel.getNameForSlot(0))); 7613 Results.AddResult(Builder.TakeString()); 7614 continue; 7615 } 7616 7617 std::string Accumulator; 7618 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I) { 7619 if (I == SelIdents.size()) { 7620 if (!Accumulator.empty()) { 7621 Builder.AddInformativeChunk( 7622 Builder.getAllocator().CopyString(Accumulator)); 7623 Accumulator.clear(); 7624 } 7625 } 7626 7627 Accumulator += Sel.getNameForSlot(I); 7628 Accumulator += ':'; 7629 } 7630 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(Accumulator)); 7631 Results.AddResult(Builder.TakeString()); 7632 } 7633 Results.ExitScope(); 7634 7635 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 7636 Results.data(), Results.size()); 7637 } 7638 7639 /// Add all of the protocol declarations that we find in the given 7640 /// (translation unit) context. 7641 static void AddProtocolResults(DeclContext *Ctx, DeclContext *CurContext, 7642 bool OnlyForwardDeclarations, 7643 ResultBuilder &Results) { 7644 typedef CodeCompletionResult Result; 7645 7646 for (const auto *D : Ctx->decls()) { 7647 // Record any protocols we find. 7648 if (const auto *Proto = dyn_cast<ObjCProtocolDecl>(D)) 7649 if (!OnlyForwardDeclarations || !Proto->hasDefinition()) 7650 Results.AddResult( 7651 Result(Proto, Results.getBasePriority(Proto), nullptr), CurContext, 7652 nullptr, false); 7653 } 7654 } 7655 7656 void Sema::CodeCompleteObjCProtocolReferences( 7657 ArrayRef<IdentifierLocPair> Protocols) { 7658 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 7659 CodeCompleter->getCodeCompletionTUInfo(), 7660 CodeCompletionContext::CCC_ObjCProtocolName); 7661 7662 if (CodeCompleter->includeGlobals()) { 7663 Results.EnterNewScope(); 7664 7665 // Tell the result set to ignore all of the protocols we have 7666 // already seen. 7667 // FIXME: This doesn't work when caching code-completion results. 7668 for (const IdentifierLocPair &Pair : Protocols) 7669 if (ObjCProtocolDecl *Protocol = LookupProtocol(Pair.first, Pair.second)) 7670 Results.Ignore(Protocol); 7671 7672 // Add all protocols. 7673 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, false, 7674 Results); 7675 7676 Results.ExitScope(); 7677 } 7678 7679 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 7680 Results.data(), Results.size()); 7681 } 7682 7683 void Sema::CodeCompleteObjCProtocolDecl(Scope *) { 7684 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 7685 CodeCompleter->getCodeCompletionTUInfo(), 7686 CodeCompletionContext::CCC_ObjCProtocolName); 7687 7688 if (CodeCompleter->includeGlobals()) { 7689 Results.EnterNewScope(); 7690 7691 // Add all protocols. 7692 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, true, 7693 Results); 7694 7695 Results.ExitScope(); 7696 } 7697 7698 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 7699 Results.data(), Results.size()); 7700 } 7701 7702 /// Add all of the Objective-C interface declarations that we find in 7703 /// the given (translation unit) context. 7704 static void AddInterfaceResults(DeclContext *Ctx, DeclContext *CurContext, 7705 bool OnlyForwardDeclarations, 7706 bool OnlyUnimplemented, 7707 ResultBuilder &Results) { 7708 typedef CodeCompletionResult Result; 7709 7710 for (const auto *D : Ctx->decls()) { 7711 // Record any interfaces we find. 7712 if (const auto *Class = dyn_cast<ObjCInterfaceDecl>(D)) 7713 if ((!OnlyForwardDeclarations || !Class->hasDefinition()) && 7714 (!OnlyUnimplemented || !Class->getImplementation())) 7715 Results.AddResult( 7716 Result(Class, Results.getBasePriority(Class), nullptr), CurContext, 7717 nullptr, false); 7718 } 7719 } 7720 7721 void Sema::CodeCompleteObjCInterfaceDecl(Scope *S) { 7722 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 7723 CodeCompleter->getCodeCompletionTUInfo(), 7724 CodeCompletionContext::CCC_ObjCInterfaceName); 7725 Results.EnterNewScope(); 7726 7727 if (CodeCompleter->includeGlobals()) { 7728 // Add all classes. 7729 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false, 7730 false, Results); 7731 } 7732 7733 Results.ExitScope(); 7734 7735 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 7736 Results.data(), Results.size()); 7737 } 7738 7739 void Sema::CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName, 7740 SourceLocation ClassNameLoc) { 7741 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 7742 CodeCompleter->getCodeCompletionTUInfo(), 7743 CodeCompletionContext::CCC_ObjCInterfaceName); 7744 Results.EnterNewScope(); 7745 7746 // Make sure that we ignore the class we're currently defining. 7747 NamedDecl *CurClass = 7748 LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName); 7749 if (CurClass && isa<ObjCInterfaceDecl>(CurClass)) 7750 Results.Ignore(CurClass); 7751 7752 if (CodeCompleter->includeGlobals()) { 7753 // Add all classes. 7754 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false, 7755 false, Results); 7756 } 7757 7758 Results.ExitScope(); 7759 7760 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 7761 Results.data(), Results.size()); 7762 } 7763 7764 void Sema::CodeCompleteObjCImplementationDecl(Scope *S) { 7765 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 7766 CodeCompleter->getCodeCompletionTUInfo(), 7767 CodeCompletionContext::CCC_ObjCImplementation); 7768 Results.EnterNewScope(); 7769 7770 if (CodeCompleter->includeGlobals()) { 7771 // Add all unimplemented classes. 7772 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false, 7773 true, Results); 7774 } 7775 7776 Results.ExitScope(); 7777 7778 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 7779 Results.data(), Results.size()); 7780 } 7781 7782 void Sema::CodeCompleteObjCInterfaceCategory(Scope *S, 7783 IdentifierInfo *ClassName, 7784 SourceLocation ClassNameLoc) { 7785 typedef CodeCompletionResult Result; 7786 7787 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 7788 CodeCompleter->getCodeCompletionTUInfo(), 7789 CodeCompletionContext::CCC_ObjCCategoryName); 7790 7791 // Ignore any categories we find that have already been implemented by this 7792 // interface. 7793 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames; 7794 NamedDecl *CurClass = 7795 LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName); 7796 if (ObjCInterfaceDecl *Class = 7797 dyn_cast_or_null<ObjCInterfaceDecl>(CurClass)) { 7798 for (const auto *Cat : Class->visible_categories()) 7799 CategoryNames.insert(Cat->getIdentifier()); 7800 } 7801 7802 // Add all of the categories we know about. 7803 Results.EnterNewScope(); 7804 TranslationUnitDecl *TU = Context.getTranslationUnitDecl(); 7805 for (const auto *D : TU->decls()) 7806 if (const auto *Category = dyn_cast<ObjCCategoryDecl>(D)) 7807 if (CategoryNames.insert(Category->getIdentifier()).second) 7808 Results.AddResult( 7809 Result(Category, Results.getBasePriority(Category), nullptr), 7810 CurContext, nullptr, false); 7811 Results.ExitScope(); 7812 7813 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 7814 Results.data(), Results.size()); 7815 } 7816 7817 void Sema::CodeCompleteObjCImplementationCategory(Scope *S, 7818 IdentifierInfo *ClassName, 7819 SourceLocation ClassNameLoc) { 7820 typedef CodeCompletionResult Result; 7821 7822 // Find the corresponding interface. If we couldn't find the interface, the 7823 // program itself is ill-formed. However, we'll try to be helpful still by 7824 // providing the list of all of the categories we know about. 7825 NamedDecl *CurClass = 7826 LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName); 7827 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass); 7828 if (!Class) 7829 return CodeCompleteObjCInterfaceCategory(S, ClassName, ClassNameLoc); 7830 7831 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 7832 CodeCompleter->getCodeCompletionTUInfo(), 7833 CodeCompletionContext::CCC_ObjCCategoryName); 7834 7835 // Add all of the categories that have have corresponding interface 7836 // declarations in this class and any of its superclasses, except for 7837 // already-implemented categories in the class itself. 7838 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames; 7839 Results.EnterNewScope(); 7840 bool IgnoreImplemented = true; 7841 while (Class) { 7842 for (const auto *Cat : Class->visible_categories()) { 7843 if ((!IgnoreImplemented || !Cat->getImplementation()) && 7844 CategoryNames.insert(Cat->getIdentifier()).second) 7845 Results.AddResult(Result(Cat, Results.getBasePriority(Cat), nullptr), 7846 CurContext, nullptr, false); 7847 } 7848 7849 Class = Class->getSuperClass(); 7850 IgnoreImplemented = false; 7851 } 7852 Results.ExitScope(); 7853 7854 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 7855 Results.data(), Results.size()); 7856 } 7857 7858 void Sema::CodeCompleteObjCPropertyDefinition(Scope *S) { 7859 CodeCompletionContext CCContext(CodeCompletionContext::CCC_Other); 7860 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 7861 CodeCompleter->getCodeCompletionTUInfo(), CCContext); 7862 7863 // Figure out where this @synthesize lives. 7864 ObjCContainerDecl *Container = 7865 dyn_cast_or_null<ObjCContainerDecl>(CurContext); 7866 if (!Container || (!isa<ObjCImplementationDecl>(Container) && 7867 !isa<ObjCCategoryImplDecl>(Container))) 7868 return; 7869 7870 // Ignore any properties that have already been implemented. 7871 Container = getContainerDef(Container); 7872 for (const auto *D : Container->decls()) 7873 if (const auto *PropertyImpl = dyn_cast<ObjCPropertyImplDecl>(D)) 7874 Results.Ignore(PropertyImpl->getPropertyDecl()); 7875 7876 // Add any properties that we find. 7877 AddedPropertiesSet AddedProperties; 7878 Results.EnterNewScope(); 7879 if (ObjCImplementationDecl *ClassImpl = 7880 dyn_cast<ObjCImplementationDecl>(Container)) 7881 AddObjCProperties(CCContext, ClassImpl->getClassInterface(), false, 7882 /*AllowNullaryMethods=*/false, CurContext, 7883 AddedProperties, Results); 7884 else 7885 AddObjCProperties(CCContext, 7886 cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl(), 7887 false, /*AllowNullaryMethods=*/false, CurContext, 7888 AddedProperties, Results); 7889 Results.ExitScope(); 7890 7891 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 7892 Results.data(), Results.size()); 7893 } 7894 7895 void Sema::CodeCompleteObjCPropertySynthesizeIvar( 7896 Scope *S, IdentifierInfo *PropertyName) { 7897 typedef CodeCompletionResult Result; 7898 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 7899 CodeCompleter->getCodeCompletionTUInfo(), 7900 CodeCompletionContext::CCC_Other); 7901 7902 // Figure out where this @synthesize lives. 7903 ObjCContainerDecl *Container = 7904 dyn_cast_or_null<ObjCContainerDecl>(CurContext); 7905 if (!Container || (!isa<ObjCImplementationDecl>(Container) && 7906 !isa<ObjCCategoryImplDecl>(Container))) 7907 return; 7908 7909 // Figure out which interface we're looking into. 7910 ObjCInterfaceDecl *Class = nullptr; 7911 if (ObjCImplementationDecl *ClassImpl = 7912 dyn_cast<ObjCImplementationDecl>(Container)) 7913 Class = ClassImpl->getClassInterface(); 7914 else 7915 Class = cast<ObjCCategoryImplDecl>(Container) 7916 ->getCategoryDecl() 7917 ->getClassInterface(); 7918 7919 // Determine the type of the property we're synthesizing. 7920 QualType PropertyType = Context.getObjCIdType(); 7921 if (Class) { 7922 if (ObjCPropertyDecl *Property = Class->FindPropertyDeclaration( 7923 PropertyName, ObjCPropertyQueryKind::OBJC_PR_query_instance)) { 7924 PropertyType = 7925 Property->getType().getNonReferenceType().getUnqualifiedType(); 7926 7927 // Give preference to ivars 7928 Results.setPreferredType(PropertyType); 7929 } 7930 } 7931 7932 // Add all of the instance variables in this class and its superclasses. 7933 Results.EnterNewScope(); 7934 bool SawSimilarlyNamedIvar = false; 7935 std::string NameWithPrefix; 7936 NameWithPrefix += '_'; 7937 NameWithPrefix += PropertyName->getName(); 7938 std::string NameWithSuffix = PropertyName->getName().str(); 7939 NameWithSuffix += '_'; 7940 for (; Class; Class = Class->getSuperClass()) { 7941 for (ObjCIvarDecl *Ivar = Class->all_declared_ivar_begin(); Ivar; 7942 Ivar = Ivar->getNextIvar()) { 7943 Results.AddResult(Result(Ivar, Results.getBasePriority(Ivar), nullptr), 7944 CurContext, nullptr, false); 7945 7946 // Determine whether we've seen an ivar with a name similar to the 7947 // property. 7948 if ((PropertyName == Ivar->getIdentifier() || 7949 NameWithPrefix == Ivar->getName() || 7950 NameWithSuffix == Ivar->getName())) { 7951 SawSimilarlyNamedIvar = true; 7952 7953 // Reduce the priority of this result by one, to give it a slight 7954 // advantage over other results whose names don't match so closely. 7955 if (Results.size() && 7956 Results.data()[Results.size() - 1].Kind == 7957 CodeCompletionResult::RK_Declaration && 7958 Results.data()[Results.size() - 1].Declaration == Ivar) 7959 Results.data()[Results.size() - 1].Priority--; 7960 } 7961 } 7962 } 7963 7964 if (!SawSimilarlyNamedIvar) { 7965 // Create ivar result _propName, that the user can use to synthesize 7966 // an ivar of the appropriate type. 7967 unsigned Priority = CCP_MemberDeclaration + 1; 7968 typedef CodeCompletionResult Result; 7969 CodeCompletionAllocator &Allocator = Results.getAllocator(); 7970 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo(), 7971 Priority, CXAvailability_Available); 7972 7973 PrintingPolicy Policy = getCompletionPrintingPolicy(*this); 7974 Builder.AddResultTypeChunk( 7975 GetCompletionTypeString(PropertyType, Context, Policy, Allocator)); 7976 Builder.AddTypedTextChunk(Allocator.CopyString(NameWithPrefix)); 7977 Results.AddResult( 7978 Result(Builder.TakeString(), Priority, CXCursor_ObjCIvarDecl)); 7979 } 7980 7981 Results.ExitScope(); 7982 7983 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 7984 Results.data(), Results.size()); 7985 } 7986 7987 // Mapping from selectors to the methods that implement that selector, along 7988 // with the "in original class" flag. 7989 typedef llvm::DenseMap<Selector, 7990 llvm::PointerIntPair<ObjCMethodDecl *, 1, bool>> 7991 KnownMethodsMap; 7992 7993 /// Find all of the methods that reside in the given container 7994 /// (and its superclasses, protocols, etc.) that meet the given 7995 /// criteria. Insert those methods into the map of known methods, 7996 /// indexed by selector so they can be easily found. 7997 static void FindImplementableMethods(ASTContext &Context, 7998 ObjCContainerDecl *Container, 7999 Optional<bool> WantInstanceMethods, 8000 QualType ReturnType, 8001 KnownMethodsMap &KnownMethods, 8002 bool InOriginalClass = true) { 8003 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)) { 8004 // Make sure we have a definition; that's what we'll walk. 8005 if (!IFace->hasDefinition()) 8006 return; 8007 8008 IFace = IFace->getDefinition(); 8009 Container = IFace; 8010 8011 const ObjCList<ObjCProtocolDecl> &Protocols = 8012 IFace->getReferencedProtocols(); 8013 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(), 8014 E = Protocols.end(); 8015 I != E; ++I) 8016 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType, 8017 KnownMethods, InOriginalClass); 8018 8019 // Add methods from any class extensions and categories. 8020 for (auto *Cat : IFace->visible_categories()) { 8021 FindImplementableMethods(Context, Cat, WantInstanceMethods, ReturnType, 8022 KnownMethods, false); 8023 } 8024 8025 // Visit the superclass. 8026 if (IFace->getSuperClass()) 8027 FindImplementableMethods(Context, IFace->getSuperClass(), 8028 WantInstanceMethods, ReturnType, KnownMethods, 8029 false); 8030 } 8031 8032 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) { 8033 // Recurse into protocols. 8034 const ObjCList<ObjCProtocolDecl> &Protocols = 8035 Category->getReferencedProtocols(); 8036 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(), 8037 E = Protocols.end(); 8038 I != E; ++I) 8039 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType, 8040 KnownMethods, InOriginalClass); 8041 8042 // If this category is the original class, jump to the interface. 8043 if (InOriginalClass && Category->getClassInterface()) 8044 FindImplementableMethods(Context, Category->getClassInterface(), 8045 WantInstanceMethods, ReturnType, KnownMethods, 8046 false); 8047 } 8048 8049 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) { 8050 // Make sure we have a definition; that's what we'll walk. 8051 if (!Protocol->hasDefinition()) 8052 return; 8053 Protocol = Protocol->getDefinition(); 8054 Container = Protocol; 8055 8056 // Recurse into protocols. 8057 const ObjCList<ObjCProtocolDecl> &Protocols = 8058 Protocol->getReferencedProtocols(); 8059 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(), 8060 E = Protocols.end(); 8061 I != E; ++I) 8062 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType, 8063 KnownMethods, false); 8064 } 8065 8066 // Add methods in this container. This operation occurs last because 8067 // we want the methods from this container to override any methods 8068 // we've previously seen with the same selector. 8069 for (auto *M : Container->methods()) { 8070 if (!WantInstanceMethods || M->isInstanceMethod() == *WantInstanceMethods) { 8071 if (!ReturnType.isNull() && 8072 !Context.hasSameUnqualifiedType(ReturnType, M->getReturnType())) 8073 continue; 8074 8075 KnownMethods[M->getSelector()] = 8076 KnownMethodsMap::mapped_type(M, InOriginalClass); 8077 } 8078 } 8079 } 8080 8081 /// Add the parenthesized return or parameter type chunk to a code 8082 /// completion string. 8083 static void AddObjCPassingTypeChunk(QualType Type, unsigned ObjCDeclQuals, 8084 ASTContext &Context, 8085 const PrintingPolicy &Policy, 8086 CodeCompletionBuilder &Builder) { 8087 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 8088 std::string Quals = formatObjCParamQualifiers(ObjCDeclQuals, Type); 8089 if (!Quals.empty()) 8090 Builder.AddTextChunk(Builder.getAllocator().CopyString(Quals)); 8091 Builder.AddTextChunk( 8092 GetCompletionTypeString(Type, Context, Policy, Builder.getAllocator())); 8093 Builder.AddChunk(CodeCompletionString::CK_RightParen); 8094 } 8095 8096 /// Determine whether the given class is or inherits from a class by 8097 /// the given name. 8098 static bool InheritsFromClassNamed(ObjCInterfaceDecl *Class, StringRef Name) { 8099 if (!Class) 8100 return false; 8101 8102 if (Class->getIdentifier() && Class->getIdentifier()->getName() == Name) 8103 return true; 8104 8105 return InheritsFromClassNamed(Class->getSuperClass(), Name); 8106 } 8107 8108 /// Add code completions for Objective-C Key-Value Coding (KVC) and 8109 /// Key-Value Observing (KVO). 8110 static void AddObjCKeyValueCompletions(ObjCPropertyDecl *Property, 8111 bool IsInstanceMethod, 8112 QualType ReturnType, ASTContext &Context, 8113 VisitedSelectorSet &KnownSelectors, 8114 ResultBuilder &Results) { 8115 IdentifierInfo *PropName = Property->getIdentifier(); 8116 if (!PropName || PropName->getLength() == 0) 8117 return; 8118 8119 PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema()); 8120 8121 // Builder that will create each code completion. 8122 typedef CodeCompletionResult Result; 8123 CodeCompletionAllocator &Allocator = Results.getAllocator(); 8124 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo()); 8125 8126 // The selector table. 8127 SelectorTable &Selectors = Context.Selectors; 8128 8129 // The property name, copied into the code completion allocation region 8130 // on demand. 8131 struct KeyHolder { 8132 CodeCompletionAllocator &Allocator; 8133 StringRef Key; 8134 const char *CopiedKey; 8135 8136 KeyHolder(CodeCompletionAllocator &Allocator, StringRef Key) 8137 : Allocator(Allocator), Key(Key), CopiedKey(nullptr) {} 8138 8139 operator const char *() { 8140 if (CopiedKey) 8141 return CopiedKey; 8142 8143 return CopiedKey = Allocator.CopyString(Key); 8144 } 8145 } Key(Allocator, PropName->getName()); 8146 8147 // The uppercased name of the property name. 8148 std::string UpperKey = std::string(PropName->getName()); 8149 if (!UpperKey.empty()) 8150 UpperKey[0] = toUppercase(UpperKey[0]); 8151 8152 bool ReturnTypeMatchesProperty = 8153 ReturnType.isNull() || 8154 Context.hasSameUnqualifiedType(ReturnType.getNonReferenceType(), 8155 Property->getType()); 8156 bool ReturnTypeMatchesVoid = ReturnType.isNull() || ReturnType->isVoidType(); 8157 8158 // Add the normal accessor -(type)key. 8159 if (IsInstanceMethod && 8160 KnownSelectors.insert(Selectors.getNullarySelector(PropName)).second && 8161 ReturnTypeMatchesProperty && !Property->getGetterMethodDecl()) { 8162 if (ReturnType.isNull()) 8163 AddObjCPassingTypeChunk(Property->getType(), /*Quals=*/0, Context, Policy, 8164 Builder); 8165 8166 Builder.AddTypedTextChunk(Key); 8167 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern, 8168 CXCursor_ObjCInstanceMethodDecl)); 8169 } 8170 8171 // If we have an integral or boolean property (or the user has provided 8172 // an integral or boolean return type), add the accessor -(type)isKey. 8173 if (IsInstanceMethod && 8174 ((!ReturnType.isNull() && 8175 (ReturnType->isIntegerType() || ReturnType->isBooleanType())) || 8176 (ReturnType.isNull() && (Property->getType()->isIntegerType() || 8177 Property->getType()->isBooleanType())))) { 8178 std::string SelectorName = (Twine("is") + UpperKey).str(); 8179 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 8180 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId)) 8181 .second) { 8182 if (ReturnType.isNull()) { 8183 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 8184 Builder.AddTextChunk("BOOL"); 8185 Builder.AddChunk(CodeCompletionString::CK_RightParen); 8186 } 8187 8188 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorId->getName())); 8189 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern, 8190 CXCursor_ObjCInstanceMethodDecl)); 8191 } 8192 } 8193 8194 // Add the normal mutator. 8195 if (IsInstanceMethod && ReturnTypeMatchesVoid && 8196 !Property->getSetterMethodDecl()) { 8197 std::string SelectorName = (Twine("set") + UpperKey).str(); 8198 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 8199 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 8200 if (ReturnType.isNull()) { 8201 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 8202 Builder.AddTextChunk("void"); 8203 Builder.AddChunk(CodeCompletionString::CK_RightParen); 8204 } 8205 8206 Builder.AddTypedTextChunk( 8207 Allocator.CopyString(SelectorId->getName() + ":")); 8208 AddObjCPassingTypeChunk(Property->getType(), /*Quals=*/0, Context, Policy, 8209 Builder); 8210 Builder.AddTextChunk(Key); 8211 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern, 8212 CXCursor_ObjCInstanceMethodDecl)); 8213 } 8214 } 8215 8216 // Indexed and unordered accessors 8217 unsigned IndexedGetterPriority = CCP_CodePattern; 8218 unsigned IndexedSetterPriority = CCP_CodePattern; 8219 unsigned UnorderedGetterPriority = CCP_CodePattern; 8220 unsigned UnorderedSetterPriority = CCP_CodePattern; 8221 if (const auto *ObjCPointer = 8222 Property->getType()->getAs<ObjCObjectPointerType>()) { 8223 if (ObjCInterfaceDecl *IFace = ObjCPointer->getInterfaceDecl()) { 8224 // If this interface type is not provably derived from a known 8225 // collection, penalize the corresponding completions. 8226 if (!InheritsFromClassNamed(IFace, "NSMutableArray")) { 8227 IndexedSetterPriority += CCD_ProbablyNotObjCCollection; 8228 if (!InheritsFromClassNamed(IFace, "NSArray")) 8229 IndexedGetterPriority += CCD_ProbablyNotObjCCollection; 8230 } 8231 8232 if (!InheritsFromClassNamed(IFace, "NSMutableSet")) { 8233 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection; 8234 if (!InheritsFromClassNamed(IFace, "NSSet")) 8235 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection; 8236 } 8237 } 8238 } else { 8239 IndexedGetterPriority += CCD_ProbablyNotObjCCollection; 8240 IndexedSetterPriority += CCD_ProbablyNotObjCCollection; 8241 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection; 8242 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection; 8243 } 8244 8245 // Add -(NSUInteger)countOf<key> 8246 if (IsInstanceMethod && 8247 (ReturnType.isNull() || ReturnType->isIntegerType())) { 8248 std::string SelectorName = (Twine("countOf") + UpperKey).str(); 8249 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 8250 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId)) 8251 .second) { 8252 if (ReturnType.isNull()) { 8253 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 8254 Builder.AddTextChunk("NSUInteger"); 8255 Builder.AddChunk(CodeCompletionString::CK_RightParen); 8256 } 8257 8258 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorId->getName())); 8259 Results.AddResult( 8260 Result(Builder.TakeString(), 8261 std::min(IndexedGetterPriority, UnorderedGetterPriority), 8262 CXCursor_ObjCInstanceMethodDecl)); 8263 } 8264 } 8265 8266 // Indexed getters 8267 // Add -(id)objectInKeyAtIndex:(NSUInteger)index 8268 if (IsInstanceMethod && 8269 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) { 8270 std::string SelectorName = (Twine("objectIn") + UpperKey + "AtIndex").str(); 8271 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 8272 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 8273 if (ReturnType.isNull()) { 8274 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 8275 Builder.AddTextChunk("id"); 8276 Builder.AddChunk(CodeCompletionString::CK_RightParen); 8277 } 8278 8279 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 8280 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 8281 Builder.AddTextChunk("NSUInteger"); 8282 Builder.AddChunk(CodeCompletionString::CK_RightParen); 8283 Builder.AddTextChunk("index"); 8284 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority, 8285 CXCursor_ObjCInstanceMethodDecl)); 8286 } 8287 } 8288 8289 // Add -(NSArray *)keyAtIndexes:(NSIndexSet *)indexes 8290 if (IsInstanceMethod && 8291 (ReturnType.isNull() || 8292 (ReturnType->isObjCObjectPointerType() && 8293 ReturnType->castAs<ObjCObjectPointerType>()->getInterfaceDecl() && 8294 ReturnType->castAs<ObjCObjectPointerType>() 8295 ->getInterfaceDecl() 8296 ->getName() == "NSArray"))) { 8297 std::string SelectorName = (Twine(Property->getName()) + "AtIndexes").str(); 8298 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 8299 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 8300 if (ReturnType.isNull()) { 8301 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 8302 Builder.AddTextChunk("NSArray *"); 8303 Builder.AddChunk(CodeCompletionString::CK_RightParen); 8304 } 8305 8306 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 8307 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 8308 Builder.AddTextChunk("NSIndexSet *"); 8309 Builder.AddChunk(CodeCompletionString::CK_RightParen); 8310 Builder.AddTextChunk("indexes"); 8311 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority, 8312 CXCursor_ObjCInstanceMethodDecl)); 8313 } 8314 } 8315 8316 // Add -(void)getKey:(type **)buffer range:(NSRange)inRange 8317 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 8318 std::string SelectorName = (Twine("get") + UpperKey).str(); 8319 IdentifierInfo *SelectorIds[2] = {&Context.Idents.get(SelectorName), 8320 &Context.Idents.get("range")}; 8321 8322 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) { 8323 if (ReturnType.isNull()) { 8324 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 8325 Builder.AddTextChunk("void"); 8326 Builder.AddChunk(CodeCompletionString::CK_RightParen); 8327 } 8328 8329 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 8330 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 8331 Builder.AddPlaceholderChunk("object-type"); 8332 Builder.AddTextChunk(" **"); 8333 Builder.AddChunk(CodeCompletionString::CK_RightParen); 8334 Builder.AddTextChunk("buffer"); 8335 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 8336 Builder.AddTypedTextChunk("range:"); 8337 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 8338 Builder.AddTextChunk("NSRange"); 8339 Builder.AddChunk(CodeCompletionString::CK_RightParen); 8340 Builder.AddTextChunk("inRange"); 8341 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority, 8342 CXCursor_ObjCInstanceMethodDecl)); 8343 } 8344 } 8345 8346 // Mutable indexed accessors 8347 8348 // - (void)insertObject:(type *)object inKeyAtIndex:(NSUInteger)index 8349 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 8350 std::string SelectorName = (Twine("in") + UpperKey + "AtIndex").str(); 8351 IdentifierInfo *SelectorIds[2] = {&Context.Idents.get("insertObject"), 8352 &Context.Idents.get(SelectorName)}; 8353 8354 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) { 8355 if (ReturnType.isNull()) { 8356 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 8357 Builder.AddTextChunk("void"); 8358 Builder.AddChunk(CodeCompletionString::CK_RightParen); 8359 } 8360 8361 Builder.AddTypedTextChunk("insertObject:"); 8362 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 8363 Builder.AddPlaceholderChunk("object-type"); 8364 Builder.AddTextChunk(" *"); 8365 Builder.AddChunk(CodeCompletionString::CK_RightParen); 8366 Builder.AddTextChunk("object"); 8367 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 8368 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 8369 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 8370 Builder.AddPlaceholderChunk("NSUInteger"); 8371 Builder.AddChunk(CodeCompletionString::CK_RightParen); 8372 Builder.AddTextChunk("index"); 8373 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority, 8374 CXCursor_ObjCInstanceMethodDecl)); 8375 } 8376 } 8377 8378 // - (void)insertKey:(NSArray *)array atIndexes:(NSIndexSet *)indexes 8379 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 8380 std::string SelectorName = (Twine("insert") + UpperKey).str(); 8381 IdentifierInfo *SelectorIds[2] = {&Context.Idents.get(SelectorName), 8382 &Context.Idents.get("atIndexes")}; 8383 8384 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) { 8385 if (ReturnType.isNull()) { 8386 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 8387 Builder.AddTextChunk("void"); 8388 Builder.AddChunk(CodeCompletionString::CK_RightParen); 8389 } 8390 8391 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 8392 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 8393 Builder.AddTextChunk("NSArray *"); 8394 Builder.AddChunk(CodeCompletionString::CK_RightParen); 8395 Builder.AddTextChunk("array"); 8396 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 8397 Builder.AddTypedTextChunk("atIndexes:"); 8398 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 8399 Builder.AddPlaceholderChunk("NSIndexSet *"); 8400 Builder.AddChunk(CodeCompletionString::CK_RightParen); 8401 Builder.AddTextChunk("indexes"); 8402 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority, 8403 CXCursor_ObjCInstanceMethodDecl)); 8404 } 8405 } 8406 8407 // -(void)removeObjectFromKeyAtIndex:(NSUInteger)index 8408 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 8409 std::string SelectorName = 8410 (Twine("removeObjectFrom") + UpperKey + "AtIndex").str(); 8411 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 8412 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 8413 if (ReturnType.isNull()) { 8414 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 8415 Builder.AddTextChunk("void"); 8416 Builder.AddChunk(CodeCompletionString::CK_RightParen); 8417 } 8418 8419 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 8420 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 8421 Builder.AddTextChunk("NSUInteger"); 8422 Builder.AddChunk(CodeCompletionString::CK_RightParen); 8423 Builder.AddTextChunk("index"); 8424 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority, 8425 CXCursor_ObjCInstanceMethodDecl)); 8426 } 8427 } 8428 8429 // -(void)removeKeyAtIndexes:(NSIndexSet *)indexes 8430 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 8431 std::string SelectorName = (Twine("remove") + UpperKey + "AtIndexes").str(); 8432 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 8433 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 8434 if (ReturnType.isNull()) { 8435 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 8436 Builder.AddTextChunk("void"); 8437 Builder.AddChunk(CodeCompletionString::CK_RightParen); 8438 } 8439 8440 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 8441 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 8442 Builder.AddTextChunk("NSIndexSet *"); 8443 Builder.AddChunk(CodeCompletionString::CK_RightParen); 8444 Builder.AddTextChunk("indexes"); 8445 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority, 8446 CXCursor_ObjCInstanceMethodDecl)); 8447 } 8448 } 8449 8450 // - (void)replaceObjectInKeyAtIndex:(NSUInteger)index withObject:(id)object 8451 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 8452 std::string SelectorName = 8453 (Twine("replaceObjectIn") + UpperKey + "AtIndex").str(); 8454 IdentifierInfo *SelectorIds[2] = {&Context.Idents.get(SelectorName), 8455 &Context.Idents.get("withObject")}; 8456 8457 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) { 8458 if (ReturnType.isNull()) { 8459 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 8460 Builder.AddTextChunk("void"); 8461 Builder.AddChunk(CodeCompletionString::CK_RightParen); 8462 } 8463 8464 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 8465 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 8466 Builder.AddPlaceholderChunk("NSUInteger"); 8467 Builder.AddChunk(CodeCompletionString::CK_RightParen); 8468 Builder.AddTextChunk("index"); 8469 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 8470 Builder.AddTypedTextChunk("withObject:"); 8471 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 8472 Builder.AddTextChunk("id"); 8473 Builder.AddChunk(CodeCompletionString::CK_RightParen); 8474 Builder.AddTextChunk("object"); 8475 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority, 8476 CXCursor_ObjCInstanceMethodDecl)); 8477 } 8478 } 8479 8480 // - (void)replaceKeyAtIndexes:(NSIndexSet *)indexes withKey:(NSArray *)array 8481 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 8482 std::string SelectorName1 = 8483 (Twine("replace") + UpperKey + "AtIndexes").str(); 8484 std::string SelectorName2 = (Twine("with") + UpperKey).str(); 8485 IdentifierInfo *SelectorIds[2] = {&Context.Idents.get(SelectorName1), 8486 &Context.Idents.get(SelectorName2)}; 8487 8488 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) { 8489 if (ReturnType.isNull()) { 8490 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 8491 Builder.AddTextChunk("void"); 8492 Builder.AddChunk(CodeCompletionString::CK_RightParen); 8493 } 8494 8495 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName1 + ":")); 8496 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 8497 Builder.AddPlaceholderChunk("NSIndexSet *"); 8498 Builder.AddChunk(CodeCompletionString::CK_RightParen); 8499 Builder.AddTextChunk("indexes"); 8500 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 8501 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName2 + ":")); 8502 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 8503 Builder.AddTextChunk("NSArray *"); 8504 Builder.AddChunk(CodeCompletionString::CK_RightParen); 8505 Builder.AddTextChunk("array"); 8506 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority, 8507 CXCursor_ObjCInstanceMethodDecl)); 8508 } 8509 } 8510 8511 // Unordered getters 8512 // - (NSEnumerator *)enumeratorOfKey 8513 if (IsInstanceMethod && 8514 (ReturnType.isNull() || 8515 (ReturnType->isObjCObjectPointerType() && 8516 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() && 8517 ReturnType->getAs<ObjCObjectPointerType>() 8518 ->getInterfaceDecl() 8519 ->getName() == "NSEnumerator"))) { 8520 std::string SelectorName = (Twine("enumeratorOf") + UpperKey).str(); 8521 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 8522 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId)) 8523 .second) { 8524 if (ReturnType.isNull()) { 8525 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 8526 Builder.AddTextChunk("NSEnumerator *"); 8527 Builder.AddChunk(CodeCompletionString::CK_RightParen); 8528 } 8529 8530 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName)); 8531 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority, 8532 CXCursor_ObjCInstanceMethodDecl)); 8533 } 8534 } 8535 8536 // - (type *)memberOfKey:(type *)object 8537 if (IsInstanceMethod && 8538 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) { 8539 std::string SelectorName = (Twine("memberOf") + UpperKey).str(); 8540 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 8541 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 8542 if (ReturnType.isNull()) { 8543 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 8544 Builder.AddPlaceholderChunk("object-type"); 8545 Builder.AddTextChunk(" *"); 8546 Builder.AddChunk(CodeCompletionString::CK_RightParen); 8547 } 8548 8549 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 8550 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 8551 if (ReturnType.isNull()) { 8552 Builder.AddPlaceholderChunk("object-type"); 8553 Builder.AddTextChunk(" *"); 8554 } else { 8555 Builder.AddTextChunk(GetCompletionTypeString( 8556 ReturnType, Context, Policy, Builder.getAllocator())); 8557 } 8558 Builder.AddChunk(CodeCompletionString::CK_RightParen); 8559 Builder.AddTextChunk("object"); 8560 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority, 8561 CXCursor_ObjCInstanceMethodDecl)); 8562 } 8563 } 8564 8565 // Mutable unordered accessors 8566 // - (void)addKeyObject:(type *)object 8567 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 8568 std::string SelectorName = 8569 (Twine("add") + UpperKey + Twine("Object")).str(); 8570 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 8571 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 8572 if (ReturnType.isNull()) { 8573 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 8574 Builder.AddTextChunk("void"); 8575 Builder.AddChunk(CodeCompletionString::CK_RightParen); 8576 } 8577 8578 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 8579 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 8580 Builder.AddPlaceholderChunk("object-type"); 8581 Builder.AddTextChunk(" *"); 8582 Builder.AddChunk(CodeCompletionString::CK_RightParen); 8583 Builder.AddTextChunk("object"); 8584 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority, 8585 CXCursor_ObjCInstanceMethodDecl)); 8586 } 8587 } 8588 8589 // - (void)addKey:(NSSet *)objects 8590 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 8591 std::string SelectorName = (Twine("add") + UpperKey).str(); 8592 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 8593 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 8594 if (ReturnType.isNull()) { 8595 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 8596 Builder.AddTextChunk("void"); 8597 Builder.AddChunk(CodeCompletionString::CK_RightParen); 8598 } 8599 8600 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 8601 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 8602 Builder.AddTextChunk("NSSet *"); 8603 Builder.AddChunk(CodeCompletionString::CK_RightParen); 8604 Builder.AddTextChunk("objects"); 8605 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority, 8606 CXCursor_ObjCInstanceMethodDecl)); 8607 } 8608 } 8609 8610 // - (void)removeKeyObject:(type *)object 8611 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 8612 std::string SelectorName = 8613 (Twine("remove") + UpperKey + Twine("Object")).str(); 8614 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 8615 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 8616 if (ReturnType.isNull()) { 8617 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 8618 Builder.AddTextChunk("void"); 8619 Builder.AddChunk(CodeCompletionString::CK_RightParen); 8620 } 8621 8622 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 8623 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 8624 Builder.AddPlaceholderChunk("object-type"); 8625 Builder.AddTextChunk(" *"); 8626 Builder.AddChunk(CodeCompletionString::CK_RightParen); 8627 Builder.AddTextChunk("object"); 8628 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority, 8629 CXCursor_ObjCInstanceMethodDecl)); 8630 } 8631 } 8632 8633 // - (void)removeKey:(NSSet *)objects 8634 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 8635 std::string SelectorName = (Twine("remove") + UpperKey).str(); 8636 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 8637 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 8638 if (ReturnType.isNull()) { 8639 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 8640 Builder.AddTextChunk("void"); 8641 Builder.AddChunk(CodeCompletionString::CK_RightParen); 8642 } 8643 8644 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 8645 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 8646 Builder.AddTextChunk("NSSet *"); 8647 Builder.AddChunk(CodeCompletionString::CK_RightParen); 8648 Builder.AddTextChunk("objects"); 8649 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority, 8650 CXCursor_ObjCInstanceMethodDecl)); 8651 } 8652 } 8653 8654 // - (void)intersectKey:(NSSet *)objects 8655 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 8656 std::string SelectorName = (Twine("intersect") + UpperKey).str(); 8657 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 8658 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 8659 if (ReturnType.isNull()) { 8660 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 8661 Builder.AddTextChunk("void"); 8662 Builder.AddChunk(CodeCompletionString::CK_RightParen); 8663 } 8664 8665 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 8666 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 8667 Builder.AddTextChunk("NSSet *"); 8668 Builder.AddChunk(CodeCompletionString::CK_RightParen); 8669 Builder.AddTextChunk("objects"); 8670 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority, 8671 CXCursor_ObjCInstanceMethodDecl)); 8672 } 8673 } 8674 8675 // Key-Value Observing 8676 // + (NSSet *)keyPathsForValuesAffectingKey 8677 if (!IsInstanceMethod && 8678 (ReturnType.isNull() || 8679 (ReturnType->isObjCObjectPointerType() && 8680 ReturnType->castAs<ObjCObjectPointerType>()->getInterfaceDecl() && 8681 ReturnType->castAs<ObjCObjectPointerType>() 8682 ->getInterfaceDecl() 8683 ->getName() == "NSSet"))) { 8684 std::string SelectorName = 8685 (Twine("keyPathsForValuesAffecting") + UpperKey).str(); 8686 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 8687 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId)) 8688 .second) { 8689 if (ReturnType.isNull()) { 8690 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 8691 Builder.AddTextChunk("NSSet<NSString *> *"); 8692 Builder.AddChunk(CodeCompletionString::CK_RightParen); 8693 } 8694 8695 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName)); 8696 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern, 8697 CXCursor_ObjCClassMethodDecl)); 8698 } 8699 } 8700 8701 // + (BOOL)automaticallyNotifiesObserversForKey 8702 if (!IsInstanceMethod && 8703 (ReturnType.isNull() || ReturnType->isIntegerType() || 8704 ReturnType->isBooleanType())) { 8705 std::string SelectorName = 8706 (Twine("automaticallyNotifiesObserversOf") + UpperKey).str(); 8707 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 8708 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId)) 8709 .second) { 8710 if (ReturnType.isNull()) { 8711 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 8712 Builder.AddTextChunk("BOOL"); 8713 Builder.AddChunk(CodeCompletionString::CK_RightParen); 8714 } 8715 8716 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName)); 8717 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern, 8718 CXCursor_ObjCClassMethodDecl)); 8719 } 8720 } 8721 } 8722 8723 void Sema::CodeCompleteObjCMethodDecl(Scope *S, Optional<bool> IsInstanceMethod, 8724 ParsedType ReturnTy) { 8725 // Determine the return type of the method we're declaring, if 8726 // provided. 8727 QualType ReturnType = GetTypeFromParser(ReturnTy); 8728 Decl *IDecl = nullptr; 8729 if (CurContext->isObjCContainer()) { 8730 ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext); 8731 IDecl = OCD; 8732 } 8733 // Determine where we should start searching for methods. 8734 ObjCContainerDecl *SearchDecl = nullptr; 8735 bool IsInImplementation = false; 8736 if (Decl *D = IDecl) { 8737 if (ObjCImplementationDecl *Impl = dyn_cast<ObjCImplementationDecl>(D)) { 8738 SearchDecl = Impl->getClassInterface(); 8739 IsInImplementation = true; 8740 } else if (ObjCCategoryImplDecl *CatImpl = 8741 dyn_cast<ObjCCategoryImplDecl>(D)) { 8742 SearchDecl = CatImpl->getCategoryDecl(); 8743 IsInImplementation = true; 8744 } else 8745 SearchDecl = dyn_cast<ObjCContainerDecl>(D); 8746 } 8747 8748 if (!SearchDecl && S) { 8749 if (DeclContext *DC = S->getEntity()) 8750 SearchDecl = dyn_cast<ObjCContainerDecl>(DC); 8751 } 8752 8753 if (!SearchDecl) { 8754 HandleCodeCompleteResults(this, CodeCompleter, 8755 CodeCompletionContext::CCC_Other, nullptr, 0); 8756 return; 8757 } 8758 8759 // Find all of the methods that we could declare/implement here. 8760 KnownMethodsMap KnownMethods; 8761 FindImplementableMethods(Context, SearchDecl, IsInstanceMethod, ReturnType, 8762 KnownMethods); 8763 8764 // Add declarations or definitions for each of the known methods. 8765 typedef CodeCompletionResult Result; 8766 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 8767 CodeCompleter->getCodeCompletionTUInfo(), 8768 CodeCompletionContext::CCC_Other); 8769 Results.EnterNewScope(); 8770 PrintingPolicy Policy = getCompletionPrintingPolicy(*this); 8771 for (KnownMethodsMap::iterator M = KnownMethods.begin(), 8772 MEnd = KnownMethods.end(); 8773 M != MEnd; ++M) { 8774 ObjCMethodDecl *Method = M->second.getPointer(); 8775 CodeCompletionBuilder Builder(Results.getAllocator(), 8776 Results.getCodeCompletionTUInfo()); 8777 8778 // Add the '-'/'+' prefix if it wasn't provided yet. 8779 if (!IsInstanceMethod) { 8780 Builder.AddTextChunk(Method->isInstanceMethod() ? "-" : "+"); 8781 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 8782 } 8783 8784 // If the result type was not already provided, add it to the 8785 // pattern as (type). 8786 if (ReturnType.isNull()) { 8787 QualType ResTy = Method->getSendResultType().stripObjCKindOfType(Context); 8788 AttributedType::stripOuterNullability(ResTy); 8789 AddObjCPassingTypeChunk(ResTy, Method->getObjCDeclQualifier(), Context, 8790 Policy, Builder); 8791 } 8792 8793 Selector Sel = Method->getSelector(); 8794 8795 if (Sel.isUnarySelector()) { 8796 // Unary selectors have no arguments. 8797 Builder.AddTypedTextChunk( 8798 Builder.getAllocator().CopyString(Sel.getNameForSlot(0))); 8799 } else { 8800 // Add all parameters to the pattern. 8801 unsigned I = 0; 8802 for (ObjCMethodDecl::param_iterator P = Method->param_begin(), 8803 PEnd = Method->param_end(); 8804 P != PEnd; (void)++P, ++I) { 8805 // Add the part of the selector name. 8806 if (I == 0) 8807 Builder.AddTypedTextChunk( 8808 Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":")); 8809 else if (I < Sel.getNumArgs()) { 8810 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 8811 Builder.AddTypedTextChunk( 8812 Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":")); 8813 } else 8814 break; 8815 8816 // Add the parameter type. 8817 QualType ParamType; 8818 if ((*P)->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 8819 ParamType = (*P)->getType(); 8820 else 8821 ParamType = (*P)->getOriginalType(); 8822 ParamType = ParamType.substObjCTypeArgs( 8823 Context, {}, ObjCSubstitutionContext::Parameter); 8824 AttributedType::stripOuterNullability(ParamType); 8825 AddObjCPassingTypeChunk(ParamType, (*P)->getObjCDeclQualifier(), 8826 Context, Policy, Builder); 8827 8828 if (IdentifierInfo *Id = (*P)->getIdentifier()) 8829 Builder.AddTextChunk( 8830 Builder.getAllocator().CopyString(Id->getName())); 8831 } 8832 } 8833 8834 if (Method->isVariadic()) { 8835 if (Method->param_size() > 0) 8836 Builder.AddChunk(CodeCompletionString::CK_Comma); 8837 Builder.AddTextChunk("..."); 8838 } 8839 8840 if (IsInImplementation && Results.includeCodePatterns()) { 8841 // We will be defining the method here, so add a compound statement. 8842 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 8843 Builder.AddChunk(CodeCompletionString::CK_LeftBrace); 8844 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); 8845 if (!Method->getReturnType()->isVoidType()) { 8846 // If the result type is not void, add a return clause. 8847 Builder.AddTextChunk("return"); 8848 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 8849 Builder.AddPlaceholderChunk("expression"); 8850 Builder.AddChunk(CodeCompletionString::CK_SemiColon); 8851 } else 8852 Builder.AddPlaceholderChunk("statements"); 8853 8854 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); 8855 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 8856 } 8857 8858 unsigned Priority = CCP_CodePattern; 8859 auto R = Result(Builder.TakeString(), Method, Priority); 8860 if (!M->second.getInt()) 8861 setInBaseClass(R); 8862 Results.AddResult(std::move(R)); 8863 } 8864 8865 // Add Key-Value-Coding and Key-Value-Observing accessor methods for all of 8866 // the properties in this class and its categories. 8867 if (Context.getLangOpts().ObjC) { 8868 SmallVector<ObjCContainerDecl *, 4> Containers; 8869 Containers.push_back(SearchDecl); 8870 8871 VisitedSelectorSet KnownSelectors; 8872 for (KnownMethodsMap::iterator M = KnownMethods.begin(), 8873 MEnd = KnownMethods.end(); 8874 M != MEnd; ++M) 8875 KnownSelectors.insert(M->first); 8876 8877 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(SearchDecl); 8878 if (!IFace) 8879 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(SearchDecl)) 8880 IFace = Category->getClassInterface(); 8881 8882 if (IFace) 8883 for (auto *Cat : IFace->visible_categories()) 8884 Containers.push_back(Cat); 8885 8886 if (IsInstanceMethod) { 8887 for (unsigned I = 0, N = Containers.size(); I != N; ++I) 8888 for (auto *P : Containers[I]->instance_properties()) 8889 AddObjCKeyValueCompletions(P, *IsInstanceMethod, ReturnType, Context, 8890 KnownSelectors, Results); 8891 } 8892 } 8893 8894 Results.ExitScope(); 8895 8896 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 8897 Results.data(), Results.size()); 8898 } 8899 8900 void Sema::CodeCompleteObjCMethodDeclSelector( 8901 Scope *S, bool IsInstanceMethod, bool AtParameterName, ParsedType ReturnTy, 8902 ArrayRef<IdentifierInfo *> SelIdents) { 8903 // If we have an external source, load the entire class method 8904 // pool from the AST file. 8905 if (ExternalSource) { 8906 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors(); I != N; 8907 ++I) { 8908 Selector Sel = ExternalSource->GetExternalSelector(I); 8909 if (Sel.isNull() || MethodPool.count(Sel)) 8910 continue; 8911 8912 ReadMethodPool(Sel); 8913 } 8914 } 8915 8916 // Build the set of methods we can see. 8917 typedef CodeCompletionResult Result; 8918 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 8919 CodeCompleter->getCodeCompletionTUInfo(), 8920 CodeCompletionContext::CCC_Other); 8921 8922 if (ReturnTy) 8923 Results.setPreferredType(GetTypeFromParser(ReturnTy).getNonReferenceType()); 8924 8925 Results.EnterNewScope(); 8926 for (GlobalMethodPool::iterator M = MethodPool.begin(), 8927 MEnd = MethodPool.end(); 8928 M != MEnd; ++M) { 8929 for (ObjCMethodList *MethList = IsInstanceMethod ? &M->second.first 8930 : &M->second.second; 8931 MethList && MethList->getMethod(); MethList = MethList->getNext()) { 8932 if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents)) 8933 continue; 8934 8935 if (AtParameterName) { 8936 // Suggest parameter names we've seen before. 8937 unsigned NumSelIdents = SelIdents.size(); 8938 if (NumSelIdents && 8939 NumSelIdents <= MethList->getMethod()->param_size()) { 8940 ParmVarDecl *Param = 8941 MethList->getMethod()->parameters()[NumSelIdents - 1]; 8942 if (Param->getIdentifier()) { 8943 CodeCompletionBuilder Builder(Results.getAllocator(), 8944 Results.getCodeCompletionTUInfo()); 8945 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString( 8946 Param->getIdentifier()->getName())); 8947 Results.AddResult(Builder.TakeString()); 8948 } 8949 } 8950 8951 continue; 8952 } 8953 8954 Result R(MethList->getMethod(), 8955 Results.getBasePriority(MethList->getMethod()), nullptr); 8956 R.StartParameter = SelIdents.size(); 8957 R.AllParametersAreInformative = false; 8958 R.DeclaringEntity = true; 8959 Results.MaybeAddResult(R, CurContext); 8960 } 8961 } 8962 8963 Results.ExitScope(); 8964 8965 if (!AtParameterName && !SelIdents.empty() && 8966 SelIdents.front()->getName().startswith("init")) { 8967 for (const auto &M : PP.macros()) { 8968 if (M.first->getName() != "NS_DESIGNATED_INITIALIZER") 8969 continue; 8970 Results.EnterNewScope(); 8971 CodeCompletionBuilder Builder(Results.getAllocator(), 8972 Results.getCodeCompletionTUInfo()); 8973 Builder.AddTypedTextChunk( 8974 Builder.getAllocator().CopyString(M.first->getName())); 8975 Results.AddResult(CodeCompletionResult(Builder.TakeString(), CCP_Macro, 8976 CXCursor_MacroDefinition)); 8977 Results.ExitScope(); 8978 } 8979 } 8980 8981 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 8982 Results.data(), Results.size()); 8983 } 8984 8985 void Sema::CodeCompletePreprocessorDirective(bool InConditional) { 8986 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 8987 CodeCompleter->getCodeCompletionTUInfo(), 8988 CodeCompletionContext::CCC_PreprocessorDirective); 8989 Results.EnterNewScope(); 8990 8991 // #if <condition> 8992 CodeCompletionBuilder Builder(Results.getAllocator(), 8993 Results.getCodeCompletionTUInfo()); 8994 Builder.AddTypedTextChunk("if"); 8995 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 8996 Builder.AddPlaceholderChunk("condition"); 8997 Results.AddResult(Builder.TakeString()); 8998 8999 // #ifdef <macro> 9000 Builder.AddTypedTextChunk("ifdef"); 9001 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 9002 Builder.AddPlaceholderChunk("macro"); 9003 Results.AddResult(Builder.TakeString()); 9004 9005 // #ifndef <macro> 9006 Builder.AddTypedTextChunk("ifndef"); 9007 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 9008 Builder.AddPlaceholderChunk("macro"); 9009 Results.AddResult(Builder.TakeString()); 9010 9011 if (InConditional) { 9012 // #elif <condition> 9013 Builder.AddTypedTextChunk("elif"); 9014 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 9015 Builder.AddPlaceholderChunk("condition"); 9016 Results.AddResult(Builder.TakeString()); 9017 9018 // #else 9019 Builder.AddTypedTextChunk("else"); 9020 Results.AddResult(Builder.TakeString()); 9021 9022 // #endif 9023 Builder.AddTypedTextChunk("endif"); 9024 Results.AddResult(Builder.TakeString()); 9025 } 9026 9027 // #include "header" 9028 Builder.AddTypedTextChunk("include"); 9029 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 9030 Builder.AddTextChunk("\""); 9031 Builder.AddPlaceholderChunk("header"); 9032 Builder.AddTextChunk("\""); 9033 Results.AddResult(Builder.TakeString()); 9034 9035 // #include <header> 9036 Builder.AddTypedTextChunk("include"); 9037 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 9038 Builder.AddTextChunk("<"); 9039 Builder.AddPlaceholderChunk("header"); 9040 Builder.AddTextChunk(">"); 9041 Results.AddResult(Builder.TakeString()); 9042 9043 // #define <macro> 9044 Builder.AddTypedTextChunk("define"); 9045 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 9046 Builder.AddPlaceholderChunk("macro"); 9047 Results.AddResult(Builder.TakeString()); 9048 9049 // #define <macro>(<args>) 9050 Builder.AddTypedTextChunk("define"); 9051 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 9052 Builder.AddPlaceholderChunk("macro"); 9053 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 9054 Builder.AddPlaceholderChunk("args"); 9055 Builder.AddChunk(CodeCompletionString::CK_RightParen); 9056 Results.AddResult(Builder.TakeString()); 9057 9058 // #undef <macro> 9059 Builder.AddTypedTextChunk("undef"); 9060 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 9061 Builder.AddPlaceholderChunk("macro"); 9062 Results.AddResult(Builder.TakeString()); 9063 9064 // #line <number> 9065 Builder.AddTypedTextChunk("line"); 9066 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 9067 Builder.AddPlaceholderChunk("number"); 9068 Results.AddResult(Builder.TakeString()); 9069 9070 // #line <number> "filename" 9071 Builder.AddTypedTextChunk("line"); 9072 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 9073 Builder.AddPlaceholderChunk("number"); 9074 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 9075 Builder.AddTextChunk("\""); 9076 Builder.AddPlaceholderChunk("filename"); 9077 Builder.AddTextChunk("\""); 9078 Results.AddResult(Builder.TakeString()); 9079 9080 // #error <message> 9081 Builder.AddTypedTextChunk("error"); 9082 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 9083 Builder.AddPlaceholderChunk("message"); 9084 Results.AddResult(Builder.TakeString()); 9085 9086 // #pragma <arguments> 9087 Builder.AddTypedTextChunk("pragma"); 9088 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 9089 Builder.AddPlaceholderChunk("arguments"); 9090 Results.AddResult(Builder.TakeString()); 9091 9092 if (getLangOpts().ObjC) { 9093 // #import "header" 9094 Builder.AddTypedTextChunk("import"); 9095 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 9096 Builder.AddTextChunk("\""); 9097 Builder.AddPlaceholderChunk("header"); 9098 Builder.AddTextChunk("\""); 9099 Results.AddResult(Builder.TakeString()); 9100 9101 // #import <header> 9102 Builder.AddTypedTextChunk("import"); 9103 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 9104 Builder.AddTextChunk("<"); 9105 Builder.AddPlaceholderChunk("header"); 9106 Builder.AddTextChunk(">"); 9107 Results.AddResult(Builder.TakeString()); 9108 } 9109 9110 // #include_next "header" 9111 Builder.AddTypedTextChunk("include_next"); 9112 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 9113 Builder.AddTextChunk("\""); 9114 Builder.AddPlaceholderChunk("header"); 9115 Builder.AddTextChunk("\""); 9116 Results.AddResult(Builder.TakeString()); 9117 9118 // #include_next <header> 9119 Builder.AddTypedTextChunk("include_next"); 9120 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 9121 Builder.AddTextChunk("<"); 9122 Builder.AddPlaceholderChunk("header"); 9123 Builder.AddTextChunk(">"); 9124 Results.AddResult(Builder.TakeString()); 9125 9126 // #warning <message> 9127 Builder.AddTypedTextChunk("warning"); 9128 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 9129 Builder.AddPlaceholderChunk("message"); 9130 Results.AddResult(Builder.TakeString()); 9131 9132 // Note: #ident and #sccs are such crazy anachronisms that we don't provide 9133 // completions for them. And __include_macros is a Clang-internal extension 9134 // that we don't want to encourage anyone to use. 9135 9136 // FIXME: we don't support #assert or #unassert, so don't suggest them. 9137 Results.ExitScope(); 9138 9139 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 9140 Results.data(), Results.size()); 9141 } 9142 9143 void Sema::CodeCompleteInPreprocessorConditionalExclusion(Scope *S) { 9144 CodeCompleteOrdinaryName(S, S->getFnParent() ? Sema::PCC_RecoveryInFunction 9145 : Sema::PCC_Namespace); 9146 } 9147 9148 void Sema::CodeCompletePreprocessorMacroName(bool IsDefinition) { 9149 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 9150 CodeCompleter->getCodeCompletionTUInfo(), 9151 IsDefinition ? CodeCompletionContext::CCC_MacroName 9152 : CodeCompletionContext::CCC_MacroNameUse); 9153 if (!IsDefinition && (!CodeCompleter || CodeCompleter->includeMacros())) { 9154 // Add just the names of macros, not their arguments. 9155 CodeCompletionBuilder Builder(Results.getAllocator(), 9156 Results.getCodeCompletionTUInfo()); 9157 Results.EnterNewScope(); 9158 for (Preprocessor::macro_iterator M = PP.macro_begin(), 9159 MEnd = PP.macro_end(); 9160 M != MEnd; ++M) { 9161 Builder.AddTypedTextChunk( 9162 Builder.getAllocator().CopyString(M->first->getName())); 9163 Results.AddResult(CodeCompletionResult( 9164 Builder.TakeString(), CCP_CodePattern, CXCursor_MacroDefinition)); 9165 } 9166 Results.ExitScope(); 9167 } else if (IsDefinition) { 9168 // FIXME: Can we detect when the user just wrote an include guard above? 9169 } 9170 9171 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 9172 Results.data(), Results.size()); 9173 } 9174 9175 void Sema::CodeCompletePreprocessorExpression() { 9176 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 9177 CodeCompleter->getCodeCompletionTUInfo(), 9178 CodeCompletionContext::CCC_PreprocessorExpression); 9179 9180 if (!CodeCompleter || CodeCompleter->includeMacros()) 9181 AddMacroResults(PP, Results, 9182 !CodeCompleter || CodeCompleter->loadExternal(), true); 9183 9184 // defined (<macro>) 9185 Results.EnterNewScope(); 9186 CodeCompletionBuilder Builder(Results.getAllocator(), 9187 Results.getCodeCompletionTUInfo()); 9188 Builder.AddTypedTextChunk("defined"); 9189 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 9190 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 9191 Builder.AddPlaceholderChunk("macro"); 9192 Builder.AddChunk(CodeCompletionString::CK_RightParen); 9193 Results.AddResult(Builder.TakeString()); 9194 Results.ExitScope(); 9195 9196 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 9197 Results.data(), Results.size()); 9198 } 9199 9200 void Sema::CodeCompletePreprocessorMacroArgument(Scope *S, 9201 IdentifierInfo *Macro, 9202 MacroInfo *MacroInfo, 9203 unsigned Argument) { 9204 // FIXME: In the future, we could provide "overload" results, much like we 9205 // do for function calls. 9206 9207 // Now just ignore this. There will be another code-completion callback 9208 // for the expanded tokens. 9209 } 9210 9211 // This handles completion inside an #include filename, e.g. #include <foo/ba 9212 // We look for the directory "foo" under each directory on the include path, 9213 // list its files, and reassemble the appropriate #include. 9214 void Sema::CodeCompleteIncludedFile(llvm::StringRef Dir, bool Angled) { 9215 // RelDir should use /, but unescaped \ is possible on windows! 9216 // Our completions will normalize to / for simplicity, this case is rare. 9217 std::string RelDir = llvm::sys::path::convert_to_slash(Dir); 9218 // We need the native slashes for the actual file system interactions. 9219 SmallString<128> NativeRelDir = StringRef(RelDir); 9220 llvm::sys::path::native(NativeRelDir); 9221 llvm::vfs::FileSystem &FS = 9222 getSourceManager().getFileManager().getVirtualFileSystem(); 9223 9224 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 9225 CodeCompleter->getCodeCompletionTUInfo(), 9226 CodeCompletionContext::CCC_IncludedFile); 9227 llvm::DenseSet<StringRef> SeenResults; // To deduplicate results. 9228 9229 // Helper: adds one file or directory completion result. 9230 auto AddCompletion = [&](StringRef Filename, bool IsDirectory) { 9231 SmallString<64> TypedChunk = Filename; 9232 // Directory completion is up to the slash, e.g. <sys/ 9233 TypedChunk.push_back(IsDirectory ? '/' : Angled ? '>' : '"'); 9234 auto R = SeenResults.insert(TypedChunk); 9235 if (R.second) { // New completion 9236 const char *InternedTyped = Results.getAllocator().CopyString(TypedChunk); 9237 *R.first = InternedTyped; // Avoid dangling StringRef. 9238 CodeCompletionBuilder Builder(CodeCompleter->getAllocator(), 9239 CodeCompleter->getCodeCompletionTUInfo()); 9240 Builder.AddTypedTextChunk(InternedTyped); 9241 // The result is a "Pattern", which is pretty opaque. 9242 // We may want to include the real filename to allow smart ranking. 9243 Results.AddResult(CodeCompletionResult(Builder.TakeString())); 9244 } 9245 }; 9246 9247 // Helper: scans IncludeDir for nice files, and adds results for each. 9248 auto AddFilesFromIncludeDir = [&](StringRef IncludeDir, 9249 bool IsSystem, 9250 DirectoryLookup::LookupType_t LookupType) { 9251 llvm::SmallString<128> Dir = IncludeDir; 9252 if (!NativeRelDir.empty()) { 9253 if (LookupType == DirectoryLookup::LT_Framework) { 9254 // For a framework dir, #include <Foo/Bar/> actually maps to 9255 // a path of Foo.framework/Headers/Bar/. 9256 auto Begin = llvm::sys::path::begin(NativeRelDir); 9257 auto End = llvm::sys::path::end(NativeRelDir); 9258 9259 llvm::sys::path::append(Dir, *Begin + ".framework", "Headers"); 9260 llvm::sys::path::append(Dir, ++Begin, End); 9261 } else { 9262 llvm::sys::path::append(Dir, NativeRelDir); 9263 } 9264 } 9265 9266 std::error_code EC; 9267 unsigned Count = 0; 9268 for (auto It = FS.dir_begin(Dir, EC); 9269 !EC && It != llvm::vfs::directory_iterator(); It.increment(EC)) { 9270 if (++Count == 2500) // If we happen to hit a huge directory, 9271 break; // bail out early so we're not too slow. 9272 StringRef Filename = llvm::sys::path::filename(It->path()); 9273 9274 // To know whether a symlink should be treated as file or a directory, we 9275 // have to stat it. This should be cheap enough as there shouldn't be many 9276 // symlinks. 9277 llvm::sys::fs::file_type Type = It->type(); 9278 if (Type == llvm::sys::fs::file_type::symlink_file) { 9279 if (auto FileStatus = FS.status(It->path())) 9280 Type = FileStatus->getType(); 9281 } 9282 switch (Type) { 9283 case llvm::sys::fs::file_type::directory_file: 9284 // All entries in a framework directory must have a ".framework" suffix, 9285 // but the suffix does not appear in the source code's include/import. 9286 if (LookupType == DirectoryLookup::LT_Framework && 9287 NativeRelDir.empty() && !Filename.consume_back(".framework")) 9288 break; 9289 9290 AddCompletion(Filename, /*IsDirectory=*/true); 9291 break; 9292 case llvm::sys::fs::file_type::regular_file: 9293 // Only files that really look like headers. (Except in system dirs). 9294 if (!IsSystem) { 9295 // Header extensions from Types.def, which we can't depend on here. 9296 if (!(Filename.endswith_lower(".h") || 9297 Filename.endswith_lower(".hh") || 9298 Filename.endswith_lower(".hpp") || 9299 Filename.endswith_lower(".inc"))) 9300 break; 9301 } 9302 AddCompletion(Filename, /*IsDirectory=*/false); 9303 break; 9304 default: 9305 break; 9306 } 9307 } 9308 }; 9309 9310 // Helper: adds results relative to IncludeDir, if possible. 9311 auto AddFilesFromDirLookup = [&](const DirectoryLookup &IncludeDir, 9312 bool IsSystem) { 9313 switch (IncludeDir.getLookupType()) { 9314 case DirectoryLookup::LT_HeaderMap: 9315 // header maps are not (currently) enumerable. 9316 break; 9317 case DirectoryLookup::LT_NormalDir: 9318 AddFilesFromIncludeDir(IncludeDir.getDir()->getName(), IsSystem, 9319 DirectoryLookup::LT_NormalDir); 9320 break; 9321 case DirectoryLookup::LT_Framework: 9322 AddFilesFromIncludeDir(IncludeDir.getFrameworkDir()->getName(), IsSystem, 9323 DirectoryLookup::LT_Framework); 9324 break; 9325 } 9326 }; 9327 9328 // Finally with all our helpers, we can scan the include path. 9329 // Do this in standard order so deduplication keeps the right file. 9330 // (In case we decide to add more details to the results later). 9331 const auto &S = PP.getHeaderSearchInfo(); 9332 using llvm::make_range; 9333 if (!Angled) { 9334 // The current directory is on the include path for "quoted" includes. 9335 auto *CurFile = PP.getCurrentFileLexer()->getFileEntry(); 9336 if (CurFile && CurFile->getDir()) 9337 AddFilesFromIncludeDir(CurFile->getDir()->getName(), false, 9338 DirectoryLookup::LT_NormalDir); 9339 for (const auto &D : make_range(S.quoted_dir_begin(), S.quoted_dir_end())) 9340 AddFilesFromDirLookup(D, false); 9341 } 9342 for (const auto &D : make_range(S.angled_dir_begin(), S.angled_dir_end())) 9343 AddFilesFromDirLookup(D, false); 9344 for (const auto &D : make_range(S.system_dir_begin(), S.system_dir_end())) 9345 AddFilesFromDirLookup(D, true); 9346 9347 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 9348 Results.data(), Results.size()); 9349 } 9350 9351 void Sema::CodeCompleteNaturalLanguage() { 9352 HandleCodeCompleteResults(this, CodeCompleter, 9353 CodeCompletionContext::CCC_NaturalLanguage, nullptr, 9354 0); 9355 } 9356 9357 void Sema::CodeCompleteAvailabilityPlatformName() { 9358 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 9359 CodeCompleter->getCodeCompletionTUInfo(), 9360 CodeCompletionContext::CCC_Other); 9361 Results.EnterNewScope(); 9362 static const char *Platforms[] = {"macOS", "iOS", "watchOS", "tvOS"}; 9363 for (const char *Platform : llvm::makeArrayRef(Platforms)) { 9364 Results.AddResult(CodeCompletionResult(Platform)); 9365 Results.AddResult(CodeCompletionResult(Results.getAllocator().CopyString( 9366 Twine(Platform) + "ApplicationExtension"))); 9367 } 9368 Results.ExitScope(); 9369 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 9370 Results.data(), Results.size()); 9371 } 9372 9373 void Sema::GatherGlobalCodeCompletions( 9374 CodeCompletionAllocator &Allocator, CodeCompletionTUInfo &CCTUInfo, 9375 SmallVectorImpl<CodeCompletionResult> &Results) { 9376 ResultBuilder Builder(*this, Allocator, CCTUInfo, 9377 CodeCompletionContext::CCC_Recovery); 9378 if (!CodeCompleter || CodeCompleter->includeGlobals()) { 9379 CodeCompletionDeclConsumer Consumer(Builder, 9380 Context.getTranslationUnitDecl()); 9381 LookupVisibleDecls(Context.getTranslationUnitDecl(), LookupAnyName, 9382 Consumer, 9383 !CodeCompleter || CodeCompleter->loadExternal()); 9384 } 9385 9386 if (!CodeCompleter || CodeCompleter->includeMacros()) 9387 AddMacroResults(PP, Builder, 9388 !CodeCompleter || CodeCompleter->loadExternal(), true); 9389 9390 Results.clear(); 9391 Results.insert(Results.end(), Builder.data(), 9392 Builder.data() + Builder.size()); 9393 } 9394