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 if (SemaRef.getLangOpts().CPlusPlus11 || SemaRef.getLangOpts().ObjC) { 2299 // for ( range_declaration (:|in) range_expression ) { statements } 2300 Builder.AddTypedTextChunk("for"); 2301 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 2302 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 2303 Builder.AddPlaceholderChunk("range-declaration"); 2304 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 2305 if (SemaRef.getLangOpts().ObjC) 2306 Builder.AddTextChunk("in"); 2307 else 2308 Builder.AddChunk(CodeCompletionString::CK_Colon); 2309 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 2310 Builder.AddPlaceholderChunk("range-expression"); 2311 Builder.AddChunk(CodeCompletionString::CK_RightParen); 2312 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 2313 Builder.AddChunk(CodeCompletionString::CK_LeftBrace); 2314 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); 2315 Builder.AddPlaceholderChunk("statements"); 2316 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); 2317 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 2318 Results.AddResult(Result(Builder.TakeString())); 2319 } 2320 } 2321 2322 if (S->getContinueParent()) { 2323 // continue ; 2324 Builder.AddTypedTextChunk("continue"); 2325 Builder.AddChunk(CodeCompletionString::CK_SemiColon); 2326 Results.AddResult(Result(Builder.TakeString())); 2327 } 2328 2329 if (S->getBreakParent()) { 2330 // break ; 2331 Builder.AddTypedTextChunk("break"); 2332 Builder.AddChunk(CodeCompletionString::CK_SemiColon); 2333 Results.AddResult(Result(Builder.TakeString())); 2334 } 2335 2336 // "return expression ;" or "return ;", depending on the return type. 2337 QualType ReturnType; 2338 if (const auto *Function = dyn_cast<FunctionDecl>(SemaRef.CurContext)) 2339 ReturnType = Function->getReturnType(); 2340 else if (const auto *Method = dyn_cast<ObjCMethodDecl>(SemaRef.CurContext)) 2341 ReturnType = Method->getReturnType(); 2342 else if (SemaRef.getCurBlock() && 2343 !SemaRef.getCurBlock()->ReturnType.isNull()) 2344 ReturnType = SemaRef.getCurBlock()->ReturnType;; 2345 if (ReturnType.isNull() || ReturnType->isVoidType()) { 2346 Builder.AddTypedTextChunk("return"); 2347 Builder.AddChunk(CodeCompletionString::CK_SemiColon); 2348 Results.AddResult(Result(Builder.TakeString())); 2349 } else { 2350 assert(!ReturnType.isNull()); 2351 // "return expression ;" 2352 Builder.AddTypedTextChunk("return"); 2353 Builder.AddChunk(clang::CodeCompletionString::CK_HorizontalSpace); 2354 Builder.AddPlaceholderChunk("expression"); 2355 Builder.AddChunk(CodeCompletionString::CK_SemiColon); 2356 Results.AddResult(Result(Builder.TakeString())); 2357 // When boolean, also add 'return true;' and 'return false;'. 2358 if (ReturnType->isBooleanType()) { 2359 Builder.AddTypedTextChunk("return true"); 2360 Builder.AddChunk(CodeCompletionString::CK_SemiColon); 2361 Results.AddResult(Result(Builder.TakeString())); 2362 2363 Builder.AddTypedTextChunk("return false"); 2364 Builder.AddChunk(CodeCompletionString::CK_SemiColon); 2365 Results.AddResult(Result(Builder.TakeString())); 2366 } 2367 // For pointers, suggest 'return nullptr' in C++. 2368 if (SemaRef.getLangOpts().CPlusPlus11 && 2369 (ReturnType->isPointerType() || ReturnType->isMemberPointerType())) { 2370 Builder.AddTypedTextChunk("return nullptr"); 2371 Builder.AddChunk(CodeCompletionString::CK_SemiColon); 2372 Results.AddResult(Result(Builder.TakeString())); 2373 } 2374 } 2375 2376 // goto identifier ; 2377 Builder.AddTypedTextChunk("goto"); 2378 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 2379 Builder.AddPlaceholderChunk("label"); 2380 Builder.AddChunk(CodeCompletionString::CK_SemiColon); 2381 Results.AddResult(Result(Builder.TakeString())); 2382 2383 // Using directives 2384 Builder.AddTypedTextChunk("using namespace"); 2385 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 2386 Builder.AddPlaceholderChunk("identifier"); 2387 Builder.AddChunk(CodeCompletionString::CK_SemiColon); 2388 Results.AddResult(Result(Builder.TakeString())); 2389 2390 AddStaticAssertResult(Builder, Results, SemaRef.getLangOpts()); 2391 } 2392 LLVM_FALLTHROUGH; 2393 2394 // Fall through (for statement expressions). 2395 case Sema::PCC_ForInit: 2396 case Sema::PCC_Condition: 2397 AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results); 2398 // Fall through: conditions and statements can have expressions. 2399 LLVM_FALLTHROUGH; 2400 2401 case Sema::PCC_ParenthesizedExpression: 2402 if (SemaRef.getLangOpts().ObjCAutoRefCount && 2403 CCC == Sema::PCC_ParenthesizedExpression) { 2404 // (__bridge <type>)<expression> 2405 Builder.AddTypedTextChunk("__bridge"); 2406 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 2407 Builder.AddPlaceholderChunk("type"); 2408 Builder.AddChunk(CodeCompletionString::CK_RightParen); 2409 Builder.AddPlaceholderChunk("expression"); 2410 Results.AddResult(Result(Builder.TakeString())); 2411 2412 // (__bridge_transfer <Objective-C type>)<expression> 2413 Builder.AddTypedTextChunk("__bridge_transfer"); 2414 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 2415 Builder.AddPlaceholderChunk("Objective-C type"); 2416 Builder.AddChunk(CodeCompletionString::CK_RightParen); 2417 Builder.AddPlaceholderChunk("expression"); 2418 Results.AddResult(Result(Builder.TakeString())); 2419 2420 // (__bridge_retained <CF type>)<expression> 2421 Builder.AddTypedTextChunk("__bridge_retained"); 2422 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 2423 Builder.AddPlaceholderChunk("CF type"); 2424 Builder.AddChunk(CodeCompletionString::CK_RightParen); 2425 Builder.AddPlaceholderChunk("expression"); 2426 Results.AddResult(Result(Builder.TakeString())); 2427 } 2428 // Fall through 2429 LLVM_FALLTHROUGH; 2430 2431 case Sema::PCC_Expression: { 2432 if (SemaRef.getLangOpts().CPlusPlus) { 2433 // 'this', if we're in a non-static member function. 2434 addThisCompletion(SemaRef, Results); 2435 2436 // true 2437 Builder.AddResultTypeChunk("bool"); 2438 Builder.AddTypedTextChunk("true"); 2439 Results.AddResult(Result(Builder.TakeString())); 2440 2441 // false 2442 Builder.AddResultTypeChunk("bool"); 2443 Builder.AddTypedTextChunk("false"); 2444 Results.AddResult(Result(Builder.TakeString())); 2445 2446 if (SemaRef.getLangOpts().RTTI) { 2447 // dynamic_cast < type-id > ( expression ) 2448 Builder.AddTypedTextChunk("dynamic_cast"); 2449 Builder.AddChunk(CodeCompletionString::CK_LeftAngle); 2450 Builder.AddPlaceholderChunk("type"); 2451 Builder.AddChunk(CodeCompletionString::CK_RightAngle); 2452 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 2453 Builder.AddPlaceholderChunk("expression"); 2454 Builder.AddChunk(CodeCompletionString::CK_RightParen); 2455 Results.AddResult(Result(Builder.TakeString())); 2456 } 2457 2458 // static_cast < type-id > ( expression ) 2459 Builder.AddTypedTextChunk("static_cast"); 2460 Builder.AddChunk(CodeCompletionString::CK_LeftAngle); 2461 Builder.AddPlaceholderChunk("type"); 2462 Builder.AddChunk(CodeCompletionString::CK_RightAngle); 2463 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 2464 Builder.AddPlaceholderChunk("expression"); 2465 Builder.AddChunk(CodeCompletionString::CK_RightParen); 2466 Results.AddResult(Result(Builder.TakeString())); 2467 2468 // reinterpret_cast < type-id > ( expression ) 2469 Builder.AddTypedTextChunk("reinterpret_cast"); 2470 Builder.AddChunk(CodeCompletionString::CK_LeftAngle); 2471 Builder.AddPlaceholderChunk("type"); 2472 Builder.AddChunk(CodeCompletionString::CK_RightAngle); 2473 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 2474 Builder.AddPlaceholderChunk("expression"); 2475 Builder.AddChunk(CodeCompletionString::CK_RightParen); 2476 Results.AddResult(Result(Builder.TakeString())); 2477 2478 // const_cast < type-id > ( expression ) 2479 Builder.AddTypedTextChunk("const_cast"); 2480 Builder.AddChunk(CodeCompletionString::CK_LeftAngle); 2481 Builder.AddPlaceholderChunk("type"); 2482 Builder.AddChunk(CodeCompletionString::CK_RightAngle); 2483 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 2484 Builder.AddPlaceholderChunk("expression"); 2485 Builder.AddChunk(CodeCompletionString::CK_RightParen); 2486 Results.AddResult(Result(Builder.TakeString())); 2487 2488 if (SemaRef.getLangOpts().RTTI) { 2489 // typeid ( expression-or-type ) 2490 Builder.AddResultTypeChunk("std::type_info"); 2491 Builder.AddTypedTextChunk("typeid"); 2492 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 2493 Builder.AddPlaceholderChunk("expression-or-type"); 2494 Builder.AddChunk(CodeCompletionString::CK_RightParen); 2495 Results.AddResult(Result(Builder.TakeString())); 2496 } 2497 2498 // new T ( ... ) 2499 Builder.AddTypedTextChunk("new"); 2500 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 2501 Builder.AddPlaceholderChunk("type"); 2502 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 2503 Builder.AddPlaceholderChunk("expressions"); 2504 Builder.AddChunk(CodeCompletionString::CK_RightParen); 2505 Results.AddResult(Result(Builder.TakeString())); 2506 2507 // new T [ ] ( ... ) 2508 Builder.AddTypedTextChunk("new"); 2509 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 2510 Builder.AddPlaceholderChunk("type"); 2511 Builder.AddChunk(CodeCompletionString::CK_LeftBracket); 2512 Builder.AddPlaceholderChunk("size"); 2513 Builder.AddChunk(CodeCompletionString::CK_RightBracket); 2514 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 2515 Builder.AddPlaceholderChunk("expressions"); 2516 Builder.AddChunk(CodeCompletionString::CK_RightParen); 2517 Results.AddResult(Result(Builder.TakeString())); 2518 2519 // delete expression 2520 Builder.AddResultTypeChunk("void"); 2521 Builder.AddTypedTextChunk("delete"); 2522 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 2523 Builder.AddPlaceholderChunk("expression"); 2524 Results.AddResult(Result(Builder.TakeString())); 2525 2526 // delete [] expression 2527 Builder.AddResultTypeChunk("void"); 2528 Builder.AddTypedTextChunk("delete"); 2529 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 2530 Builder.AddChunk(CodeCompletionString::CK_LeftBracket); 2531 Builder.AddChunk(CodeCompletionString::CK_RightBracket); 2532 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 2533 Builder.AddPlaceholderChunk("expression"); 2534 Results.AddResult(Result(Builder.TakeString())); 2535 2536 if (SemaRef.getLangOpts().CXXExceptions) { 2537 // throw expression 2538 Builder.AddResultTypeChunk("void"); 2539 Builder.AddTypedTextChunk("throw"); 2540 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 2541 Builder.AddPlaceholderChunk("expression"); 2542 Results.AddResult(Result(Builder.TakeString())); 2543 } 2544 2545 // FIXME: Rethrow? 2546 2547 if (SemaRef.getLangOpts().CPlusPlus11) { 2548 // nullptr 2549 Builder.AddResultTypeChunk("std::nullptr_t"); 2550 Builder.AddTypedTextChunk("nullptr"); 2551 Results.AddResult(Result(Builder.TakeString())); 2552 2553 // alignof 2554 Builder.AddResultTypeChunk("size_t"); 2555 Builder.AddTypedTextChunk("alignof"); 2556 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 2557 Builder.AddPlaceholderChunk("type"); 2558 Builder.AddChunk(CodeCompletionString::CK_RightParen); 2559 Results.AddResult(Result(Builder.TakeString())); 2560 2561 // noexcept 2562 Builder.AddResultTypeChunk("bool"); 2563 Builder.AddTypedTextChunk("noexcept"); 2564 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 2565 Builder.AddPlaceholderChunk("expression"); 2566 Builder.AddChunk(CodeCompletionString::CK_RightParen); 2567 Results.AddResult(Result(Builder.TakeString())); 2568 2569 // sizeof... expression 2570 Builder.AddResultTypeChunk("size_t"); 2571 Builder.AddTypedTextChunk("sizeof..."); 2572 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 2573 Builder.AddPlaceholderChunk("parameter-pack"); 2574 Builder.AddChunk(CodeCompletionString::CK_RightParen); 2575 Results.AddResult(Result(Builder.TakeString())); 2576 } 2577 } 2578 2579 if (SemaRef.getLangOpts().ObjC) { 2580 // Add "super", if we're in an Objective-C class with a superclass. 2581 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) { 2582 // The interface can be NULL. 2583 if (ObjCInterfaceDecl *ID = Method->getClassInterface()) 2584 if (ID->getSuperClass()) { 2585 std::string SuperType; 2586 SuperType = ID->getSuperClass()->getNameAsString(); 2587 if (Method->isInstanceMethod()) 2588 SuperType += " *"; 2589 2590 Builder.AddResultTypeChunk(Allocator.CopyString(SuperType)); 2591 Builder.AddTypedTextChunk("super"); 2592 Results.AddResult(Result(Builder.TakeString())); 2593 } 2594 } 2595 2596 AddObjCExpressionResults(Results, true); 2597 } 2598 2599 if (SemaRef.getLangOpts().C11) { 2600 // _Alignof 2601 Builder.AddResultTypeChunk("size_t"); 2602 if (SemaRef.PP.isMacroDefined("alignof")) 2603 Builder.AddTypedTextChunk("alignof"); 2604 else 2605 Builder.AddTypedTextChunk("_Alignof"); 2606 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 2607 Builder.AddPlaceholderChunk("type"); 2608 Builder.AddChunk(CodeCompletionString::CK_RightParen); 2609 Results.AddResult(Result(Builder.TakeString())); 2610 } 2611 2612 // sizeof expression 2613 Builder.AddResultTypeChunk("size_t"); 2614 Builder.AddTypedTextChunk("sizeof"); 2615 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 2616 Builder.AddPlaceholderChunk("expression-or-type"); 2617 Builder.AddChunk(CodeCompletionString::CK_RightParen); 2618 Results.AddResult(Result(Builder.TakeString())); 2619 break; 2620 } 2621 2622 case Sema::PCC_Type: 2623 case Sema::PCC_LocalDeclarationSpecifiers: 2624 break; 2625 } 2626 2627 if (WantTypesInContext(CCC, SemaRef.getLangOpts())) 2628 AddTypeSpecifierResults(SemaRef.getLangOpts(), Results); 2629 2630 if (SemaRef.getLangOpts().CPlusPlus && CCC != Sema::PCC_Type) 2631 Results.AddResult(Result("operator")); 2632 } 2633 2634 /// If the given declaration has an associated type, add it as a result 2635 /// type chunk. 2636 static void AddResultTypeChunk(ASTContext &Context, 2637 const PrintingPolicy &Policy, 2638 const NamedDecl *ND, QualType BaseType, 2639 CodeCompletionBuilder &Result) { 2640 if (!ND) 2641 return; 2642 2643 // Skip constructors and conversion functions, which have their return types 2644 // built into their names. 2645 if (isConstructor(ND) || isa<CXXConversionDecl>(ND)) 2646 return; 2647 2648 // Determine the type of the declaration (if it has a type). 2649 QualType T; 2650 if (const FunctionDecl *Function = ND->getAsFunction()) 2651 T = Function->getReturnType(); 2652 else if (const auto *Method = dyn_cast<ObjCMethodDecl>(ND)) { 2653 if (!BaseType.isNull()) 2654 T = Method->getSendResultType(BaseType); 2655 else 2656 T = Method->getReturnType(); 2657 } else if (const auto *Enumerator = dyn_cast<EnumConstantDecl>(ND)) { 2658 T = Context.getTypeDeclType(cast<TypeDecl>(Enumerator->getDeclContext())); 2659 T = clang::TypeName::getFullyQualifiedType(T, Context); 2660 } else if (isa<UnresolvedUsingValueDecl>(ND)) { 2661 /* Do nothing: ignore unresolved using declarations*/ 2662 } else if (const auto *Ivar = dyn_cast<ObjCIvarDecl>(ND)) { 2663 if (!BaseType.isNull()) 2664 T = Ivar->getUsageType(BaseType); 2665 else 2666 T = Ivar->getType(); 2667 } else if (const auto *Value = dyn_cast<ValueDecl>(ND)) { 2668 T = Value->getType(); 2669 } else if (const auto *Property = dyn_cast<ObjCPropertyDecl>(ND)) { 2670 if (!BaseType.isNull()) 2671 T = Property->getUsageType(BaseType); 2672 else 2673 T = Property->getType(); 2674 } 2675 2676 if (T.isNull() || Context.hasSameType(T, Context.DependentTy)) 2677 return; 2678 2679 Result.AddResultTypeChunk( 2680 GetCompletionTypeString(T, Context, Policy, Result.getAllocator())); 2681 } 2682 2683 static void MaybeAddSentinel(Preprocessor &PP, 2684 const NamedDecl *FunctionOrMethod, 2685 CodeCompletionBuilder &Result) { 2686 if (SentinelAttr *Sentinel = FunctionOrMethod->getAttr<SentinelAttr>()) 2687 if (Sentinel->getSentinel() == 0) { 2688 if (PP.getLangOpts().ObjC && PP.isMacroDefined("nil")) 2689 Result.AddTextChunk(", nil"); 2690 else if (PP.isMacroDefined("NULL")) 2691 Result.AddTextChunk(", NULL"); 2692 else 2693 Result.AddTextChunk(", (void*)0"); 2694 } 2695 } 2696 2697 static std::string formatObjCParamQualifiers(unsigned ObjCQuals, 2698 QualType &Type) { 2699 std::string Result; 2700 if (ObjCQuals & Decl::OBJC_TQ_In) 2701 Result += "in "; 2702 else if (ObjCQuals & Decl::OBJC_TQ_Inout) 2703 Result += "inout "; 2704 else if (ObjCQuals & Decl::OBJC_TQ_Out) 2705 Result += "out "; 2706 if (ObjCQuals & Decl::OBJC_TQ_Bycopy) 2707 Result += "bycopy "; 2708 else if (ObjCQuals & Decl::OBJC_TQ_Byref) 2709 Result += "byref "; 2710 if (ObjCQuals & Decl::OBJC_TQ_Oneway) 2711 Result += "oneway "; 2712 if (ObjCQuals & Decl::OBJC_TQ_CSNullability) { 2713 if (auto nullability = AttributedType::stripOuterNullability(Type)) { 2714 switch (*nullability) { 2715 case NullabilityKind::NonNull: 2716 Result += "nonnull "; 2717 break; 2718 2719 case NullabilityKind::Nullable: 2720 Result += "nullable "; 2721 break; 2722 2723 case NullabilityKind::Unspecified: 2724 Result += "null_unspecified "; 2725 break; 2726 2727 case NullabilityKind::NullableResult: 2728 llvm_unreachable("Not supported as a context-sensitive keyword!"); 2729 break; 2730 } 2731 } 2732 } 2733 return Result; 2734 } 2735 2736 /// Tries to find the most appropriate type location for an Objective-C 2737 /// block placeholder. 2738 /// 2739 /// This function ignores things like typedefs and qualifiers in order to 2740 /// present the most relevant and accurate block placeholders in code completion 2741 /// results. 2742 static void findTypeLocationForBlockDecl(const TypeSourceInfo *TSInfo, 2743 FunctionTypeLoc &Block, 2744 FunctionProtoTypeLoc &BlockProto, 2745 bool SuppressBlock = false) { 2746 if (!TSInfo) 2747 return; 2748 TypeLoc TL = TSInfo->getTypeLoc().getUnqualifiedLoc(); 2749 while (true) { 2750 // Look through typedefs. 2751 if (!SuppressBlock) { 2752 if (TypedefTypeLoc TypedefTL = TL.getAs<TypedefTypeLoc>()) { 2753 if (TypeSourceInfo *InnerTSInfo = 2754 TypedefTL.getTypedefNameDecl()->getTypeSourceInfo()) { 2755 TL = InnerTSInfo->getTypeLoc().getUnqualifiedLoc(); 2756 continue; 2757 } 2758 } 2759 2760 // Look through qualified types 2761 if (QualifiedTypeLoc QualifiedTL = TL.getAs<QualifiedTypeLoc>()) { 2762 TL = QualifiedTL.getUnqualifiedLoc(); 2763 continue; 2764 } 2765 2766 if (AttributedTypeLoc AttrTL = TL.getAs<AttributedTypeLoc>()) { 2767 TL = AttrTL.getModifiedLoc(); 2768 continue; 2769 } 2770 } 2771 2772 // Try to get the function prototype behind the block pointer type, 2773 // then we're done. 2774 if (BlockPointerTypeLoc BlockPtr = TL.getAs<BlockPointerTypeLoc>()) { 2775 TL = BlockPtr.getPointeeLoc().IgnoreParens(); 2776 Block = TL.getAs<FunctionTypeLoc>(); 2777 BlockProto = TL.getAs<FunctionProtoTypeLoc>(); 2778 } 2779 break; 2780 } 2781 } 2782 2783 static std::string 2784 formatBlockPlaceholder(const PrintingPolicy &Policy, const NamedDecl *BlockDecl, 2785 FunctionTypeLoc &Block, FunctionProtoTypeLoc &BlockProto, 2786 bool SuppressBlockName = false, 2787 bool SuppressBlock = false, 2788 Optional<ArrayRef<QualType>> ObjCSubsts = None); 2789 2790 static std::string 2791 FormatFunctionParameter(const PrintingPolicy &Policy, const ParmVarDecl *Param, 2792 bool SuppressName = false, bool SuppressBlock = false, 2793 Optional<ArrayRef<QualType>> ObjCSubsts = None) { 2794 // Params are unavailable in FunctionTypeLoc if the FunctionType is invalid. 2795 // It would be better to pass in the param Type, which is usually avaliable. 2796 // But this case is rare, so just pretend we fell back to int as elsewhere. 2797 if (!Param) 2798 return "int"; 2799 bool ObjCMethodParam = isa<ObjCMethodDecl>(Param->getDeclContext()); 2800 if (Param->getType()->isDependentType() || 2801 !Param->getType()->isBlockPointerType()) { 2802 // The argument for a dependent or non-block parameter is a placeholder 2803 // containing that parameter's type. 2804 std::string Result; 2805 2806 if (Param->getIdentifier() && !ObjCMethodParam && !SuppressName) 2807 Result = std::string(Param->getIdentifier()->getName()); 2808 2809 QualType Type = Param->getType(); 2810 if (ObjCSubsts) 2811 Type = Type.substObjCTypeArgs(Param->getASTContext(), *ObjCSubsts, 2812 ObjCSubstitutionContext::Parameter); 2813 if (ObjCMethodParam) { 2814 Result = 2815 "(" + formatObjCParamQualifiers(Param->getObjCDeclQualifier(), Type); 2816 Result += Type.getAsString(Policy) + ")"; 2817 if (Param->getIdentifier() && !SuppressName) 2818 Result += Param->getIdentifier()->getName(); 2819 } else { 2820 Type.getAsStringInternal(Result, Policy); 2821 } 2822 return Result; 2823 } 2824 2825 // The argument for a block pointer parameter is a block literal with 2826 // the appropriate type. 2827 FunctionTypeLoc Block; 2828 FunctionProtoTypeLoc BlockProto; 2829 findTypeLocationForBlockDecl(Param->getTypeSourceInfo(), Block, BlockProto, 2830 SuppressBlock); 2831 // Try to retrieve the block type information from the property if this is a 2832 // parameter in a setter. 2833 if (!Block && ObjCMethodParam && 2834 cast<ObjCMethodDecl>(Param->getDeclContext())->isPropertyAccessor()) { 2835 if (const auto *PD = cast<ObjCMethodDecl>(Param->getDeclContext()) 2836 ->findPropertyDecl(/*CheckOverrides=*/false)) 2837 findTypeLocationForBlockDecl(PD->getTypeSourceInfo(), Block, BlockProto, 2838 SuppressBlock); 2839 } 2840 2841 if (!Block) { 2842 // We were unable to find a FunctionProtoTypeLoc with parameter names 2843 // for the block; just use the parameter type as a placeholder. 2844 std::string Result; 2845 if (!ObjCMethodParam && Param->getIdentifier()) 2846 Result = std::string(Param->getIdentifier()->getName()); 2847 2848 QualType Type = Param->getType().getUnqualifiedType(); 2849 2850 if (ObjCMethodParam) { 2851 Result = Type.getAsString(Policy); 2852 std::string Quals = 2853 formatObjCParamQualifiers(Param->getObjCDeclQualifier(), Type); 2854 if (!Quals.empty()) 2855 Result = "(" + Quals + " " + Result + ")"; 2856 if (Result.back() != ')') 2857 Result += " "; 2858 if (Param->getIdentifier()) 2859 Result += Param->getIdentifier()->getName(); 2860 } else { 2861 Type.getAsStringInternal(Result, Policy); 2862 } 2863 2864 return Result; 2865 } 2866 2867 // We have the function prototype behind the block pointer type, as it was 2868 // written in the source. 2869 return formatBlockPlaceholder(Policy, Param, Block, BlockProto, 2870 /*SuppressBlockName=*/false, SuppressBlock, 2871 ObjCSubsts); 2872 } 2873 2874 /// Returns a placeholder string that corresponds to an Objective-C block 2875 /// declaration. 2876 /// 2877 /// \param BlockDecl A declaration with an Objective-C block type. 2878 /// 2879 /// \param Block The most relevant type location for that block type. 2880 /// 2881 /// \param SuppressBlockName Determines whether or not the name of the block 2882 /// declaration is included in the resulting string. 2883 static std::string 2884 formatBlockPlaceholder(const PrintingPolicy &Policy, const NamedDecl *BlockDecl, 2885 FunctionTypeLoc &Block, FunctionProtoTypeLoc &BlockProto, 2886 bool SuppressBlockName, bool SuppressBlock, 2887 Optional<ArrayRef<QualType>> ObjCSubsts) { 2888 std::string Result; 2889 QualType ResultType = Block.getTypePtr()->getReturnType(); 2890 if (ObjCSubsts) 2891 ResultType = 2892 ResultType.substObjCTypeArgs(BlockDecl->getASTContext(), *ObjCSubsts, 2893 ObjCSubstitutionContext::Result); 2894 if (!ResultType->isVoidType() || SuppressBlock) 2895 ResultType.getAsStringInternal(Result, Policy); 2896 2897 // Format the parameter list. 2898 std::string Params; 2899 if (!BlockProto || Block.getNumParams() == 0) { 2900 if (BlockProto && BlockProto.getTypePtr()->isVariadic()) 2901 Params = "(...)"; 2902 else 2903 Params = "(void)"; 2904 } else { 2905 Params += "("; 2906 for (unsigned I = 0, N = Block.getNumParams(); I != N; ++I) { 2907 if (I) 2908 Params += ", "; 2909 Params += FormatFunctionParameter(Policy, Block.getParam(I), 2910 /*SuppressName=*/false, 2911 /*SuppressBlock=*/true, ObjCSubsts); 2912 2913 if (I == N - 1 && BlockProto.getTypePtr()->isVariadic()) 2914 Params += ", ..."; 2915 } 2916 Params += ")"; 2917 } 2918 2919 if (SuppressBlock) { 2920 // Format as a parameter. 2921 Result = Result + " (^"; 2922 if (!SuppressBlockName && BlockDecl->getIdentifier()) 2923 Result += BlockDecl->getIdentifier()->getName(); 2924 Result += ")"; 2925 Result += Params; 2926 } else { 2927 // Format as a block literal argument. 2928 Result = '^' + Result; 2929 Result += Params; 2930 2931 if (!SuppressBlockName && BlockDecl->getIdentifier()) 2932 Result += BlockDecl->getIdentifier()->getName(); 2933 } 2934 2935 return Result; 2936 } 2937 2938 static std::string GetDefaultValueString(const ParmVarDecl *Param, 2939 const SourceManager &SM, 2940 const LangOptions &LangOpts) { 2941 const SourceRange SrcRange = Param->getDefaultArgRange(); 2942 CharSourceRange CharSrcRange = CharSourceRange::getTokenRange(SrcRange); 2943 bool Invalid = CharSrcRange.isInvalid(); 2944 if (Invalid) 2945 return ""; 2946 StringRef srcText = 2947 Lexer::getSourceText(CharSrcRange, SM, LangOpts, &Invalid); 2948 if (Invalid) 2949 return ""; 2950 2951 if (srcText.empty() || srcText == "=") { 2952 // Lexer can't determine the value. 2953 // This happens if the code is incorrect (for example class is forward 2954 // declared). 2955 return ""; 2956 } 2957 std::string DefValue(srcText.str()); 2958 // FIXME: remove this check if the Lexer::getSourceText value is fixed and 2959 // this value always has (or always does not have) '=' in front of it 2960 if (DefValue.at(0) != '=') { 2961 // If we don't have '=' in front of value. 2962 // Lexer returns built-in types values without '=' and user-defined types 2963 // values with it. 2964 return " = " + DefValue; 2965 } 2966 return " " + DefValue; 2967 } 2968 2969 /// Add function parameter chunks to the given code completion string. 2970 static void AddFunctionParameterChunks(Preprocessor &PP, 2971 const PrintingPolicy &Policy, 2972 const FunctionDecl *Function, 2973 CodeCompletionBuilder &Result, 2974 unsigned Start = 0, 2975 bool InOptional = false) { 2976 bool FirstParameter = true; 2977 2978 for (unsigned P = Start, N = Function->getNumParams(); P != N; ++P) { 2979 const ParmVarDecl *Param = Function->getParamDecl(P); 2980 2981 if (Param->hasDefaultArg() && !InOptional) { 2982 // When we see an optional default argument, put that argument and 2983 // the remaining default arguments into a new, optional string. 2984 CodeCompletionBuilder Opt(Result.getAllocator(), 2985 Result.getCodeCompletionTUInfo()); 2986 if (!FirstParameter) 2987 Opt.AddChunk(CodeCompletionString::CK_Comma); 2988 AddFunctionParameterChunks(PP, Policy, Function, Opt, P, true); 2989 Result.AddOptionalChunk(Opt.TakeString()); 2990 break; 2991 } 2992 2993 if (FirstParameter) 2994 FirstParameter = false; 2995 else 2996 Result.AddChunk(CodeCompletionString::CK_Comma); 2997 2998 InOptional = false; 2999 3000 // Format the placeholder string. 3001 std::string PlaceholderStr = FormatFunctionParameter(Policy, Param); 3002 if (Param->hasDefaultArg()) 3003 PlaceholderStr += 3004 GetDefaultValueString(Param, PP.getSourceManager(), PP.getLangOpts()); 3005 3006 if (Function->isVariadic() && P == N - 1) 3007 PlaceholderStr += ", ..."; 3008 3009 // Add the placeholder string. 3010 Result.AddPlaceholderChunk( 3011 Result.getAllocator().CopyString(PlaceholderStr)); 3012 } 3013 3014 if (const auto *Proto = Function->getType()->getAs<FunctionProtoType>()) 3015 if (Proto->isVariadic()) { 3016 if (Proto->getNumParams() == 0) 3017 Result.AddPlaceholderChunk("..."); 3018 3019 MaybeAddSentinel(PP, Function, Result); 3020 } 3021 } 3022 3023 /// Add template parameter chunks to the given code completion string. 3024 static void AddTemplateParameterChunks( 3025 ASTContext &Context, const PrintingPolicy &Policy, 3026 const TemplateDecl *Template, CodeCompletionBuilder &Result, 3027 unsigned MaxParameters = 0, unsigned Start = 0, bool InDefaultArg = false) { 3028 bool FirstParameter = true; 3029 3030 // Prefer to take the template parameter names from the first declaration of 3031 // the template. 3032 Template = cast<TemplateDecl>(Template->getCanonicalDecl()); 3033 3034 TemplateParameterList *Params = Template->getTemplateParameters(); 3035 TemplateParameterList::iterator PEnd = Params->end(); 3036 if (MaxParameters) 3037 PEnd = Params->begin() + MaxParameters; 3038 for (TemplateParameterList::iterator P = Params->begin() + Start; P != PEnd; 3039 ++P) { 3040 bool HasDefaultArg = false; 3041 std::string PlaceholderStr; 3042 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) { 3043 if (TTP->wasDeclaredWithTypename()) 3044 PlaceholderStr = "typename"; 3045 else if (const auto *TC = TTP->getTypeConstraint()) { 3046 llvm::raw_string_ostream OS(PlaceholderStr); 3047 TC->print(OS, Policy); 3048 OS.flush(); 3049 } else 3050 PlaceholderStr = "class"; 3051 3052 if (TTP->getIdentifier()) { 3053 PlaceholderStr += ' '; 3054 PlaceholderStr += TTP->getIdentifier()->getName(); 3055 } 3056 3057 HasDefaultArg = TTP->hasDefaultArgument(); 3058 } else if (NonTypeTemplateParmDecl *NTTP = 3059 dyn_cast<NonTypeTemplateParmDecl>(*P)) { 3060 if (NTTP->getIdentifier()) 3061 PlaceholderStr = std::string(NTTP->getIdentifier()->getName()); 3062 NTTP->getType().getAsStringInternal(PlaceholderStr, Policy); 3063 HasDefaultArg = NTTP->hasDefaultArgument(); 3064 } else { 3065 assert(isa<TemplateTemplateParmDecl>(*P)); 3066 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P); 3067 3068 // Since putting the template argument list into the placeholder would 3069 // be very, very long, we just use an abbreviation. 3070 PlaceholderStr = "template<...> class"; 3071 if (TTP->getIdentifier()) { 3072 PlaceholderStr += ' '; 3073 PlaceholderStr += TTP->getIdentifier()->getName(); 3074 } 3075 3076 HasDefaultArg = TTP->hasDefaultArgument(); 3077 } 3078 3079 if (HasDefaultArg && !InDefaultArg) { 3080 // When we see an optional default argument, put that argument and 3081 // the remaining default arguments into a new, optional string. 3082 CodeCompletionBuilder Opt(Result.getAllocator(), 3083 Result.getCodeCompletionTUInfo()); 3084 if (!FirstParameter) 3085 Opt.AddChunk(CodeCompletionString::CK_Comma); 3086 AddTemplateParameterChunks(Context, Policy, Template, Opt, MaxParameters, 3087 P - Params->begin(), true); 3088 Result.AddOptionalChunk(Opt.TakeString()); 3089 break; 3090 } 3091 3092 InDefaultArg = false; 3093 3094 if (FirstParameter) 3095 FirstParameter = false; 3096 else 3097 Result.AddChunk(CodeCompletionString::CK_Comma); 3098 3099 // Add the placeholder string. 3100 Result.AddPlaceholderChunk( 3101 Result.getAllocator().CopyString(PlaceholderStr)); 3102 } 3103 } 3104 3105 /// Add a qualifier to the given code-completion string, if the 3106 /// provided nested-name-specifier is non-NULL. 3107 static void AddQualifierToCompletionString(CodeCompletionBuilder &Result, 3108 NestedNameSpecifier *Qualifier, 3109 bool QualifierIsInformative, 3110 ASTContext &Context, 3111 const PrintingPolicy &Policy) { 3112 if (!Qualifier) 3113 return; 3114 3115 std::string PrintedNNS; 3116 { 3117 llvm::raw_string_ostream OS(PrintedNNS); 3118 Qualifier->print(OS, Policy); 3119 } 3120 if (QualifierIsInformative) 3121 Result.AddInformativeChunk(Result.getAllocator().CopyString(PrintedNNS)); 3122 else 3123 Result.AddTextChunk(Result.getAllocator().CopyString(PrintedNNS)); 3124 } 3125 3126 static void 3127 AddFunctionTypeQualsToCompletionString(CodeCompletionBuilder &Result, 3128 const FunctionDecl *Function) { 3129 const auto *Proto = Function->getType()->getAs<FunctionProtoType>(); 3130 if (!Proto || !Proto->getMethodQuals()) 3131 return; 3132 3133 // FIXME: Add ref-qualifier! 3134 3135 // Handle single qualifiers without copying 3136 if (Proto->getMethodQuals().hasOnlyConst()) { 3137 Result.AddInformativeChunk(" const"); 3138 return; 3139 } 3140 3141 if (Proto->getMethodQuals().hasOnlyVolatile()) { 3142 Result.AddInformativeChunk(" volatile"); 3143 return; 3144 } 3145 3146 if (Proto->getMethodQuals().hasOnlyRestrict()) { 3147 Result.AddInformativeChunk(" restrict"); 3148 return; 3149 } 3150 3151 // Handle multiple qualifiers. 3152 std::string QualsStr; 3153 if (Proto->isConst()) 3154 QualsStr += " const"; 3155 if (Proto->isVolatile()) 3156 QualsStr += " volatile"; 3157 if (Proto->isRestrict()) 3158 QualsStr += " restrict"; 3159 Result.AddInformativeChunk(Result.getAllocator().CopyString(QualsStr)); 3160 } 3161 3162 /// Add the name of the given declaration 3163 static void AddTypedNameChunk(ASTContext &Context, const PrintingPolicy &Policy, 3164 const NamedDecl *ND, 3165 CodeCompletionBuilder &Result) { 3166 DeclarationName Name = ND->getDeclName(); 3167 if (!Name) 3168 return; 3169 3170 switch (Name.getNameKind()) { 3171 case DeclarationName::CXXOperatorName: { 3172 const char *OperatorName = nullptr; 3173 switch (Name.getCXXOverloadedOperator()) { 3174 case OO_None: 3175 case OO_Conditional: 3176 case NUM_OVERLOADED_OPERATORS: 3177 OperatorName = "operator"; 3178 break; 3179 3180 #define OVERLOADED_OPERATOR(Name, Spelling, Token, Unary, Binary, MemberOnly) \ 3181 case OO_##Name: \ 3182 OperatorName = "operator" Spelling; \ 3183 break; 3184 #define OVERLOADED_OPERATOR_MULTI(Name, Spelling, Unary, Binary, MemberOnly) 3185 #include "clang/Basic/OperatorKinds.def" 3186 3187 case OO_New: 3188 OperatorName = "operator new"; 3189 break; 3190 case OO_Delete: 3191 OperatorName = "operator delete"; 3192 break; 3193 case OO_Array_New: 3194 OperatorName = "operator new[]"; 3195 break; 3196 case OO_Array_Delete: 3197 OperatorName = "operator delete[]"; 3198 break; 3199 case OO_Call: 3200 OperatorName = "operator()"; 3201 break; 3202 case OO_Subscript: 3203 OperatorName = "operator[]"; 3204 break; 3205 } 3206 Result.AddTypedTextChunk(OperatorName); 3207 break; 3208 } 3209 3210 case DeclarationName::Identifier: 3211 case DeclarationName::CXXConversionFunctionName: 3212 case DeclarationName::CXXDestructorName: 3213 case DeclarationName::CXXLiteralOperatorName: 3214 Result.AddTypedTextChunk( 3215 Result.getAllocator().CopyString(ND->getNameAsString())); 3216 break; 3217 3218 case DeclarationName::CXXDeductionGuideName: 3219 case DeclarationName::CXXUsingDirective: 3220 case DeclarationName::ObjCZeroArgSelector: 3221 case DeclarationName::ObjCOneArgSelector: 3222 case DeclarationName::ObjCMultiArgSelector: 3223 break; 3224 3225 case DeclarationName::CXXConstructorName: { 3226 CXXRecordDecl *Record = nullptr; 3227 QualType Ty = Name.getCXXNameType(); 3228 if (const auto *RecordTy = Ty->getAs<RecordType>()) 3229 Record = cast<CXXRecordDecl>(RecordTy->getDecl()); 3230 else if (const auto *InjectedTy = Ty->getAs<InjectedClassNameType>()) 3231 Record = InjectedTy->getDecl(); 3232 else { 3233 Result.AddTypedTextChunk( 3234 Result.getAllocator().CopyString(ND->getNameAsString())); 3235 break; 3236 } 3237 3238 Result.AddTypedTextChunk( 3239 Result.getAllocator().CopyString(Record->getNameAsString())); 3240 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) { 3241 Result.AddChunk(CodeCompletionString::CK_LeftAngle); 3242 AddTemplateParameterChunks(Context, Policy, Template, Result); 3243 Result.AddChunk(CodeCompletionString::CK_RightAngle); 3244 } 3245 break; 3246 } 3247 } 3248 } 3249 3250 CodeCompletionString *CodeCompletionResult::CreateCodeCompletionString( 3251 Sema &S, const CodeCompletionContext &CCContext, 3252 CodeCompletionAllocator &Allocator, CodeCompletionTUInfo &CCTUInfo, 3253 bool IncludeBriefComments) { 3254 return CreateCodeCompletionString(S.Context, S.PP, CCContext, Allocator, 3255 CCTUInfo, IncludeBriefComments); 3256 } 3257 3258 CodeCompletionString *CodeCompletionResult::CreateCodeCompletionStringForMacro( 3259 Preprocessor &PP, CodeCompletionAllocator &Allocator, 3260 CodeCompletionTUInfo &CCTUInfo) { 3261 assert(Kind == RK_Macro); 3262 CodeCompletionBuilder Result(Allocator, CCTUInfo, Priority, Availability); 3263 const MacroInfo *MI = PP.getMacroInfo(Macro); 3264 Result.AddTypedTextChunk(Result.getAllocator().CopyString(Macro->getName())); 3265 3266 if (!MI || !MI->isFunctionLike()) 3267 return Result.TakeString(); 3268 3269 // Format a function-like macro with placeholders for the arguments. 3270 Result.AddChunk(CodeCompletionString::CK_LeftParen); 3271 MacroInfo::param_iterator A = MI->param_begin(), AEnd = MI->param_end(); 3272 3273 // C99 variadic macros add __VA_ARGS__ at the end. Skip it. 3274 if (MI->isC99Varargs()) { 3275 --AEnd; 3276 3277 if (A == AEnd) { 3278 Result.AddPlaceholderChunk("..."); 3279 } 3280 } 3281 3282 for (MacroInfo::param_iterator A = MI->param_begin(); A != AEnd; ++A) { 3283 if (A != MI->param_begin()) 3284 Result.AddChunk(CodeCompletionString::CK_Comma); 3285 3286 if (MI->isVariadic() && (A + 1) == AEnd) { 3287 SmallString<32> Arg = (*A)->getName(); 3288 if (MI->isC99Varargs()) 3289 Arg += ", ..."; 3290 else 3291 Arg += "..."; 3292 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg)); 3293 break; 3294 } 3295 3296 // Non-variadic macros are simple. 3297 Result.AddPlaceholderChunk( 3298 Result.getAllocator().CopyString((*A)->getName())); 3299 } 3300 Result.AddChunk(CodeCompletionString::CK_RightParen); 3301 return Result.TakeString(); 3302 } 3303 3304 /// If possible, create a new code completion string for the given 3305 /// result. 3306 /// 3307 /// \returns Either a new, heap-allocated code completion string describing 3308 /// how to use this result, or NULL to indicate that the string or name of the 3309 /// result is all that is needed. 3310 CodeCompletionString *CodeCompletionResult::CreateCodeCompletionString( 3311 ASTContext &Ctx, Preprocessor &PP, const CodeCompletionContext &CCContext, 3312 CodeCompletionAllocator &Allocator, CodeCompletionTUInfo &CCTUInfo, 3313 bool IncludeBriefComments) { 3314 if (Kind == RK_Macro) 3315 return CreateCodeCompletionStringForMacro(PP, Allocator, CCTUInfo); 3316 3317 CodeCompletionBuilder Result(Allocator, CCTUInfo, Priority, Availability); 3318 3319 PrintingPolicy Policy = getCompletionPrintingPolicy(Ctx, PP); 3320 if (Kind == RK_Pattern) { 3321 Pattern->Priority = Priority; 3322 Pattern->Availability = Availability; 3323 3324 if (Declaration) { 3325 Result.addParentContext(Declaration->getDeclContext()); 3326 Pattern->ParentName = Result.getParentName(); 3327 if (const RawComment *RC = 3328 getPatternCompletionComment(Ctx, Declaration)) { 3329 Result.addBriefComment(RC->getBriefText(Ctx)); 3330 Pattern->BriefComment = Result.getBriefComment(); 3331 } 3332 } 3333 3334 return Pattern; 3335 } 3336 3337 if (Kind == RK_Keyword) { 3338 Result.AddTypedTextChunk(Keyword); 3339 return Result.TakeString(); 3340 } 3341 assert(Kind == RK_Declaration && "Missed a result kind?"); 3342 return createCodeCompletionStringForDecl( 3343 PP, Ctx, Result, IncludeBriefComments, CCContext, Policy); 3344 } 3345 3346 static void printOverrideString(const CodeCompletionString &CCS, 3347 std::string &BeforeName, 3348 std::string &NameAndSignature) { 3349 bool SeenTypedChunk = false; 3350 for (auto &Chunk : CCS) { 3351 if (Chunk.Kind == CodeCompletionString::CK_Optional) { 3352 assert(SeenTypedChunk && "optional parameter before name"); 3353 // Note that we put all chunks inside into NameAndSignature. 3354 printOverrideString(*Chunk.Optional, NameAndSignature, NameAndSignature); 3355 continue; 3356 } 3357 SeenTypedChunk |= Chunk.Kind == CodeCompletionString::CK_TypedText; 3358 if (SeenTypedChunk) 3359 NameAndSignature += Chunk.Text; 3360 else 3361 BeforeName += Chunk.Text; 3362 } 3363 } 3364 3365 CodeCompletionString * 3366 CodeCompletionResult::createCodeCompletionStringForOverride( 3367 Preprocessor &PP, ASTContext &Ctx, CodeCompletionBuilder &Result, 3368 bool IncludeBriefComments, const CodeCompletionContext &CCContext, 3369 PrintingPolicy &Policy) { 3370 auto *CCS = createCodeCompletionStringForDecl(PP, Ctx, Result, 3371 /*IncludeBriefComments=*/false, 3372 CCContext, Policy); 3373 std::string BeforeName; 3374 std::string NameAndSignature; 3375 // For overrides all chunks go into the result, none are informative. 3376 printOverrideString(*CCS, BeforeName, NameAndSignature); 3377 NameAndSignature += " override"; 3378 3379 Result.AddTextChunk(Result.getAllocator().CopyString(BeforeName)); 3380 Result.AddChunk(CodeCompletionString::CK_HorizontalSpace); 3381 Result.AddTypedTextChunk(Result.getAllocator().CopyString(NameAndSignature)); 3382 return Result.TakeString(); 3383 } 3384 3385 // FIXME: Right now this works well with lambdas. Add support for other functor 3386 // types like std::function. 3387 static const NamedDecl *extractFunctorCallOperator(const NamedDecl *ND) { 3388 const auto *VD = dyn_cast<VarDecl>(ND); 3389 if (!VD) 3390 return nullptr; 3391 const auto *RecordDecl = VD->getType()->getAsCXXRecordDecl(); 3392 if (!RecordDecl || !RecordDecl->isLambda()) 3393 return nullptr; 3394 return RecordDecl->getLambdaCallOperator(); 3395 } 3396 3397 CodeCompletionString *CodeCompletionResult::createCodeCompletionStringForDecl( 3398 Preprocessor &PP, ASTContext &Ctx, CodeCompletionBuilder &Result, 3399 bool IncludeBriefComments, const CodeCompletionContext &CCContext, 3400 PrintingPolicy &Policy) { 3401 const NamedDecl *ND = Declaration; 3402 Result.addParentContext(ND->getDeclContext()); 3403 3404 if (IncludeBriefComments) { 3405 // Add documentation comment, if it exists. 3406 if (const RawComment *RC = getCompletionComment(Ctx, Declaration)) { 3407 Result.addBriefComment(RC->getBriefText(Ctx)); 3408 } 3409 } 3410 3411 if (StartsNestedNameSpecifier) { 3412 Result.AddTypedTextChunk( 3413 Result.getAllocator().CopyString(ND->getNameAsString())); 3414 Result.AddTextChunk("::"); 3415 return Result.TakeString(); 3416 } 3417 3418 for (const auto *I : ND->specific_attrs<AnnotateAttr>()) 3419 Result.AddAnnotation(Result.getAllocator().CopyString(I->getAnnotation())); 3420 3421 auto AddFunctionTypeAndResult = [&](const FunctionDecl *Function) { 3422 AddResultTypeChunk(Ctx, Policy, Function, CCContext.getBaseType(), Result); 3423 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative, 3424 Ctx, Policy); 3425 AddTypedNameChunk(Ctx, Policy, ND, Result); 3426 Result.AddChunk(CodeCompletionString::CK_LeftParen); 3427 AddFunctionParameterChunks(PP, Policy, Function, Result); 3428 Result.AddChunk(CodeCompletionString::CK_RightParen); 3429 AddFunctionTypeQualsToCompletionString(Result, Function); 3430 }; 3431 3432 if (const auto *Function = dyn_cast<FunctionDecl>(ND)) { 3433 AddFunctionTypeAndResult(Function); 3434 return Result.TakeString(); 3435 } 3436 3437 if (const auto *CallOperator = 3438 dyn_cast_or_null<FunctionDecl>(extractFunctorCallOperator(ND))) { 3439 AddFunctionTypeAndResult(CallOperator); 3440 return Result.TakeString(); 3441 } 3442 3443 AddResultTypeChunk(Ctx, Policy, ND, CCContext.getBaseType(), Result); 3444 3445 if (const FunctionTemplateDecl *FunTmpl = 3446 dyn_cast<FunctionTemplateDecl>(ND)) { 3447 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative, 3448 Ctx, Policy); 3449 FunctionDecl *Function = FunTmpl->getTemplatedDecl(); 3450 AddTypedNameChunk(Ctx, Policy, Function, Result); 3451 3452 // Figure out which template parameters are deduced (or have default 3453 // arguments). 3454 llvm::SmallBitVector Deduced; 3455 Sema::MarkDeducedTemplateParameters(Ctx, FunTmpl, Deduced); 3456 unsigned LastDeducibleArgument; 3457 for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0; 3458 --LastDeducibleArgument) { 3459 if (!Deduced[LastDeducibleArgument - 1]) { 3460 // C++0x: Figure out if the template argument has a default. If so, 3461 // the user doesn't need to type this argument. 3462 // FIXME: We need to abstract template parameters better! 3463 bool HasDefaultArg = false; 3464 NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam( 3465 LastDeducibleArgument - 1); 3466 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) 3467 HasDefaultArg = TTP->hasDefaultArgument(); 3468 else if (NonTypeTemplateParmDecl *NTTP = 3469 dyn_cast<NonTypeTemplateParmDecl>(Param)) 3470 HasDefaultArg = NTTP->hasDefaultArgument(); 3471 else { 3472 assert(isa<TemplateTemplateParmDecl>(Param)); 3473 HasDefaultArg = 3474 cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument(); 3475 } 3476 3477 if (!HasDefaultArg) 3478 break; 3479 } 3480 } 3481 3482 if (LastDeducibleArgument) { 3483 // Some of the function template arguments cannot be deduced from a 3484 // function call, so we introduce an explicit template argument list 3485 // containing all of the arguments up to the first deducible argument. 3486 Result.AddChunk(CodeCompletionString::CK_LeftAngle); 3487 AddTemplateParameterChunks(Ctx, Policy, FunTmpl, Result, 3488 LastDeducibleArgument); 3489 Result.AddChunk(CodeCompletionString::CK_RightAngle); 3490 } 3491 3492 // Add the function parameters 3493 Result.AddChunk(CodeCompletionString::CK_LeftParen); 3494 AddFunctionParameterChunks(PP, Policy, Function, Result); 3495 Result.AddChunk(CodeCompletionString::CK_RightParen); 3496 AddFunctionTypeQualsToCompletionString(Result, Function); 3497 return Result.TakeString(); 3498 } 3499 3500 if (const auto *Template = dyn_cast<TemplateDecl>(ND)) { 3501 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative, 3502 Ctx, Policy); 3503 Result.AddTypedTextChunk( 3504 Result.getAllocator().CopyString(Template->getNameAsString())); 3505 Result.AddChunk(CodeCompletionString::CK_LeftAngle); 3506 AddTemplateParameterChunks(Ctx, Policy, Template, Result); 3507 Result.AddChunk(CodeCompletionString::CK_RightAngle); 3508 return Result.TakeString(); 3509 } 3510 3511 if (const auto *Method = dyn_cast<ObjCMethodDecl>(ND)) { 3512 Selector Sel = Method->getSelector(); 3513 if (Sel.isUnarySelector()) { 3514 Result.AddTypedTextChunk( 3515 Result.getAllocator().CopyString(Sel.getNameForSlot(0))); 3516 return Result.TakeString(); 3517 } 3518 3519 std::string SelName = Sel.getNameForSlot(0).str(); 3520 SelName += ':'; 3521 if (StartParameter == 0) 3522 Result.AddTypedTextChunk(Result.getAllocator().CopyString(SelName)); 3523 else { 3524 Result.AddInformativeChunk(Result.getAllocator().CopyString(SelName)); 3525 3526 // If there is only one parameter, and we're past it, add an empty 3527 // typed-text chunk since there is nothing to type. 3528 if (Method->param_size() == 1) 3529 Result.AddTypedTextChunk(""); 3530 } 3531 unsigned Idx = 0; 3532 for (ObjCMethodDecl::param_const_iterator P = Method->param_begin(), 3533 PEnd = Method->param_end(); 3534 P != PEnd; (void)++P, ++Idx) { 3535 if (Idx > 0) { 3536 std::string Keyword; 3537 if (Idx > StartParameter) 3538 Result.AddChunk(CodeCompletionString::CK_HorizontalSpace); 3539 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(Idx)) 3540 Keyword += II->getName(); 3541 Keyword += ":"; 3542 if (Idx < StartParameter || AllParametersAreInformative) 3543 Result.AddInformativeChunk(Result.getAllocator().CopyString(Keyword)); 3544 else 3545 Result.AddTypedTextChunk(Result.getAllocator().CopyString(Keyword)); 3546 } 3547 3548 // If we're before the starting parameter, skip the placeholder. 3549 if (Idx < StartParameter) 3550 continue; 3551 3552 std::string Arg; 3553 QualType ParamType = (*P)->getType(); 3554 Optional<ArrayRef<QualType>> ObjCSubsts; 3555 if (!CCContext.getBaseType().isNull()) 3556 ObjCSubsts = CCContext.getBaseType()->getObjCSubstitutions(Method); 3557 3558 if (ParamType->isBlockPointerType() && !DeclaringEntity) 3559 Arg = FormatFunctionParameter(Policy, *P, true, 3560 /*SuppressBlock=*/false, ObjCSubsts); 3561 else { 3562 if (ObjCSubsts) 3563 ParamType = ParamType.substObjCTypeArgs( 3564 Ctx, *ObjCSubsts, ObjCSubstitutionContext::Parameter); 3565 Arg = "(" + formatObjCParamQualifiers((*P)->getObjCDeclQualifier(), 3566 ParamType); 3567 Arg += ParamType.getAsString(Policy) + ")"; 3568 if (IdentifierInfo *II = (*P)->getIdentifier()) 3569 if (DeclaringEntity || AllParametersAreInformative) 3570 Arg += II->getName(); 3571 } 3572 3573 if (Method->isVariadic() && (P + 1) == PEnd) 3574 Arg += ", ..."; 3575 3576 if (DeclaringEntity) 3577 Result.AddTextChunk(Result.getAllocator().CopyString(Arg)); 3578 else if (AllParametersAreInformative) 3579 Result.AddInformativeChunk(Result.getAllocator().CopyString(Arg)); 3580 else 3581 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg)); 3582 } 3583 3584 if (Method->isVariadic()) { 3585 if (Method->param_size() == 0) { 3586 if (DeclaringEntity) 3587 Result.AddTextChunk(", ..."); 3588 else if (AllParametersAreInformative) 3589 Result.AddInformativeChunk(", ..."); 3590 else 3591 Result.AddPlaceholderChunk(", ..."); 3592 } 3593 3594 MaybeAddSentinel(PP, Method, Result); 3595 } 3596 3597 return Result.TakeString(); 3598 } 3599 3600 if (Qualifier) 3601 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative, 3602 Ctx, Policy); 3603 3604 Result.AddTypedTextChunk( 3605 Result.getAllocator().CopyString(ND->getNameAsString())); 3606 return Result.TakeString(); 3607 } 3608 3609 const RawComment *clang::getCompletionComment(const ASTContext &Ctx, 3610 const NamedDecl *ND) { 3611 if (!ND) 3612 return nullptr; 3613 if (auto *RC = Ctx.getRawCommentForAnyRedecl(ND)) 3614 return RC; 3615 3616 // Try to find comment from a property for ObjC methods. 3617 const auto *M = dyn_cast<ObjCMethodDecl>(ND); 3618 if (!M) 3619 return nullptr; 3620 const ObjCPropertyDecl *PDecl = M->findPropertyDecl(); 3621 if (!PDecl) 3622 return nullptr; 3623 3624 return Ctx.getRawCommentForAnyRedecl(PDecl); 3625 } 3626 3627 const RawComment *clang::getPatternCompletionComment(const ASTContext &Ctx, 3628 const NamedDecl *ND) { 3629 const auto *M = dyn_cast_or_null<ObjCMethodDecl>(ND); 3630 if (!M || !M->isPropertyAccessor()) 3631 return nullptr; 3632 3633 // Provide code completion comment for self.GetterName where 3634 // GetterName is the getter method for a property with name 3635 // different from the property name (declared via a property 3636 // getter attribute. 3637 const ObjCPropertyDecl *PDecl = M->findPropertyDecl(); 3638 if (!PDecl) 3639 return nullptr; 3640 if (PDecl->getGetterName() == M->getSelector() && 3641 PDecl->getIdentifier() != M->getIdentifier()) { 3642 if (auto *RC = Ctx.getRawCommentForAnyRedecl(M)) 3643 return RC; 3644 if (auto *RC = Ctx.getRawCommentForAnyRedecl(PDecl)) 3645 return RC; 3646 } 3647 return nullptr; 3648 } 3649 3650 const RawComment *clang::getParameterComment( 3651 const ASTContext &Ctx, 3652 const CodeCompleteConsumer::OverloadCandidate &Result, unsigned ArgIndex) { 3653 auto FDecl = Result.getFunction(); 3654 if (!FDecl) 3655 return nullptr; 3656 if (ArgIndex < FDecl->getNumParams()) 3657 return Ctx.getRawCommentForAnyRedecl(FDecl->getParamDecl(ArgIndex)); 3658 return nullptr; 3659 } 3660 3661 /// Add function overload parameter chunks to the given code completion 3662 /// string. 3663 static void AddOverloadParameterChunks(ASTContext &Context, 3664 const PrintingPolicy &Policy, 3665 const FunctionDecl *Function, 3666 const FunctionProtoType *Prototype, 3667 CodeCompletionBuilder &Result, 3668 unsigned CurrentArg, unsigned Start = 0, 3669 bool InOptional = false) { 3670 bool FirstParameter = true; 3671 unsigned NumParams = 3672 Function ? Function->getNumParams() : Prototype->getNumParams(); 3673 3674 for (unsigned P = Start; P != NumParams; ++P) { 3675 if (Function && Function->getParamDecl(P)->hasDefaultArg() && !InOptional) { 3676 // When we see an optional default argument, put that argument and 3677 // the remaining default arguments into a new, optional string. 3678 CodeCompletionBuilder Opt(Result.getAllocator(), 3679 Result.getCodeCompletionTUInfo()); 3680 if (!FirstParameter) 3681 Opt.AddChunk(CodeCompletionString::CK_Comma); 3682 // Optional sections are nested. 3683 AddOverloadParameterChunks(Context, Policy, Function, Prototype, Opt, 3684 CurrentArg, P, /*InOptional=*/true); 3685 Result.AddOptionalChunk(Opt.TakeString()); 3686 return; 3687 } 3688 3689 if (FirstParameter) 3690 FirstParameter = false; 3691 else 3692 Result.AddChunk(CodeCompletionString::CK_Comma); 3693 3694 InOptional = false; 3695 3696 // Format the placeholder string. 3697 std::string Placeholder; 3698 if (Function) { 3699 const ParmVarDecl *Param = Function->getParamDecl(P); 3700 Placeholder = FormatFunctionParameter(Policy, Param); 3701 if (Param->hasDefaultArg()) 3702 Placeholder += GetDefaultValueString(Param, Context.getSourceManager(), 3703 Context.getLangOpts()); 3704 } else { 3705 Placeholder = Prototype->getParamType(P).getAsString(Policy); 3706 } 3707 3708 if (P == CurrentArg) 3709 Result.AddCurrentParameterChunk( 3710 Result.getAllocator().CopyString(Placeholder)); 3711 else 3712 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Placeholder)); 3713 } 3714 3715 if (Prototype && Prototype->isVariadic()) { 3716 CodeCompletionBuilder Opt(Result.getAllocator(), 3717 Result.getCodeCompletionTUInfo()); 3718 if (!FirstParameter) 3719 Opt.AddChunk(CodeCompletionString::CK_Comma); 3720 3721 if (CurrentArg < NumParams) 3722 Opt.AddPlaceholderChunk("..."); 3723 else 3724 Opt.AddCurrentParameterChunk("..."); 3725 3726 Result.AddOptionalChunk(Opt.TakeString()); 3727 } 3728 } 3729 3730 CodeCompletionString * 3731 CodeCompleteConsumer::OverloadCandidate::CreateSignatureString( 3732 unsigned CurrentArg, Sema &S, CodeCompletionAllocator &Allocator, 3733 CodeCompletionTUInfo &CCTUInfo, bool IncludeBriefComments) const { 3734 PrintingPolicy Policy = getCompletionPrintingPolicy(S); 3735 // Show signatures of constructors as they are declared: 3736 // vector(int n) rather than vector<string>(int n) 3737 // This is less noisy without being less clear, and avoids tricky cases. 3738 Policy.SuppressTemplateArgsInCXXConstructors = true; 3739 3740 // FIXME: Set priority, availability appropriately. 3741 CodeCompletionBuilder Result(Allocator, CCTUInfo, 1, 3742 CXAvailability_Available); 3743 FunctionDecl *FDecl = getFunction(); 3744 const FunctionProtoType *Proto = 3745 dyn_cast<FunctionProtoType>(getFunctionType()); 3746 if (!FDecl && !Proto) { 3747 // Function without a prototype. Just give the return type and a 3748 // highlighted ellipsis. 3749 const FunctionType *FT = getFunctionType(); 3750 Result.AddResultTypeChunk(Result.getAllocator().CopyString( 3751 FT->getReturnType().getAsString(Policy))); 3752 Result.AddChunk(CodeCompletionString::CK_LeftParen); 3753 Result.AddChunk(CodeCompletionString::CK_CurrentParameter, "..."); 3754 Result.AddChunk(CodeCompletionString::CK_RightParen); 3755 return Result.TakeString(); 3756 } 3757 3758 if (FDecl) { 3759 if (IncludeBriefComments) { 3760 if (auto RC = getParameterComment(S.getASTContext(), *this, CurrentArg)) 3761 Result.addBriefComment(RC->getBriefText(S.getASTContext())); 3762 } 3763 AddResultTypeChunk(S.Context, Policy, FDecl, QualType(), Result); 3764 3765 std::string Name; 3766 llvm::raw_string_ostream OS(Name); 3767 FDecl->getDeclName().print(OS, Policy); 3768 Result.AddTextChunk(Result.getAllocator().CopyString(OS.str())); 3769 } else { 3770 Result.AddResultTypeChunk(Result.getAllocator().CopyString( 3771 Proto->getReturnType().getAsString(Policy))); 3772 } 3773 3774 Result.AddChunk(CodeCompletionString::CK_LeftParen); 3775 AddOverloadParameterChunks(S.getASTContext(), Policy, FDecl, Proto, Result, 3776 CurrentArg); 3777 Result.AddChunk(CodeCompletionString::CK_RightParen); 3778 3779 return Result.TakeString(); 3780 } 3781 3782 unsigned clang::getMacroUsagePriority(StringRef MacroName, 3783 const LangOptions &LangOpts, 3784 bool PreferredTypeIsPointer) { 3785 unsigned Priority = CCP_Macro; 3786 3787 // Treat the "nil", "Nil" and "NULL" macros as null pointer constants. 3788 if (MacroName.equals("nil") || MacroName.equals("NULL") || 3789 MacroName.equals("Nil")) { 3790 Priority = CCP_Constant; 3791 if (PreferredTypeIsPointer) 3792 Priority = Priority / CCF_SimilarTypeMatch; 3793 } 3794 // Treat "YES", "NO", "true", and "false" as constants. 3795 else if (MacroName.equals("YES") || MacroName.equals("NO") || 3796 MacroName.equals("true") || MacroName.equals("false")) 3797 Priority = CCP_Constant; 3798 // Treat "bool" as a type. 3799 else if (MacroName.equals("bool")) 3800 Priority = CCP_Type + (LangOpts.ObjC ? CCD_bool_in_ObjC : 0); 3801 3802 return Priority; 3803 } 3804 3805 CXCursorKind clang::getCursorKindForDecl(const Decl *D) { 3806 if (!D) 3807 return CXCursor_UnexposedDecl; 3808 3809 switch (D->getKind()) { 3810 case Decl::Enum: 3811 return CXCursor_EnumDecl; 3812 case Decl::EnumConstant: 3813 return CXCursor_EnumConstantDecl; 3814 case Decl::Field: 3815 return CXCursor_FieldDecl; 3816 case Decl::Function: 3817 return CXCursor_FunctionDecl; 3818 case Decl::ObjCCategory: 3819 return CXCursor_ObjCCategoryDecl; 3820 case Decl::ObjCCategoryImpl: 3821 return CXCursor_ObjCCategoryImplDecl; 3822 case Decl::ObjCImplementation: 3823 return CXCursor_ObjCImplementationDecl; 3824 3825 case Decl::ObjCInterface: 3826 return CXCursor_ObjCInterfaceDecl; 3827 case Decl::ObjCIvar: 3828 return CXCursor_ObjCIvarDecl; 3829 case Decl::ObjCMethod: 3830 return cast<ObjCMethodDecl>(D)->isInstanceMethod() 3831 ? CXCursor_ObjCInstanceMethodDecl 3832 : CXCursor_ObjCClassMethodDecl; 3833 case Decl::CXXMethod: 3834 return CXCursor_CXXMethod; 3835 case Decl::CXXConstructor: 3836 return CXCursor_Constructor; 3837 case Decl::CXXDestructor: 3838 return CXCursor_Destructor; 3839 case Decl::CXXConversion: 3840 return CXCursor_ConversionFunction; 3841 case Decl::ObjCProperty: 3842 return CXCursor_ObjCPropertyDecl; 3843 case Decl::ObjCProtocol: 3844 return CXCursor_ObjCProtocolDecl; 3845 case Decl::ParmVar: 3846 return CXCursor_ParmDecl; 3847 case Decl::Typedef: 3848 return CXCursor_TypedefDecl; 3849 case Decl::TypeAlias: 3850 return CXCursor_TypeAliasDecl; 3851 case Decl::TypeAliasTemplate: 3852 return CXCursor_TypeAliasTemplateDecl; 3853 case Decl::Var: 3854 return CXCursor_VarDecl; 3855 case Decl::Namespace: 3856 return CXCursor_Namespace; 3857 case Decl::NamespaceAlias: 3858 return CXCursor_NamespaceAlias; 3859 case Decl::TemplateTypeParm: 3860 return CXCursor_TemplateTypeParameter; 3861 case Decl::NonTypeTemplateParm: 3862 return CXCursor_NonTypeTemplateParameter; 3863 case Decl::TemplateTemplateParm: 3864 return CXCursor_TemplateTemplateParameter; 3865 case Decl::FunctionTemplate: 3866 return CXCursor_FunctionTemplate; 3867 case Decl::ClassTemplate: 3868 return CXCursor_ClassTemplate; 3869 case Decl::AccessSpec: 3870 return CXCursor_CXXAccessSpecifier; 3871 case Decl::ClassTemplatePartialSpecialization: 3872 return CXCursor_ClassTemplatePartialSpecialization; 3873 case Decl::UsingDirective: 3874 return CXCursor_UsingDirective; 3875 case Decl::StaticAssert: 3876 return CXCursor_StaticAssert; 3877 case Decl::Friend: 3878 return CXCursor_FriendDecl; 3879 case Decl::TranslationUnit: 3880 return CXCursor_TranslationUnit; 3881 3882 case Decl::Using: 3883 case Decl::UnresolvedUsingValue: 3884 case Decl::UnresolvedUsingTypename: 3885 return CXCursor_UsingDeclaration; 3886 3887 case Decl::ObjCPropertyImpl: 3888 switch (cast<ObjCPropertyImplDecl>(D)->getPropertyImplementation()) { 3889 case ObjCPropertyImplDecl::Dynamic: 3890 return CXCursor_ObjCDynamicDecl; 3891 3892 case ObjCPropertyImplDecl::Synthesize: 3893 return CXCursor_ObjCSynthesizeDecl; 3894 } 3895 llvm_unreachable("Unexpected Kind!"); 3896 3897 case Decl::Import: 3898 return CXCursor_ModuleImportDecl; 3899 3900 case Decl::ObjCTypeParam: 3901 return CXCursor_TemplateTypeParameter; 3902 3903 default: 3904 if (const auto *TD = dyn_cast<TagDecl>(D)) { 3905 switch (TD->getTagKind()) { 3906 case TTK_Interface: // fall through 3907 case TTK_Struct: 3908 return CXCursor_StructDecl; 3909 case TTK_Class: 3910 return CXCursor_ClassDecl; 3911 case TTK_Union: 3912 return CXCursor_UnionDecl; 3913 case TTK_Enum: 3914 return CXCursor_EnumDecl; 3915 } 3916 } 3917 } 3918 3919 return CXCursor_UnexposedDecl; 3920 } 3921 3922 static void AddMacroResults(Preprocessor &PP, ResultBuilder &Results, 3923 bool LoadExternal, bool IncludeUndefined, 3924 bool TargetTypeIsPointer = false) { 3925 typedef CodeCompletionResult Result; 3926 3927 Results.EnterNewScope(); 3928 3929 for (Preprocessor::macro_iterator M = PP.macro_begin(LoadExternal), 3930 MEnd = PP.macro_end(LoadExternal); 3931 M != MEnd; ++M) { 3932 auto MD = PP.getMacroDefinition(M->first); 3933 if (IncludeUndefined || MD) { 3934 MacroInfo *MI = MD.getMacroInfo(); 3935 if (MI && MI->isUsedForHeaderGuard()) 3936 continue; 3937 3938 Results.AddResult( 3939 Result(M->first, MI, 3940 getMacroUsagePriority(M->first->getName(), PP.getLangOpts(), 3941 TargetTypeIsPointer))); 3942 } 3943 } 3944 3945 Results.ExitScope(); 3946 } 3947 3948 static void AddPrettyFunctionResults(const LangOptions &LangOpts, 3949 ResultBuilder &Results) { 3950 typedef CodeCompletionResult Result; 3951 3952 Results.EnterNewScope(); 3953 3954 Results.AddResult(Result("__PRETTY_FUNCTION__", CCP_Constant)); 3955 Results.AddResult(Result("__FUNCTION__", CCP_Constant)); 3956 if (LangOpts.C99 || LangOpts.CPlusPlus11) 3957 Results.AddResult(Result("__func__", CCP_Constant)); 3958 Results.ExitScope(); 3959 } 3960 3961 static void HandleCodeCompleteResults(Sema *S, 3962 CodeCompleteConsumer *CodeCompleter, 3963 CodeCompletionContext Context, 3964 CodeCompletionResult *Results, 3965 unsigned NumResults) { 3966 if (CodeCompleter) 3967 CodeCompleter->ProcessCodeCompleteResults(*S, Context, Results, NumResults); 3968 } 3969 3970 static CodeCompletionContext 3971 mapCodeCompletionContext(Sema &S, Sema::ParserCompletionContext PCC) { 3972 switch (PCC) { 3973 case Sema::PCC_Namespace: 3974 return CodeCompletionContext::CCC_TopLevel; 3975 3976 case Sema::PCC_Class: 3977 return CodeCompletionContext::CCC_ClassStructUnion; 3978 3979 case Sema::PCC_ObjCInterface: 3980 return CodeCompletionContext::CCC_ObjCInterface; 3981 3982 case Sema::PCC_ObjCImplementation: 3983 return CodeCompletionContext::CCC_ObjCImplementation; 3984 3985 case Sema::PCC_ObjCInstanceVariableList: 3986 return CodeCompletionContext::CCC_ObjCIvarList; 3987 3988 case Sema::PCC_Template: 3989 case Sema::PCC_MemberTemplate: 3990 if (S.CurContext->isFileContext()) 3991 return CodeCompletionContext::CCC_TopLevel; 3992 if (S.CurContext->isRecord()) 3993 return CodeCompletionContext::CCC_ClassStructUnion; 3994 return CodeCompletionContext::CCC_Other; 3995 3996 case Sema::PCC_RecoveryInFunction: 3997 return CodeCompletionContext::CCC_Recovery; 3998 3999 case Sema::PCC_ForInit: 4000 if (S.getLangOpts().CPlusPlus || S.getLangOpts().C99 || 4001 S.getLangOpts().ObjC) 4002 return CodeCompletionContext::CCC_ParenthesizedExpression; 4003 else 4004 return CodeCompletionContext::CCC_Expression; 4005 4006 case Sema::PCC_Expression: 4007 return CodeCompletionContext::CCC_Expression; 4008 case Sema::PCC_Condition: 4009 return CodeCompletionContext(CodeCompletionContext::CCC_Expression, 4010 S.getASTContext().BoolTy); 4011 4012 case Sema::PCC_Statement: 4013 return CodeCompletionContext::CCC_Statement; 4014 4015 case Sema::PCC_Type: 4016 return CodeCompletionContext::CCC_Type; 4017 4018 case Sema::PCC_ParenthesizedExpression: 4019 return CodeCompletionContext::CCC_ParenthesizedExpression; 4020 4021 case Sema::PCC_LocalDeclarationSpecifiers: 4022 return CodeCompletionContext::CCC_Type; 4023 } 4024 4025 llvm_unreachable("Invalid ParserCompletionContext!"); 4026 } 4027 4028 /// If we're in a C++ virtual member function, add completion results 4029 /// that invoke the functions we override, since it's common to invoke the 4030 /// overridden function as well as adding new functionality. 4031 /// 4032 /// \param S The semantic analysis object for which we are generating results. 4033 /// 4034 /// \param InContext This context in which the nested-name-specifier preceding 4035 /// the code-completion point 4036 static void MaybeAddOverrideCalls(Sema &S, DeclContext *InContext, 4037 ResultBuilder &Results) { 4038 // Look through blocks. 4039 DeclContext *CurContext = S.CurContext; 4040 while (isa<BlockDecl>(CurContext)) 4041 CurContext = CurContext->getParent(); 4042 4043 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(CurContext); 4044 if (!Method || !Method->isVirtual()) 4045 return; 4046 4047 // We need to have names for all of the parameters, if we're going to 4048 // generate a forwarding call. 4049 for (auto P : Method->parameters()) 4050 if (!P->getDeclName()) 4051 return; 4052 4053 PrintingPolicy Policy = getCompletionPrintingPolicy(S); 4054 for (const CXXMethodDecl *Overridden : Method->overridden_methods()) { 4055 CodeCompletionBuilder Builder(Results.getAllocator(), 4056 Results.getCodeCompletionTUInfo()); 4057 if (Overridden->getCanonicalDecl() == Method->getCanonicalDecl()) 4058 continue; 4059 4060 // If we need a nested-name-specifier, add one now. 4061 if (!InContext) { 4062 NestedNameSpecifier *NNS = getRequiredQualification( 4063 S.Context, CurContext, Overridden->getDeclContext()); 4064 if (NNS) { 4065 std::string Str; 4066 llvm::raw_string_ostream OS(Str); 4067 NNS->print(OS, Policy); 4068 Builder.AddTextChunk(Results.getAllocator().CopyString(OS.str())); 4069 } 4070 } else if (!InContext->Equals(Overridden->getDeclContext())) 4071 continue; 4072 4073 Builder.AddTypedTextChunk( 4074 Results.getAllocator().CopyString(Overridden->getNameAsString())); 4075 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 4076 bool FirstParam = true; 4077 for (auto P : Method->parameters()) { 4078 if (FirstParam) 4079 FirstParam = false; 4080 else 4081 Builder.AddChunk(CodeCompletionString::CK_Comma); 4082 4083 Builder.AddPlaceholderChunk( 4084 Results.getAllocator().CopyString(P->getIdentifier()->getName())); 4085 } 4086 Builder.AddChunk(CodeCompletionString::CK_RightParen); 4087 Results.AddResult(CodeCompletionResult( 4088 Builder.TakeString(), CCP_SuperCompletion, CXCursor_CXXMethod, 4089 CXAvailability_Available, Overridden)); 4090 Results.Ignore(Overridden); 4091 } 4092 } 4093 4094 void Sema::CodeCompleteModuleImport(SourceLocation ImportLoc, 4095 ModuleIdPath Path) { 4096 typedef CodeCompletionResult Result; 4097 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 4098 CodeCompleter->getCodeCompletionTUInfo(), 4099 CodeCompletionContext::CCC_Other); 4100 Results.EnterNewScope(); 4101 4102 CodeCompletionAllocator &Allocator = Results.getAllocator(); 4103 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo()); 4104 typedef CodeCompletionResult Result; 4105 if (Path.empty()) { 4106 // Enumerate all top-level modules. 4107 SmallVector<Module *, 8> Modules; 4108 PP.getHeaderSearchInfo().collectAllModules(Modules); 4109 for (unsigned I = 0, N = Modules.size(); I != N; ++I) { 4110 Builder.AddTypedTextChunk( 4111 Builder.getAllocator().CopyString(Modules[I]->Name)); 4112 Results.AddResult(Result( 4113 Builder.TakeString(), CCP_Declaration, CXCursor_ModuleImportDecl, 4114 Modules[I]->isAvailable() ? CXAvailability_Available 4115 : CXAvailability_NotAvailable)); 4116 } 4117 } else if (getLangOpts().Modules) { 4118 // Load the named module. 4119 Module *Mod = 4120 PP.getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible, 4121 /*IsInclusionDirective=*/false); 4122 // Enumerate submodules. 4123 if (Mod) { 4124 for (Module::submodule_iterator Sub = Mod->submodule_begin(), 4125 SubEnd = Mod->submodule_end(); 4126 Sub != SubEnd; ++Sub) { 4127 4128 Builder.AddTypedTextChunk( 4129 Builder.getAllocator().CopyString((*Sub)->Name)); 4130 Results.AddResult(Result( 4131 Builder.TakeString(), CCP_Declaration, CXCursor_ModuleImportDecl, 4132 (*Sub)->isAvailable() ? CXAvailability_Available 4133 : CXAvailability_NotAvailable)); 4134 } 4135 } 4136 } 4137 Results.ExitScope(); 4138 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 4139 Results.data(), Results.size()); 4140 } 4141 4142 void Sema::CodeCompleteOrdinaryName(Scope *S, 4143 ParserCompletionContext CompletionContext) { 4144 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 4145 CodeCompleter->getCodeCompletionTUInfo(), 4146 mapCodeCompletionContext(*this, CompletionContext)); 4147 Results.EnterNewScope(); 4148 4149 // Determine how to filter results, e.g., so that the names of 4150 // values (functions, enumerators, function templates, etc.) are 4151 // only allowed where we can have an expression. 4152 switch (CompletionContext) { 4153 case PCC_Namespace: 4154 case PCC_Class: 4155 case PCC_ObjCInterface: 4156 case PCC_ObjCImplementation: 4157 case PCC_ObjCInstanceVariableList: 4158 case PCC_Template: 4159 case PCC_MemberTemplate: 4160 case PCC_Type: 4161 case PCC_LocalDeclarationSpecifiers: 4162 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName); 4163 break; 4164 4165 case PCC_Statement: 4166 case PCC_ParenthesizedExpression: 4167 case PCC_Expression: 4168 case PCC_ForInit: 4169 case PCC_Condition: 4170 if (WantTypesInContext(CompletionContext, getLangOpts())) 4171 Results.setFilter(&ResultBuilder::IsOrdinaryName); 4172 else 4173 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName); 4174 4175 if (getLangOpts().CPlusPlus) 4176 MaybeAddOverrideCalls(*this, /*InContext=*/nullptr, Results); 4177 break; 4178 4179 case PCC_RecoveryInFunction: 4180 // Unfiltered 4181 break; 4182 } 4183 4184 // If we are in a C++ non-static member function, check the qualifiers on 4185 // the member function to filter/prioritize the results list. 4186 auto ThisType = getCurrentThisType(); 4187 if (!ThisType.isNull()) 4188 Results.setObjectTypeQualifiers(ThisType->getPointeeType().getQualifiers(), 4189 VK_LValue); 4190 4191 CodeCompletionDeclConsumer Consumer(Results, CurContext); 4192 LookupVisibleDecls(S, LookupOrdinaryName, Consumer, 4193 CodeCompleter->includeGlobals(), 4194 CodeCompleter->loadExternal()); 4195 4196 AddOrdinaryNameResults(CompletionContext, S, *this, Results); 4197 Results.ExitScope(); 4198 4199 switch (CompletionContext) { 4200 case PCC_ParenthesizedExpression: 4201 case PCC_Expression: 4202 case PCC_Statement: 4203 case PCC_RecoveryInFunction: 4204 if (S->getFnParent()) 4205 AddPrettyFunctionResults(getLangOpts(), Results); 4206 break; 4207 4208 case PCC_Namespace: 4209 case PCC_Class: 4210 case PCC_ObjCInterface: 4211 case PCC_ObjCImplementation: 4212 case PCC_ObjCInstanceVariableList: 4213 case PCC_Template: 4214 case PCC_MemberTemplate: 4215 case PCC_ForInit: 4216 case PCC_Condition: 4217 case PCC_Type: 4218 case PCC_LocalDeclarationSpecifiers: 4219 break; 4220 } 4221 4222 if (CodeCompleter->includeMacros()) 4223 AddMacroResults(PP, Results, CodeCompleter->loadExternal(), false); 4224 4225 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 4226 Results.data(), Results.size()); 4227 } 4228 4229 static void AddClassMessageCompletions(Sema &SemaRef, Scope *S, 4230 ParsedType Receiver, 4231 ArrayRef<IdentifierInfo *> SelIdents, 4232 bool AtArgumentExpression, bool IsSuper, 4233 ResultBuilder &Results); 4234 4235 void Sema::CodeCompleteDeclSpec(Scope *S, DeclSpec &DS, 4236 bool AllowNonIdentifiers, 4237 bool AllowNestedNameSpecifiers) { 4238 typedef CodeCompletionResult Result; 4239 ResultBuilder Results( 4240 *this, CodeCompleter->getAllocator(), 4241 CodeCompleter->getCodeCompletionTUInfo(), 4242 AllowNestedNameSpecifiers 4243 // FIXME: Try to separate codepath leading here to deduce whether we 4244 // need an existing symbol or a new one. 4245 ? CodeCompletionContext::CCC_SymbolOrNewName 4246 : CodeCompletionContext::CCC_NewName); 4247 Results.EnterNewScope(); 4248 4249 // Type qualifiers can come after names. 4250 Results.AddResult(Result("const")); 4251 Results.AddResult(Result("volatile")); 4252 if (getLangOpts().C99) 4253 Results.AddResult(Result("restrict")); 4254 4255 if (getLangOpts().CPlusPlus) { 4256 if (getLangOpts().CPlusPlus11 && 4257 (DS.getTypeSpecType() == DeclSpec::TST_class || 4258 DS.getTypeSpecType() == DeclSpec::TST_struct)) 4259 Results.AddResult("final"); 4260 4261 if (AllowNonIdentifiers) { 4262 Results.AddResult(Result("operator")); 4263 } 4264 4265 // Add nested-name-specifiers. 4266 if (AllowNestedNameSpecifiers) { 4267 Results.allowNestedNameSpecifiers(); 4268 Results.setFilter(&ResultBuilder::IsImpossibleToSatisfy); 4269 CodeCompletionDeclConsumer Consumer(Results, CurContext); 4270 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer, 4271 CodeCompleter->includeGlobals(), 4272 CodeCompleter->loadExternal()); 4273 Results.setFilter(nullptr); 4274 } 4275 } 4276 Results.ExitScope(); 4277 4278 // If we're in a context where we might have an expression (rather than a 4279 // declaration), and what we've seen so far is an Objective-C type that could 4280 // be a receiver of a class message, this may be a class message send with 4281 // the initial opening bracket '[' missing. Add appropriate completions. 4282 if (AllowNonIdentifiers && !AllowNestedNameSpecifiers && 4283 DS.getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier && 4284 DS.getTypeSpecType() == DeclSpec::TST_typename && 4285 DS.getTypeSpecComplex() == DeclSpec::TSC_unspecified && 4286 DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified && 4287 !DS.isTypeAltiVecVector() && S && 4288 (S->getFlags() & Scope::DeclScope) != 0 && 4289 (S->getFlags() & (Scope::ClassScope | Scope::TemplateParamScope | 4290 Scope::FunctionPrototypeScope | Scope::AtCatchScope)) == 4291 0) { 4292 ParsedType T = DS.getRepAsType(); 4293 if (!T.get().isNull() && T.get()->isObjCObjectOrInterfaceType()) 4294 AddClassMessageCompletions(*this, S, T, None, false, false, Results); 4295 } 4296 4297 // Note that we intentionally suppress macro results here, since we do not 4298 // encourage using macros to produce the names of entities. 4299 4300 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 4301 Results.data(), Results.size()); 4302 } 4303 4304 struct Sema::CodeCompleteExpressionData { 4305 CodeCompleteExpressionData(QualType PreferredType = QualType(), 4306 bool IsParenthesized = false) 4307 : PreferredType(PreferredType), IntegralConstantExpression(false), 4308 ObjCCollection(false), IsParenthesized(IsParenthesized) {} 4309 4310 QualType PreferredType; 4311 bool IntegralConstantExpression; 4312 bool ObjCCollection; 4313 bool IsParenthesized; 4314 SmallVector<Decl *, 4> IgnoreDecls; 4315 }; 4316 4317 namespace { 4318 /// Information that allows to avoid completing redundant enumerators. 4319 struct CoveredEnumerators { 4320 llvm::SmallPtrSet<EnumConstantDecl *, 8> Seen; 4321 NestedNameSpecifier *SuggestedQualifier = nullptr; 4322 }; 4323 } // namespace 4324 4325 static void AddEnumerators(ResultBuilder &Results, ASTContext &Context, 4326 EnumDecl *Enum, DeclContext *CurContext, 4327 const CoveredEnumerators &Enumerators) { 4328 NestedNameSpecifier *Qualifier = Enumerators.SuggestedQualifier; 4329 if (Context.getLangOpts().CPlusPlus && !Qualifier && Enumerators.Seen.empty()) { 4330 // If there are no prior enumerators in C++, check whether we have to 4331 // qualify the names of the enumerators that we suggest, because they 4332 // may not be visible in this scope. 4333 Qualifier = getRequiredQualification(Context, CurContext, Enum); 4334 } 4335 4336 Results.EnterNewScope(); 4337 for (auto *E : Enum->enumerators()) { 4338 if (Enumerators.Seen.count(E)) 4339 continue; 4340 4341 CodeCompletionResult R(E, CCP_EnumInCase, Qualifier); 4342 Results.AddResult(R, CurContext, nullptr, false); 4343 } 4344 Results.ExitScope(); 4345 } 4346 4347 /// Try to find a corresponding FunctionProtoType for function-like types (e.g. 4348 /// function pointers, std::function, etc). 4349 static const FunctionProtoType *TryDeconstructFunctionLike(QualType T) { 4350 assert(!T.isNull()); 4351 // Try to extract first template argument from std::function<> and similar. 4352 // Note we only handle the sugared types, they closely match what users wrote. 4353 // We explicitly choose to not handle ClassTemplateSpecializationDecl. 4354 if (auto *Specialization = T->getAs<TemplateSpecializationType>()) { 4355 if (Specialization->getNumArgs() != 1) 4356 return nullptr; 4357 const TemplateArgument &Argument = Specialization->getArg(0); 4358 if (Argument.getKind() != TemplateArgument::Type) 4359 return nullptr; 4360 return Argument.getAsType()->getAs<FunctionProtoType>(); 4361 } 4362 // Handle other cases. 4363 if (T->isPointerType()) 4364 T = T->getPointeeType(); 4365 return T->getAs<FunctionProtoType>(); 4366 } 4367 4368 /// Adds a pattern completion for a lambda expression with the specified 4369 /// parameter types and placeholders for parameter names. 4370 static void AddLambdaCompletion(ResultBuilder &Results, 4371 llvm::ArrayRef<QualType> Parameters, 4372 const LangOptions &LangOpts) { 4373 if (!Results.includeCodePatterns()) 4374 return; 4375 CodeCompletionBuilder Completion(Results.getAllocator(), 4376 Results.getCodeCompletionTUInfo()); 4377 // [](<parameters>) {} 4378 Completion.AddChunk(CodeCompletionString::CK_LeftBracket); 4379 Completion.AddPlaceholderChunk("="); 4380 Completion.AddChunk(CodeCompletionString::CK_RightBracket); 4381 if (!Parameters.empty()) { 4382 Completion.AddChunk(CodeCompletionString::CK_LeftParen); 4383 bool First = true; 4384 for (auto Parameter : Parameters) { 4385 if (!First) 4386 Completion.AddChunk(CodeCompletionString::ChunkKind::CK_Comma); 4387 else 4388 First = false; 4389 4390 constexpr llvm::StringLiteral NamePlaceholder = "!#!NAME_GOES_HERE!#!"; 4391 std::string Type = std::string(NamePlaceholder); 4392 Parameter.getAsStringInternal(Type, PrintingPolicy(LangOpts)); 4393 llvm::StringRef Prefix, Suffix; 4394 std::tie(Prefix, Suffix) = llvm::StringRef(Type).split(NamePlaceholder); 4395 Prefix = Prefix.rtrim(); 4396 Suffix = Suffix.ltrim(); 4397 4398 Completion.AddTextChunk(Completion.getAllocator().CopyString(Prefix)); 4399 Completion.AddChunk(CodeCompletionString::CK_HorizontalSpace); 4400 Completion.AddPlaceholderChunk("parameter"); 4401 Completion.AddTextChunk(Completion.getAllocator().CopyString(Suffix)); 4402 }; 4403 Completion.AddChunk(CodeCompletionString::CK_RightParen); 4404 } 4405 Completion.AddChunk(clang::CodeCompletionString::CK_HorizontalSpace); 4406 Completion.AddChunk(CodeCompletionString::CK_LeftBrace); 4407 Completion.AddChunk(CodeCompletionString::CK_HorizontalSpace); 4408 Completion.AddPlaceholderChunk("body"); 4409 Completion.AddChunk(CodeCompletionString::CK_HorizontalSpace); 4410 Completion.AddChunk(CodeCompletionString::CK_RightBrace); 4411 4412 Results.AddResult(Completion.TakeString()); 4413 } 4414 4415 /// Perform code-completion in an expression context when we know what 4416 /// type we're looking for. 4417 void Sema::CodeCompleteExpression(Scope *S, 4418 const CodeCompleteExpressionData &Data) { 4419 ResultBuilder Results( 4420 *this, CodeCompleter->getAllocator(), 4421 CodeCompleter->getCodeCompletionTUInfo(), 4422 CodeCompletionContext( 4423 Data.IsParenthesized 4424 ? CodeCompletionContext::CCC_ParenthesizedExpression 4425 : CodeCompletionContext::CCC_Expression, 4426 Data.PreferredType)); 4427 auto PCC = 4428 Data.IsParenthesized ? PCC_ParenthesizedExpression : PCC_Expression; 4429 if (Data.ObjCCollection) 4430 Results.setFilter(&ResultBuilder::IsObjCCollection); 4431 else if (Data.IntegralConstantExpression) 4432 Results.setFilter(&ResultBuilder::IsIntegralConstantValue); 4433 else if (WantTypesInContext(PCC, getLangOpts())) 4434 Results.setFilter(&ResultBuilder::IsOrdinaryName); 4435 else 4436 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName); 4437 4438 if (!Data.PreferredType.isNull()) 4439 Results.setPreferredType(Data.PreferredType.getNonReferenceType()); 4440 4441 // Ignore any declarations that we were told that we don't care about. 4442 for (unsigned I = 0, N = Data.IgnoreDecls.size(); I != N; ++I) 4443 Results.Ignore(Data.IgnoreDecls[I]); 4444 4445 CodeCompletionDeclConsumer Consumer(Results, CurContext); 4446 LookupVisibleDecls(S, LookupOrdinaryName, Consumer, 4447 CodeCompleter->includeGlobals(), 4448 CodeCompleter->loadExternal()); 4449 4450 Results.EnterNewScope(); 4451 AddOrdinaryNameResults(PCC, S, *this, Results); 4452 Results.ExitScope(); 4453 4454 bool PreferredTypeIsPointer = false; 4455 if (!Data.PreferredType.isNull()) { 4456 PreferredTypeIsPointer = Data.PreferredType->isAnyPointerType() || 4457 Data.PreferredType->isMemberPointerType() || 4458 Data.PreferredType->isBlockPointerType(); 4459 if (Data.PreferredType->isEnumeralType()) { 4460 EnumDecl *Enum = Data.PreferredType->castAs<EnumType>()->getDecl(); 4461 if (auto *Def = Enum->getDefinition()) 4462 Enum = Def; 4463 // FIXME: collect covered enumerators in cases like: 4464 // if (x == my_enum::one) { ... } else if (x == ^) {} 4465 AddEnumerators(Results, Context, Enum, CurContext, CoveredEnumerators()); 4466 } 4467 } 4468 4469 if (S->getFnParent() && !Data.ObjCCollection && 4470 !Data.IntegralConstantExpression) 4471 AddPrettyFunctionResults(getLangOpts(), Results); 4472 4473 if (CodeCompleter->includeMacros()) 4474 AddMacroResults(PP, Results, CodeCompleter->loadExternal(), false, 4475 PreferredTypeIsPointer); 4476 4477 // Complete a lambda expression when preferred type is a function. 4478 if (!Data.PreferredType.isNull() && getLangOpts().CPlusPlus11) { 4479 if (const FunctionProtoType *F = 4480 TryDeconstructFunctionLike(Data.PreferredType)) 4481 AddLambdaCompletion(Results, F->getParamTypes(), getLangOpts()); 4482 } 4483 4484 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 4485 Results.data(), Results.size()); 4486 } 4487 4488 void Sema::CodeCompleteExpression(Scope *S, QualType PreferredType, 4489 bool IsParenthesized) { 4490 return CodeCompleteExpression( 4491 S, CodeCompleteExpressionData(PreferredType, IsParenthesized)); 4492 } 4493 4494 void Sema::CodeCompletePostfixExpression(Scope *S, ExprResult E, 4495 QualType PreferredType) { 4496 if (E.isInvalid()) 4497 CodeCompleteExpression(S, PreferredType); 4498 else if (getLangOpts().ObjC) 4499 CodeCompleteObjCInstanceMessage(S, E.get(), None, false); 4500 } 4501 4502 /// The set of properties that have already been added, referenced by 4503 /// property name. 4504 typedef llvm::SmallPtrSet<IdentifierInfo *, 16> AddedPropertiesSet; 4505 4506 /// Retrieve the container definition, if any? 4507 static ObjCContainerDecl *getContainerDef(ObjCContainerDecl *Container) { 4508 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) { 4509 if (Interface->hasDefinition()) 4510 return Interface->getDefinition(); 4511 4512 return Interface; 4513 } 4514 4515 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) { 4516 if (Protocol->hasDefinition()) 4517 return Protocol->getDefinition(); 4518 4519 return Protocol; 4520 } 4521 return Container; 4522 } 4523 4524 /// Adds a block invocation code completion result for the given block 4525 /// declaration \p BD. 4526 static void AddObjCBlockCall(ASTContext &Context, const PrintingPolicy &Policy, 4527 CodeCompletionBuilder &Builder, 4528 const NamedDecl *BD, 4529 const FunctionTypeLoc &BlockLoc, 4530 const FunctionProtoTypeLoc &BlockProtoLoc) { 4531 Builder.AddResultTypeChunk( 4532 GetCompletionTypeString(BlockLoc.getReturnLoc().getType(), Context, 4533 Policy, Builder.getAllocator())); 4534 4535 AddTypedNameChunk(Context, Policy, BD, Builder); 4536 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 4537 4538 if (BlockProtoLoc && BlockProtoLoc.getTypePtr()->isVariadic()) { 4539 Builder.AddPlaceholderChunk("..."); 4540 } else { 4541 for (unsigned I = 0, N = BlockLoc.getNumParams(); I != N; ++I) { 4542 if (I) 4543 Builder.AddChunk(CodeCompletionString::CK_Comma); 4544 4545 // Format the placeholder string. 4546 std::string PlaceholderStr = 4547 FormatFunctionParameter(Policy, BlockLoc.getParam(I)); 4548 4549 if (I == N - 1 && BlockProtoLoc && 4550 BlockProtoLoc.getTypePtr()->isVariadic()) 4551 PlaceholderStr += ", ..."; 4552 4553 // Add the placeholder string. 4554 Builder.AddPlaceholderChunk( 4555 Builder.getAllocator().CopyString(PlaceholderStr)); 4556 } 4557 } 4558 4559 Builder.AddChunk(CodeCompletionString::CK_RightParen); 4560 } 4561 4562 static void 4563 AddObjCProperties(const CodeCompletionContext &CCContext, 4564 ObjCContainerDecl *Container, bool AllowCategories, 4565 bool AllowNullaryMethods, DeclContext *CurContext, 4566 AddedPropertiesSet &AddedProperties, ResultBuilder &Results, 4567 bool IsBaseExprStatement = false, 4568 bool IsClassProperty = false, bool InOriginalClass = true) { 4569 typedef CodeCompletionResult Result; 4570 4571 // Retrieve the definition. 4572 Container = getContainerDef(Container); 4573 4574 // Add properties in this container. 4575 const auto AddProperty = [&](const ObjCPropertyDecl *P) { 4576 if (!AddedProperties.insert(P->getIdentifier()).second) 4577 return; 4578 4579 // FIXME: Provide block invocation completion for non-statement 4580 // expressions. 4581 if (!P->getType().getTypePtr()->isBlockPointerType() || 4582 !IsBaseExprStatement) { 4583 Result R = Result(P, Results.getBasePriority(P), nullptr); 4584 if (!InOriginalClass) 4585 setInBaseClass(R); 4586 Results.MaybeAddResult(R, CurContext); 4587 return; 4588 } 4589 4590 // Block setter and invocation completion is provided only when we are able 4591 // to find the FunctionProtoTypeLoc with parameter names for the block. 4592 FunctionTypeLoc BlockLoc; 4593 FunctionProtoTypeLoc BlockProtoLoc; 4594 findTypeLocationForBlockDecl(P->getTypeSourceInfo(), BlockLoc, 4595 BlockProtoLoc); 4596 if (!BlockLoc) { 4597 Result R = Result(P, Results.getBasePriority(P), nullptr); 4598 if (!InOriginalClass) 4599 setInBaseClass(R); 4600 Results.MaybeAddResult(R, CurContext); 4601 return; 4602 } 4603 4604 // The default completion result for block properties should be the block 4605 // invocation completion when the base expression is a statement. 4606 CodeCompletionBuilder Builder(Results.getAllocator(), 4607 Results.getCodeCompletionTUInfo()); 4608 AddObjCBlockCall(Container->getASTContext(), 4609 getCompletionPrintingPolicy(Results.getSema()), Builder, P, 4610 BlockLoc, BlockProtoLoc); 4611 Result R = Result(Builder.TakeString(), P, Results.getBasePriority(P)); 4612 if (!InOriginalClass) 4613 setInBaseClass(R); 4614 Results.MaybeAddResult(R, CurContext); 4615 4616 // Provide additional block setter completion iff the base expression is a 4617 // statement and the block property is mutable. 4618 if (!P->isReadOnly()) { 4619 CodeCompletionBuilder Builder(Results.getAllocator(), 4620 Results.getCodeCompletionTUInfo()); 4621 AddResultTypeChunk(Container->getASTContext(), 4622 getCompletionPrintingPolicy(Results.getSema()), P, 4623 CCContext.getBaseType(), Builder); 4624 Builder.AddTypedTextChunk( 4625 Results.getAllocator().CopyString(P->getName())); 4626 Builder.AddChunk(CodeCompletionString::CK_Equal); 4627 4628 std::string PlaceholderStr = formatBlockPlaceholder( 4629 getCompletionPrintingPolicy(Results.getSema()), P, BlockLoc, 4630 BlockProtoLoc, /*SuppressBlockName=*/true); 4631 // Add the placeholder string. 4632 Builder.AddPlaceholderChunk( 4633 Builder.getAllocator().CopyString(PlaceholderStr)); 4634 4635 // When completing blocks properties that return void the default 4636 // property completion result should show up before the setter, 4637 // otherwise the setter completion should show up before the default 4638 // property completion, as we normally want to use the result of the 4639 // call. 4640 Result R = 4641 Result(Builder.TakeString(), P, 4642 Results.getBasePriority(P) + 4643 (BlockLoc.getTypePtr()->getReturnType()->isVoidType() 4644 ? CCD_BlockPropertySetter 4645 : -CCD_BlockPropertySetter)); 4646 if (!InOriginalClass) 4647 setInBaseClass(R); 4648 Results.MaybeAddResult(R, CurContext); 4649 } 4650 }; 4651 4652 if (IsClassProperty) { 4653 for (const auto *P : Container->class_properties()) 4654 AddProperty(P); 4655 } else { 4656 for (const auto *P : Container->instance_properties()) 4657 AddProperty(P); 4658 } 4659 4660 // Add nullary methods or implicit class properties 4661 if (AllowNullaryMethods) { 4662 ASTContext &Context = Container->getASTContext(); 4663 PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema()); 4664 // Adds a method result 4665 const auto AddMethod = [&](const ObjCMethodDecl *M) { 4666 IdentifierInfo *Name = M->getSelector().getIdentifierInfoForSlot(0); 4667 if (!Name) 4668 return; 4669 if (!AddedProperties.insert(Name).second) 4670 return; 4671 CodeCompletionBuilder Builder(Results.getAllocator(), 4672 Results.getCodeCompletionTUInfo()); 4673 AddResultTypeChunk(Context, Policy, M, CCContext.getBaseType(), Builder); 4674 Builder.AddTypedTextChunk( 4675 Results.getAllocator().CopyString(Name->getName())); 4676 Result R = Result(Builder.TakeString(), M, 4677 CCP_MemberDeclaration + CCD_MethodAsProperty); 4678 if (!InOriginalClass) 4679 setInBaseClass(R); 4680 Results.MaybeAddResult(R, CurContext); 4681 }; 4682 4683 if (IsClassProperty) { 4684 for (const auto *M : Container->methods()) { 4685 // Gather the class method that can be used as implicit property 4686 // getters. Methods with arguments or methods that return void aren't 4687 // added to the results as they can't be used as a getter. 4688 if (!M->getSelector().isUnarySelector() || 4689 M->getReturnType()->isVoidType() || M->isInstanceMethod()) 4690 continue; 4691 AddMethod(M); 4692 } 4693 } else { 4694 for (auto *M : Container->methods()) { 4695 if (M->getSelector().isUnarySelector()) 4696 AddMethod(M); 4697 } 4698 } 4699 } 4700 4701 // Add properties in referenced protocols. 4702 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) { 4703 for (auto *P : Protocol->protocols()) 4704 AddObjCProperties(CCContext, P, AllowCategories, AllowNullaryMethods, 4705 CurContext, AddedProperties, Results, 4706 IsBaseExprStatement, IsClassProperty, 4707 /*InOriginalClass*/ false); 4708 } else if (ObjCInterfaceDecl *IFace = 4709 dyn_cast<ObjCInterfaceDecl>(Container)) { 4710 if (AllowCategories) { 4711 // Look through categories. 4712 for (auto *Cat : IFace->known_categories()) 4713 AddObjCProperties(CCContext, Cat, AllowCategories, AllowNullaryMethods, 4714 CurContext, AddedProperties, Results, 4715 IsBaseExprStatement, IsClassProperty, 4716 InOriginalClass); 4717 } 4718 4719 // Look through protocols. 4720 for (auto *I : IFace->all_referenced_protocols()) 4721 AddObjCProperties(CCContext, I, AllowCategories, AllowNullaryMethods, 4722 CurContext, AddedProperties, Results, 4723 IsBaseExprStatement, IsClassProperty, 4724 /*InOriginalClass*/ false); 4725 4726 // Look in the superclass. 4727 if (IFace->getSuperClass()) 4728 AddObjCProperties(CCContext, IFace->getSuperClass(), AllowCategories, 4729 AllowNullaryMethods, CurContext, AddedProperties, 4730 Results, IsBaseExprStatement, IsClassProperty, 4731 /*InOriginalClass*/ false); 4732 } else if (const auto *Category = 4733 dyn_cast<ObjCCategoryDecl>(Container)) { 4734 // Look through protocols. 4735 for (auto *P : Category->protocols()) 4736 AddObjCProperties(CCContext, P, AllowCategories, AllowNullaryMethods, 4737 CurContext, AddedProperties, Results, 4738 IsBaseExprStatement, IsClassProperty, 4739 /*InOriginalClass*/ false); 4740 } 4741 } 4742 4743 static void AddRecordMembersCompletionResults( 4744 Sema &SemaRef, ResultBuilder &Results, Scope *S, QualType BaseType, 4745 ExprValueKind BaseKind, RecordDecl *RD, Optional<FixItHint> AccessOpFixIt) { 4746 // Indicate that we are performing a member access, and the cv-qualifiers 4747 // for the base object type. 4748 Results.setObjectTypeQualifiers(BaseType.getQualifiers(), BaseKind); 4749 4750 // Access to a C/C++ class, struct, or union. 4751 Results.allowNestedNameSpecifiers(); 4752 std::vector<FixItHint> FixIts; 4753 if (AccessOpFixIt) 4754 FixIts.emplace_back(AccessOpFixIt.getValue()); 4755 CodeCompletionDeclConsumer Consumer(Results, RD, BaseType, std::move(FixIts)); 4756 SemaRef.LookupVisibleDecls(RD, Sema::LookupMemberName, Consumer, 4757 SemaRef.CodeCompleter->includeGlobals(), 4758 /*IncludeDependentBases=*/true, 4759 SemaRef.CodeCompleter->loadExternal()); 4760 4761 if (SemaRef.getLangOpts().CPlusPlus) { 4762 if (!Results.empty()) { 4763 // The "template" keyword can follow "->" or "." in the grammar. 4764 // However, we only want to suggest the template keyword if something 4765 // is dependent. 4766 bool IsDependent = BaseType->isDependentType(); 4767 if (!IsDependent) { 4768 for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent()) 4769 if (DeclContext *Ctx = DepScope->getEntity()) { 4770 IsDependent = Ctx->isDependentContext(); 4771 break; 4772 } 4773 } 4774 4775 if (IsDependent) 4776 Results.AddResult(CodeCompletionResult("template")); 4777 } 4778 } 4779 } 4780 4781 // Returns the RecordDecl inside the BaseType, falling back to primary template 4782 // in case of specializations. Since we might not have a decl for the 4783 // instantiation/specialization yet, e.g. dependent code. 4784 static RecordDecl *getAsRecordDecl(const QualType BaseType) { 4785 if (auto *RD = BaseType->getAsRecordDecl()) 4786 return RD; 4787 4788 if (const auto *TST = BaseType->getAs<TemplateSpecializationType>()) { 4789 if (const auto *TD = dyn_cast_or_null<ClassTemplateDecl>( 4790 TST->getTemplateName().getAsTemplateDecl())) { 4791 return TD->getTemplatedDecl(); 4792 } 4793 } 4794 4795 return nullptr; 4796 } 4797 4798 namespace { 4799 // Collects completion-relevant information about a concept-constrainted type T. 4800 // In particular, examines the constraint expressions to find members of T. 4801 // 4802 // The design is very simple: we walk down each constraint looking for 4803 // expressions of the form T.foo(). 4804 // If we're extra lucky, the return type is specified. 4805 // We don't do any clever handling of && or || in constraint expressions, we 4806 // take members from both branches. 4807 // 4808 // For example, given: 4809 // template <class T> concept X = requires (T t, string& s) { t.print(s); }; 4810 // template <X U> void foo(U u) { u.^ } 4811 // We want to suggest the inferred member function 'print(string)'. 4812 // We see that u has type U, so X<U> holds. 4813 // X<U> requires t.print(s) to be valid, where t has type U (substituted for T). 4814 // By looking at the CallExpr we find the signature of print(). 4815 // 4816 // While we tend to know in advance which kind of members (access via . -> ::) 4817 // we want, it's simpler just to gather them all and post-filter. 4818 // 4819 // FIXME: some of this machinery could be used for non-concept type-parms too, 4820 // enabling completion for type parameters based on other uses of that param. 4821 // 4822 // FIXME: there are other cases where a type can be constrained by a concept, 4823 // e.g. inside `if constexpr(ConceptSpecializationExpr) { ... }` 4824 class ConceptInfo { 4825 public: 4826 // Describes a likely member of a type, inferred by concept constraints. 4827 // Offered as a code completion for T. T-> and T:: contexts. 4828 struct Member { 4829 // Always non-null: we only handle members with ordinary identifier names. 4830 const IdentifierInfo *Name = nullptr; 4831 // Set for functions we've seen called. 4832 // We don't have the declared parameter types, only the actual types of 4833 // arguments we've seen. These are still valuable, as it's hard to render 4834 // a useful function completion with neither parameter types nor names! 4835 llvm::Optional<SmallVector<QualType, 1>> ArgTypes; 4836 // Whether this is accessed as T.member, T->member, or T::member. 4837 enum AccessOperator { 4838 Colons, 4839 Arrow, 4840 Dot, 4841 } Operator = Dot; 4842 // What's known about the type of a variable or return type of a function. 4843 const TypeConstraint *ResultType = nullptr; 4844 // FIXME: also track: 4845 // - kind of entity (function/variable/type), to expose structured results 4846 // - template args kinds/types, as a proxy for template params 4847 4848 // For now we simply return these results as "pattern" strings. 4849 CodeCompletionString *render(Sema &S, CodeCompletionAllocator &Alloc, 4850 CodeCompletionTUInfo &Info) const { 4851 CodeCompletionBuilder B(Alloc, Info); 4852 // Result type 4853 if (ResultType) { 4854 std::string AsString; 4855 { 4856 llvm::raw_string_ostream OS(AsString); 4857 QualType ExactType = deduceType(*ResultType); 4858 if (!ExactType.isNull()) 4859 ExactType.print(OS, getCompletionPrintingPolicy(S)); 4860 else 4861 ResultType->print(OS, getCompletionPrintingPolicy(S)); 4862 } 4863 B.AddResultTypeChunk(Alloc.CopyString(AsString)); 4864 } 4865 // Member name 4866 B.AddTypedTextChunk(Alloc.CopyString(Name->getName())); 4867 // Function argument list 4868 if (ArgTypes) { 4869 B.AddChunk(clang::CodeCompletionString::CK_LeftParen); 4870 bool First = true; 4871 for (QualType Arg : *ArgTypes) { 4872 if (First) 4873 First = false; 4874 else { 4875 B.AddChunk(clang::CodeCompletionString::CK_Comma); 4876 B.AddChunk(clang::CodeCompletionString::CK_HorizontalSpace); 4877 } 4878 B.AddPlaceholderChunk(Alloc.CopyString( 4879 Arg.getAsString(getCompletionPrintingPolicy(S)))); 4880 } 4881 B.AddChunk(clang::CodeCompletionString::CK_RightParen); 4882 } 4883 return B.TakeString(); 4884 } 4885 }; 4886 4887 // BaseType is the type parameter T to infer members from. 4888 // T must be accessible within S, as we use it to find the template entity 4889 // that T is attached to in order to gather the relevant constraints. 4890 ConceptInfo(const TemplateTypeParmType &BaseType, Scope *S) { 4891 auto *TemplatedEntity = getTemplatedEntity(BaseType.getDecl(), S); 4892 for (const Expr *E : constraintsForTemplatedEntity(TemplatedEntity)) 4893 believe(E, &BaseType); 4894 } 4895 4896 std::vector<Member> members() { 4897 std::vector<Member> Results; 4898 for (const auto &E : this->Results) 4899 Results.push_back(E.second); 4900 llvm::sort(Results, [](const Member &L, const Member &R) { 4901 return L.Name->getName() < R.Name->getName(); 4902 }); 4903 return Results; 4904 } 4905 4906 private: 4907 // Infer members of T, given that the expression E (dependent on T) is true. 4908 void believe(const Expr *E, const TemplateTypeParmType *T) { 4909 if (!E || !T) 4910 return; 4911 if (auto *CSE = dyn_cast<ConceptSpecializationExpr>(E)) { 4912 // If the concept is 4913 // template <class A, class B> concept CD = f<A, B>(); 4914 // And the concept specialization is 4915 // CD<int, T> 4916 // Then we're substituting T for B, so we want to make f<A, B>() true 4917 // by adding members to B - i.e. believe(f<A, B>(), B); 4918 // 4919 // For simplicity: 4920 // - we don't attempt to substitute int for A 4921 // - when T is used in other ways (like CD<T*>) we ignore it 4922 ConceptDecl *CD = CSE->getNamedConcept(); 4923 TemplateParameterList *Params = CD->getTemplateParameters(); 4924 unsigned Index = 0; 4925 for (const auto &Arg : CSE->getTemplateArguments()) { 4926 if (Index >= Params->size()) 4927 break; // Won't happen in valid code. 4928 if (isApprox(Arg, T)) { 4929 auto *TTPD = dyn_cast<TemplateTypeParmDecl>(Params->getParam(Index)); 4930 if (!TTPD) 4931 continue; 4932 // T was used as an argument, and bound to the parameter TT. 4933 auto *TT = cast<TemplateTypeParmType>(TTPD->getTypeForDecl()); 4934 // So now we know the constraint as a function of TT is true. 4935 believe(CD->getConstraintExpr(), TT); 4936 // (concepts themselves have no associated constraints to require) 4937 } 4938 4939 ++Index; 4940 } 4941 } else if (auto *BO = dyn_cast<BinaryOperator>(E)) { 4942 // For A && B, we can infer members from both branches. 4943 // For A || B, the union is still more useful than the intersection. 4944 if (BO->getOpcode() == BO_LAnd || BO->getOpcode() == BO_LOr) { 4945 believe(BO->getLHS(), T); 4946 believe(BO->getRHS(), T); 4947 } 4948 } else if (auto *RE = dyn_cast<RequiresExpr>(E)) { 4949 // A requires(){...} lets us infer members from each requirement. 4950 for (const concepts::Requirement *Req : RE->getRequirements()) { 4951 if (!Req->isDependent()) 4952 continue; // Can't tell us anything about T. 4953 // Now Req cannot a substitution-error: those aren't dependent. 4954 4955 if (auto *TR = dyn_cast<concepts::TypeRequirement>(Req)) { 4956 // Do a full traversal so we get `foo` from `typename T::foo::bar`. 4957 QualType AssertedType = TR->getType()->getType(); 4958 ValidVisitor(this, T).TraverseType(AssertedType); 4959 } else if (auto *ER = dyn_cast<concepts::ExprRequirement>(Req)) { 4960 ValidVisitor Visitor(this, T); 4961 // If we have a type constraint on the value of the expression, 4962 // AND the whole outer expression describes a member, then we'll 4963 // be able to use the constraint to provide the return type. 4964 if (ER->getReturnTypeRequirement().isTypeConstraint()) { 4965 Visitor.OuterType = 4966 ER->getReturnTypeRequirement().getTypeConstraint(); 4967 Visitor.OuterExpr = ER->getExpr(); 4968 } 4969 Visitor.TraverseStmt(ER->getExpr()); 4970 } else if (auto *NR = dyn_cast<concepts::NestedRequirement>(Req)) { 4971 believe(NR->getConstraintExpr(), T); 4972 } 4973 } 4974 } 4975 } 4976 4977 // This visitor infers members of T based on traversing expressions/types 4978 // that involve T. It is invoked with code known to be valid for T. 4979 class ValidVisitor : public RecursiveASTVisitor<ValidVisitor> { 4980 ConceptInfo *Outer; 4981 const TemplateTypeParmType *T; 4982 4983 CallExpr *Caller = nullptr; 4984 Expr *Callee = nullptr; 4985 4986 public: 4987 // If set, OuterExpr is constrained by OuterType. 4988 Expr *OuterExpr = nullptr; 4989 const TypeConstraint *OuterType = nullptr; 4990 4991 ValidVisitor(ConceptInfo *Outer, const TemplateTypeParmType *T) 4992 : Outer(Outer), T(T) { 4993 assert(T); 4994 } 4995 4996 // In T.foo or T->foo, `foo` is a member function/variable. 4997 bool VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E) { 4998 const Type *Base = E->getBaseType().getTypePtr(); 4999 bool IsArrow = E->isArrow(); 5000 if (Base->isPointerType() && IsArrow) { 5001 IsArrow = false; 5002 Base = Base->getPointeeType().getTypePtr(); 5003 } 5004 if (isApprox(Base, T)) 5005 addValue(E, E->getMember(), IsArrow ? Member::Arrow : Member::Dot); 5006 return true; 5007 } 5008 5009 // In T::foo, `foo` is a static member function/variable. 5010 bool VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) { 5011 if (E->getQualifier() && isApprox(E->getQualifier()->getAsType(), T)) 5012 addValue(E, E->getDeclName(), Member::Colons); 5013 return true; 5014 } 5015 5016 // In T::typename foo, `foo` is a type. 5017 bool VisitDependentNameType(DependentNameType *DNT) { 5018 const auto *Q = DNT->getQualifier(); 5019 if (Q && isApprox(Q->getAsType(), T)) 5020 addType(DNT->getIdentifier()); 5021 return true; 5022 } 5023 5024 // In T::foo::bar, `foo` must be a type. 5025 // VisitNNS() doesn't exist, and TraverseNNS isn't always called :-( 5026 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNSL) { 5027 if (NNSL) { 5028 NestedNameSpecifier *NNS = NNSL.getNestedNameSpecifier(); 5029 const auto *Q = NNS->getPrefix(); 5030 if (Q && isApprox(Q->getAsType(), T)) 5031 addType(NNS->getAsIdentifier()); 5032 } 5033 // FIXME: also handle T::foo<X>::bar 5034 return RecursiveASTVisitor::TraverseNestedNameSpecifierLoc(NNSL); 5035 } 5036 5037 // FIXME also handle T::foo<X> 5038 5039 // Track the innermost caller/callee relationship so we can tell if a 5040 // nested expr is being called as a function. 5041 bool VisitCallExpr(CallExpr *CE) { 5042 Caller = CE; 5043 Callee = CE->getCallee(); 5044 return true; 5045 } 5046 5047 private: 5048 void addResult(Member &&M) { 5049 auto R = Outer->Results.try_emplace(M.Name); 5050 Member &O = R.first->second; 5051 // Overwrite existing if the new member has more info. 5052 // The preference of . vs :: vs -> is fairly arbitrary. 5053 if (/*Inserted*/ R.second || 5054 std::make_tuple(M.ArgTypes.hasValue(), M.ResultType != nullptr, 5055 M.Operator) > std::make_tuple(O.ArgTypes.hasValue(), 5056 O.ResultType != nullptr, 5057 O.Operator)) 5058 O = std::move(M); 5059 } 5060 5061 void addType(const IdentifierInfo *Name) { 5062 if (!Name) 5063 return; 5064 Member M; 5065 M.Name = Name; 5066 M.Operator = Member::Colons; 5067 addResult(std::move(M)); 5068 } 5069 5070 void addValue(Expr *E, DeclarationName Name, 5071 Member::AccessOperator Operator) { 5072 if (!Name.isIdentifier()) 5073 return; 5074 Member Result; 5075 Result.Name = Name.getAsIdentifierInfo(); 5076 Result.Operator = Operator; 5077 // If this is the callee of an immediately-enclosing CallExpr, then 5078 // treat it as a method, otherwise it's a variable. 5079 if (Caller != nullptr && Callee == E) { 5080 Result.ArgTypes.emplace(); 5081 for (const auto *Arg : Caller->arguments()) 5082 Result.ArgTypes->push_back(Arg->getType()); 5083 if (Caller == OuterExpr) { 5084 Result.ResultType = OuterType; 5085 } 5086 } else { 5087 if (E == OuterExpr) 5088 Result.ResultType = OuterType; 5089 } 5090 addResult(std::move(Result)); 5091 } 5092 }; 5093 5094 static bool isApprox(const TemplateArgument &Arg, const Type *T) { 5095 return Arg.getKind() == TemplateArgument::Type && 5096 isApprox(Arg.getAsType().getTypePtr(), T); 5097 } 5098 5099 static bool isApprox(const Type *T1, const Type *T2) { 5100 return T1 && T2 && 5101 T1->getCanonicalTypeUnqualified() == 5102 T2->getCanonicalTypeUnqualified(); 5103 } 5104 5105 // Returns the DeclContext immediately enclosed by the template parameter 5106 // scope. For primary templates, this is the templated (e.g.) CXXRecordDecl. 5107 // For specializations, this is e.g. ClassTemplatePartialSpecializationDecl. 5108 static DeclContext *getTemplatedEntity(const TemplateTypeParmDecl *D, 5109 Scope *S) { 5110 if (D == nullptr) 5111 return nullptr; 5112 Scope *Inner = nullptr; 5113 while (S) { 5114 if (S->isTemplateParamScope() && S->isDeclScope(D)) 5115 return Inner ? Inner->getEntity() : nullptr; 5116 Inner = S; 5117 S = S->getParent(); 5118 } 5119 return nullptr; 5120 } 5121 5122 // Gets all the type constraint expressions that might apply to the type 5123 // variables associated with DC (as returned by getTemplatedEntity()). 5124 static SmallVector<const Expr *, 1> 5125 constraintsForTemplatedEntity(DeclContext *DC) { 5126 SmallVector<const Expr *, 1> Result; 5127 if (DC == nullptr) 5128 return Result; 5129 // Primary templates can have constraints. 5130 if (const auto *TD = cast<Decl>(DC)->getDescribedTemplate()) 5131 TD->getAssociatedConstraints(Result); 5132 // Partial specializations may have constraints. 5133 if (const auto *CTPSD = 5134 dyn_cast<ClassTemplatePartialSpecializationDecl>(DC)) 5135 CTPSD->getAssociatedConstraints(Result); 5136 if (const auto *VTPSD = dyn_cast<VarTemplatePartialSpecializationDecl>(DC)) 5137 VTPSD->getAssociatedConstraints(Result); 5138 return Result; 5139 } 5140 5141 // Attempt to find the unique type satisfying a constraint. 5142 // This lets us show e.g. `int` instead of `std::same_as<int>`. 5143 static QualType deduceType(const TypeConstraint &T) { 5144 // Assume a same_as<T> return type constraint is std::same_as or equivalent. 5145 // In this case the return type is T. 5146 DeclarationName DN = T.getNamedConcept()->getDeclName(); 5147 if (DN.isIdentifier() && DN.getAsIdentifierInfo()->isStr("same_as")) 5148 if (const auto *Args = T.getTemplateArgsAsWritten()) 5149 if (Args->getNumTemplateArgs() == 1) { 5150 const auto &Arg = Args->arguments().front().getArgument(); 5151 if (Arg.getKind() == TemplateArgument::Type) 5152 return Arg.getAsType(); 5153 } 5154 return {}; 5155 } 5156 5157 llvm::DenseMap<const IdentifierInfo *, Member> Results; 5158 }; 5159 } // namespace 5160 5161 void Sema::CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base, 5162 Expr *OtherOpBase, 5163 SourceLocation OpLoc, bool IsArrow, 5164 bool IsBaseExprStatement, 5165 QualType PreferredType) { 5166 if (!Base || !CodeCompleter) 5167 return; 5168 5169 ExprResult ConvertedBase = PerformMemberExprBaseConversion(Base, IsArrow); 5170 if (ConvertedBase.isInvalid()) 5171 return; 5172 QualType ConvertedBaseType = ConvertedBase.get()->getType(); 5173 5174 enum CodeCompletionContext::Kind contextKind; 5175 5176 if (IsArrow) { 5177 if (const auto *Ptr = ConvertedBaseType->getAs<PointerType>()) 5178 ConvertedBaseType = Ptr->getPointeeType(); 5179 } 5180 5181 if (IsArrow) { 5182 contextKind = CodeCompletionContext::CCC_ArrowMemberAccess; 5183 } else { 5184 if (ConvertedBaseType->isObjCObjectPointerType() || 5185 ConvertedBaseType->isObjCObjectOrInterfaceType()) { 5186 contextKind = CodeCompletionContext::CCC_ObjCPropertyAccess; 5187 } else { 5188 contextKind = CodeCompletionContext::CCC_DotMemberAccess; 5189 } 5190 } 5191 5192 CodeCompletionContext CCContext(contextKind, ConvertedBaseType); 5193 CCContext.setPreferredType(PreferredType); 5194 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5195 CodeCompleter->getCodeCompletionTUInfo(), CCContext, 5196 &ResultBuilder::IsMember); 5197 5198 auto DoCompletion = [&](Expr *Base, bool IsArrow, 5199 Optional<FixItHint> AccessOpFixIt) -> bool { 5200 if (!Base) 5201 return false; 5202 5203 ExprResult ConvertedBase = PerformMemberExprBaseConversion(Base, IsArrow); 5204 if (ConvertedBase.isInvalid()) 5205 return false; 5206 Base = ConvertedBase.get(); 5207 5208 QualType BaseType = Base->getType(); 5209 if (BaseType.isNull()) 5210 return false; 5211 ExprValueKind BaseKind = Base->getValueKind(); 5212 5213 if (IsArrow) { 5214 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 5215 BaseType = Ptr->getPointeeType(); 5216 BaseKind = VK_LValue; 5217 } else if (BaseType->isObjCObjectPointerType() || 5218 BaseType->isTemplateTypeParmType()) { 5219 // Both cases (dot/arrow) handled below. 5220 } else { 5221 return false; 5222 } 5223 } 5224 5225 if (RecordDecl *RD = getAsRecordDecl(BaseType)) { 5226 AddRecordMembersCompletionResults(*this, Results, S, BaseType, BaseKind, 5227 RD, std::move(AccessOpFixIt)); 5228 } else if (const auto *TTPT = 5229 dyn_cast<TemplateTypeParmType>(BaseType.getTypePtr())) { 5230 auto Operator = 5231 IsArrow ? ConceptInfo::Member::Arrow : ConceptInfo::Member::Dot; 5232 for (const auto &R : ConceptInfo(*TTPT, S).members()) { 5233 if (R.Operator != Operator) 5234 continue; 5235 CodeCompletionResult Result( 5236 R.render(*this, CodeCompleter->getAllocator(), 5237 CodeCompleter->getCodeCompletionTUInfo())); 5238 if (AccessOpFixIt) 5239 Result.FixIts.push_back(*AccessOpFixIt); 5240 Results.AddResult(std::move(Result)); 5241 } 5242 } else if (!IsArrow && BaseType->isObjCObjectPointerType()) { 5243 // Objective-C property reference. Bail if we're performing fix-it code 5244 // completion since Objective-C properties are normally backed by ivars, 5245 // most Objective-C fix-its here would have little value. 5246 if (AccessOpFixIt.hasValue()) { 5247 return false; 5248 } 5249 AddedPropertiesSet AddedProperties; 5250 5251 if (const ObjCObjectPointerType *ObjCPtr = 5252 BaseType->getAsObjCInterfacePointerType()) { 5253 // Add property results based on our interface. 5254 assert(ObjCPtr && "Non-NULL pointer guaranteed above!"); 5255 AddObjCProperties(CCContext, ObjCPtr->getInterfaceDecl(), true, 5256 /*AllowNullaryMethods=*/true, CurContext, 5257 AddedProperties, Results, IsBaseExprStatement); 5258 } 5259 5260 // Add properties from the protocols in a qualified interface. 5261 for (auto *I : BaseType->castAs<ObjCObjectPointerType>()->quals()) 5262 AddObjCProperties(CCContext, I, true, /*AllowNullaryMethods=*/true, 5263 CurContext, AddedProperties, Results, 5264 IsBaseExprStatement, /*IsClassProperty*/ false, 5265 /*InOriginalClass*/ false); 5266 } else if ((IsArrow && BaseType->isObjCObjectPointerType()) || 5267 (!IsArrow && BaseType->isObjCObjectType())) { 5268 // Objective-C instance variable access. Bail if we're performing fix-it 5269 // code completion since Objective-C properties are normally backed by 5270 // ivars, most Objective-C fix-its here would have little value. 5271 if (AccessOpFixIt.hasValue()) { 5272 return false; 5273 } 5274 ObjCInterfaceDecl *Class = nullptr; 5275 if (const ObjCObjectPointerType *ObjCPtr = 5276 BaseType->getAs<ObjCObjectPointerType>()) 5277 Class = ObjCPtr->getInterfaceDecl(); 5278 else 5279 Class = BaseType->castAs<ObjCObjectType>()->getInterface(); 5280 5281 // Add all ivars from this class and its superclasses. 5282 if (Class) { 5283 CodeCompletionDeclConsumer Consumer(Results, Class, BaseType); 5284 Results.setFilter(&ResultBuilder::IsObjCIvar); 5285 LookupVisibleDecls( 5286 Class, LookupMemberName, Consumer, CodeCompleter->includeGlobals(), 5287 /*IncludeDependentBases=*/false, CodeCompleter->loadExternal()); 5288 } 5289 } 5290 5291 // FIXME: How do we cope with isa? 5292 return true; 5293 }; 5294 5295 Results.EnterNewScope(); 5296 5297 bool CompletionSucceded = DoCompletion(Base, IsArrow, None); 5298 if (CodeCompleter->includeFixIts()) { 5299 const CharSourceRange OpRange = 5300 CharSourceRange::getTokenRange(OpLoc, OpLoc); 5301 CompletionSucceded |= DoCompletion( 5302 OtherOpBase, !IsArrow, 5303 FixItHint::CreateReplacement(OpRange, IsArrow ? "." : "->")); 5304 } 5305 5306 Results.ExitScope(); 5307 5308 if (!CompletionSucceded) 5309 return; 5310 5311 // Hand off the results found for code completion. 5312 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 5313 Results.data(), Results.size()); 5314 } 5315 5316 void Sema::CodeCompleteObjCClassPropertyRefExpr(Scope *S, 5317 IdentifierInfo &ClassName, 5318 SourceLocation ClassNameLoc, 5319 bool IsBaseExprStatement) { 5320 IdentifierInfo *ClassNamePtr = &ClassName; 5321 ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(ClassNamePtr, ClassNameLoc); 5322 if (!IFace) 5323 return; 5324 CodeCompletionContext CCContext( 5325 CodeCompletionContext::CCC_ObjCPropertyAccess); 5326 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5327 CodeCompleter->getCodeCompletionTUInfo(), CCContext, 5328 &ResultBuilder::IsMember); 5329 Results.EnterNewScope(); 5330 AddedPropertiesSet AddedProperties; 5331 AddObjCProperties(CCContext, IFace, true, 5332 /*AllowNullaryMethods=*/true, CurContext, AddedProperties, 5333 Results, IsBaseExprStatement, 5334 /*IsClassProperty=*/true); 5335 Results.ExitScope(); 5336 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 5337 Results.data(), Results.size()); 5338 } 5339 5340 void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) { 5341 if (!CodeCompleter) 5342 return; 5343 5344 ResultBuilder::LookupFilter Filter = nullptr; 5345 enum CodeCompletionContext::Kind ContextKind = 5346 CodeCompletionContext::CCC_Other; 5347 switch ((DeclSpec::TST)TagSpec) { 5348 case DeclSpec::TST_enum: 5349 Filter = &ResultBuilder::IsEnum; 5350 ContextKind = CodeCompletionContext::CCC_EnumTag; 5351 break; 5352 5353 case DeclSpec::TST_union: 5354 Filter = &ResultBuilder::IsUnion; 5355 ContextKind = CodeCompletionContext::CCC_UnionTag; 5356 break; 5357 5358 case DeclSpec::TST_struct: 5359 case DeclSpec::TST_class: 5360 case DeclSpec::TST_interface: 5361 Filter = &ResultBuilder::IsClassOrStruct; 5362 ContextKind = CodeCompletionContext::CCC_ClassOrStructTag; 5363 break; 5364 5365 default: 5366 llvm_unreachable("Unknown type specifier kind in CodeCompleteTag"); 5367 } 5368 5369 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5370 CodeCompleter->getCodeCompletionTUInfo(), ContextKind); 5371 CodeCompletionDeclConsumer Consumer(Results, CurContext); 5372 5373 // First pass: look for tags. 5374 Results.setFilter(Filter); 5375 LookupVisibleDecls(S, LookupTagName, Consumer, 5376 CodeCompleter->includeGlobals(), 5377 CodeCompleter->loadExternal()); 5378 5379 if (CodeCompleter->includeGlobals()) { 5380 // Second pass: look for nested name specifiers. 5381 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier); 5382 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer, 5383 CodeCompleter->includeGlobals(), 5384 CodeCompleter->loadExternal()); 5385 } 5386 5387 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 5388 Results.data(), Results.size()); 5389 } 5390 5391 static void AddTypeQualifierResults(DeclSpec &DS, ResultBuilder &Results, 5392 const LangOptions &LangOpts) { 5393 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_const)) 5394 Results.AddResult("const"); 5395 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_volatile)) 5396 Results.AddResult("volatile"); 5397 if (LangOpts.C99 && !(DS.getTypeQualifiers() & DeclSpec::TQ_restrict)) 5398 Results.AddResult("restrict"); 5399 if (LangOpts.C11 && !(DS.getTypeQualifiers() & DeclSpec::TQ_atomic)) 5400 Results.AddResult("_Atomic"); 5401 if (LangOpts.MSVCCompat && !(DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)) 5402 Results.AddResult("__unaligned"); 5403 } 5404 5405 void Sema::CodeCompleteTypeQualifiers(DeclSpec &DS) { 5406 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5407 CodeCompleter->getCodeCompletionTUInfo(), 5408 CodeCompletionContext::CCC_TypeQualifiers); 5409 Results.EnterNewScope(); 5410 AddTypeQualifierResults(DS, Results, LangOpts); 5411 Results.ExitScope(); 5412 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 5413 Results.data(), Results.size()); 5414 } 5415 5416 void Sema::CodeCompleteFunctionQualifiers(DeclSpec &DS, Declarator &D, 5417 const VirtSpecifiers *VS) { 5418 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5419 CodeCompleter->getCodeCompletionTUInfo(), 5420 CodeCompletionContext::CCC_TypeQualifiers); 5421 Results.EnterNewScope(); 5422 AddTypeQualifierResults(DS, Results, LangOpts); 5423 if (LangOpts.CPlusPlus11) { 5424 Results.AddResult("noexcept"); 5425 if (D.getContext() == DeclaratorContext::Member && !D.isCtorOrDtor() && 5426 !D.isStaticMember()) { 5427 if (!VS || !VS->isFinalSpecified()) 5428 Results.AddResult("final"); 5429 if (!VS || !VS->isOverrideSpecified()) 5430 Results.AddResult("override"); 5431 } 5432 } 5433 Results.ExitScope(); 5434 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 5435 Results.data(), Results.size()); 5436 } 5437 5438 void Sema::CodeCompleteBracketDeclarator(Scope *S) { 5439 CodeCompleteExpression(S, QualType(getASTContext().getSizeType())); 5440 } 5441 5442 void Sema::CodeCompleteCase(Scope *S) { 5443 if (getCurFunction()->SwitchStack.empty() || !CodeCompleter) 5444 return; 5445 5446 SwitchStmt *Switch = getCurFunction()->SwitchStack.back().getPointer(); 5447 // Condition expression might be invalid, do not continue in this case. 5448 if (!Switch->getCond()) 5449 return; 5450 QualType type = Switch->getCond()->IgnoreImplicit()->getType(); 5451 if (!type->isEnumeralType()) { 5452 CodeCompleteExpressionData Data(type); 5453 Data.IntegralConstantExpression = true; 5454 CodeCompleteExpression(S, Data); 5455 return; 5456 } 5457 5458 // Code-complete the cases of a switch statement over an enumeration type 5459 // by providing the list of 5460 EnumDecl *Enum = type->castAs<EnumType>()->getDecl(); 5461 if (EnumDecl *Def = Enum->getDefinition()) 5462 Enum = Def; 5463 5464 // Determine which enumerators we have already seen in the switch statement. 5465 // FIXME: Ideally, we would also be able to look *past* the code-completion 5466 // token, in case we are code-completing in the middle of the switch and not 5467 // at the end. However, we aren't able to do so at the moment. 5468 CoveredEnumerators Enumerators; 5469 for (SwitchCase *SC = Switch->getSwitchCaseList(); SC; 5470 SC = SC->getNextSwitchCase()) { 5471 CaseStmt *Case = dyn_cast<CaseStmt>(SC); 5472 if (!Case) 5473 continue; 5474 5475 Expr *CaseVal = Case->getLHS()->IgnoreParenCasts(); 5476 if (auto *DRE = dyn_cast<DeclRefExpr>(CaseVal)) 5477 if (auto *Enumerator = 5478 dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 5479 // We look into the AST of the case statement to determine which 5480 // enumerator was named. Alternatively, we could compute the value of 5481 // the integral constant expression, then compare it against the 5482 // values of each enumerator. However, value-based approach would not 5483 // work as well with C++ templates where enumerators declared within a 5484 // template are type- and value-dependent. 5485 Enumerators.Seen.insert(Enumerator); 5486 5487 // If this is a qualified-id, keep track of the nested-name-specifier 5488 // so that we can reproduce it as part of code completion, e.g., 5489 // 5490 // switch (TagD.getKind()) { 5491 // case TagDecl::TK_enum: 5492 // break; 5493 // case XXX 5494 // 5495 // At the XXX, our completions are TagDecl::TK_union, 5496 // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union, 5497 // TK_struct, and TK_class. 5498 Enumerators.SuggestedQualifier = DRE->getQualifier(); 5499 } 5500 } 5501 5502 // Add any enumerators that have not yet been mentioned. 5503 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5504 CodeCompleter->getCodeCompletionTUInfo(), 5505 CodeCompletionContext::CCC_Expression); 5506 AddEnumerators(Results, Context, Enum, CurContext, Enumerators); 5507 5508 if (CodeCompleter->includeMacros()) { 5509 AddMacroResults(PP, Results, CodeCompleter->loadExternal(), false); 5510 } 5511 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 5512 Results.data(), Results.size()); 5513 } 5514 5515 static bool anyNullArguments(ArrayRef<Expr *> Args) { 5516 if (Args.size() && !Args.data()) 5517 return true; 5518 5519 for (unsigned I = 0; I != Args.size(); ++I) 5520 if (!Args[I]) 5521 return true; 5522 5523 return false; 5524 } 5525 5526 typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate; 5527 5528 static void mergeCandidatesWithResults( 5529 Sema &SemaRef, SmallVectorImpl<ResultCandidate> &Results, 5530 OverloadCandidateSet &CandidateSet, SourceLocation Loc, size_t ArgSize) { 5531 // Sort the overload candidate set by placing the best overloads first. 5532 llvm::stable_sort(CandidateSet, [&](const OverloadCandidate &X, 5533 const OverloadCandidate &Y) { 5534 return isBetterOverloadCandidate(SemaRef, X, Y, Loc, 5535 CandidateSet.getKind()); 5536 }); 5537 5538 // Add the remaining viable overload candidates as code-completion results. 5539 for (OverloadCandidate &Candidate : CandidateSet) { 5540 if (Candidate.Function) { 5541 if (Candidate.Function->isDeleted()) 5542 continue; 5543 if (!Candidate.Function->isVariadic() && 5544 Candidate.Function->getNumParams() <= ArgSize && 5545 // Having zero args is annoying, normally we don't surface a function 5546 // with 2 params, if you already have 2 params, because you are 5547 // inserting the 3rd now. But with zero, it helps the user to figure 5548 // out there are no overloads that take any arguments. Hence we are 5549 // keeping the overload. 5550 ArgSize > 0) 5551 continue; 5552 } 5553 if (Candidate.Viable) 5554 Results.push_back(ResultCandidate(Candidate.Function)); 5555 } 5556 } 5557 5558 /// Get the type of the Nth parameter from a given set of overload 5559 /// candidates. 5560 static QualType getParamType(Sema &SemaRef, 5561 ArrayRef<ResultCandidate> Candidates, unsigned N) { 5562 5563 // Given the overloads 'Candidates' for a function call matching all arguments 5564 // up to N, return the type of the Nth parameter if it is the same for all 5565 // overload candidates. 5566 QualType ParamType; 5567 for (auto &Candidate : Candidates) { 5568 if (const auto *FType = Candidate.getFunctionType()) 5569 if (const auto *Proto = dyn_cast<FunctionProtoType>(FType)) 5570 if (N < Proto->getNumParams()) { 5571 if (ParamType.isNull()) 5572 ParamType = Proto->getParamType(N); 5573 else if (!SemaRef.Context.hasSameUnqualifiedType( 5574 ParamType.getNonReferenceType(), 5575 Proto->getParamType(N).getNonReferenceType())) 5576 // Otherwise return a default-constructed QualType. 5577 return QualType(); 5578 } 5579 } 5580 5581 return ParamType; 5582 } 5583 5584 static QualType 5585 ProduceSignatureHelp(Sema &SemaRef, Scope *S, 5586 MutableArrayRef<ResultCandidate> Candidates, 5587 unsigned CurrentArg, SourceLocation OpenParLoc) { 5588 if (Candidates.empty()) 5589 return QualType(); 5590 SemaRef.CodeCompleter->ProcessOverloadCandidates( 5591 SemaRef, CurrentArg, Candidates.data(), Candidates.size(), OpenParLoc); 5592 return getParamType(SemaRef, Candidates, CurrentArg); 5593 } 5594 5595 QualType Sema::ProduceCallSignatureHelp(Scope *S, Expr *Fn, 5596 ArrayRef<Expr *> Args, 5597 SourceLocation OpenParLoc) { 5598 if (!CodeCompleter) 5599 return QualType(); 5600 5601 // FIXME: Provide support for variadic template functions. 5602 // Ignore type-dependent call expressions entirely. 5603 if (!Fn || Fn->isTypeDependent() || anyNullArguments(Args)) 5604 return QualType(); 5605 // In presence of dependent args we surface all possible signatures using the 5606 // non-dependent args in the prefix. Afterwards we do a post filtering to make 5607 // sure provided candidates satisfy parameter count restrictions. 5608 auto ArgsWithoutDependentTypes = 5609 Args.take_while([](Expr *Arg) { return !Arg->isTypeDependent(); }); 5610 5611 SmallVector<ResultCandidate, 8> Results; 5612 5613 Expr *NakedFn = Fn->IgnoreParenCasts(); 5614 // Build an overload candidate set based on the functions we find. 5615 SourceLocation Loc = Fn->getExprLoc(); 5616 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); 5617 5618 if (auto ULE = dyn_cast<UnresolvedLookupExpr>(NakedFn)) { 5619 AddOverloadedCallCandidates(ULE, ArgsWithoutDependentTypes, CandidateSet, 5620 /*PartialOverloading=*/true); 5621 } else if (auto UME = dyn_cast<UnresolvedMemberExpr>(NakedFn)) { 5622 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 5623 if (UME->hasExplicitTemplateArgs()) { 5624 UME->copyTemplateArgumentsInto(TemplateArgsBuffer); 5625 TemplateArgs = &TemplateArgsBuffer; 5626 } 5627 5628 // Add the base as first argument (use a nullptr if the base is implicit). 5629 SmallVector<Expr *, 12> ArgExprs( 5630 1, UME->isImplicitAccess() ? nullptr : UME->getBase()); 5631 ArgExprs.append(ArgsWithoutDependentTypes.begin(), 5632 ArgsWithoutDependentTypes.end()); 5633 UnresolvedSet<8> Decls; 5634 Decls.append(UME->decls_begin(), UME->decls_end()); 5635 const bool FirstArgumentIsBase = !UME->isImplicitAccess() && UME->getBase(); 5636 AddFunctionCandidates(Decls, ArgExprs, CandidateSet, TemplateArgs, 5637 /*SuppressUserConversions=*/false, 5638 /*PartialOverloading=*/true, FirstArgumentIsBase); 5639 } else { 5640 FunctionDecl *FD = nullptr; 5641 if (auto *MCE = dyn_cast<MemberExpr>(NakedFn)) 5642 FD = dyn_cast<FunctionDecl>(MCE->getMemberDecl()); 5643 else if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) 5644 FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 5645 if (FD) { // We check whether it's a resolved function declaration. 5646 if (!getLangOpts().CPlusPlus || 5647 !FD->getType()->getAs<FunctionProtoType>()) 5648 Results.push_back(ResultCandidate(FD)); 5649 else 5650 AddOverloadCandidate(FD, DeclAccessPair::make(FD, FD->getAccess()), 5651 ArgsWithoutDependentTypes, CandidateSet, 5652 /*SuppressUserConversions=*/false, 5653 /*PartialOverloading=*/true); 5654 5655 } else if (auto DC = NakedFn->getType()->getAsCXXRecordDecl()) { 5656 // If expression's type is CXXRecordDecl, it may overload the function 5657 // call operator, so we check if it does and add them as candidates. 5658 // A complete type is needed to lookup for member function call operators. 5659 if (isCompleteType(Loc, NakedFn->getType())) { 5660 DeclarationName OpName = 5661 Context.DeclarationNames.getCXXOperatorName(OO_Call); 5662 LookupResult R(*this, OpName, Loc, LookupOrdinaryName); 5663 LookupQualifiedName(R, DC); 5664 R.suppressDiagnostics(); 5665 SmallVector<Expr *, 12> ArgExprs(1, NakedFn); 5666 ArgExprs.append(ArgsWithoutDependentTypes.begin(), 5667 ArgsWithoutDependentTypes.end()); 5668 AddFunctionCandidates(R.asUnresolvedSet(), ArgExprs, CandidateSet, 5669 /*ExplicitArgs=*/nullptr, 5670 /*SuppressUserConversions=*/false, 5671 /*PartialOverloading=*/true); 5672 } 5673 } else { 5674 // Lastly we check whether expression's type is function pointer or 5675 // function. 5676 QualType T = NakedFn->getType(); 5677 if (!T->getPointeeType().isNull()) 5678 T = T->getPointeeType(); 5679 5680 if (auto FP = T->getAs<FunctionProtoType>()) { 5681 if (!TooManyArguments(FP->getNumParams(), 5682 ArgsWithoutDependentTypes.size(), 5683 /*PartialOverloading=*/true) || 5684 FP->isVariadic()) 5685 Results.push_back(ResultCandidate(FP)); 5686 } else if (auto FT = T->getAs<FunctionType>()) 5687 // No prototype and declaration, it may be a K & R style function. 5688 Results.push_back(ResultCandidate(FT)); 5689 } 5690 } 5691 mergeCandidatesWithResults(*this, Results, CandidateSet, Loc, Args.size()); 5692 QualType ParamType = 5693 ProduceSignatureHelp(*this, S, Results, Args.size(), OpenParLoc); 5694 return !CandidateSet.empty() ? ParamType : QualType(); 5695 } 5696 5697 QualType Sema::ProduceConstructorSignatureHelp(Scope *S, QualType Type, 5698 SourceLocation Loc, 5699 ArrayRef<Expr *> Args, 5700 SourceLocation OpenParLoc) { 5701 if (!CodeCompleter) 5702 return QualType(); 5703 5704 // A complete type is needed to lookup for constructors. 5705 CXXRecordDecl *RD = 5706 isCompleteType(Loc, Type) ? Type->getAsCXXRecordDecl() : nullptr; 5707 if (!RD) 5708 return Type; 5709 5710 // FIXME: Provide support for member initializers. 5711 // FIXME: Provide support for variadic template constructors. 5712 5713 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); 5714 5715 for (NamedDecl *C : LookupConstructors(RD)) { 5716 if (auto *FD = dyn_cast<FunctionDecl>(C)) { 5717 AddOverloadCandidate(FD, DeclAccessPair::make(FD, C->getAccess()), Args, 5718 CandidateSet, 5719 /*SuppressUserConversions=*/false, 5720 /*PartialOverloading=*/true, 5721 /*AllowExplicit*/ true); 5722 } else if (auto *FTD = dyn_cast<FunctionTemplateDecl>(C)) { 5723 AddTemplateOverloadCandidate( 5724 FTD, DeclAccessPair::make(FTD, C->getAccess()), 5725 /*ExplicitTemplateArgs=*/nullptr, Args, CandidateSet, 5726 /*SuppressUserConversions=*/false, 5727 /*PartialOverloading=*/true); 5728 } 5729 } 5730 5731 SmallVector<ResultCandidate, 8> Results; 5732 mergeCandidatesWithResults(*this, Results, CandidateSet, Loc, Args.size()); 5733 return ProduceSignatureHelp(*this, S, Results, Args.size(), OpenParLoc); 5734 } 5735 5736 QualType Sema::ProduceCtorInitMemberSignatureHelp( 5737 Scope *S, Decl *ConstructorDecl, CXXScopeSpec SS, ParsedType TemplateTypeTy, 5738 ArrayRef<Expr *> ArgExprs, IdentifierInfo *II, SourceLocation OpenParLoc) { 5739 if (!CodeCompleter) 5740 return QualType(); 5741 5742 CXXConstructorDecl *Constructor = 5743 dyn_cast<CXXConstructorDecl>(ConstructorDecl); 5744 if (!Constructor) 5745 return QualType(); 5746 // FIXME: Add support for Base class constructors as well. 5747 if (ValueDecl *MemberDecl = tryLookupCtorInitMemberDecl( 5748 Constructor->getParent(), SS, TemplateTypeTy, II)) 5749 return ProduceConstructorSignatureHelp(getCurScope(), MemberDecl->getType(), 5750 MemberDecl->getLocation(), ArgExprs, 5751 OpenParLoc); 5752 return QualType(); 5753 } 5754 5755 void Sema::CodeCompleteDesignator(const QualType BaseType, 5756 llvm::ArrayRef<Expr *> InitExprs, 5757 const Designation &D) { 5758 if (BaseType.isNull()) 5759 return; 5760 // FIXME: Handle nested designations, e.g. : .x.^ 5761 if (!D.empty()) 5762 return; 5763 5764 const auto *RD = getAsRecordDecl(BaseType); 5765 if (!RD) 5766 return; 5767 if (const auto *CTSD = llvm::dyn_cast<ClassTemplateSpecializationDecl>(RD)) { 5768 // Template might not be instantiated yet, fall back to primary template in 5769 // such cases. 5770 if (CTSD->getTemplateSpecializationKind() == TSK_Undeclared) 5771 RD = CTSD->getSpecializedTemplate()->getTemplatedDecl(); 5772 } 5773 if (RD->fields().empty()) 5774 return; 5775 5776 CodeCompletionContext CCC(CodeCompletionContext::CCC_DotMemberAccess, 5777 BaseType); 5778 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5779 CodeCompleter->getCodeCompletionTUInfo(), CCC); 5780 5781 Results.EnterNewScope(); 5782 for (const auto *FD : RD->fields()) { 5783 // FIXME: Make use of previous designators to mark any fields before those 5784 // inaccessible, and also compute the next initializer priority. 5785 ResultBuilder::Result Result(FD, Results.getBasePriority(FD)); 5786 Results.AddResult(Result, CurContext, /*Hiding=*/nullptr); 5787 } 5788 Results.ExitScope(); 5789 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 5790 Results.data(), Results.size()); 5791 } 5792 5793 void Sema::CodeCompleteInitializer(Scope *S, Decl *D) { 5794 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D); 5795 if (!VD) { 5796 CodeCompleteOrdinaryName(S, PCC_Expression); 5797 return; 5798 } 5799 5800 CodeCompleteExpressionData Data; 5801 Data.PreferredType = VD->getType(); 5802 // Ignore VD to avoid completing the variable itself, e.g. in 'int foo = ^'. 5803 Data.IgnoreDecls.push_back(VD); 5804 5805 CodeCompleteExpression(S, Data); 5806 } 5807 5808 void Sema::CodeCompleteAfterIf(Scope *S, bool IsBracedThen) { 5809 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5810 CodeCompleter->getCodeCompletionTUInfo(), 5811 mapCodeCompletionContext(*this, PCC_Statement)); 5812 Results.setFilter(&ResultBuilder::IsOrdinaryName); 5813 Results.EnterNewScope(); 5814 5815 CodeCompletionDeclConsumer Consumer(Results, CurContext); 5816 LookupVisibleDecls(S, LookupOrdinaryName, Consumer, 5817 CodeCompleter->includeGlobals(), 5818 CodeCompleter->loadExternal()); 5819 5820 AddOrdinaryNameResults(PCC_Statement, S, *this, Results); 5821 5822 // "else" block 5823 CodeCompletionBuilder Builder(Results.getAllocator(), 5824 Results.getCodeCompletionTUInfo()); 5825 5826 auto AddElseBodyPattern = [&] { 5827 if (IsBracedThen) { 5828 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 5829 Builder.AddChunk(CodeCompletionString::CK_LeftBrace); 5830 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); 5831 Builder.AddPlaceholderChunk("statements"); 5832 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); 5833 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 5834 } else { 5835 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); 5836 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 5837 Builder.AddPlaceholderChunk("statement"); 5838 Builder.AddChunk(CodeCompletionString::CK_SemiColon); 5839 } 5840 }; 5841 Builder.AddTypedTextChunk("else"); 5842 if (Results.includeCodePatterns()) 5843 AddElseBodyPattern(); 5844 Results.AddResult(Builder.TakeString()); 5845 5846 // "else if" block 5847 Builder.AddTypedTextChunk("else if"); 5848 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 5849 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 5850 if (getLangOpts().CPlusPlus) 5851 Builder.AddPlaceholderChunk("condition"); 5852 else 5853 Builder.AddPlaceholderChunk("expression"); 5854 Builder.AddChunk(CodeCompletionString::CK_RightParen); 5855 if (Results.includeCodePatterns()) { 5856 AddElseBodyPattern(); 5857 } 5858 Results.AddResult(Builder.TakeString()); 5859 5860 Results.ExitScope(); 5861 5862 if (S->getFnParent()) 5863 AddPrettyFunctionResults(getLangOpts(), Results); 5864 5865 if (CodeCompleter->includeMacros()) 5866 AddMacroResults(PP, Results, CodeCompleter->loadExternal(), false); 5867 5868 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 5869 Results.data(), Results.size()); 5870 } 5871 5872 void Sema::CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS, 5873 bool EnteringContext, 5874 bool IsUsingDeclaration, QualType BaseType, 5875 QualType PreferredType) { 5876 if (SS.isEmpty() || !CodeCompleter) 5877 return; 5878 5879 CodeCompletionContext CC(CodeCompletionContext::CCC_Symbol, PreferredType); 5880 CC.setIsUsingDeclaration(IsUsingDeclaration); 5881 CC.setCXXScopeSpecifier(SS); 5882 5883 // We want to keep the scope specifier even if it's invalid (e.g. the scope 5884 // "a::b::" is not corresponding to any context/namespace in the AST), since 5885 // it can be useful for global code completion which have information about 5886 // contexts/symbols that are not in the AST. 5887 if (SS.isInvalid()) { 5888 // As SS is invalid, we try to collect accessible contexts from the current 5889 // scope with a dummy lookup so that the completion consumer can try to 5890 // guess what the specified scope is. 5891 ResultBuilder DummyResults(*this, CodeCompleter->getAllocator(), 5892 CodeCompleter->getCodeCompletionTUInfo(), CC); 5893 if (!PreferredType.isNull()) 5894 DummyResults.setPreferredType(PreferredType); 5895 if (S->getEntity()) { 5896 CodeCompletionDeclConsumer Consumer(DummyResults, S->getEntity(), 5897 BaseType); 5898 LookupVisibleDecls(S, LookupOrdinaryName, Consumer, 5899 /*IncludeGlobalScope=*/false, 5900 /*LoadExternal=*/false); 5901 } 5902 HandleCodeCompleteResults(this, CodeCompleter, 5903 DummyResults.getCompletionContext(), nullptr, 0); 5904 return; 5905 } 5906 // Always pretend to enter a context to ensure that a dependent type 5907 // resolves to a dependent record. 5908 DeclContext *Ctx = computeDeclContext(SS, /*EnteringContext=*/true); 5909 5910 // Try to instantiate any non-dependent declaration contexts before 5911 // we look in them. Bail out if we fail. 5912 NestedNameSpecifier *NNS = SS.getScopeRep(); 5913 if (NNS != nullptr && SS.isValid() && !NNS->isDependent()) { 5914 if (Ctx == nullptr || RequireCompleteDeclContext(SS, Ctx)) 5915 return; 5916 } 5917 5918 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5919 CodeCompleter->getCodeCompletionTUInfo(), CC); 5920 if (!PreferredType.isNull()) 5921 Results.setPreferredType(PreferredType); 5922 Results.EnterNewScope(); 5923 5924 // The "template" keyword can follow "::" in the grammar, but only 5925 // put it into the grammar if the nested-name-specifier is dependent. 5926 // FIXME: results is always empty, this appears to be dead. 5927 if (!Results.empty() && NNS->isDependent()) 5928 Results.AddResult("template"); 5929 5930 // If the scope is a concept-constrained type parameter, infer nested 5931 // members based on the constraints. 5932 if (const auto *TTPT = 5933 dyn_cast_or_null<TemplateTypeParmType>(NNS->getAsType())) { 5934 for (const auto &R : ConceptInfo(*TTPT, S).members()) { 5935 if (R.Operator != ConceptInfo::Member::Colons) 5936 continue; 5937 Results.AddResult(CodeCompletionResult( 5938 R.render(*this, CodeCompleter->getAllocator(), 5939 CodeCompleter->getCodeCompletionTUInfo()))); 5940 } 5941 } 5942 5943 // Add calls to overridden virtual functions, if there are any. 5944 // 5945 // FIXME: This isn't wonderful, because we don't know whether we're actually 5946 // in a context that permits expressions. This is a general issue with 5947 // qualified-id completions. 5948 if (Ctx && !EnteringContext) 5949 MaybeAddOverrideCalls(*this, Ctx, Results); 5950 Results.ExitScope(); 5951 5952 if (Ctx && 5953 (CodeCompleter->includeNamespaceLevelDecls() || !Ctx->isFileContext())) { 5954 CodeCompletionDeclConsumer Consumer(Results, Ctx, BaseType); 5955 LookupVisibleDecls(Ctx, LookupOrdinaryName, Consumer, 5956 /*IncludeGlobalScope=*/true, 5957 /*IncludeDependentBases=*/true, 5958 CodeCompleter->loadExternal()); 5959 } 5960 5961 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 5962 Results.data(), Results.size()); 5963 } 5964 5965 void Sema::CodeCompleteUsing(Scope *S) { 5966 if (!CodeCompleter) 5967 return; 5968 5969 // This can be both a using alias or using declaration, in the former we 5970 // expect a new name and a symbol in the latter case. 5971 CodeCompletionContext Context(CodeCompletionContext::CCC_SymbolOrNewName); 5972 Context.setIsUsingDeclaration(true); 5973 5974 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 5975 CodeCompleter->getCodeCompletionTUInfo(), Context, 5976 &ResultBuilder::IsNestedNameSpecifier); 5977 Results.EnterNewScope(); 5978 5979 // If we aren't in class scope, we could see the "namespace" keyword. 5980 if (!S->isClassScope()) 5981 Results.AddResult(CodeCompletionResult("namespace")); 5982 5983 // After "using", we can see anything that would start a 5984 // nested-name-specifier. 5985 CodeCompletionDeclConsumer Consumer(Results, CurContext); 5986 LookupVisibleDecls(S, LookupOrdinaryName, Consumer, 5987 CodeCompleter->includeGlobals(), 5988 CodeCompleter->loadExternal()); 5989 Results.ExitScope(); 5990 5991 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 5992 Results.data(), Results.size()); 5993 } 5994 5995 void Sema::CodeCompleteUsingDirective(Scope *S) { 5996 if (!CodeCompleter) 5997 return; 5998 5999 // After "using namespace", we expect to see a namespace name or namespace 6000 // alias. 6001 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 6002 CodeCompleter->getCodeCompletionTUInfo(), 6003 CodeCompletionContext::CCC_Namespace, 6004 &ResultBuilder::IsNamespaceOrAlias); 6005 Results.EnterNewScope(); 6006 CodeCompletionDeclConsumer Consumer(Results, CurContext); 6007 LookupVisibleDecls(S, LookupOrdinaryName, Consumer, 6008 CodeCompleter->includeGlobals(), 6009 CodeCompleter->loadExternal()); 6010 Results.ExitScope(); 6011 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 6012 Results.data(), Results.size()); 6013 } 6014 6015 void Sema::CodeCompleteNamespaceDecl(Scope *S) { 6016 if (!CodeCompleter) 6017 return; 6018 6019 DeclContext *Ctx = S->getEntity(); 6020 if (!S->getParent()) 6021 Ctx = Context.getTranslationUnitDecl(); 6022 6023 bool SuppressedGlobalResults = 6024 Ctx && !CodeCompleter->includeGlobals() && isa<TranslationUnitDecl>(Ctx); 6025 6026 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 6027 CodeCompleter->getCodeCompletionTUInfo(), 6028 SuppressedGlobalResults 6029 ? CodeCompletionContext::CCC_Namespace 6030 : CodeCompletionContext::CCC_Other, 6031 &ResultBuilder::IsNamespace); 6032 6033 if (Ctx && Ctx->isFileContext() && !SuppressedGlobalResults) { 6034 // We only want to see those namespaces that have already been defined 6035 // within this scope, because its likely that the user is creating an 6036 // extended namespace declaration. Keep track of the most recent 6037 // definition of each namespace. 6038 std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest; 6039 for (DeclContext::specific_decl_iterator<NamespaceDecl> 6040 NS(Ctx->decls_begin()), 6041 NSEnd(Ctx->decls_end()); 6042 NS != NSEnd; ++NS) 6043 OrigToLatest[NS->getOriginalNamespace()] = *NS; 6044 6045 // Add the most recent definition (or extended definition) of each 6046 // namespace to the list of results. 6047 Results.EnterNewScope(); 6048 for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator 6049 NS = OrigToLatest.begin(), 6050 NSEnd = OrigToLatest.end(); 6051 NS != NSEnd; ++NS) 6052 Results.AddResult( 6053 CodeCompletionResult(NS->second, Results.getBasePriority(NS->second), 6054 nullptr), 6055 CurContext, nullptr, false); 6056 Results.ExitScope(); 6057 } 6058 6059 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 6060 Results.data(), Results.size()); 6061 } 6062 6063 void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) { 6064 if (!CodeCompleter) 6065 return; 6066 6067 // After "namespace", we expect to see a namespace or alias. 6068 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 6069 CodeCompleter->getCodeCompletionTUInfo(), 6070 CodeCompletionContext::CCC_Namespace, 6071 &ResultBuilder::IsNamespaceOrAlias); 6072 CodeCompletionDeclConsumer Consumer(Results, CurContext); 6073 LookupVisibleDecls(S, LookupOrdinaryName, Consumer, 6074 CodeCompleter->includeGlobals(), 6075 CodeCompleter->loadExternal()); 6076 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 6077 Results.data(), Results.size()); 6078 } 6079 6080 void Sema::CodeCompleteOperatorName(Scope *S) { 6081 if (!CodeCompleter) 6082 return; 6083 6084 typedef CodeCompletionResult Result; 6085 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 6086 CodeCompleter->getCodeCompletionTUInfo(), 6087 CodeCompletionContext::CCC_Type, 6088 &ResultBuilder::IsType); 6089 Results.EnterNewScope(); 6090 6091 // Add the names of overloadable operators. Note that OO_Conditional is not 6092 // actually overloadable. 6093 #define OVERLOADED_OPERATOR(Name, Spelling, Token, Unary, Binary, MemberOnly) \ 6094 if (OO_##Name != OO_Conditional) \ 6095 Results.AddResult(Result(Spelling)); 6096 #include "clang/Basic/OperatorKinds.def" 6097 6098 // Add any type names visible from the current scope 6099 Results.allowNestedNameSpecifiers(); 6100 CodeCompletionDeclConsumer Consumer(Results, CurContext); 6101 LookupVisibleDecls(S, LookupOrdinaryName, Consumer, 6102 CodeCompleter->includeGlobals(), 6103 CodeCompleter->loadExternal()); 6104 6105 // Add any type specifiers 6106 AddTypeSpecifierResults(getLangOpts(), Results); 6107 Results.ExitScope(); 6108 6109 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 6110 Results.data(), Results.size()); 6111 } 6112 6113 void Sema::CodeCompleteConstructorInitializer( 6114 Decl *ConstructorD, ArrayRef<CXXCtorInitializer *> Initializers) { 6115 if (!ConstructorD) 6116 return; 6117 6118 AdjustDeclIfTemplate(ConstructorD); 6119 6120 auto *Constructor = dyn_cast<CXXConstructorDecl>(ConstructorD); 6121 if (!Constructor) 6122 return; 6123 6124 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 6125 CodeCompleter->getCodeCompletionTUInfo(), 6126 CodeCompletionContext::CCC_Symbol); 6127 Results.EnterNewScope(); 6128 6129 // Fill in any already-initialized fields or base classes. 6130 llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields; 6131 llvm::SmallPtrSet<CanQualType, 4> InitializedBases; 6132 for (unsigned I = 0, E = Initializers.size(); I != E; ++I) { 6133 if (Initializers[I]->isBaseInitializer()) 6134 InitializedBases.insert(Context.getCanonicalType( 6135 QualType(Initializers[I]->getBaseClass(), 0))); 6136 else 6137 InitializedFields.insert( 6138 cast<FieldDecl>(Initializers[I]->getAnyMember())); 6139 } 6140 6141 // Add completions for base classes. 6142 PrintingPolicy Policy = getCompletionPrintingPolicy(*this); 6143 bool SawLastInitializer = Initializers.empty(); 6144 CXXRecordDecl *ClassDecl = Constructor->getParent(); 6145 6146 auto GenerateCCS = [&](const NamedDecl *ND, const char *Name) { 6147 CodeCompletionBuilder Builder(Results.getAllocator(), 6148 Results.getCodeCompletionTUInfo()); 6149 Builder.AddTypedTextChunk(Name); 6150 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 6151 if (const auto *Function = dyn_cast<FunctionDecl>(ND)) 6152 AddFunctionParameterChunks(PP, Policy, Function, Builder); 6153 else if (const auto *FunTemplDecl = dyn_cast<FunctionTemplateDecl>(ND)) 6154 AddFunctionParameterChunks(PP, Policy, FunTemplDecl->getTemplatedDecl(), 6155 Builder); 6156 Builder.AddChunk(CodeCompletionString::CK_RightParen); 6157 return Builder.TakeString(); 6158 }; 6159 auto AddDefaultCtorInit = [&](const char *Name, const char *Type, 6160 const NamedDecl *ND) { 6161 CodeCompletionBuilder Builder(Results.getAllocator(), 6162 Results.getCodeCompletionTUInfo()); 6163 Builder.AddTypedTextChunk(Name); 6164 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 6165 Builder.AddPlaceholderChunk(Type); 6166 Builder.AddChunk(CodeCompletionString::CK_RightParen); 6167 if (ND) { 6168 auto CCR = CodeCompletionResult( 6169 Builder.TakeString(), ND, 6170 SawLastInitializer ? CCP_NextInitializer : CCP_MemberDeclaration); 6171 if (isa<FieldDecl>(ND)) 6172 CCR.CursorKind = CXCursor_MemberRef; 6173 return Results.AddResult(CCR); 6174 } 6175 return Results.AddResult(CodeCompletionResult( 6176 Builder.TakeString(), 6177 SawLastInitializer ? CCP_NextInitializer : CCP_MemberDeclaration)); 6178 }; 6179 auto AddCtorsWithName = [&](const CXXRecordDecl *RD, unsigned int Priority, 6180 const char *Name, const FieldDecl *FD) { 6181 if (!RD) 6182 return AddDefaultCtorInit(Name, 6183 FD ? Results.getAllocator().CopyString( 6184 FD->getType().getAsString(Policy)) 6185 : Name, 6186 FD); 6187 auto Ctors = getConstructors(Context, RD); 6188 if (Ctors.begin() == Ctors.end()) 6189 return AddDefaultCtorInit(Name, Name, RD); 6190 for (const NamedDecl *Ctor : Ctors) { 6191 auto CCR = CodeCompletionResult(GenerateCCS(Ctor, Name), RD, Priority); 6192 CCR.CursorKind = getCursorKindForDecl(Ctor); 6193 Results.AddResult(CCR); 6194 } 6195 }; 6196 auto AddBase = [&](const CXXBaseSpecifier &Base) { 6197 const char *BaseName = 6198 Results.getAllocator().CopyString(Base.getType().getAsString(Policy)); 6199 const auto *RD = Base.getType()->getAsCXXRecordDecl(); 6200 AddCtorsWithName( 6201 RD, SawLastInitializer ? CCP_NextInitializer : CCP_MemberDeclaration, 6202 BaseName, nullptr); 6203 }; 6204 auto AddField = [&](const FieldDecl *FD) { 6205 const char *FieldName = 6206 Results.getAllocator().CopyString(FD->getIdentifier()->getName()); 6207 const CXXRecordDecl *RD = FD->getType()->getAsCXXRecordDecl(); 6208 AddCtorsWithName( 6209 RD, SawLastInitializer ? CCP_NextInitializer : CCP_MemberDeclaration, 6210 FieldName, FD); 6211 }; 6212 6213 for (const auto &Base : ClassDecl->bases()) { 6214 if (!InitializedBases.insert(Context.getCanonicalType(Base.getType())) 6215 .second) { 6216 SawLastInitializer = 6217 !Initializers.empty() && Initializers.back()->isBaseInitializer() && 6218 Context.hasSameUnqualifiedType( 6219 Base.getType(), QualType(Initializers.back()->getBaseClass(), 0)); 6220 continue; 6221 } 6222 6223 AddBase(Base); 6224 SawLastInitializer = false; 6225 } 6226 6227 // Add completions for virtual base classes. 6228 for (const auto &Base : ClassDecl->vbases()) { 6229 if (!InitializedBases.insert(Context.getCanonicalType(Base.getType())) 6230 .second) { 6231 SawLastInitializer = 6232 !Initializers.empty() && Initializers.back()->isBaseInitializer() && 6233 Context.hasSameUnqualifiedType( 6234 Base.getType(), QualType(Initializers.back()->getBaseClass(), 0)); 6235 continue; 6236 } 6237 6238 AddBase(Base); 6239 SawLastInitializer = false; 6240 } 6241 6242 // Add completions for members. 6243 for (auto *Field : ClassDecl->fields()) { 6244 if (!InitializedFields.insert(cast<FieldDecl>(Field->getCanonicalDecl())) 6245 .second) { 6246 SawLastInitializer = !Initializers.empty() && 6247 Initializers.back()->isAnyMemberInitializer() && 6248 Initializers.back()->getAnyMember() == Field; 6249 continue; 6250 } 6251 6252 if (!Field->getDeclName()) 6253 continue; 6254 6255 AddField(Field); 6256 SawLastInitializer = false; 6257 } 6258 Results.ExitScope(); 6259 6260 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 6261 Results.data(), Results.size()); 6262 } 6263 6264 /// Determine whether this scope denotes a namespace. 6265 static bool isNamespaceScope(Scope *S) { 6266 DeclContext *DC = S->getEntity(); 6267 if (!DC) 6268 return false; 6269 6270 return DC->isFileContext(); 6271 } 6272 6273 void Sema::CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro, 6274 bool AfterAmpersand) { 6275 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 6276 CodeCompleter->getCodeCompletionTUInfo(), 6277 CodeCompletionContext::CCC_Other); 6278 Results.EnterNewScope(); 6279 6280 // Note what has already been captured. 6281 llvm::SmallPtrSet<IdentifierInfo *, 4> Known; 6282 bool IncludedThis = false; 6283 for (const auto &C : Intro.Captures) { 6284 if (C.Kind == LCK_This) { 6285 IncludedThis = true; 6286 continue; 6287 } 6288 6289 Known.insert(C.Id); 6290 } 6291 6292 // Look for other capturable variables. 6293 for (; S && !isNamespaceScope(S); S = S->getParent()) { 6294 for (const auto *D : S->decls()) { 6295 const auto *Var = dyn_cast<VarDecl>(D); 6296 if (!Var || !Var->hasLocalStorage() || Var->hasAttr<BlocksAttr>()) 6297 continue; 6298 6299 if (Known.insert(Var->getIdentifier()).second) 6300 Results.AddResult(CodeCompletionResult(Var, CCP_LocalDeclaration), 6301 CurContext, nullptr, false); 6302 } 6303 } 6304 6305 // Add 'this', if it would be valid. 6306 if (!IncludedThis && !AfterAmpersand && Intro.Default != LCD_ByCopy) 6307 addThisCompletion(*this, Results); 6308 6309 Results.ExitScope(); 6310 6311 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 6312 Results.data(), Results.size()); 6313 } 6314 6315 void Sema::CodeCompleteAfterFunctionEquals(Declarator &D) { 6316 if (!LangOpts.CPlusPlus11) 6317 return; 6318 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 6319 CodeCompleter->getCodeCompletionTUInfo(), 6320 CodeCompletionContext::CCC_Other); 6321 auto ShouldAddDefault = [&D, this]() { 6322 if (!D.isFunctionDeclarator()) 6323 return false; 6324 auto &Id = D.getName(); 6325 if (Id.getKind() == UnqualifiedIdKind::IK_DestructorName) 6326 return true; 6327 // FIXME(liuhui): Ideally, we should check the constructor parameter list to 6328 // verify that it is the default, copy or move constructor? 6329 if (Id.getKind() == UnqualifiedIdKind::IK_ConstructorName && 6330 D.getFunctionTypeInfo().NumParams <= 1) 6331 return true; 6332 if (Id.getKind() == UnqualifiedIdKind::IK_OperatorFunctionId) { 6333 auto Op = Id.OperatorFunctionId.Operator; 6334 // FIXME(liuhui): Ideally, we should check the function parameter list to 6335 // verify that it is the copy or move assignment? 6336 if (Op == OverloadedOperatorKind::OO_Equal) 6337 return true; 6338 if (LangOpts.CPlusPlus20 && 6339 (Op == OverloadedOperatorKind::OO_EqualEqual || 6340 Op == OverloadedOperatorKind::OO_ExclaimEqual || 6341 Op == OverloadedOperatorKind::OO_Less || 6342 Op == OverloadedOperatorKind::OO_LessEqual || 6343 Op == OverloadedOperatorKind::OO_Greater || 6344 Op == OverloadedOperatorKind::OO_GreaterEqual || 6345 Op == OverloadedOperatorKind::OO_Spaceship)) 6346 return true; 6347 } 6348 return false; 6349 }; 6350 6351 Results.EnterNewScope(); 6352 if (ShouldAddDefault()) 6353 Results.AddResult("default"); 6354 // FIXME(liuhui): Ideally, we should only provide `delete` completion for the 6355 // first function declaration. 6356 Results.AddResult("delete"); 6357 Results.ExitScope(); 6358 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 6359 Results.data(), Results.size()); 6360 } 6361 6362 /// Macro that optionally prepends an "@" to the string literal passed in via 6363 /// Keyword, depending on whether NeedAt is true or false. 6364 #define OBJC_AT_KEYWORD_NAME(NeedAt, Keyword) ((NeedAt) ? "@" Keyword : Keyword) 6365 6366 static void AddObjCImplementationResults(const LangOptions &LangOpts, 6367 ResultBuilder &Results, bool NeedAt) { 6368 typedef CodeCompletionResult Result; 6369 // Since we have an implementation, we can end it. 6370 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "end"))); 6371 6372 CodeCompletionBuilder Builder(Results.getAllocator(), 6373 Results.getCodeCompletionTUInfo()); 6374 if (LangOpts.ObjC) { 6375 // @dynamic 6376 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "dynamic")); 6377 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 6378 Builder.AddPlaceholderChunk("property"); 6379 Results.AddResult(Result(Builder.TakeString())); 6380 6381 // @synthesize 6382 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "synthesize")); 6383 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 6384 Builder.AddPlaceholderChunk("property"); 6385 Results.AddResult(Result(Builder.TakeString())); 6386 } 6387 } 6388 6389 static void AddObjCInterfaceResults(const LangOptions &LangOpts, 6390 ResultBuilder &Results, bool NeedAt) { 6391 typedef CodeCompletionResult Result; 6392 6393 // Since we have an interface or protocol, we can end it. 6394 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "end"))); 6395 6396 if (LangOpts.ObjC) { 6397 // @property 6398 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "property"))); 6399 6400 // @required 6401 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "required"))); 6402 6403 // @optional 6404 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "optional"))); 6405 } 6406 } 6407 6408 static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt) { 6409 typedef CodeCompletionResult Result; 6410 CodeCompletionBuilder Builder(Results.getAllocator(), 6411 Results.getCodeCompletionTUInfo()); 6412 6413 // @class name ; 6414 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "class")); 6415 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 6416 Builder.AddPlaceholderChunk("name"); 6417 Results.AddResult(Result(Builder.TakeString())); 6418 6419 if (Results.includeCodePatterns()) { 6420 // @interface name 6421 // FIXME: Could introduce the whole pattern, including superclasses and 6422 // such. 6423 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "interface")); 6424 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 6425 Builder.AddPlaceholderChunk("class"); 6426 Results.AddResult(Result(Builder.TakeString())); 6427 6428 // @protocol name 6429 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "protocol")); 6430 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 6431 Builder.AddPlaceholderChunk("protocol"); 6432 Results.AddResult(Result(Builder.TakeString())); 6433 6434 // @implementation name 6435 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "implementation")); 6436 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 6437 Builder.AddPlaceholderChunk("class"); 6438 Results.AddResult(Result(Builder.TakeString())); 6439 } 6440 6441 // @compatibility_alias name 6442 Builder.AddTypedTextChunk( 6443 OBJC_AT_KEYWORD_NAME(NeedAt, "compatibility_alias")); 6444 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 6445 Builder.AddPlaceholderChunk("alias"); 6446 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 6447 Builder.AddPlaceholderChunk("class"); 6448 Results.AddResult(Result(Builder.TakeString())); 6449 6450 if (Results.getSema().getLangOpts().Modules) { 6451 // @import name 6452 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "import")); 6453 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 6454 Builder.AddPlaceholderChunk("module"); 6455 Results.AddResult(Result(Builder.TakeString())); 6456 } 6457 } 6458 6459 void Sema::CodeCompleteObjCAtDirective(Scope *S) { 6460 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 6461 CodeCompleter->getCodeCompletionTUInfo(), 6462 CodeCompletionContext::CCC_Other); 6463 Results.EnterNewScope(); 6464 if (isa<ObjCImplDecl>(CurContext)) 6465 AddObjCImplementationResults(getLangOpts(), Results, false); 6466 else if (CurContext->isObjCContainer()) 6467 AddObjCInterfaceResults(getLangOpts(), Results, false); 6468 else 6469 AddObjCTopLevelResults(Results, false); 6470 Results.ExitScope(); 6471 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 6472 Results.data(), Results.size()); 6473 } 6474 6475 static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt) { 6476 typedef CodeCompletionResult Result; 6477 CodeCompletionBuilder Builder(Results.getAllocator(), 6478 Results.getCodeCompletionTUInfo()); 6479 6480 // @encode ( type-name ) 6481 const char *EncodeType = "char[]"; 6482 if (Results.getSema().getLangOpts().CPlusPlus || 6483 Results.getSema().getLangOpts().ConstStrings) 6484 EncodeType = "const char[]"; 6485 Builder.AddResultTypeChunk(EncodeType); 6486 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "encode")); 6487 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 6488 Builder.AddPlaceholderChunk("type-name"); 6489 Builder.AddChunk(CodeCompletionString::CK_RightParen); 6490 Results.AddResult(Result(Builder.TakeString())); 6491 6492 // @protocol ( protocol-name ) 6493 Builder.AddResultTypeChunk("Protocol *"); 6494 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "protocol")); 6495 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 6496 Builder.AddPlaceholderChunk("protocol-name"); 6497 Builder.AddChunk(CodeCompletionString::CK_RightParen); 6498 Results.AddResult(Result(Builder.TakeString())); 6499 6500 // @selector ( selector ) 6501 Builder.AddResultTypeChunk("SEL"); 6502 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "selector")); 6503 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 6504 Builder.AddPlaceholderChunk("selector"); 6505 Builder.AddChunk(CodeCompletionString::CK_RightParen); 6506 Results.AddResult(Result(Builder.TakeString())); 6507 6508 // @"string" 6509 Builder.AddResultTypeChunk("NSString *"); 6510 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "\"")); 6511 Builder.AddPlaceholderChunk("string"); 6512 Builder.AddTextChunk("\""); 6513 Results.AddResult(Result(Builder.TakeString())); 6514 6515 // @[objects, ...] 6516 Builder.AddResultTypeChunk("NSArray *"); 6517 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "[")); 6518 Builder.AddPlaceholderChunk("objects, ..."); 6519 Builder.AddChunk(CodeCompletionString::CK_RightBracket); 6520 Results.AddResult(Result(Builder.TakeString())); 6521 6522 // @{key : object, ...} 6523 Builder.AddResultTypeChunk("NSDictionary *"); 6524 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "{")); 6525 Builder.AddPlaceholderChunk("key"); 6526 Builder.AddChunk(CodeCompletionString::CK_Colon); 6527 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 6528 Builder.AddPlaceholderChunk("object, ..."); 6529 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 6530 Results.AddResult(Result(Builder.TakeString())); 6531 6532 // @(expression) 6533 Builder.AddResultTypeChunk("id"); 6534 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "(")); 6535 Builder.AddPlaceholderChunk("expression"); 6536 Builder.AddChunk(CodeCompletionString::CK_RightParen); 6537 Results.AddResult(Result(Builder.TakeString())); 6538 } 6539 6540 static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt) { 6541 typedef CodeCompletionResult Result; 6542 CodeCompletionBuilder Builder(Results.getAllocator(), 6543 Results.getCodeCompletionTUInfo()); 6544 6545 if (Results.includeCodePatterns()) { 6546 // @try { statements } @catch ( declaration ) { statements } @finally 6547 // { statements } 6548 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "try")); 6549 Builder.AddChunk(CodeCompletionString::CK_LeftBrace); 6550 Builder.AddPlaceholderChunk("statements"); 6551 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 6552 Builder.AddTextChunk("@catch"); 6553 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 6554 Builder.AddPlaceholderChunk("parameter"); 6555 Builder.AddChunk(CodeCompletionString::CK_RightParen); 6556 Builder.AddChunk(CodeCompletionString::CK_LeftBrace); 6557 Builder.AddPlaceholderChunk("statements"); 6558 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 6559 Builder.AddTextChunk("@finally"); 6560 Builder.AddChunk(CodeCompletionString::CK_LeftBrace); 6561 Builder.AddPlaceholderChunk("statements"); 6562 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 6563 Results.AddResult(Result(Builder.TakeString())); 6564 } 6565 6566 // @throw 6567 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "throw")); 6568 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 6569 Builder.AddPlaceholderChunk("expression"); 6570 Results.AddResult(Result(Builder.TakeString())); 6571 6572 if (Results.includeCodePatterns()) { 6573 // @synchronized ( expression ) { statements } 6574 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "synchronized")); 6575 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 6576 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 6577 Builder.AddPlaceholderChunk("expression"); 6578 Builder.AddChunk(CodeCompletionString::CK_RightParen); 6579 Builder.AddChunk(CodeCompletionString::CK_LeftBrace); 6580 Builder.AddPlaceholderChunk("statements"); 6581 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 6582 Results.AddResult(Result(Builder.TakeString())); 6583 } 6584 } 6585 6586 static void AddObjCVisibilityResults(const LangOptions &LangOpts, 6587 ResultBuilder &Results, bool NeedAt) { 6588 typedef CodeCompletionResult Result; 6589 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "private"))); 6590 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "protected"))); 6591 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "public"))); 6592 if (LangOpts.ObjC) 6593 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "package"))); 6594 } 6595 6596 void Sema::CodeCompleteObjCAtVisibility(Scope *S) { 6597 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 6598 CodeCompleter->getCodeCompletionTUInfo(), 6599 CodeCompletionContext::CCC_Other); 6600 Results.EnterNewScope(); 6601 AddObjCVisibilityResults(getLangOpts(), Results, false); 6602 Results.ExitScope(); 6603 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 6604 Results.data(), Results.size()); 6605 } 6606 6607 void Sema::CodeCompleteObjCAtStatement(Scope *S) { 6608 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 6609 CodeCompleter->getCodeCompletionTUInfo(), 6610 CodeCompletionContext::CCC_Other); 6611 Results.EnterNewScope(); 6612 AddObjCStatementResults(Results, false); 6613 AddObjCExpressionResults(Results, false); 6614 Results.ExitScope(); 6615 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 6616 Results.data(), Results.size()); 6617 } 6618 6619 void Sema::CodeCompleteObjCAtExpression(Scope *S) { 6620 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 6621 CodeCompleter->getCodeCompletionTUInfo(), 6622 CodeCompletionContext::CCC_Other); 6623 Results.EnterNewScope(); 6624 AddObjCExpressionResults(Results, false); 6625 Results.ExitScope(); 6626 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 6627 Results.data(), Results.size()); 6628 } 6629 6630 /// Determine whether the addition of the given flag to an Objective-C 6631 /// property's attributes will cause a conflict. 6632 static bool ObjCPropertyFlagConflicts(unsigned Attributes, unsigned NewFlag) { 6633 // Check if we've already added this flag. 6634 if (Attributes & NewFlag) 6635 return true; 6636 6637 Attributes |= NewFlag; 6638 6639 // Check for collisions with "readonly". 6640 if ((Attributes & ObjCPropertyAttribute::kind_readonly) && 6641 (Attributes & ObjCPropertyAttribute::kind_readwrite)) 6642 return true; 6643 6644 // Check for more than one of { assign, copy, retain, strong, weak }. 6645 unsigned AssignCopyRetMask = 6646 Attributes & 6647 (ObjCPropertyAttribute::kind_assign | 6648 ObjCPropertyAttribute::kind_unsafe_unretained | 6649 ObjCPropertyAttribute::kind_copy | ObjCPropertyAttribute::kind_retain | 6650 ObjCPropertyAttribute::kind_strong | ObjCPropertyAttribute::kind_weak); 6651 if (AssignCopyRetMask && 6652 AssignCopyRetMask != ObjCPropertyAttribute::kind_assign && 6653 AssignCopyRetMask != ObjCPropertyAttribute::kind_unsafe_unretained && 6654 AssignCopyRetMask != ObjCPropertyAttribute::kind_copy && 6655 AssignCopyRetMask != ObjCPropertyAttribute::kind_retain && 6656 AssignCopyRetMask != ObjCPropertyAttribute::kind_strong && 6657 AssignCopyRetMask != ObjCPropertyAttribute::kind_weak) 6658 return true; 6659 6660 return false; 6661 } 6662 6663 void Sema::CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS) { 6664 if (!CodeCompleter) 6665 return; 6666 6667 unsigned Attributes = ODS.getPropertyAttributes(); 6668 6669 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 6670 CodeCompleter->getCodeCompletionTUInfo(), 6671 CodeCompletionContext::CCC_Other); 6672 Results.EnterNewScope(); 6673 if (!ObjCPropertyFlagConflicts(Attributes, 6674 ObjCPropertyAttribute::kind_readonly)) 6675 Results.AddResult(CodeCompletionResult("readonly")); 6676 if (!ObjCPropertyFlagConflicts(Attributes, 6677 ObjCPropertyAttribute::kind_assign)) 6678 Results.AddResult(CodeCompletionResult("assign")); 6679 if (!ObjCPropertyFlagConflicts(Attributes, 6680 ObjCPropertyAttribute::kind_unsafe_unretained)) 6681 Results.AddResult(CodeCompletionResult("unsafe_unretained")); 6682 if (!ObjCPropertyFlagConflicts(Attributes, 6683 ObjCPropertyAttribute::kind_readwrite)) 6684 Results.AddResult(CodeCompletionResult("readwrite")); 6685 if (!ObjCPropertyFlagConflicts(Attributes, 6686 ObjCPropertyAttribute::kind_retain)) 6687 Results.AddResult(CodeCompletionResult("retain")); 6688 if (!ObjCPropertyFlagConflicts(Attributes, 6689 ObjCPropertyAttribute::kind_strong)) 6690 Results.AddResult(CodeCompletionResult("strong")); 6691 if (!ObjCPropertyFlagConflicts(Attributes, ObjCPropertyAttribute::kind_copy)) 6692 Results.AddResult(CodeCompletionResult("copy")); 6693 if (!ObjCPropertyFlagConflicts(Attributes, 6694 ObjCPropertyAttribute::kind_nonatomic)) 6695 Results.AddResult(CodeCompletionResult("nonatomic")); 6696 if (!ObjCPropertyFlagConflicts(Attributes, 6697 ObjCPropertyAttribute::kind_atomic)) 6698 Results.AddResult(CodeCompletionResult("atomic")); 6699 6700 // Only suggest "weak" if we're compiling for ARC-with-weak-references or GC. 6701 if (getLangOpts().ObjCWeak || getLangOpts().getGC() != LangOptions::NonGC) 6702 if (!ObjCPropertyFlagConflicts(Attributes, 6703 ObjCPropertyAttribute::kind_weak)) 6704 Results.AddResult(CodeCompletionResult("weak")); 6705 6706 if (!ObjCPropertyFlagConflicts(Attributes, 6707 ObjCPropertyAttribute::kind_setter)) { 6708 CodeCompletionBuilder Setter(Results.getAllocator(), 6709 Results.getCodeCompletionTUInfo()); 6710 Setter.AddTypedTextChunk("setter"); 6711 Setter.AddTextChunk("="); 6712 Setter.AddPlaceholderChunk("method"); 6713 Results.AddResult(CodeCompletionResult(Setter.TakeString())); 6714 } 6715 if (!ObjCPropertyFlagConflicts(Attributes, 6716 ObjCPropertyAttribute::kind_getter)) { 6717 CodeCompletionBuilder Getter(Results.getAllocator(), 6718 Results.getCodeCompletionTUInfo()); 6719 Getter.AddTypedTextChunk("getter"); 6720 Getter.AddTextChunk("="); 6721 Getter.AddPlaceholderChunk("method"); 6722 Results.AddResult(CodeCompletionResult(Getter.TakeString())); 6723 } 6724 if (!ObjCPropertyFlagConflicts(Attributes, 6725 ObjCPropertyAttribute::kind_nullability)) { 6726 Results.AddResult(CodeCompletionResult("nonnull")); 6727 Results.AddResult(CodeCompletionResult("nullable")); 6728 Results.AddResult(CodeCompletionResult("null_unspecified")); 6729 Results.AddResult(CodeCompletionResult("null_resettable")); 6730 } 6731 Results.ExitScope(); 6732 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 6733 Results.data(), Results.size()); 6734 } 6735 6736 /// Describes the kind of Objective-C method that we want to find 6737 /// via code completion. 6738 enum ObjCMethodKind { 6739 MK_Any, ///< Any kind of method, provided it means other specified criteria. 6740 MK_ZeroArgSelector, ///< Zero-argument (unary) selector. 6741 MK_OneArgSelector ///< One-argument selector. 6742 }; 6743 6744 static bool isAcceptableObjCSelector(Selector Sel, ObjCMethodKind WantKind, 6745 ArrayRef<IdentifierInfo *> SelIdents, 6746 bool AllowSameLength = true) { 6747 unsigned NumSelIdents = SelIdents.size(); 6748 if (NumSelIdents > Sel.getNumArgs()) 6749 return false; 6750 6751 switch (WantKind) { 6752 case MK_Any: 6753 break; 6754 case MK_ZeroArgSelector: 6755 return Sel.isUnarySelector(); 6756 case MK_OneArgSelector: 6757 return Sel.getNumArgs() == 1; 6758 } 6759 6760 if (!AllowSameLength && NumSelIdents && NumSelIdents == Sel.getNumArgs()) 6761 return false; 6762 6763 for (unsigned I = 0; I != NumSelIdents; ++I) 6764 if (SelIdents[I] != Sel.getIdentifierInfoForSlot(I)) 6765 return false; 6766 6767 return true; 6768 } 6769 6770 static bool isAcceptableObjCMethod(ObjCMethodDecl *Method, 6771 ObjCMethodKind WantKind, 6772 ArrayRef<IdentifierInfo *> SelIdents, 6773 bool AllowSameLength = true) { 6774 return isAcceptableObjCSelector(Method->getSelector(), WantKind, SelIdents, 6775 AllowSameLength); 6776 } 6777 6778 /// A set of selectors, which is used to avoid introducing multiple 6779 /// completions with the same selector into the result set. 6780 typedef llvm::SmallPtrSet<Selector, 16> VisitedSelectorSet; 6781 6782 /// Add all of the Objective-C methods in the given Objective-C 6783 /// container to the set of results. 6784 /// 6785 /// The container will be a class, protocol, category, or implementation of 6786 /// any of the above. This mether will recurse to include methods from 6787 /// the superclasses of classes along with their categories, protocols, and 6788 /// implementations. 6789 /// 6790 /// \param Container the container in which we'll look to find methods. 6791 /// 6792 /// \param WantInstanceMethods Whether to add instance methods (only); if 6793 /// false, this routine will add factory methods (only). 6794 /// 6795 /// \param CurContext the context in which we're performing the lookup that 6796 /// finds methods. 6797 /// 6798 /// \param AllowSameLength Whether we allow a method to be added to the list 6799 /// when it has the same number of parameters as we have selector identifiers. 6800 /// 6801 /// \param Results the structure into which we'll add results. 6802 static void AddObjCMethods(ObjCContainerDecl *Container, 6803 bool WantInstanceMethods, ObjCMethodKind WantKind, 6804 ArrayRef<IdentifierInfo *> SelIdents, 6805 DeclContext *CurContext, 6806 VisitedSelectorSet &Selectors, bool AllowSameLength, 6807 ResultBuilder &Results, bool InOriginalClass = true, 6808 bool IsRootClass = false) { 6809 typedef CodeCompletionResult Result; 6810 Container = getContainerDef(Container); 6811 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container); 6812 IsRootClass = IsRootClass || (IFace && !IFace->getSuperClass()); 6813 for (ObjCMethodDecl *M : Container->methods()) { 6814 // The instance methods on the root class can be messaged via the 6815 // metaclass. 6816 if (M->isInstanceMethod() == WantInstanceMethods || 6817 (IsRootClass && !WantInstanceMethods)) { 6818 // Check whether the selector identifiers we've been given are a 6819 // subset of the identifiers for this particular method. 6820 if (!isAcceptableObjCMethod(M, WantKind, SelIdents, AllowSameLength)) 6821 continue; 6822 6823 if (!Selectors.insert(M->getSelector()).second) 6824 continue; 6825 6826 Result R = Result(M, Results.getBasePriority(M), nullptr); 6827 R.StartParameter = SelIdents.size(); 6828 R.AllParametersAreInformative = (WantKind != MK_Any); 6829 if (!InOriginalClass) 6830 setInBaseClass(R); 6831 Results.MaybeAddResult(R, CurContext); 6832 } 6833 } 6834 6835 // Visit the protocols of protocols. 6836 if (const auto *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) { 6837 if (Protocol->hasDefinition()) { 6838 const ObjCList<ObjCProtocolDecl> &Protocols = 6839 Protocol->getReferencedProtocols(); 6840 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(), 6841 E = Protocols.end(); 6842 I != E; ++I) 6843 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, CurContext, 6844 Selectors, AllowSameLength, Results, false, IsRootClass); 6845 } 6846 } 6847 6848 if (!IFace || !IFace->hasDefinition()) 6849 return; 6850 6851 // Add methods in protocols. 6852 for (ObjCProtocolDecl *I : IFace->protocols()) 6853 AddObjCMethods(I, WantInstanceMethods, WantKind, SelIdents, CurContext, 6854 Selectors, AllowSameLength, Results, false, IsRootClass); 6855 6856 // Add methods in categories. 6857 for (ObjCCategoryDecl *CatDecl : IFace->known_categories()) { 6858 AddObjCMethods(CatDecl, WantInstanceMethods, WantKind, SelIdents, 6859 CurContext, Selectors, AllowSameLength, Results, 6860 InOriginalClass, IsRootClass); 6861 6862 // Add a categories protocol methods. 6863 const ObjCList<ObjCProtocolDecl> &Protocols = 6864 CatDecl->getReferencedProtocols(); 6865 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(), 6866 E = Protocols.end(); 6867 I != E; ++I) 6868 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, CurContext, 6869 Selectors, AllowSameLength, Results, false, IsRootClass); 6870 6871 // Add methods in category implementations. 6872 if (ObjCCategoryImplDecl *Impl = CatDecl->getImplementation()) 6873 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents, CurContext, 6874 Selectors, AllowSameLength, Results, InOriginalClass, 6875 IsRootClass); 6876 } 6877 6878 // Add methods in superclass. 6879 // Avoid passing in IsRootClass since root classes won't have super classes. 6880 if (IFace->getSuperClass()) 6881 AddObjCMethods(IFace->getSuperClass(), WantInstanceMethods, WantKind, 6882 SelIdents, CurContext, Selectors, AllowSameLength, Results, 6883 /*IsRootClass=*/false); 6884 6885 // Add methods in our implementation, if any. 6886 if (ObjCImplementationDecl *Impl = IFace->getImplementation()) 6887 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents, CurContext, 6888 Selectors, AllowSameLength, Results, InOriginalClass, 6889 IsRootClass); 6890 } 6891 6892 void Sema::CodeCompleteObjCPropertyGetter(Scope *S) { 6893 // Try to find the interface where getters might live. 6894 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext); 6895 if (!Class) { 6896 if (ObjCCategoryDecl *Category = 6897 dyn_cast_or_null<ObjCCategoryDecl>(CurContext)) 6898 Class = Category->getClassInterface(); 6899 6900 if (!Class) 6901 return; 6902 } 6903 6904 // Find all of the potential getters. 6905 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 6906 CodeCompleter->getCodeCompletionTUInfo(), 6907 CodeCompletionContext::CCC_Other); 6908 Results.EnterNewScope(); 6909 6910 VisitedSelectorSet Selectors; 6911 AddObjCMethods(Class, true, MK_ZeroArgSelector, None, CurContext, Selectors, 6912 /*AllowSameLength=*/true, Results); 6913 Results.ExitScope(); 6914 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 6915 Results.data(), Results.size()); 6916 } 6917 6918 void Sema::CodeCompleteObjCPropertySetter(Scope *S) { 6919 // Try to find the interface where setters might live. 6920 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext); 6921 if (!Class) { 6922 if (ObjCCategoryDecl *Category = 6923 dyn_cast_or_null<ObjCCategoryDecl>(CurContext)) 6924 Class = Category->getClassInterface(); 6925 6926 if (!Class) 6927 return; 6928 } 6929 6930 // Find all of the potential getters. 6931 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 6932 CodeCompleter->getCodeCompletionTUInfo(), 6933 CodeCompletionContext::CCC_Other); 6934 Results.EnterNewScope(); 6935 6936 VisitedSelectorSet Selectors; 6937 AddObjCMethods(Class, true, MK_OneArgSelector, None, CurContext, Selectors, 6938 /*AllowSameLength=*/true, Results); 6939 6940 Results.ExitScope(); 6941 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 6942 Results.data(), Results.size()); 6943 } 6944 6945 void Sema::CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS, 6946 bool IsParameter) { 6947 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 6948 CodeCompleter->getCodeCompletionTUInfo(), 6949 CodeCompletionContext::CCC_Type); 6950 Results.EnterNewScope(); 6951 6952 // Add context-sensitive, Objective-C parameter-passing keywords. 6953 bool AddedInOut = false; 6954 if ((DS.getObjCDeclQualifier() & 6955 (ObjCDeclSpec::DQ_In | ObjCDeclSpec::DQ_Inout)) == 0) { 6956 Results.AddResult("in"); 6957 Results.AddResult("inout"); 6958 AddedInOut = true; 6959 } 6960 if ((DS.getObjCDeclQualifier() & 6961 (ObjCDeclSpec::DQ_Out | ObjCDeclSpec::DQ_Inout)) == 0) { 6962 Results.AddResult("out"); 6963 if (!AddedInOut) 6964 Results.AddResult("inout"); 6965 } 6966 if ((DS.getObjCDeclQualifier() & 6967 (ObjCDeclSpec::DQ_Bycopy | ObjCDeclSpec::DQ_Byref | 6968 ObjCDeclSpec::DQ_Oneway)) == 0) { 6969 Results.AddResult("bycopy"); 6970 Results.AddResult("byref"); 6971 Results.AddResult("oneway"); 6972 } 6973 if ((DS.getObjCDeclQualifier() & ObjCDeclSpec::DQ_CSNullability) == 0) { 6974 Results.AddResult("nonnull"); 6975 Results.AddResult("nullable"); 6976 Results.AddResult("null_unspecified"); 6977 } 6978 6979 // If we're completing the return type of an Objective-C method and the 6980 // identifier IBAction refers to a macro, provide a completion item for 6981 // an action, e.g., 6982 // IBAction)<#selector#>:(id)sender 6983 if (DS.getObjCDeclQualifier() == 0 && !IsParameter && 6984 PP.isMacroDefined("IBAction")) { 6985 CodeCompletionBuilder Builder(Results.getAllocator(), 6986 Results.getCodeCompletionTUInfo(), 6987 CCP_CodePattern, CXAvailability_Available); 6988 Builder.AddTypedTextChunk("IBAction"); 6989 Builder.AddChunk(CodeCompletionString::CK_RightParen); 6990 Builder.AddPlaceholderChunk("selector"); 6991 Builder.AddChunk(CodeCompletionString::CK_Colon); 6992 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 6993 Builder.AddTextChunk("id"); 6994 Builder.AddChunk(CodeCompletionString::CK_RightParen); 6995 Builder.AddTextChunk("sender"); 6996 Results.AddResult(CodeCompletionResult(Builder.TakeString())); 6997 } 6998 6999 // If we're completing the return type, provide 'instancetype'. 7000 if (!IsParameter) { 7001 Results.AddResult(CodeCompletionResult("instancetype")); 7002 } 7003 7004 // Add various builtin type names and specifiers. 7005 AddOrdinaryNameResults(PCC_Type, S, *this, Results); 7006 Results.ExitScope(); 7007 7008 // Add the various type names 7009 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName); 7010 CodeCompletionDeclConsumer Consumer(Results, CurContext); 7011 LookupVisibleDecls(S, LookupOrdinaryName, Consumer, 7012 CodeCompleter->includeGlobals(), 7013 CodeCompleter->loadExternal()); 7014 7015 if (CodeCompleter->includeMacros()) 7016 AddMacroResults(PP, Results, CodeCompleter->loadExternal(), false); 7017 7018 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 7019 Results.data(), Results.size()); 7020 } 7021 7022 /// When we have an expression with type "id", we may assume 7023 /// that it has some more-specific class type based on knowledge of 7024 /// common uses of Objective-C. This routine returns that class type, 7025 /// or NULL if no better result could be determined. 7026 static ObjCInterfaceDecl *GetAssumedMessageSendExprType(Expr *E) { 7027 auto *Msg = dyn_cast_or_null<ObjCMessageExpr>(E); 7028 if (!Msg) 7029 return nullptr; 7030 7031 Selector Sel = Msg->getSelector(); 7032 if (Sel.isNull()) 7033 return nullptr; 7034 7035 IdentifierInfo *Id = Sel.getIdentifierInfoForSlot(0); 7036 if (!Id) 7037 return nullptr; 7038 7039 ObjCMethodDecl *Method = Msg->getMethodDecl(); 7040 if (!Method) 7041 return nullptr; 7042 7043 // Determine the class that we're sending the message to. 7044 ObjCInterfaceDecl *IFace = nullptr; 7045 switch (Msg->getReceiverKind()) { 7046 case ObjCMessageExpr::Class: 7047 if (const ObjCObjectType *ObjType = 7048 Msg->getClassReceiver()->getAs<ObjCObjectType>()) 7049 IFace = ObjType->getInterface(); 7050 break; 7051 7052 case ObjCMessageExpr::Instance: { 7053 QualType T = Msg->getInstanceReceiver()->getType(); 7054 if (const ObjCObjectPointerType *Ptr = T->getAs<ObjCObjectPointerType>()) 7055 IFace = Ptr->getInterfaceDecl(); 7056 break; 7057 } 7058 7059 case ObjCMessageExpr::SuperInstance: 7060 case ObjCMessageExpr::SuperClass: 7061 break; 7062 } 7063 7064 if (!IFace) 7065 return nullptr; 7066 7067 ObjCInterfaceDecl *Super = IFace->getSuperClass(); 7068 if (Method->isInstanceMethod()) 7069 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName()) 7070 .Case("retain", IFace) 7071 .Case("strong", IFace) 7072 .Case("autorelease", IFace) 7073 .Case("copy", IFace) 7074 .Case("copyWithZone", IFace) 7075 .Case("mutableCopy", IFace) 7076 .Case("mutableCopyWithZone", IFace) 7077 .Case("awakeFromCoder", IFace) 7078 .Case("replacementObjectFromCoder", IFace) 7079 .Case("class", IFace) 7080 .Case("classForCoder", IFace) 7081 .Case("superclass", Super) 7082 .Default(nullptr); 7083 7084 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName()) 7085 .Case("new", IFace) 7086 .Case("alloc", IFace) 7087 .Case("allocWithZone", IFace) 7088 .Case("class", IFace) 7089 .Case("superclass", Super) 7090 .Default(nullptr); 7091 } 7092 7093 // Add a special completion for a message send to "super", which fills in the 7094 // most likely case of forwarding all of our arguments to the superclass 7095 // function. 7096 /// 7097 /// \param S The semantic analysis object. 7098 /// 7099 /// \param NeedSuperKeyword Whether we need to prefix this completion with 7100 /// the "super" keyword. Otherwise, we just need to provide the arguments. 7101 /// 7102 /// \param SelIdents The identifiers in the selector that have already been 7103 /// provided as arguments for a send to "super". 7104 /// 7105 /// \param Results The set of results to augment. 7106 /// 7107 /// \returns the Objective-C method declaration that would be invoked by 7108 /// this "super" completion. If NULL, no completion was added. 7109 static ObjCMethodDecl * 7110 AddSuperSendCompletion(Sema &S, bool NeedSuperKeyword, 7111 ArrayRef<IdentifierInfo *> SelIdents, 7112 ResultBuilder &Results) { 7113 ObjCMethodDecl *CurMethod = S.getCurMethodDecl(); 7114 if (!CurMethod) 7115 return nullptr; 7116 7117 ObjCInterfaceDecl *Class = CurMethod->getClassInterface(); 7118 if (!Class) 7119 return nullptr; 7120 7121 // Try to find a superclass method with the same selector. 7122 ObjCMethodDecl *SuperMethod = nullptr; 7123 while ((Class = Class->getSuperClass()) && !SuperMethod) { 7124 // Check in the class 7125 SuperMethod = Class->getMethod(CurMethod->getSelector(), 7126 CurMethod->isInstanceMethod()); 7127 7128 // Check in categories or class extensions. 7129 if (!SuperMethod) { 7130 for (const auto *Cat : Class->known_categories()) { 7131 if ((SuperMethod = Cat->getMethod(CurMethod->getSelector(), 7132 CurMethod->isInstanceMethod()))) 7133 break; 7134 } 7135 } 7136 } 7137 7138 if (!SuperMethod) 7139 return nullptr; 7140 7141 // Check whether the superclass method has the same signature. 7142 if (CurMethod->param_size() != SuperMethod->param_size() || 7143 CurMethod->isVariadic() != SuperMethod->isVariadic()) 7144 return nullptr; 7145 7146 for (ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin(), 7147 CurPEnd = CurMethod->param_end(), 7148 SuperP = SuperMethod->param_begin(); 7149 CurP != CurPEnd; ++CurP, ++SuperP) { 7150 // Make sure the parameter types are compatible. 7151 if (!S.Context.hasSameUnqualifiedType((*CurP)->getType(), 7152 (*SuperP)->getType())) 7153 return nullptr; 7154 7155 // Make sure we have a parameter name to forward! 7156 if (!(*CurP)->getIdentifier()) 7157 return nullptr; 7158 } 7159 7160 // We have a superclass method. Now, form the send-to-super completion. 7161 CodeCompletionBuilder Builder(Results.getAllocator(), 7162 Results.getCodeCompletionTUInfo()); 7163 7164 // Give this completion a return type. 7165 AddResultTypeChunk(S.Context, getCompletionPrintingPolicy(S), SuperMethod, 7166 Results.getCompletionContext().getBaseType(), Builder); 7167 7168 // If we need the "super" keyword, add it (plus some spacing). 7169 if (NeedSuperKeyword) { 7170 Builder.AddTypedTextChunk("super"); 7171 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7172 } 7173 7174 Selector Sel = CurMethod->getSelector(); 7175 if (Sel.isUnarySelector()) { 7176 if (NeedSuperKeyword) 7177 Builder.AddTextChunk( 7178 Builder.getAllocator().CopyString(Sel.getNameForSlot(0))); 7179 else 7180 Builder.AddTypedTextChunk( 7181 Builder.getAllocator().CopyString(Sel.getNameForSlot(0))); 7182 } else { 7183 ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin(); 7184 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I, ++CurP) { 7185 if (I > SelIdents.size()) 7186 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 7187 7188 if (I < SelIdents.size()) 7189 Builder.AddInformativeChunk( 7190 Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":")); 7191 else if (NeedSuperKeyword || I > SelIdents.size()) { 7192 Builder.AddTextChunk( 7193 Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":")); 7194 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString( 7195 (*CurP)->getIdentifier()->getName())); 7196 } else { 7197 Builder.AddTypedTextChunk( 7198 Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":")); 7199 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString( 7200 (*CurP)->getIdentifier()->getName())); 7201 } 7202 } 7203 } 7204 7205 Results.AddResult(CodeCompletionResult(Builder.TakeString(), SuperMethod, 7206 CCP_SuperCompletion)); 7207 return SuperMethod; 7208 } 7209 7210 void Sema::CodeCompleteObjCMessageReceiver(Scope *S) { 7211 typedef CodeCompletionResult Result; 7212 ResultBuilder Results( 7213 *this, CodeCompleter->getAllocator(), 7214 CodeCompleter->getCodeCompletionTUInfo(), 7215 CodeCompletionContext::CCC_ObjCMessageReceiver, 7216 getLangOpts().CPlusPlus11 7217 ? &ResultBuilder::IsObjCMessageReceiverOrLambdaCapture 7218 : &ResultBuilder::IsObjCMessageReceiver); 7219 7220 CodeCompletionDeclConsumer Consumer(Results, CurContext); 7221 Results.EnterNewScope(); 7222 LookupVisibleDecls(S, LookupOrdinaryName, Consumer, 7223 CodeCompleter->includeGlobals(), 7224 CodeCompleter->loadExternal()); 7225 7226 // If we are in an Objective-C method inside a class that has a superclass, 7227 // add "super" as an option. 7228 if (ObjCMethodDecl *Method = getCurMethodDecl()) 7229 if (ObjCInterfaceDecl *Iface = Method->getClassInterface()) 7230 if (Iface->getSuperClass()) { 7231 Results.AddResult(Result("super")); 7232 7233 AddSuperSendCompletion(*this, /*NeedSuperKeyword=*/true, None, Results); 7234 } 7235 7236 if (getLangOpts().CPlusPlus11) 7237 addThisCompletion(*this, Results); 7238 7239 Results.ExitScope(); 7240 7241 if (CodeCompleter->includeMacros()) 7242 AddMacroResults(PP, Results, CodeCompleter->loadExternal(), false); 7243 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 7244 Results.data(), Results.size()); 7245 } 7246 7247 void Sema::CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc, 7248 ArrayRef<IdentifierInfo *> SelIdents, 7249 bool AtArgumentExpression) { 7250 ObjCInterfaceDecl *CDecl = nullptr; 7251 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) { 7252 // Figure out which interface we're in. 7253 CDecl = CurMethod->getClassInterface(); 7254 if (!CDecl) 7255 return; 7256 7257 // Find the superclass of this class. 7258 CDecl = CDecl->getSuperClass(); 7259 if (!CDecl) 7260 return; 7261 7262 if (CurMethod->isInstanceMethod()) { 7263 // We are inside an instance method, which means that the message 7264 // send [super ...] is actually calling an instance method on the 7265 // current object. 7266 return CodeCompleteObjCInstanceMessage(S, nullptr, SelIdents, 7267 AtArgumentExpression, CDecl); 7268 } 7269 7270 // Fall through to send to the superclass in CDecl. 7271 } else { 7272 // "super" may be the name of a type or variable. Figure out which 7273 // it is. 7274 IdentifierInfo *Super = getSuperIdentifier(); 7275 NamedDecl *ND = LookupSingleName(S, Super, SuperLoc, LookupOrdinaryName); 7276 if ((CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(ND))) { 7277 // "super" names an interface. Use it. 7278 } else if (TypeDecl *TD = dyn_cast_or_null<TypeDecl>(ND)) { 7279 if (const ObjCObjectType *Iface = 7280 Context.getTypeDeclType(TD)->getAs<ObjCObjectType>()) 7281 CDecl = Iface->getInterface(); 7282 } else if (ND && isa<UnresolvedUsingTypenameDecl>(ND)) { 7283 // "super" names an unresolved type; we can't be more specific. 7284 } else { 7285 // Assume that "super" names some kind of value and parse that way. 7286 CXXScopeSpec SS; 7287 SourceLocation TemplateKWLoc; 7288 UnqualifiedId id; 7289 id.setIdentifier(Super, SuperLoc); 7290 ExprResult SuperExpr = ActOnIdExpression(S, SS, TemplateKWLoc, id, 7291 /*HasTrailingLParen=*/false, 7292 /*IsAddressOfOperand=*/false); 7293 return CodeCompleteObjCInstanceMessage(S, (Expr *)SuperExpr.get(), 7294 SelIdents, AtArgumentExpression); 7295 } 7296 7297 // Fall through 7298 } 7299 7300 ParsedType Receiver; 7301 if (CDecl) 7302 Receiver = ParsedType::make(Context.getObjCInterfaceType(CDecl)); 7303 return CodeCompleteObjCClassMessage(S, Receiver, SelIdents, 7304 AtArgumentExpression, 7305 /*IsSuper=*/true); 7306 } 7307 7308 /// Given a set of code-completion results for the argument of a message 7309 /// send, determine the preferred type (if any) for that argument expression. 7310 static QualType getPreferredArgumentTypeForMessageSend(ResultBuilder &Results, 7311 unsigned NumSelIdents) { 7312 typedef CodeCompletionResult Result; 7313 ASTContext &Context = Results.getSema().Context; 7314 7315 QualType PreferredType; 7316 unsigned BestPriority = CCP_Unlikely * 2; 7317 Result *ResultsData = Results.data(); 7318 for (unsigned I = 0, N = Results.size(); I != N; ++I) { 7319 Result &R = ResultsData[I]; 7320 if (R.Kind == Result::RK_Declaration && 7321 isa<ObjCMethodDecl>(R.Declaration)) { 7322 if (R.Priority <= BestPriority) { 7323 const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(R.Declaration); 7324 if (NumSelIdents <= Method->param_size()) { 7325 QualType MyPreferredType = 7326 Method->parameters()[NumSelIdents - 1]->getType(); 7327 if (R.Priority < BestPriority || PreferredType.isNull()) { 7328 BestPriority = R.Priority; 7329 PreferredType = MyPreferredType; 7330 } else if (!Context.hasSameUnqualifiedType(PreferredType, 7331 MyPreferredType)) { 7332 PreferredType = QualType(); 7333 } 7334 } 7335 } 7336 } 7337 } 7338 7339 return PreferredType; 7340 } 7341 7342 static void AddClassMessageCompletions(Sema &SemaRef, Scope *S, 7343 ParsedType Receiver, 7344 ArrayRef<IdentifierInfo *> SelIdents, 7345 bool AtArgumentExpression, bool IsSuper, 7346 ResultBuilder &Results) { 7347 typedef CodeCompletionResult Result; 7348 ObjCInterfaceDecl *CDecl = nullptr; 7349 7350 // If the given name refers to an interface type, retrieve the 7351 // corresponding declaration. 7352 if (Receiver) { 7353 QualType T = SemaRef.GetTypeFromParser(Receiver, nullptr); 7354 if (!T.isNull()) 7355 if (const ObjCObjectType *Interface = T->getAs<ObjCObjectType>()) 7356 CDecl = Interface->getInterface(); 7357 } 7358 7359 // Add all of the factory methods in this Objective-C class, its protocols, 7360 // superclasses, categories, implementation, etc. 7361 Results.EnterNewScope(); 7362 7363 // If this is a send-to-super, try to add the special "super" send 7364 // completion. 7365 if (IsSuper) { 7366 if (ObjCMethodDecl *SuperMethod = 7367 AddSuperSendCompletion(SemaRef, false, SelIdents, Results)) 7368 Results.Ignore(SuperMethod); 7369 } 7370 7371 // If we're inside an Objective-C method definition, prefer its selector to 7372 // others. 7373 if (ObjCMethodDecl *CurMethod = SemaRef.getCurMethodDecl()) 7374 Results.setPreferredSelector(CurMethod->getSelector()); 7375 7376 VisitedSelectorSet Selectors; 7377 if (CDecl) 7378 AddObjCMethods(CDecl, false, MK_Any, SelIdents, SemaRef.CurContext, 7379 Selectors, AtArgumentExpression, Results); 7380 else { 7381 // We're messaging "id" as a type; provide all class/factory methods. 7382 7383 // If we have an external source, load the entire class method 7384 // pool from the AST file. 7385 if (SemaRef.getExternalSource()) { 7386 for (uint32_t I = 0, 7387 N = SemaRef.getExternalSource()->GetNumExternalSelectors(); 7388 I != N; ++I) { 7389 Selector Sel = SemaRef.getExternalSource()->GetExternalSelector(I); 7390 if (Sel.isNull() || SemaRef.MethodPool.count(Sel)) 7391 continue; 7392 7393 SemaRef.ReadMethodPool(Sel); 7394 } 7395 } 7396 7397 for (Sema::GlobalMethodPool::iterator M = SemaRef.MethodPool.begin(), 7398 MEnd = SemaRef.MethodPool.end(); 7399 M != MEnd; ++M) { 7400 for (ObjCMethodList *MethList = &M->second.second; 7401 MethList && MethList->getMethod(); MethList = MethList->getNext()) { 7402 if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents)) 7403 continue; 7404 7405 Result R(MethList->getMethod(), 7406 Results.getBasePriority(MethList->getMethod()), nullptr); 7407 R.StartParameter = SelIdents.size(); 7408 R.AllParametersAreInformative = false; 7409 Results.MaybeAddResult(R, SemaRef.CurContext); 7410 } 7411 } 7412 } 7413 7414 Results.ExitScope(); 7415 } 7416 7417 void Sema::CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver, 7418 ArrayRef<IdentifierInfo *> SelIdents, 7419 bool AtArgumentExpression, 7420 bool IsSuper) { 7421 7422 QualType T = this->GetTypeFromParser(Receiver); 7423 7424 ResultBuilder Results( 7425 *this, CodeCompleter->getAllocator(), 7426 CodeCompleter->getCodeCompletionTUInfo(), 7427 CodeCompletionContext(CodeCompletionContext::CCC_ObjCClassMessage, T, 7428 SelIdents)); 7429 7430 AddClassMessageCompletions(*this, S, Receiver, SelIdents, 7431 AtArgumentExpression, IsSuper, Results); 7432 7433 // If we're actually at the argument expression (rather than prior to the 7434 // selector), we're actually performing code completion for an expression. 7435 // Determine whether we have a single, best method. If so, we can 7436 // code-complete the expression using the corresponding parameter type as 7437 // our preferred type, improving completion results. 7438 if (AtArgumentExpression) { 7439 QualType PreferredType = 7440 getPreferredArgumentTypeForMessageSend(Results, SelIdents.size()); 7441 if (PreferredType.isNull()) 7442 CodeCompleteOrdinaryName(S, PCC_Expression); 7443 else 7444 CodeCompleteExpression(S, PreferredType); 7445 return; 7446 } 7447 7448 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 7449 Results.data(), Results.size()); 7450 } 7451 7452 void Sema::CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver, 7453 ArrayRef<IdentifierInfo *> SelIdents, 7454 bool AtArgumentExpression, 7455 ObjCInterfaceDecl *Super) { 7456 typedef CodeCompletionResult Result; 7457 7458 Expr *RecExpr = static_cast<Expr *>(Receiver); 7459 7460 // If necessary, apply function/array conversion to the receiver. 7461 // C99 6.7.5.3p[7,8]. 7462 if (RecExpr) { 7463 ExprResult Conv = DefaultFunctionArrayLvalueConversion(RecExpr); 7464 if (Conv.isInvalid()) // conversion failed. bail. 7465 return; 7466 RecExpr = Conv.get(); 7467 } 7468 QualType ReceiverType = RecExpr 7469 ? RecExpr->getType() 7470 : Super ? Context.getObjCObjectPointerType( 7471 Context.getObjCInterfaceType(Super)) 7472 : Context.getObjCIdType(); 7473 7474 // If we're messaging an expression with type "id" or "Class", check 7475 // whether we know something special about the receiver that allows 7476 // us to assume a more-specific receiver type. 7477 if (ReceiverType->isObjCIdType() || ReceiverType->isObjCClassType()) { 7478 if (ObjCInterfaceDecl *IFace = GetAssumedMessageSendExprType(RecExpr)) { 7479 if (ReceiverType->isObjCClassType()) 7480 return CodeCompleteObjCClassMessage( 7481 S, ParsedType::make(Context.getObjCInterfaceType(IFace)), SelIdents, 7482 AtArgumentExpression, Super); 7483 7484 ReceiverType = 7485 Context.getObjCObjectPointerType(Context.getObjCInterfaceType(IFace)); 7486 } 7487 } else if (RecExpr && getLangOpts().CPlusPlus) { 7488 ExprResult Conv = PerformContextuallyConvertToObjCPointer(RecExpr); 7489 if (Conv.isUsable()) { 7490 RecExpr = Conv.get(); 7491 ReceiverType = RecExpr->getType(); 7492 } 7493 } 7494 7495 // Build the set of methods we can see. 7496 ResultBuilder Results( 7497 *this, CodeCompleter->getAllocator(), 7498 CodeCompleter->getCodeCompletionTUInfo(), 7499 CodeCompletionContext(CodeCompletionContext::CCC_ObjCInstanceMessage, 7500 ReceiverType, SelIdents)); 7501 7502 Results.EnterNewScope(); 7503 7504 // If this is a send-to-super, try to add the special "super" send 7505 // completion. 7506 if (Super) { 7507 if (ObjCMethodDecl *SuperMethod = 7508 AddSuperSendCompletion(*this, false, SelIdents, Results)) 7509 Results.Ignore(SuperMethod); 7510 } 7511 7512 // If we're inside an Objective-C method definition, prefer its selector to 7513 // others. 7514 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) 7515 Results.setPreferredSelector(CurMethod->getSelector()); 7516 7517 // Keep track of the selectors we've already added. 7518 VisitedSelectorSet Selectors; 7519 7520 // Handle messages to Class. This really isn't a message to an instance 7521 // method, so we treat it the same way we would treat a message send to a 7522 // class method. 7523 if (ReceiverType->isObjCClassType() || 7524 ReceiverType->isObjCQualifiedClassType()) { 7525 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) { 7526 if (ObjCInterfaceDecl *ClassDecl = CurMethod->getClassInterface()) 7527 AddObjCMethods(ClassDecl, false, MK_Any, SelIdents, CurContext, 7528 Selectors, AtArgumentExpression, Results); 7529 } 7530 } 7531 // Handle messages to a qualified ID ("id<foo>"). 7532 else if (const ObjCObjectPointerType *QualID = 7533 ReceiverType->getAsObjCQualifiedIdType()) { 7534 // Search protocols for instance methods. 7535 for (auto *I : QualID->quals()) 7536 AddObjCMethods(I, true, MK_Any, SelIdents, CurContext, Selectors, 7537 AtArgumentExpression, Results); 7538 } 7539 // Handle messages to a pointer to interface type. 7540 else if (const ObjCObjectPointerType *IFacePtr = 7541 ReceiverType->getAsObjCInterfacePointerType()) { 7542 // Search the class, its superclasses, etc., for instance methods. 7543 AddObjCMethods(IFacePtr->getInterfaceDecl(), true, MK_Any, SelIdents, 7544 CurContext, Selectors, AtArgumentExpression, Results); 7545 7546 // Search protocols for instance methods. 7547 for (auto *I : IFacePtr->quals()) 7548 AddObjCMethods(I, true, MK_Any, SelIdents, CurContext, Selectors, 7549 AtArgumentExpression, Results); 7550 } 7551 // Handle messages to "id". 7552 else if (ReceiverType->isObjCIdType()) { 7553 // We're messaging "id", so provide all instance methods we know 7554 // about as code-completion results. 7555 7556 // If we have an external source, load the entire class method 7557 // pool from the AST file. 7558 if (ExternalSource) { 7559 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors(); 7560 I != N; ++I) { 7561 Selector Sel = ExternalSource->GetExternalSelector(I); 7562 if (Sel.isNull() || MethodPool.count(Sel)) 7563 continue; 7564 7565 ReadMethodPool(Sel); 7566 } 7567 } 7568 7569 for (GlobalMethodPool::iterator M = MethodPool.begin(), 7570 MEnd = MethodPool.end(); 7571 M != MEnd; ++M) { 7572 for (ObjCMethodList *MethList = &M->second.first; 7573 MethList && MethList->getMethod(); MethList = MethList->getNext()) { 7574 if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents)) 7575 continue; 7576 7577 if (!Selectors.insert(MethList->getMethod()->getSelector()).second) 7578 continue; 7579 7580 Result R(MethList->getMethod(), 7581 Results.getBasePriority(MethList->getMethod()), nullptr); 7582 R.StartParameter = SelIdents.size(); 7583 R.AllParametersAreInformative = false; 7584 Results.MaybeAddResult(R, CurContext); 7585 } 7586 } 7587 } 7588 Results.ExitScope(); 7589 7590 // If we're actually at the argument expression (rather than prior to the 7591 // selector), we're actually performing code completion for an expression. 7592 // Determine whether we have a single, best method. If so, we can 7593 // code-complete the expression using the corresponding parameter type as 7594 // our preferred type, improving completion results. 7595 if (AtArgumentExpression) { 7596 QualType PreferredType = 7597 getPreferredArgumentTypeForMessageSend(Results, SelIdents.size()); 7598 if (PreferredType.isNull()) 7599 CodeCompleteOrdinaryName(S, PCC_Expression); 7600 else 7601 CodeCompleteExpression(S, PreferredType); 7602 return; 7603 } 7604 7605 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 7606 Results.data(), Results.size()); 7607 } 7608 7609 void Sema::CodeCompleteObjCForCollection(Scope *S, 7610 DeclGroupPtrTy IterationVar) { 7611 CodeCompleteExpressionData Data; 7612 Data.ObjCCollection = true; 7613 7614 if (IterationVar.getAsOpaquePtr()) { 7615 DeclGroupRef DG = IterationVar.get(); 7616 for (DeclGroupRef::iterator I = DG.begin(), End = DG.end(); I != End; ++I) { 7617 if (*I) 7618 Data.IgnoreDecls.push_back(*I); 7619 } 7620 } 7621 7622 CodeCompleteExpression(S, Data); 7623 } 7624 7625 void Sema::CodeCompleteObjCSelector(Scope *S, 7626 ArrayRef<IdentifierInfo *> SelIdents) { 7627 // If we have an external source, load the entire class method 7628 // pool from the AST file. 7629 if (ExternalSource) { 7630 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors(); I != N; 7631 ++I) { 7632 Selector Sel = ExternalSource->GetExternalSelector(I); 7633 if (Sel.isNull() || MethodPool.count(Sel)) 7634 continue; 7635 7636 ReadMethodPool(Sel); 7637 } 7638 } 7639 7640 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 7641 CodeCompleter->getCodeCompletionTUInfo(), 7642 CodeCompletionContext::CCC_SelectorName); 7643 Results.EnterNewScope(); 7644 for (GlobalMethodPool::iterator M = MethodPool.begin(), 7645 MEnd = MethodPool.end(); 7646 M != MEnd; ++M) { 7647 7648 Selector Sel = M->first; 7649 if (!isAcceptableObjCSelector(Sel, MK_Any, SelIdents)) 7650 continue; 7651 7652 CodeCompletionBuilder Builder(Results.getAllocator(), 7653 Results.getCodeCompletionTUInfo()); 7654 if (Sel.isUnarySelector()) { 7655 Builder.AddTypedTextChunk( 7656 Builder.getAllocator().CopyString(Sel.getNameForSlot(0))); 7657 Results.AddResult(Builder.TakeString()); 7658 continue; 7659 } 7660 7661 std::string Accumulator; 7662 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I) { 7663 if (I == SelIdents.size()) { 7664 if (!Accumulator.empty()) { 7665 Builder.AddInformativeChunk( 7666 Builder.getAllocator().CopyString(Accumulator)); 7667 Accumulator.clear(); 7668 } 7669 } 7670 7671 Accumulator += Sel.getNameForSlot(I); 7672 Accumulator += ':'; 7673 } 7674 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(Accumulator)); 7675 Results.AddResult(Builder.TakeString()); 7676 } 7677 Results.ExitScope(); 7678 7679 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 7680 Results.data(), Results.size()); 7681 } 7682 7683 /// Add all of the protocol declarations that we find in the given 7684 /// (translation unit) context. 7685 static void AddProtocolResults(DeclContext *Ctx, DeclContext *CurContext, 7686 bool OnlyForwardDeclarations, 7687 ResultBuilder &Results) { 7688 typedef CodeCompletionResult Result; 7689 7690 for (const auto *D : Ctx->decls()) { 7691 // Record any protocols we find. 7692 if (const auto *Proto = dyn_cast<ObjCProtocolDecl>(D)) 7693 if (!OnlyForwardDeclarations || !Proto->hasDefinition()) 7694 Results.AddResult( 7695 Result(Proto, Results.getBasePriority(Proto), nullptr), CurContext, 7696 nullptr, false); 7697 } 7698 } 7699 7700 void Sema::CodeCompleteObjCProtocolReferences( 7701 ArrayRef<IdentifierLocPair> Protocols) { 7702 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 7703 CodeCompleter->getCodeCompletionTUInfo(), 7704 CodeCompletionContext::CCC_ObjCProtocolName); 7705 7706 if (CodeCompleter->includeGlobals()) { 7707 Results.EnterNewScope(); 7708 7709 // Tell the result set to ignore all of the protocols we have 7710 // already seen. 7711 // FIXME: This doesn't work when caching code-completion results. 7712 for (const IdentifierLocPair &Pair : Protocols) 7713 if (ObjCProtocolDecl *Protocol = LookupProtocol(Pair.first, Pair.second)) 7714 Results.Ignore(Protocol); 7715 7716 // Add all protocols. 7717 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, false, 7718 Results); 7719 7720 Results.ExitScope(); 7721 } 7722 7723 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 7724 Results.data(), Results.size()); 7725 } 7726 7727 void Sema::CodeCompleteObjCProtocolDecl(Scope *) { 7728 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 7729 CodeCompleter->getCodeCompletionTUInfo(), 7730 CodeCompletionContext::CCC_ObjCProtocolName); 7731 7732 if (CodeCompleter->includeGlobals()) { 7733 Results.EnterNewScope(); 7734 7735 // Add all protocols. 7736 AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, true, 7737 Results); 7738 7739 Results.ExitScope(); 7740 } 7741 7742 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 7743 Results.data(), Results.size()); 7744 } 7745 7746 /// Add all of the Objective-C interface declarations that we find in 7747 /// the given (translation unit) context. 7748 static void AddInterfaceResults(DeclContext *Ctx, DeclContext *CurContext, 7749 bool OnlyForwardDeclarations, 7750 bool OnlyUnimplemented, 7751 ResultBuilder &Results) { 7752 typedef CodeCompletionResult Result; 7753 7754 for (const auto *D : Ctx->decls()) { 7755 // Record any interfaces we find. 7756 if (const auto *Class = dyn_cast<ObjCInterfaceDecl>(D)) 7757 if ((!OnlyForwardDeclarations || !Class->hasDefinition()) && 7758 (!OnlyUnimplemented || !Class->getImplementation())) 7759 Results.AddResult( 7760 Result(Class, Results.getBasePriority(Class), nullptr), CurContext, 7761 nullptr, false); 7762 } 7763 } 7764 7765 void Sema::CodeCompleteObjCInterfaceDecl(Scope *S) { 7766 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 7767 CodeCompleter->getCodeCompletionTUInfo(), 7768 CodeCompletionContext::CCC_ObjCInterfaceName); 7769 Results.EnterNewScope(); 7770 7771 if (CodeCompleter->includeGlobals()) { 7772 // Add all classes. 7773 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false, 7774 false, Results); 7775 } 7776 7777 Results.ExitScope(); 7778 7779 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 7780 Results.data(), Results.size()); 7781 } 7782 7783 void Sema::CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName, 7784 SourceLocation ClassNameLoc) { 7785 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 7786 CodeCompleter->getCodeCompletionTUInfo(), 7787 CodeCompletionContext::CCC_ObjCInterfaceName); 7788 Results.EnterNewScope(); 7789 7790 // Make sure that we ignore the class we're currently defining. 7791 NamedDecl *CurClass = 7792 LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName); 7793 if (CurClass && isa<ObjCInterfaceDecl>(CurClass)) 7794 Results.Ignore(CurClass); 7795 7796 if (CodeCompleter->includeGlobals()) { 7797 // Add all classes. 7798 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false, 7799 false, Results); 7800 } 7801 7802 Results.ExitScope(); 7803 7804 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 7805 Results.data(), Results.size()); 7806 } 7807 7808 void Sema::CodeCompleteObjCImplementationDecl(Scope *S) { 7809 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 7810 CodeCompleter->getCodeCompletionTUInfo(), 7811 CodeCompletionContext::CCC_ObjCImplementation); 7812 Results.EnterNewScope(); 7813 7814 if (CodeCompleter->includeGlobals()) { 7815 // Add all unimplemented classes. 7816 AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false, 7817 true, Results); 7818 } 7819 7820 Results.ExitScope(); 7821 7822 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 7823 Results.data(), Results.size()); 7824 } 7825 7826 void Sema::CodeCompleteObjCInterfaceCategory(Scope *S, 7827 IdentifierInfo *ClassName, 7828 SourceLocation ClassNameLoc) { 7829 typedef CodeCompletionResult Result; 7830 7831 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 7832 CodeCompleter->getCodeCompletionTUInfo(), 7833 CodeCompletionContext::CCC_ObjCCategoryName); 7834 7835 // Ignore any categories we find that have already been implemented by this 7836 // interface. 7837 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames; 7838 NamedDecl *CurClass = 7839 LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName); 7840 if (ObjCInterfaceDecl *Class = 7841 dyn_cast_or_null<ObjCInterfaceDecl>(CurClass)) { 7842 for (const auto *Cat : Class->visible_categories()) 7843 CategoryNames.insert(Cat->getIdentifier()); 7844 } 7845 7846 // Add all of the categories we know about. 7847 Results.EnterNewScope(); 7848 TranslationUnitDecl *TU = Context.getTranslationUnitDecl(); 7849 for (const auto *D : TU->decls()) 7850 if (const auto *Category = dyn_cast<ObjCCategoryDecl>(D)) 7851 if (CategoryNames.insert(Category->getIdentifier()).second) 7852 Results.AddResult( 7853 Result(Category, Results.getBasePriority(Category), nullptr), 7854 CurContext, nullptr, false); 7855 Results.ExitScope(); 7856 7857 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 7858 Results.data(), Results.size()); 7859 } 7860 7861 void Sema::CodeCompleteObjCImplementationCategory(Scope *S, 7862 IdentifierInfo *ClassName, 7863 SourceLocation ClassNameLoc) { 7864 typedef CodeCompletionResult Result; 7865 7866 // Find the corresponding interface. If we couldn't find the interface, the 7867 // program itself is ill-formed. However, we'll try to be helpful still by 7868 // providing the list of all of the categories we know about. 7869 NamedDecl *CurClass = 7870 LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName); 7871 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass); 7872 if (!Class) 7873 return CodeCompleteObjCInterfaceCategory(S, ClassName, ClassNameLoc); 7874 7875 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 7876 CodeCompleter->getCodeCompletionTUInfo(), 7877 CodeCompletionContext::CCC_ObjCCategoryName); 7878 7879 // Add all of the categories that have have corresponding interface 7880 // declarations in this class and any of its superclasses, except for 7881 // already-implemented categories in the class itself. 7882 llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames; 7883 Results.EnterNewScope(); 7884 bool IgnoreImplemented = true; 7885 while (Class) { 7886 for (const auto *Cat : Class->visible_categories()) { 7887 if ((!IgnoreImplemented || !Cat->getImplementation()) && 7888 CategoryNames.insert(Cat->getIdentifier()).second) 7889 Results.AddResult(Result(Cat, Results.getBasePriority(Cat), nullptr), 7890 CurContext, nullptr, false); 7891 } 7892 7893 Class = Class->getSuperClass(); 7894 IgnoreImplemented = false; 7895 } 7896 Results.ExitScope(); 7897 7898 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 7899 Results.data(), Results.size()); 7900 } 7901 7902 void Sema::CodeCompleteObjCPropertyDefinition(Scope *S) { 7903 CodeCompletionContext CCContext(CodeCompletionContext::CCC_Other); 7904 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 7905 CodeCompleter->getCodeCompletionTUInfo(), CCContext); 7906 7907 // Figure out where this @synthesize lives. 7908 ObjCContainerDecl *Container = 7909 dyn_cast_or_null<ObjCContainerDecl>(CurContext); 7910 if (!Container || (!isa<ObjCImplementationDecl>(Container) && 7911 !isa<ObjCCategoryImplDecl>(Container))) 7912 return; 7913 7914 // Ignore any properties that have already been implemented. 7915 Container = getContainerDef(Container); 7916 for (const auto *D : Container->decls()) 7917 if (const auto *PropertyImpl = dyn_cast<ObjCPropertyImplDecl>(D)) 7918 Results.Ignore(PropertyImpl->getPropertyDecl()); 7919 7920 // Add any properties that we find. 7921 AddedPropertiesSet AddedProperties; 7922 Results.EnterNewScope(); 7923 if (ObjCImplementationDecl *ClassImpl = 7924 dyn_cast<ObjCImplementationDecl>(Container)) 7925 AddObjCProperties(CCContext, ClassImpl->getClassInterface(), false, 7926 /*AllowNullaryMethods=*/false, CurContext, 7927 AddedProperties, Results); 7928 else 7929 AddObjCProperties(CCContext, 7930 cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl(), 7931 false, /*AllowNullaryMethods=*/false, CurContext, 7932 AddedProperties, Results); 7933 Results.ExitScope(); 7934 7935 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 7936 Results.data(), Results.size()); 7937 } 7938 7939 void Sema::CodeCompleteObjCPropertySynthesizeIvar( 7940 Scope *S, IdentifierInfo *PropertyName) { 7941 typedef CodeCompletionResult Result; 7942 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 7943 CodeCompleter->getCodeCompletionTUInfo(), 7944 CodeCompletionContext::CCC_Other); 7945 7946 // Figure out where this @synthesize lives. 7947 ObjCContainerDecl *Container = 7948 dyn_cast_or_null<ObjCContainerDecl>(CurContext); 7949 if (!Container || (!isa<ObjCImplementationDecl>(Container) && 7950 !isa<ObjCCategoryImplDecl>(Container))) 7951 return; 7952 7953 // Figure out which interface we're looking into. 7954 ObjCInterfaceDecl *Class = nullptr; 7955 if (ObjCImplementationDecl *ClassImpl = 7956 dyn_cast<ObjCImplementationDecl>(Container)) 7957 Class = ClassImpl->getClassInterface(); 7958 else 7959 Class = cast<ObjCCategoryImplDecl>(Container) 7960 ->getCategoryDecl() 7961 ->getClassInterface(); 7962 7963 // Determine the type of the property we're synthesizing. 7964 QualType PropertyType = Context.getObjCIdType(); 7965 if (Class) { 7966 if (ObjCPropertyDecl *Property = Class->FindPropertyDeclaration( 7967 PropertyName, ObjCPropertyQueryKind::OBJC_PR_query_instance)) { 7968 PropertyType = 7969 Property->getType().getNonReferenceType().getUnqualifiedType(); 7970 7971 // Give preference to ivars 7972 Results.setPreferredType(PropertyType); 7973 } 7974 } 7975 7976 // Add all of the instance variables in this class and its superclasses. 7977 Results.EnterNewScope(); 7978 bool SawSimilarlyNamedIvar = false; 7979 std::string NameWithPrefix; 7980 NameWithPrefix += '_'; 7981 NameWithPrefix += PropertyName->getName(); 7982 std::string NameWithSuffix = PropertyName->getName().str(); 7983 NameWithSuffix += '_'; 7984 for (; Class; Class = Class->getSuperClass()) { 7985 for (ObjCIvarDecl *Ivar = Class->all_declared_ivar_begin(); Ivar; 7986 Ivar = Ivar->getNextIvar()) { 7987 Results.AddResult(Result(Ivar, Results.getBasePriority(Ivar), nullptr), 7988 CurContext, nullptr, false); 7989 7990 // Determine whether we've seen an ivar with a name similar to the 7991 // property. 7992 if ((PropertyName == Ivar->getIdentifier() || 7993 NameWithPrefix == Ivar->getName() || 7994 NameWithSuffix == Ivar->getName())) { 7995 SawSimilarlyNamedIvar = true; 7996 7997 // Reduce the priority of this result by one, to give it a slight 7998 // advantage over other results whose names don't match so closely. 7999 if (Results.size() && 8000 Results.data()[Results.size() - 1].Kind == 8001 CodeCompletionResult::RK_Declaration && 8002 Results.data()[Results.size() - 1].Declaration == Ivar) 8003 Results.data()[Results.size() - 1].Priority--; 8004 } 8005 } 8006 } 8007 8008 if (!SawSimilarlyNamedIvar) { 8009 // Create ivar result _propName, that the user can use to synthesize 8010 // an ivar of the appropriate type. 8011 unsigned Priority = CCP_MemberDeclaration + 1; 8012 typedef CodeCompletionResult Result; 8013 CodeCompletionAllocator &Allocator = Results.getAllocator(); 8014 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo(), 8015 Priority, CXAvailability_Available); 8016 8017 PrintingPolicy Policy = getCompletionPrintingPolicy(*this); 8018 Builder.AddResultTypeChunk( 8019 GetCompletionTypeString(PropertyType, Context, Policy, Allocator)); 8020 Builder.AddTypedTextChunk(Allocator.CopyString(NameWithPrefix)); 8021 Results.AddResult( 8022 Result(Builder.TakeString(), Priority, CXCursor_ObjCIvarDecl)); 8023 } 8024 8025 Results.ExitScope(); 8026 8027 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 8028 Results.data(), Results.size()); 8029 } 8030 8031 // Mapping from selectors to the methods that implement that selector, along 8032 // with the "in original class" flag. 8033 typedef llvm::DenseMap<Selector, 8034 llvm::PointerIntPair<ObjCMethodDecl *, 1, bool>> 8035 KnownMethodsMap; 8036 8037 /// Find all of the methods that reside in the given container 8038 /// (and its superclasses, protocols, etc.) that meet the given 8039 /// criteria. Insert those methods into the map of known methods, 8040 /// indexed by selector so they can be easily found. 8041 static void FindImplementableMethods(ASTContext &Context, 8042 ObjCContainerDecl *Container, 8043 Optional<bool> WantInstanceMethods, 8044 QualType ReturnType, 8045 KnownMethodsMap &KnownMethods, 8046 bool InOriginalClass = true) { 8047 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)) { 8048 // Make sure we have a definition; that's what we'll walk. 8049 if (!IFace->hasDefinition()) 8050 return; 8051 8052 IFace = IFace->getDefinition(); 8053 Container = IFace; 8054 8055 const ObjCList<ObjCProtocolDecl> &Protocols = 8056 IFace->getReferencedProtocols(); 8057 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(), 8058 E = Protocols.end(); 8059 I != E; ++I) 8060 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType, 8061 KnownMethods, InOriginalClass); 8062 8063 // Add methods from any class extensions and categories. 8064 for (auto *Cat : IFace->visible_categories()) { 8065 FindImplementableMethods(Context, Cat, WantInstanceMethods, ReturnType, 8066 KnownMethods, false); 8067 } 8068 8069 // Visit the superclass. 8070 if (IFace->getSuperClass()) 8071 FindImplementableMethods(Context, IFace->getSuperClass(), 8072 WantInstanceMethods, ReturnType, KnownMethods, 8073 false); 8074 } 8075 8076 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) { 8077 // Recurse into protocols. 8078 const ObjCList<ObjCProtocolDecl> &Protocols = 8079 Category->getReferencedProtocols(); 8080 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(), 8081 E = Protocols.end(); 8082 I != E; ++I) 8083 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType, 8084 KnownMethods, InOriginalClass); 8085 8086 // If this category is the original class, jump to the interface. 8087 if (InOriginalClass && Category->getClassInterface()) 8088 FindImplementableMethods(Context, Category->getClassInterface(), 8089 WantInstanceMethods, ReturnType, KnownMethods, 8090 false); 8091 } 8092 8093 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) { 8094 // Make sure we have a definition; that's what we'll walk. 8095 if (!Protocol->hasDefinition()) 8096 return; 8097 Protocol = Protocol->getDefinition(); 8098 Container = Protocol; 8099 8100 // Recurse into protocols. 8101 const ObjCList<ObjCProtocolDecl> &Protocols = 8102 Protocol->getReferencedProtocols(); 8103 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(), 8104 E = Protocols.end(); 8105 I != E; ++I) 8106 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType, 8107 KnownMethods, false); 8108 } 8109 8110 // Add methods in this container. This operation occurs last because 8111 // we want the methods from this container to override any methods 8112 // we've previously seen with the same selector. 8113 for (auto *M : Container->methods()) { 8114 if (!WantInstanceMethods || M->isInstanceMethod() == *WantInstanceMethods) { 8115 if (!ReturnType.isNull() && 8116 !Context.hasSameUnqualifiedType(ReturnType, M->getReturnType())) 8117 continue; 8118 8119 KnownMethods[M->getSelector()] = 8120 KnownMethodsMap::mapped_type(M, InOriginalClass); 8121 } 8122 } 8123 } 8124 8125 /// Add the parenthesized return or parameter type chunk to a code 8126 /// completion string. 8127 static void AddObjCPassingTypeChunk(QualType Type, unsigned ObjCDeclQuals, 8128 ASTContext &Context, 8129 const PrintingPolicy &Policy, 8130 CodeCompletionBuilder &Builder) { 8131 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 8132 std::string Quals = formatObjCParamQualifiers(ObjCDeclQuals, Type); 8133 if (!Quals.empty()) 8134 Builder.AddTextChunk(Builder.getAllocator().CopyString(Quals)); 8135 Builder.AddTextChunk( 8136 GetCompletionTypeString(Type, Context, Policy, Builder.getAllocator())); 8137 Builder.AddChunk(CodeCompletionString::CK_RightParen); 8138 } 8139 8140 /// Determine whether the given class is or inherits from a class by 8141 /// the given name. 8142 static bool InheritsFromClassNamed(ObjCInterfaceDecl *Class, StringRef Name) { 8143 if (!Class) 8144 return false; 8145 8146 if (Class->getIdentifier() && Class->getIdentifier()->getName() == Name) 8147 return true; 8148 8149 return InheritsFromClassNamed(Class->getSuperClass(), Name); 8150 } 8151 8152 /// Add code completions for Objective-C Key-Value Coding (KVC) and 8153 /// Key-Value Observing (KVO). 8154 static void AddObjCKeyValueCompletions(ObjCPropertyDecl *Property, 8155 bool IsInstanceMethod, 8156 QualType ReturnType, ASTContext &Context, 8157 VisitedSelectorSet &KnownSelectors, 8158 ResultBuilder &Results) { 8159 IdentifierInfo *PropName = Property->getIdentifier(); 8160 if (!PropName || PropName->getLength() == 0) 8161 return; 8162 8163 PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema()); 8164 8165 // Builder that will create each code completion. 8166 typedef CodeCompletionResult Result; 8167 CodeCompletionAllocator &Allocator = Results.getAllocator(); 8168 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo()); 8169 8170 // The selector table. 8171 SelectorTable &Selectors = Context.Selectors; 8172 8173 // The property name, copied into the code completion allocation region 8174 // on demand. 8175 struct KeyHolder { 8176 CodeCompletionAllocator &Allocator; 8177 StringRef Key; 8178 const char *CopiedKey; 8179 8180 KeyHolder(CodeCompletionAllocator &Allocator, StringRef Key) 8181 : Allocator(Allocator), Key(Key), CopiedKey(nullptr) {} 8182 8183 operator const char *() { 8184 if (CopiedKey) 8185 return CopiedKey; 8186 8187 return CopiedKey = Allocator.CopyString(Key); 8188 } 8189 } Key(Allocator, PropName->getName()); 8190 8191 // The uppercased name of the property name. 8192 std::string UpperKey = std::string(PropName->getName()); 8193 if (!UpperKey.empty()) 8194 UpperKey[0] = toUppercase(UpperKey[0]); 8195 8196 bool ReturnTypeMatchesProperty = 8197 ReturnType.isNull() || 8198 Context.hasSameUnqualifiedType(ReturnType.getNonReferenceType(), 8199 Property->getType()); 8200 bool ReturnTypeMatchesVoid = ReturnType.isNull() || ReturnType->isVoidType(); 8201 8202 // Add the normal accessor -(type)key. 8203 if (IsInstanceMethod && 8204 KnownSelectors.insert(Selectors.getNullarySelector(PropName)).second && 8205 ReturnTypeMatchesProperty && !Property->getGetterMethodDecl()) { 8206 if (ReturnType.isNull()) 8207 AddObjCPassingTypeChunk(Property->getType(), /*Quals=*/0, Context, Policy, 8208 Builder); 8209 8210 Builder.AddTypedTextChunk(Key); 8211 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern, 8212 CXCursor_ObjCInstanceMethodDecl)); 8213 } 8214 8215 // If we have an integral or boolean property (or the user has provided 8216 // an integral or boolean return type), add the accessor -(type)isKey. 8217 if (IsInstanceMethod && 8218 ((!ReturnType.isNull() && 8219 (ReturnType->isIntegerType() || ReturnType->isBooleanType())) || 8220 (ReturnType.isNull() && (Property->getType()->isIntegerType() || 8221 Property->getType()->isBooleanType())))) { 8222 std::string SelectorName = (Twine("is") + UpperKey).str(); 8223 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 8224 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId)) 8225 .second) { 8226 if (ReturnType.isNull()) { 8227 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 8228 Builder.AddTextChunk("BOOL"); 8229 Builder.AddChunk(CodeCompletionString::CK_RightParen); 8230 } 8231 8232 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorId->getName())); 8233 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern, 8234 CXCursor_ObjCInstanceMethodDecl)); 8235 } 8236 } 8237 8238 // Add the normal mutator. 8239 if (IsInstanceMethod && ReturnTypeMatchesVoid && 8240 !Property->getSetterMethodDecl()) { 8241 std::string SelectorName = (Twine("set") + UpperKey).str(); 8242 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 8243 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 8244 if (ReturnType.isNull()) { 8245 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 8246 Builder.AddTextChunk("void"); 8247 Builder.AddChunk(CodeCompletionString::CK_RightParen); 8248 } 8249 8250 Builder.AddTypedTextChunk( 8251 Allocator.CopyString(SelectorId->getName() + ":")); 8252 AddObjCPassingTypeChunk(Property->getType(), /*Quals=*/0, Context, Policy, 8253 Builder); 8254 Builder.AddTextChunk(Key); 8255 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern, 8256 CXCursor_ObjCInstanceMethodDecl)); 8257 } 8258 } 8259 8260 // Indexed and unordered accessors 8261 unsigned IndexedGetterPriority = CCP_CodePattern; 8262 unsigned IndexedSetterPriority = CCP_CodePattern; 8263 unsigned UnorderedGetterPriority = CCP_CodePattern; 8264 unsigned UnorderedSetterPriority = CCP_CodePattern; 8265 if (const auto *ObjCPointer = 8266 Property->getType()->getAs<ObjCObjectPointerType>()) { 8267 if (ObjCInterfaceDecl *IFace = ObjCPointer->getInterfaceDecl()) { 8268 // If this interface type is not provably derived from a known 8269 // collection, penalize the corresponding completions. 8270 if (!InheritsFromClassNamed(IFace, "NSMutableArray")) { 8271 IndexedSetterPriority += CCD_ProbablyNotObjCCollection; 8272 if (!InheritsFromClassNamed(IFace, "NSArray")) 8273 IndexedGetterPriority += CCD_ProbablyNotObjCCollection; 8274 } 8275 8276 if (!InheritsFromClassNamed(IFace, "NSMutableSet")) { 8277 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection; 8278 if (!InheritsFromClassNamed(IFace, "NSSet")) 8279 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection; 8280 } 8281 } 8282 } else { 8283 IndexedGetterPriority += CCD_ProbablyNotObjCCollection; 8284 IndexedSetterPriority += CCD_ProbablyNotObjCCollection; 8285 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection; 8286 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection; 8287 } 8288 8289 // Add -(NSUInteger)countOf<key> 8290 if (IsInstanceMethod && 8291 (ReturnType.isNull() || ReturnType->isIntegerType())) { 8292 std::string SelectorName = (Twine("countOf") + UpperKey).str(); 8293 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 8294 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId)) 8295 .second) { 8296 if (ReturnType.isNull()) { 8297 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 8298 Builder.AddTextChunk("NSUInteger"); 8299 Builder.AddChunk(CodeCompletionString::CK_RightParen); 8300 } 8301 8302 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorId->getName())); 8303 Results.AddResult( 8304 Result(Builder.TakeString(), 8305 std::min(IndexedGetterPriority, UnorderedGetterPriority), 8306 CXCursor_ObjCInstanceMethodDecl)); 8307 } 8308 } 8309 8310 // Indexed getters 8311 // Add -(id)objectInKeyAtIndex:(NSUInteger)index 8312 if (IsInstanceMethod && 8313 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) { 8314 std::string SelectorName = (Twine("objectIn") + UpperKey + "AtIndex").str(); 8315 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 8316 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 8317 if (ReturnType.isNull()) { 8318 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 8319 Builder.AddTextChunk("id"); 8320 Builder.AddChunk(CodeCompletionString::CK_RightParen); 8321 } 8322 8323 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 8324 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 8325 Builder.AddTextChunk("NSUInteger"); 8326 Builder.AddChunk(CodeCompletionString::CK_RightParen); 8327 Builder.AddTextChunk("index"); 8328 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority, 8329 CXCursor_ObjCInstanceMethodDecl)); 8330 } 8331 } 8332 8333 // Add -(NSArray *)keyAtIndexes:(NSIndexSet *)indexes 8334 if (IsInstanceMethod && 8335 (ReturnType.isNull() || 8336 (ReturnType->isObjCObjectPointerType() && 8337 ReturnType->castAs<ObjCObjectPointerType>()->getInterfaceDecl() && 8338 ReturnType->castAs<ObjCObjectPointerType>() 8339 ->getInterfaceDecl() 8340 ->getName() == "NSArray"))) { 8341 std::string SelectorName = (Twine(Property->getName()) + "AtIndexes").str(); 8342 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 8343 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 8344 if (ReturnType.isNull()) { 8345 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 8346 Builder.AddTextChunk("NSArray *"); 8347 Builder.AddChunk(CodeCompletionString::CK_RightParen); 8348 } 8349 8350 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 8351 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 8352 Builder.AddTextChunk("NSIndexSet *"); 8353 Builder.AddChunk(CodeCompletionString::CK_RightParen); 8354 Builder.AddTextChunk("indexes"); 8355 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority, 8356 CXCursor_ObjCInstanceMethodDecl)); 8357 } 8358 } 8359 8360 // Add -(void)getKey:(type **)buffer range:(NSRange)inRange 8361 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 8362 std::string SelectorName = (Twine("get") + UpperKey).str(); 8363 IdentifierInfo *SelectorIds[2] = {&Context.Idents.get(SelectorName), 8364 &Context.Idents.get("range")}; 8365 8366 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) { 8367 if (ReturnType.isNull()) { 8368 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 8369 Builder.AddTextChunk("void"); 8370 Builder.AddChunk(CodeCompletionString::CK_RightParen); 8371 } 8372 8373 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 8374 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 8375 Builder.AddPlaceholderChunk("object-type"); 8376 Builder.AddTextChunk(" **"); 8377 Builder.AddChunk(CodeCompletionString::CK_RightParen); 8378 Builder.AddTextChunk("buffer"); 8379 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 8380 Builder.AddTypedTextChunk("range:"); 8381 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 8382 Builder.AddTextChunk("NSRange"); 8383 Builder.AddChunk(CodeCompletionString::CK_RightParen); 8384 Builder.AddTextChunk("inRange"); 8385 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority, 8386 CXCursor_ObjCInstanceMethodDecl)); 8387 } 8388 } 8389 8390 // Mutable indexed accessors 8391 8392 // - (void)insertObject:(type *)object inKeyAtIndex:(NSUInteger)index 8393 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 8394 std::string SelectorName = (Twine("in") + UpperKey + "AtIndex").str(); 8395 IdentifierInfo *SelectorIds[2] = {&Context.Idents.get("insertObject"), 8396 &Context.Idents.get(SelectorName)}; 8397 8398 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) { 8399 if (ReturnType.isNull()) { 8400 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 8401 Builder.AddTextChunk("void"); 8402 Builder.AddChunk(CodeCompletionString::CK_RightParen); 8403 } 8404 8405 Builder.AddTypedTextChunk("insertObject:"); 8406 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 8407 Builder.AddPlaceholderChunk("object-type"); 8408 Builder.AddTextChunk(" *"); 8409 Builder.AddChunk(CodeCompletionString::CK_RightParen); 8410 Builder.AddTextChunk("object"); 8411 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 8412 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 8413 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 8414 Builder.AddPlaceholderChunk("NSUInteger"); 8415 Builder.AddChunk(CodeCompletionString::CK_RightParen); 8416 Builder.AddTextChunk("index"); 8417 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority, 8418 CXCursor_ObjCInstanceMethodDecl)); 8419 } 8420 } 8421 8422 // - (void)insertKey:(NSArray *)array atIndexes:(NSIndexSet *)indexes 8423 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 8424 std::string SelectorName = (Twine("insert") + UpperKey).str(); 8425 IdentifierInfo *SelectorIds[2] = {&Context.Idents.get(SelectorName), 8426 &Context.Idents.get("atIndexes")}; 8427 8428 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) { 8429 if (ReturnType.isNull()) { 8430 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 8431 Builder.AddTextChunk("void"); 8432 Builder.AddChunk(CodeCompletionString::CK_RightParen); 8433 } 8434 8435 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 8436 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 8437 Builder.AddTextChunk("NSArray *"); 8438 Builder.AddChunk(CodeCompletionString::CK_RightParen); 8439 Builder.AddTextChunk("array"); 8440 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 8441 Builder.AddTypedTextChunk("atIndexes:"); 8442 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 8443 Builder.AddPlaceholderChunk("NSIndexSet *"); 8444 Builder.AddChunk(CodeCompletionString::CK_RightParen); 8445 Builder.AddTextChunk("indexes"); 8446 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority, 8447 CXCursor_ObjCInstanceMethodDecl)); 8448 } 8449 } 8450 8451 // -(void)removeObjectFromKeyAtIndex:(NSUInteger)index 8452 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 8453 std::string SelectorName = 8454 (Twine("removeObjectFrom") + UpperKey + "AtIndex").str(); 8455 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 8456 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 8457 if (ReturnType.isNull()) { 8458 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 8459 Builder.AddTextChunk("void"); 8460 Builder.AddChunk(CodeCompletionString::CK_RightParen); 8461 } 8462 8463 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 8464 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 8465 Builder.AddTextChunk("NSUInteger"); 8466 Builder.AddChunk(CodeCompletionString::CK_RightParen); 8467 Builder.AddTextChunk("index"); 8468 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority, 8469 CXCursor_ObjCInstanceMethodDecl)); 8470 } 8471 } 8472 8473 // -(void)removeKeyAtIndexes:(NSIndexSet *)indexes 8474 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 8475 std::string SelectorName = (Twine("remove") + UpperKey + "AtIndexes").str(); 8476 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 8477 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 8478 if (ReturnType.isNull()) { 8479 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 8480 Builder.AddTextChunk("void"); 8481 Builder.AddChunk(CodeCompletionString::CK_RightParen); 8482 } 8483 8484 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 8485 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 8486 Builder.AddTextChunk("NSIndexSet *"); 8487 Builder.AddChunk(CodeCompletionString::CK_RightParen); 8488 Builder.AddTextChunk("indexes"); 8489 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority, 8490 CXCursor_ObjCInstanceMethodDecl)); 8491 } 8492 } 8493 8494 // - (void)replaceObjectInKeyAtIndex:(NSUInteger)index withObject:(id)object 8495 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 8496 std::string SelectorName = 8497 (Twine("replaceObjectIn") + UpperKey + "AtIndex").str(); 8498 IdentifierInfo *SelectorIds[2] = {&Context.Idents.get(SelectorName), 8499 &Context.Idents.get("withObject")}; 8500 8501 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) { 8502 if (ReturnType.isNull()) { 8503 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 8504 Builder.AddTextChunk("void"); 8505 Builder.AddChunk(CodeCompletionString::CK_RightParen); 8506 } 8507 8508 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 8509 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 8510 Builder.AddPlaceholderChunk("NSUInteger"); 8511 Builder.AddChunk(CodeCompletionString::CK_RightParen); 8512 Builder.AddTextChunk("index"); 8513 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 8514 Builder.AddTypedTextChunk("withObject:"); 8515 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 8516 Builder.AddTextChunk("id"); 8517 Builder.AddChunk(CodeCompletionString::CK_RightParen); 8518 Builder.AddTextChunk("object"); 8519 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority, 8520 CXCursor_ObjCInstanceMethodDecl)); 8521 } 8522 } 8523 8524 // - (void)replaceKeyAtIndexes:(NSIndexSet *)indexes withKey:(NSArray *)array 8525 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 8526 std::string SelectorName1 = 8527 (Twine("replace") + UpperKey + "AtIndexes").str(); 8528 std::string SelectorName2 = (Twine("with") + UpperKey).str(); 8529 IdentifierInfo *SelectorIds[2] = {&Context.Idents.get(SelectorName1), 8530 &Context.Idents.get(SelectorName2)}; 8531 8532 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) { 8533 if (ReturnType.isNull()) { 8534 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 8535 Builder.AddTextChunk("void"); 8536 Builder.AddChunk(CodeCompletionString::CK_RightParen); 8537 } 8538 8539 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName1 + ":")); 8540 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 8541 Builder.AddPlaceholderChunk("NSIndexSet *"); 8542 Builder.AddChunk(CodeCompletionString::CK_RightParen); 8543 Builder.AddTextChunk("indexes"); 8544 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 8545 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName2 + ":")); 8546 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 8547 Builder.AddTextChunk("NSArray *"); 8548 Builder.AddChunk(CodeCompletionString::CK_RightParen); 8549 Builder.AddTextChunk("array"); 8550 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority, 8551 CXCursor_ObjCInstanceMethodDecl)); 8552 } 8553 } 8554 8555 // Unordered getters 8556 // - (NSEnumerator *)enumeratorOfKey 8557 if (IsInstanceMethod && 8558 (ReturnType.isNull() || 8559 (ReturnType->isObjCObjectPointerType() && 8560 ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() && 8561 ReturnType->getAs<ObjCObjectPointerType>() 8562 ->getInterfaceDecl() 8563 ->getName() == "NSEnumerator"))) { 8564 std::string SelectorName = (Twine("enumeratorOf") + UpperKey).str(); 8565 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 8566 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId)) 8567 .second) { 8568 if (ReturnType.isNull()) { 8569 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 8570 Builder.AddTextChunk("NSEnumerator *"); 8571 Builder.AddChunk(CodeCompletionString::CK_RightParen); 8572 } 8573 8574 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName)); 8575 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority, 8576 CXCursor_ObjCInstanceMethodDecl)); 8577 } 8578 } 8579 8580 // - (type *)memberOfKey:(type *)object 8581 if (IsInstanceMethod && 8582 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) { 8583 std::string SelectorName = (Twine("memberOf") + UpperKey).str(); 8584 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 8585 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 8586 if (ReturnType.isNull()) { 8587 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 8588 Builder.AddPlaceholderChunk("object-type"); 8589 Builder.AddTextChunk(" *"); 8590 Builder.AddChunk(CodeCompletionString::CK_RightParen); 8591 } 8592 8593 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 8594 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 8595 if (ReturnType.isNull()) { 8596 Builder.AddPlaceholderChunk("object-type"); 8597 Builder.AddTextChunk(" *"); 8598 } else { 8599 Builder.AddTextChunk(GetCompletionTypeString( 8600 ReturnType, Context, Policy, Builder.getAllocator())); 8601 } 8602 Builder.AddChunk(CodeCompletionString::CK_RightParen); 8603 Builder.AddTextChunk("object"); 8604 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority, 8605 CXCursor_ObjCInstanceMethodDecl)); 8606 } 8607 } 8608 8609 // Mutable unordered accessors 8610 // - (void)addKeyObject:(type *)object 8611 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 8612 std::string SelectorName = 8613 (Twine("add") + 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)addKey:(NSSet *)objects 8634 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 8635 std::string SelectorName = (Twine("add") + 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)removeKeyObject:(type *)object 8655 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 8656 std::string SelectorName = 8657 (Twine("remove") + UpperKey + Twine("Object")).str(); 8658 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 8659 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 8660 if (ReturnType.isNull()) { 8661 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 8662 Builder.AddTextChunk("void"); 8663 Builder.AddChunk(CodeCompletionString::CK_RightParen); 8664 } 8665 8666 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 8667 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 8668 Builder.AddPlaceholderChunk("object-type"); 8669 Builder.AddTextChunk(" *"); 8670 Builder.AddChunk(CodeCompletionString::CK_RightParen); 8671 Builder.AddTextChunk("object"); 8672 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority, 8673 CXCursor_ObjCInstanceMethodDecl)); 8674 } 8675 } 8676 8677 // - (void)removeKey:(NSSet *)objects 8678 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 8679 std::string SelectorName = (Twine("remove") + UpperKey).str(); 8680 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 8681 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 8682 if (ReturnType.isNull()) { 8683 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 8684 Builder.AddTextChunk("void"); 8685 Builder.AddChunk(CodeCompletionString::CK_RightParen); 8686 } 8687 8688 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 8689 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 8690 Builder.AddTextChunk("NSSet *"); 8691 Builder.AddChunk(CodeCompletionString::CK_RightParen); 8692 Builder.AddTextChunk("objects"); 8693 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority, 8694 CXCursor_ObjCInstanceMethodDecl)); 8695 } 8696 } 8697 8698 // - (void)intersectKey:(NSSet *)objects 8699 if (IsInstanceMethod && ReturnTypeMatchesVoid) { 8700 std::string SelectorName = (Twine("intersect") + UpperKey).str(); 8701 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 8702 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { 8703 if (ReturnType.isNull()) { 8704 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 8705 Builder.AddTextChunk("void"); 8706 Builder.AddChunk(CodeCompletionString::CK_RightParen); 8707 } 8708 8709 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); 8710 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 8711 Builder.AddTextChunk("NSSet *"); 8712 Builder.AddChunk(CodeCompletionString::CK_RightParen); 8713 Builder.AddTextChunk("objects"); 8714 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority, 8715 CXCursor_ObjCInstanceMethodDecl)); 8716 } 8717 } 8718 8719 // Key-Value Observing 8720 // + (NSSet *)keyPathsForValuesAffectingKey 8721 if (!IsInstanceMethod && 8722 (ReturnType.isNull() || 8723 (ReturnType->isObjCObjectPointerType() && 8724 ReturnType->castAs<ObjCObjectPointerType>()->getInterfaceDecl() && 8725 ReturnType->castAs<ObjCObjectPointerType>() 8726 ->getInterfaceDecl() 8727 ->getName() == "NSSet"))) { 8728 std::string SelectorName = 8729 (Twine("keyPathsForValuesAffecting") + UpperKey).str(); 8730 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 8731 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId)) 8732 .second) { 8733 if (ReturnType.isNull()) { 8734 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 8735 Builder.AddTextChunk("NSSet<NSString *> *"); 8736 Builder.AddChunk(CodeCompletionString::CK_RightParen); 8737 } 8738 8739 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName)); 8740 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern, 8741 CXCursor_ObjCClassMethodDecl)); 8742 } 8743 } 8744 8745 // + (BOOL)automaticallyNotifiesObserversForKey 8746 if (!IsInstanceMethod && 8747 (ReturnType.isNull() || ReturnType->isIntegerType() || 8748 ReturnType->isBooleanType())) { 8749 std::string SelectorName = 8750 (Twine("automaticallyNotifiesObserversOf") + UpperKey).str(); 8751 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); 8752 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId)) 8753 .second) { 8754 if (ReturnType.isNull()) { 8755 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 8756 Builder.AddTextChunk("BOOL"); 8757 Builder.AddChunk(CodeCompletionString::CK_RightParen); 8758 } 8759 8760 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName)); 8761 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern, 8762 CXCursor_ObjCClassMethodDecl)); 8763 } 8764 } 8765 } 8766 8767 void Sema::CodeCompleteObjCMethodDecl(Scope *S, Optional<bool> IsInstanceMethod, 8768 ParsedType ReturnTy) { 8769 // Determine the return type of the method we're declaring, if 8770 // provided. 8771 QualType ReturnType = GetTypeFromParser(ReturnTy); 8772 Decl *IDecl = nullptr; 8773 if (CurContext->isObjCContainer()) { 8774 ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext); 8775 IDecl = OCD; 8776 } 8777 // Determine where we should start searching for methods. 8778 ObjCContainerDecl *SearchDecl = nullptr; 8779 bool IsInImplementation = false; 8780 if (Decl *D = IDecl) { 8781 if (ObjCImplementationDecl *Impl = dyn_cast<ObjCImplementationDecl>(D)) { 8782 SearchDecl = Impl->getClassInterface(); 8783 IsInImplementation = true; 8784 } else if (ObjCCategoryImplDecl *CatImpl = 8785 dyn_cast<ObjCCategoryImplDecl>(D)) { 8786 SearchDecl = CatImpl->getCategoryDecl(); 8787 IsInImplementation = true; 8788 } else 8789 SearchDecl = dyn_cast<ObjCContainerDecl>(D); 8790 } 8791 8792 if (!SearchDecl && S) { 8793 if (DeclContext *DC = S->getEntity()) 8794 SearchDecl = dyn_cast<ObjCContainerDecl>(DC); 8795 } 8796 8797 if (!SearchDecl) { 8798 HandleCodeCompleteResults(this, CodeCompleter, 8799 CodeCompletionContext::CCC_Other, nullptr, 0); 8800 return; 8801 } 8802 8803 // Find all of the methods that we could declare/implement here. 8804 KnownMethodsMap KnownMethods; 8805 FindImplementableMethods(Context, SearchDecl, IsInstanceMethod, ReturnType, 8806 KnownMethods); 8807 8808 // Add declarations or definitions for each of the known methods. 8809 typedef CodeCompletionResult Result; 8810 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 8811 CodeCompleter->getCodeCompletionTUInfo(), 8812 CodeCompletionContext::CCC_Other); 8813 Results.EnterNewScope(); 8814 PrintingPolicy Policy = getCompletionPrintingPolicy(*this); 8815 for (KnownMethodsMap::iterator M = KnownMethods.begin(), 8816 MEnd = KnownMethods.end(); 8817 M != MEnd; ++M) { 8818 ObjCMethodDecl *Method = M->second.getPointer(); 8819 CodeCompletionBuilder Builder(Results.getAllocator(), 8820 Results.getCodeCompletionTUInfo()); 8821 8822 // Add the '-'/'+' prefix if it wasn't provided yet. 8823 if (!IsInstanceMethod) { 8824 Builder.AddTextChunk(Method->isInstanceMethod() ? "-" : "+"); 8825 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 8826 } 8827 8828 // If the result type was not already provided, add it to the 8829 // pattern as (type). 8830 if (ReturnType.isNull()) { 8831 QualType ResTy = Method->getSendResultType().stripObjCKindOfType(Context); 8832 AttributedType::stripOuterNullability(ResTy); 8833 AddObjCPassingTypeChunk(ResTy, Method->getObjCDeclQualifier(), Context, 8834 Policy, Builder); 8835 } 8836 8837 Selector Sel = Method->getSelector(); 8838 8839 if (Sel.isUnarySelector()) { 8840 // Unary selectors have no arguments. 8841 Builder.AddTypedTextChunk( 8842 Builder.getAllocator().CopyString(Sel.getNameForSlot(0))); 8843 } else { 8844 // Add all parameters to the pattern. 8845 unsigned I = 0; 8846 for (ObjCMethodDecl::param_iterator P = Method->param_begin(), 8847 PEnd = Method->param_end(); 8848 P != PEnd; (void)++P, ++I) { 8849 // Add the part of the selector name. 8850 if (I == 0) 8851 Builder.AddTypedTextChunk( 8852 Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":")); 8853 else if (I < Sel.getNumArgs()) { 8854 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 8855 Builder.AddTypedTextChunk( 8856 Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":")); 8857 } else 8858 break; 8859 8860 // Add the parameter type. 8861 QualType ParamType; 8862 if ((*P)->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 8863 ParamType = (*P)->getType(); 8864 else 8865 ParamType = (*P)->getOriginalType(); 8866 ParamType = ParamType.substObjCTypeArgs( 8867 Context, {}, ObjCSubstitutionContext::Parameter); 8868 AttributedType::stripOuterNullability(ParamType); 8869 AddObjCPassingTypeChunk(ParamType, (*P)->getObjCDeclQualifier(), 8870 Context, Policy, Builder); 8871 8872 if (IdentifierInfo *Id = (*P)->getIdentifier()) 8873 Builder.AddTextChunk( 8874 Builder.getAllocator().CopyString(Id->getName())); 8875 } 8876 } 8877 8878 if (Method->isVariadic()) { 8879 if (Method->param_size() > 0) 8880 Builder.AddChunk(CodeCompletionString::CK_Comma); 8881 Builder.AddTextChunk("..."); 8882 } 8883 8884 if (IsInImplementation && Results.includeCodePatterns()) { 8885 // We will be defining the method here, so add a compound statement. 8886 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 8887 Builder.AddChunk(CodeCompletionString::CK_LeftBrace); 8888 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); 8889 if (!Method->getReturnType()->isVoidType()) { 8890 // If the result type is not void, add a return clause. 8891 Builder.AddTextChunk("return"); 8892 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 8893 Builder.AddPlaceholderChunk("expression"); 8894 Builder.AddChunk(CodeCompletionString::CK_SemiColon); 8895 } else 8896 Builder.AddPlaceholderChunk("statements"); 8897 8898 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); 8899 Builder.AddChunk(CodeCompletionString::CK_RightBrace); 8900 } 8901 8902 unsigned Priority = CCP_CodePattern; 8903 auto R = Result(Builder.TakeString(), Method, Priority); 8904 if (!M->second.getInt()) 8905 setInBaseClass(R); 8906 Results.AddResult(std::move(R)); 8907 } 8908 8909 // Add Key-Value-Coding and Key-Value-Observing accessor methods for all of 8910 // the properties in this class and its categories. 8911 if (Context.getLangOpts().ObjC) { 8912 SmallVector<ObjCContainerDecl *, 4> Containers; 8913 Containers.push_back(SearchDecl); 8914 8915 VisitedSelectorSet KnownSelectors; 8916 for (KnownMethodsMap::iterator M = KnownMethods.begin(), 8917 MEnd = KnownMethods.end(); 8918 M != MEnd; ++M) 8919 KnownSelectors.insert(M->first); 8920 8921 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(SearchDecl); 8922 if (!IFace) 8923 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(SearchDecl)) 8924 IFace = Category->getClassInterface(); 8925 8926 if (IFace) 8927 for (auto *Cat : IFace->visible_categories()) 8928 Containers.push_back(Cat); 8929 8930 if (IsInstanceMethod) { 8931 for (unsigned I = 0, N = Containers.size(); I != N; ++I) 8932 for (auto *P : Containers[I]->instance_properties()) 8933 AddObjCKeyValueCompletions(P, *IsInstanceMethod, ReturnType, Context, 8934 KnownSelectors, Results); 8935 } 8936 } 8937 8938 Results.ExitScope(); 8939 8940 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 8941 Results.data(), Results.size()); 8942 } 8943 8944 void Sema::CodeCompleteObjCMethodDeclSelector( 8945 Scope *S, bool IsInstanceMethod, bool AtParameterName, ParsedType ReturnTy, 8946 ArrayRef<IdentifierInfo *> SelIdents) { 8947 // If we have an external source, load the entire class method 8948 // pool from the AST file. 8949 if (ExternalSource) { 8950 for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors(); I != N; 8951 ++I) { 8952 Selector Sel = ExternalSource->GetExternalSelector(I); 8953 if (Sel.isNull() || MethodPool.count(Sel)) 8954 continue; 8955 8956 ReadMethodPool(Sel); 8957 } 8958 } 8959 8960 // Build the set of methods we can see. 8961 typedef CodeCompletionResult Result; 8962 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 8963 CodeCompleter->getCodeCompletionTUInfo(), 8964 CodeCompletionContext::CCC_Other); 8965 8966 if (ReturnTy) 8967 Results.setPreferredType(GetTypeFromParser(ReturnTy).getNonReferenceType()); 8968 8969 Results.EnterNewScope(); 8970 for (GlobalMethodPool::iterator M = MethodPool.begin(), 8971 MEnd = MethodPool.end(); 8972 M != MEnd; ++M) { 8973 for (ObjCMethodList *MethList = IsInstanceMethod ? &M->second.first 8974 : &M->second.second; 8975 MethList && MethList->getMethod(); MethList = MethList->getNext()) { 8976 if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents)) 8977 continue; 8978 8979 if (AtParameterName) { 8980 // Suggest parameter names we've seen before. 8981 unsigned NumSelIdents = SelIdents.size(); 8982 if (NumSelIdents && 8983 NumSelIdents <= MethList->getMethod()->param_size()) { 8984 ParmVarDecl *Param = 8985 MethList->getMethod()->parameters()[NumSelIdents - 1]; 8986 if (Param->getIdentifier()) { 8987 CodeCompletionBuilder Builder(Results.getAllocator(), 8988 Results.getCodeCompletionTUInfo()); 8989 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString( 8990 Param->getIdentifier()->getName())); 8991 Results.AddResult(Builder.TakeString()); 8992 } 8993 } 8994 8995 continue; 8996 } 8997 8998 Result R(MethList->getMethod(), 8999 Results.getBasePriority(MethList->getMethod()), nullptr); 9000 R.StartParameter = SelIdents.size(); 9001 R.AllParametersAreInformative = false; 9002 R.DeclaringEntity = true; 9003 Results.MaybeAddResult(R, CurContext); 9004 } 9005 } 9006 9007 Results.ExitScope(); 9008 9009 if (!AtParameterName && !SelIdents.empty() && 9010 SelIdents.front()->getName().startswith("init")) { 9011 for (const auto &M : PP.macros()) { 9012 if (M.first->getName() != "NS_DESIGNATED_INITIALIZER") 9013 continue; 9014 Results.EnterNewScope(); 9015 CodeCompletionBuilder Builder(Results.getAllocator(), 9016 Results.getCodeCompletionTUInfo()); 9017 Builder.AddTypedTextChunk( 9018 Builder.getAllocator().CopyString(M.first->getName())); 9019 Results.AddResult(CodeCompletionResult(Builder.TakeString(), CCP_Macro, 9020 CXCursor_MacroDefinition)); 9021 Results.ExitScope(); 9022 } 9023 } 9024 9025 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 9026 Results.data(), Results.size()); 9027 } 9028 9029 void Sema::CodeCompletePreprocessorDirective(bool InConditional) { 9030 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 9031 CodeCompleter->getCodeCompletionTUInfo(), 9032 CodeCompletionContext::CCC_PreprocessorDirective); 9033 Results.EnterNewScope(); 9034 9035 // #if <condition> 9036 CodeCompletionBuilder Builder(Results.getAllocator(), 9037 Results.getCodeCompletionTUInfo()); 9038 Builder.AddTypedTextChunk("if"); 9039 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 9040 Builder.AddPlaceholderChunk("condition"); 9041 Results.AddResult(Builder.TakeString()); 9042 9043 // #ifdef <macro> 9044 Builder.AddTypedTextChunk("ifdef"); 9045 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 9046 Builder.AddPlaceholderChunk("macro"); 9047 Results.AddResult(Builder.TakeString()); 9048 9049 // #ifndef <macro> 9050 Builder.AddTypedTextChunk("ifndef"); 9051 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 9052 Builder.AddPlaceholderChunk("macro"); 9053 Results.AddResult(Builder.TakeString()); 9054 9055 if (InConditional) { 9056 // #elif <condition> 9057 Builder.AddTypedTextChunk("elif"); 9058 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 9059 Builder.AddPlaceholderChunk("condition"); 9060 Results.AddResult(Builder.TakeString()); 9061 9062 // #else 9063 Builder.AddTypedTextChunk("else"); 9064 Results.AddResult(Builder.TakeString()); 9065 9066 // #endif 9067 Builder.AddTypedTextChunk("endif"); 9068 Results.AddResult(Builder.TakeString()); 9069 } 9070 9071 // #include "header" 9072 Builder.AddTypedTextChunk("include"); 9073 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 9074 Builder.AddTextChunk("\""); 9075 Builder.AddPlaceholderChunk("header"); 9076 Builder.AddTextChunk("\""); 9077 Results.AddResult(Builder.TakeString()); 9078 9079 // #include <header> 9080 Builder.AddTypedTextChunk("include"); 9081 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 9082 Builder.AddTextChunk("<"); 9083 Builder.AddPlaceholderChunk("header"); 9084 Builder.AddTextChunk(">"); 9085 Results.AddResult(Builder.TakeString()); 9086 9087 // #define <macro> 9088 Builder.AddTypedTextChunk("define"); 9089 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 9090 Builder.AddPlaceholderChunk("macro"); 9091 Results.AddResult(Builder.TakeString()); 9092 9093 // #define <macro>(<args>) 9094 Builder.AddTypedTextChunk("define"); 9095 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 9096 Builder.AddPlaceholderChunk("macro"); 9097 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 9098 Builder.AddPlaceholderChunk("args"); 9099 Builder.AddChunk(CodeCompletionString::CK_RightParen); 9100 Results.AddResult(Builder.TakeString()); 9101 9102 // #undef <macro> 9103 Builder.AddTypedTextChunk("undef"); 9104 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 9105 Builder.AddPlaceholderChunk("macro"); 9106 Results.AddResult(Builder.TakeString()); 9107 9108 // #line <number> 9109 Builder.AddTypedTextChunk("line"); 9110 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 9111 Builder.AddPlaceholderChunk("number"); 9112 Results.AddResult(Builder.TakeString()); 9113 9114 // #line <number> "filename" 9115 Builder.AddTypedTextChunk("line"); 9116 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 9117 Builder.AddPlaceholderChunk("number"); 9118 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 9119 Builder.AddTextChunk("\""); 9120 Builder.AddPlaceholderChunk("filename"); 9121 Builder.AddTextChunk("\""); 9122 Results.AddResult(Builder.TakeString()); 9123 9124 // #error <message> 9125 Builder.AddTypedTextChunk("error"); 9126 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 9127 Builder.AddPlaceholderChunk("message"); 9128 Results.AddResult(Builder.TakeString()); 9129 9130 // #pragma <arguments> 9131 Builder.AddTypedTextChunk("pragma"); 9132 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 9133 Builder.AddPlaceholderChunk("arguments"); 9134 Results.AddResult(Builder.TakeString()); 9135 9136 if (getLangOpts().ObjC) { 9137 // #import "header" 9138 Builder.AddTypedTextChunk("import"); 9139 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 9140 Builder.AddTextChunk("\""); 9141 Builder.AddPlaceholderChunk("header"); 9142 Builder.AddTextChunk("\""); 9143 Results.AddResult(Builder.TakeString()); 9144 9145 // #import <header> 9146 Builder.AddTypedTextChunk("import"); 9147 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 9148 Builder.AddTextChunk("<"); 9149 Builder.AddPlaceholderChunk("header"); 9150 Builder.AddTextChunk(">"); 9151 Results.AddResult(Builder.TakeString()); 9152 } 9153 9154 // #include_next "header" 9155 Builder.AddTypedTextChunk("include_next"); 9156 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 9157 Builder.AddTextChunk("\""); 9158 Builder.AddPlaceholderChunk("header"); 9159 Builder.AddTextChunk("\""); 9160 Results.AddResult(Builder.TakeString()); 9161 9162 // #include_next <header> 9163 Builder.AddTypedTextChunk("include_next"); 9164 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 9165 Builder.AddTextChunk("<"); 9166 Builder.AddPlaceholderChunk("header"); 9167 Builder.AddTextChunk(">"); 9168 Results.AddResult(Builder.TakeString()); 9169 9170 // #warning <message> 9171 Builder.AddTypedTextChunk("warning"); 9172 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 9173 Builder.AddPlaceholderChunk("message"); 9174 Results.AddResult(Builder.TakeString()); 9175 9176 // Note: #ident and #sccs are such crazy anachronisms that we don't provide 9177 // completions for them. And __include_macros is a Clang-internal extension 9178 // that we don't want to encourage anyone to use. 9179 9180 // FIXME: we don't support #assert or #unassert, so don't suggest them. 9181 Results.ExitScope(); 9182 9183 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 9184 Results.data(), Results.size()); 9185 } 9186 9187 void Sema::CodeCompleteInPreprocessorConditionalExclusion(Scope *S) { 9188 CodeCompleteOrdinaryName(S, S->getFnParent() ? Sema::PCC_RecoveryInFunction 9189 : Sema::PCC_Namespace); 9190 } 9191 9192 void Sema::CodeCompletePreprocessorMacroName(bool IsDefinition) { 9193 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 9194 CodeCompleter->getCodeCompletionTUInfo(), 9195 IsDefinition ? CodeCompletionContext::CCC_MacroName 9196 : CodeCompletionContext::CCC_MacroNameUse); 9197 if (!IsDefinition && (!CodeCompleter || CodeCompleter->includeMacros())) { 9198 // Add just the names of macros, not their arguments. 9199 CodeCompletionBuilder Builder(Results.getAllocator(), 9200 Results.getCodeCompletionTUInfo()); 9201 Results.EnterNewScope(); 9202 for (Preprocessor::macro_iterator M = PP.macro_begin(), 9203 MEnd = PP.macro_end(); 9204 M != MEnd; ++M) { 9205 Builder.AddTypedTextChunk( 9206 Builder.getAllocator().CopyString(M->first->getName())); 9207 Results.AddResult(CodeCompletionResult( 9208 Builder.TakeString(), CCP_CodePattern, CXCursor_MacroDefinition)); 9209 } 9210 Results.ExitScope(); 9211 } else if (IsDefinition) { 9212 // FIXME: Can we detect when the user just wrote an include guard above? 9213 } 9214 9215 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 9216 Results.data(), Results.size()); 9217 } 9218 9219 void Sema::CodeCompletePreprocessorExpression() { 9220 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 9221 CodeCompleter->getCodeCompletionTUInfo(), 9222 CodeCompletionContext::CCC_PreprocessorExpression); 9223 9224 if (!CodeCompleter || CodeCompleter->includeMacros()) 9225 AddMacroResults(PP, Results, 9226 !CodeCompleter || CodeCompleter->loadExternal(), true); 9227 9228 // defined (<macro>) 9229 Results.EnterNewScope(); 9230 CodeCompletionBuilder Builder(Results.getAllocator(), 9231 Results.getCodeCompletionTUInfo()); 9232 Builder.AddTypedTextChunk("defined"); 9233 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); 9234 Builder.AddChunk(CodeCompletionString::CK_LeftParen); 9235 Builder.AddPlaceholderChunk("macro"); 9236 Builder.AddChunk(CodeCompletionString::CK_RightParen); 9237 Results.AddResult(Builder.TakeString()); 9238 Results.ExitScope(); 9239 9240 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 9241 Results.data(), Results.size()); 9242 } 9243 9244 void Sema::CodeCompletePreprocessorMacroArgument(Scope *S, 9245 IdentifierInfo *Macro, 9246 MacroInfo *MacroInfo, 9247 unsigned Argument) { 9248 // FIXME: In the future, we could provide "overload" results, much like we 9249 // do for function calls. 9250 9251 // Now just ignore this. There will be another code-completion callback 9252 // for the expanded tokens. 9253 } 9254 9255 // This handles completion inside an #include filename, e.g. #include <foo/ba 9256 // We look for the directory "foo" under each directory on the include path, 9257 // list its files, and reassemble the appropriate #include. 9258 void Sema::CodeCompleteIncludedFile(llvm::StringRef Dir, bool Angled) { 9259 // RelDir should use /, but unescaped \ is possible on windows! 9260 // Our completions will normalize to / for simplicity, this case is rare. 9261 std::string RelDir = llvm::sys::path::convert_to_slash(Dir); 9262 // We need the native slashes for the actual file system interactions. 9263 SmallString<128> NativeRelDir = StringRef(RelDir); 9264 llvm::sys::path::native(NativeRelDir); 9265 llvm::vfs::FileSystem &FS = 9266 getSourceManager().getFileManager().getVirtualFileSystem(); 9267 9268 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 9269 CodeCompleter->getCodeCompletionTUInfo(), 9270 CodeCompletionContext::CCC_IncludedFile); 9271 llvm::DenseSet<StringRef> SeenResults; // To deduplicate results. 9272 9273 // Helper: adds one file or directory completion result. 9274 auto AddCompletion = [&](StringRef Filename, bool IsDirectory) { 9275 SmallString<64> TypedChunk = Filename; 9276 // Directory completion is up to the slash, e.g. <sys/ 9277 TypedChunk.push_back(IsDirectory ? '/' : Angled ? '>' : '"'); 9278 auto R = SeenResults.insert(TypedChunk); 9279 if (R.second) { // New completion 9280 const char *InternedTyped = Results.getAllocator().CopyString(TypedChunk); 9281 *R.first = InternedTyped; // Avoid dangling StringRef. 9282 CodeCompletionBuilder Builder(CodeCompleter->getAllocator(), 9283 CodeCompleter->getCodeCompletionTUInfo()); 9284 Builder.AddTypedTextChunk(InternedTyped); 9285 // The result is a "Pattern", which is pretty opaque. 9286 // We may want to include the real filename to allow smart ranking. 9287 Results.AddResult(CodeCompletionResult(Builder.TakeString())); 9288 } 9289 }; 9290 9291 // Helper: scans IncludeDir for nice files, and adds results for each. 9292 auto AddFilesFromIncludeDir = [&](StringRef IncludeDir, 9293 bool IsSystem, 9294 DirectoryLookup::LookupType_t LookupType) { 9295 llvm::SmallString<128> Dir = IncludeDir; 9296 if (!NativeRelDir.empty()) { 9297 if (LookupType == DirectoryLookup::LT_Framework) { 9298 // For a framework dir, #include <Foo/Bar/> actually maps to 9299 // a path of Foo.framework/Headers/Bar/. 9300 auto Begin = llvm::sys::path::begin(NativeRelDir); 9301 auto End = llvm::sys::path::end(NativeRelDir); 9302 9303 llvm::sys::path::append(Dir, *Begin + ".framework", "Headers"); 9304 llvm::sys::path::append(Dir, ++Begin, End); 9305 } else { 9306 llvm::sys::path::append(Dir, NativeRelDir); 9307 } 9308 } 9309 9310 std::error_code EC; 9311 unsigned Count = 0; 9312 for (auto It = FS.dir_begin(Dir, EC); 9313 !EC && It != llvm::vfs::directory_iterator(); It.increment(EC)) { 9314 if (++Count == 2500) // If we happen to hit a huge directory, 9315 break; // bail out early so we're not too slow. 9316 StringRef Filename = llvm::sys::path::filename(It->path()); 9317 9318 // To know whether a symlink should be treated as file or a directory, we 9319 // have to stat it. This should be cheap enough as there shouldn't be many 9320 // symlinks. 9321 llvm::sys::fs::file_type Type = It->type(); 9322 if (Type == llvm::sys::fs::file_type::symlink_file) { 9323 if (auto FileStatus = FS.status(It->path())) 9324 Type = FileStatus->getType(); 9325 } 9326 switch (Type) { 9327 case llvm::sys::fs::file_type::directory_file: 9328 // All entries in a framework directory must have a ".framework" suffix, 9329 // but the suffix does not appear in the source code's include/import. 9330 if (LookupType == DirectoryLookup::LT_Framework && 9331 NativeRelDir.empty() && !Filename.consume_back(".framework")) 9332 break; 9333 9334 AddCompletion(Filename, /*IsDirectory=*/true); 9335 break; 9336 case llvm::sys::fs::file_type::regular_file: 9337 // Only files that really look like headers. (Except in system dirs). 9338 if (!IsSystem) { 9339 // Header extensions from Types.def, which we can't depend on here. 9340 if (!(Filename.endswith_lower(".h") || 9341 Filename.endswith_lower(".hh") || 9342 Filename.endswith_lower(".hpp") || 9343 Filename.endswith_lower(".inc"))) 9344 break; 9345 } 9346 AddCompletion(Filename, /*IsDirectory=*/false); 9347 break; 9348 default: 9349 break; 9350 } 9351 } 9352 }; 9353 9354 // Helper: adds results relative to IncludeDir, if possible. 9355 auto AddFilesFromDirLookup = [&](const DirectoryLookup &IncludeDir, 9356 bool IsSystem) { 9357 switch (IncludeDir.getLookupType()) { 9358 case DirectoryLookup::LT_HeaderMap: 9359 // header maps are not (currently) enumerable. 9360 break; 9361 case DirectoryLookup::LT_NormalDir: 9362 AddFilesFromIncludeDir(IncludeDir.getDir()->getName(), IsSystem, 9363 DirectoryLookup::LT_NormalDir); 9364 break; 9365 case DirectoryLookup::LT_Framework: 9366 AddFilesFromIncludeDir(IncludeDir.getFrameworkDir()->getName(), IsSystem, 9367 DirectoryLookup::LT_Framework); 9368 break; 9369 } 9370 }; 9371 9372 // Finally with all our helpers, we can scan the include path. 9373 // Do this in standard order so deduplication keeps the right file. 9374 // (In case we decide to add more details to the results later). 9375 const auto &S = PP.getHeaderSearchInfo(); 9376 using llvm::make_range; 9377 if (!Angled) { 9378 // The current directory is on the include path for "quoted" includes. 9379 auto *CurFile = PP.getCurrentFileLexer()->getFileEntry(); 9380 if (CurFile && CurFile->getDir()) 9381 AddFilesFromIncludeDir(CurFile->getDir()->getName(), false, 9382 DirectoryLookup::LT_NormalDir); 9383 for (const auto &D : make_range(S.quoted_dir_begin(), S.quoted_dir_end())) 9384 AddFilesFromDirLookup(D, false); 9385 } 9386 for (const auto &D : make_range(S.angled_dir_begin(), S.angled_dir_end())) 9387 AddFilesFromDirLookup(D, false); 9388 for (const auto &D : make_range(S.system_dir_begin(), S.system_dir_end())) 9389 AddFilesFromDirLookup(D, true); 9390 9391 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 9392 Results.data(), Results.size()); 9393 } 9394 9395 void Sema::CodeCompleteNaturalLanguage() { 9396 HandleCodeCompleteResults(this, CodeCompleter, 9397 CodeCompletionContext::CCC_NaturalLanguage, nullptr, 9398 0); 9399 } 9400 9401 void Sema::CodeCompleteAvailabilityPlatformName() { 9402 ResultBuilder Results(*this, CodeCompleter->getAllocator(), 9403 CodeCompleter->getCodeCompletionTUInfo(), 9404 CodeCompletionContext::CCC_Other); 9405 Results.EnterNewScope(); 9406 static const char *Platforms[] = {"macOS", "iOS", "watchOS", "tvOS"}; 9407 for (const char *Platform : llvm::makeArrayRef(Platforms)) { 9408 Results.AddResult(CodeCompletionResult(Platform)); 9409 Results.AddResult(CodeCompletionResult(Results.getAllocator().CopyString( 9410 Twine(Platform) + "ApplicationExtension"))); 9411 } 9412 Results.ExitScope(); 9413 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), 9414 Results.data(), Results.size()); 9415 } 9416 9417 void Sema::GatherGlobalCodeCompletions( 9418 CodeCompletionAllocator &Allocator, CodeCompletionTUInfo &CCTUInfo, 9419 SmallVectorImpl<CodeCompletionResult> &Results) { 9420 ResultBuilder Builder(*this, Allocator, CCTUInfo, 9421 CodeCompletionContext::CCC_Recovery); 9422 if (!CodeCompleter || CodeCompleter->includeGlobals()) { 9423 CodeCompletionDeclConsumer Consumer(Builder, 9424 Context.getTranslationUnitDecl()); 9425 LookupVisibleDecls(Context.getTranslationUnitDecl(), LookupAnyName, 9426 Consumer, 9427 !CodeCompleter || CodeCompleter->loadExternal()); 9428 } 9429 9430 if (!CodeCompleter || CodeCompleter->includeMacros()) 9431 AddMacroResults(PP, Builder, 9432 !CodeCompleter || CodeCompleter->loadExternal(), true); 9433 9434 Results.clear(); 9435 Results.insert(Results.end(), Builder.data(), 9436 Builder.data() + Builder.size()); 9437 } 9438