clang 19.0.0git
SemaCodeComplete.cpp
Go to the documentation of this file.
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//===----------------------------------------------------------------------===//
13#include "clang/AST/Decl.h"
14#include "clang/AST/DeclBase.h"
15#include "clang/AST/DeclCXX.h"
16#include "clang/AST/DeclObjC.h"
18#include "clang/AST/Expr.h"
19#include "clang/AST/ExprCXX.h"
21#include "clang/AST/ExprObjC.h"
26#include "clang/AST/Type.h"
32#include "clang/Lex/MacroInfo.h"
35#include "clang/Sema/DeclSpec.h"
37#include "clang/Sema/Lookup.h"
38#include "clang/Sema/Overload.h"
41#include "clang/Sema/Scope.h"
43#include "clang/Sema/Sema.h"
46#include "clang/Sema/SemaObjC.h"
47#include "llvm/ADT/ArrayRef.h"
48#include "llvm/ADT/DenseSet.h"
49#include "llvm/ADT/SmallBitVector.h"
50#include "llvm/ADT/SmallPtrSet.h"
51#include "llvm/ADT/SmallString.h"
52#include "llvm/ADT/StringExtras.h"
53#include "llvm/ADT/StringSwitch.h"
54#include "llvm/ADT/Twine.h"
55#include "llvm/ADT/iterator_range.h"
56#include "llvm/Support/Casting.h"
57#include "llvm/Support/Path.h"
58#include "llvm/Support/raw_ostream.h"
59
60#include <list>
61#include <map>
62#include <optional>
63#include <string>
64#include <vector>
65
66using namespace clang;
67using namespace sema;
68
69namespace {
70/// A container of code-completion results.
71class ResultBuilder {
72public:
73 /// The type of a name-lookup filter, which can be provided to the
74 /// name-lookup routines to specify which declarations should be included in
75 /// the result set (when it returns true) and which declarations should be
76 /// filtered out (returns false).
77 typedef bool (ResultBuilder::*LookupFilter)(const NamedDecl *) const;
78
79 typedef CodeCompletionResult Result;
80
81private:
82 /// The actual results we have found.
83 std::vector<Result> Results;
84
85 /// A record of all of the declarations we have found and placed
86 /// into the result set, used to ensure that no declaration ever gets into
87 /// the result set twice.
89
90 typedef std::pair<const NamedDecl *, unsigned> DeclIndexPair;
91
92 /// An entry in the shadow map, which is optimized to store
93 /// a single (declaration, index) mapping (the common case) but
94 /// can also store a list of (declaration, index) mappings.
95 class ShadowMapEntry {
96 typedef SmallVector<DeclIndexPair, 4> DeclIndexPairVector;
97
98 /// Contains either the solitary NamedDecl * or a vector
99 /// of (declaration, index) pairs.
100 llvm::PointerUnion<const NamedDecl *, DeclIndexPairVector *> DeclOrVector;
101
102 /// When the entry contains a single declaration, this is
103 /// the index associated with that entry.
104 unsigned SingleDeclIndex = 0;
105
106 public:
107 ShadowMapEntry() = default;
108 ShadowMapEntry(const ShadowMapEntry &) = delete;
109 ShadowMapEntry(ShadowMapEntry &&Move) { *this = std::move(Move); }
110 ShadowMapEntry &operator=(const ShadowMapEntry &) = delete;
111 ShadowMapEntry &operator=(ShadowMapEntry &&Move) {
112 SingleDeclIndex = Move.SingleDeclIndex;
113 DeclOrVector = Move.DeclOrVector;
114 Move.DeclOrVector = nullptr;
115 return *this;
116 }
117
118 void Add(const NamedDecl *ND, unsigned Index) {
119 if (DeclOrVector.isNull()) {
120 // 0 - > 1 elements: just set the single element information.
121 DeclOrVector = ND;
122 SingleDeclIndex = Index;
123 return;
124 }
125
126 if (const NamedDecl *PrevND =
127 DeclOrVector.dyn_cast<const NamedDecl *>()) {
128 // 1 -> 2 elements: create the vector of results and push in the
129 // existing declaration.
130 DeclIndexPairVector *Vec = new DeclIndexPairVector;
131 Vec->push_back(DeclIndexPair(PrevND, SingleDeclIndex));
132 DeclOrVector = Vec;
133 }
134
135 // Add the new element to the end of the vector.
136 DeclOrVector.get<DeclIndexPairVector *>()->push_back(
137 DeclIndexPair(ND, Index));
138 }
139
140 ~ShadowMapEntry() {
141 if (DeclIndexPairVector *Vec =
142 DeclOrVector.dyn_cast<DeclIndexPairVector *>()) {
143 delete Vec;
144 DeclOrVector = ((NamedDecl *)nullptr);
145 }
146 }
147
148 // Iteration.
149 class iterator;
150 iterator begin() const;
151 iterator end() const;
152 };
153
154 /// A mapping from declaration names to the declarations that have
155 /// this name within a particular scope and their index within the list of
156 /// results.
157 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
158
159 /// The semantic analysis object for which results are being
160 /// produced.
161 Sema &SemaRef;
162
163 /// The allocator used to allocate new code-completion strings.
164 CodeCompletionAllocator &Allocator;
165
166 CodeCompletionTUInfo &CCTUInfo;
167
168 /// If non-NULL, a filter function used to remove any code-completion
169 /// results that are not desirable.
170 LookupFilter Filter;
171
172 /// Whether we should allow declarations as
173 /// nested-name-specifiers that would otherwise be filtered out.
174 bool AllowNestedNameSpecifiers;
175
176 /// If set, the type that we would prefer our resulting value
177 /// declarations to have.
178 ///
179 /// Closely matching the preferred type gives a boost to a result's
180 /// priority.
181 CanQualType PreferredType;
182
183 /// A list of shadow maps, which is used to model name hiding at
184 /// different levels of, e.g., the inheritance hierarchy.
185 std::list<ShadowMap> ShadowMaps;
186
187 /// Overloaded C++ member functions found by SemaLookup.
188 /// Used to determine when one overload is dominated by another.
189 llvm::DenseMap<std::pair<DeclContext *, /*Name*/uintptr_t>, ShadowMapEntry>
190 OverloadMap;
191
192 /// If we're potentially referring to a C++ member function, the set
193 /// of qualifiers applied to the object type.
194 Qualifiers ObjectTypeQualifiers;
195 /// The kind of the object expression, for rvalue/lvalue overloads.
196 ExprValueKind ObjectKind;
197
198 /// Whether the \p ObjectTypeQualifiers field is active.
199 bool HasObjectTypeQualifiers;
200
201 /// The selector that we prefer.
202 Selector PreferredSelector;
203
204 /// The completion context in which we are gathering results.
205 CodeCompletionContext CompletionContext;
206
207 /// If we are in an instance method definition, the \@implementation
208 /// object.
209 ObjCImplementationDecl *ObjCImplementation;
210
211 void AdjustResultPriorityForDecl(Result &R);
212
213 void MaybeAddConstructorResults(Result R);
214
215public:
216 explicit ResultBuilder(Sema &SemaRef, CodeCompletionAllocator &Allocator,
217 CodeCompletionTUInfo &CCTUInfo,
218 const CodeCompletionContext &CompletionContext,
219 LookupFilter Filter = nullptr)
220 : SemaRef(SemaRef), Allocator(Allocator), CCTUInfo(CCTUInfo),
221 Filter(Filter), AllowNestedNameSpecifiers(false),
222 HasObjectTypeQualifiers(false), CompletionContext(CompletionContext),
223 ObjCImplementation(nullptr) {
224 // If this is an Objective-C instance method definition, dig out the
225 // corresponding implementation.
226 switch (CompletionContext.getKind()) {
233 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl())
234 if (Method->isInstanceMethod())
235 if (ObjCInterfaceDecl *Interface = Method->getClassInterface())
236 ObjCImplementation = Interface->getImplementation();
237 break;
238
239 default:
240 break;
241 }
242 }
243
244 /// Determine the priority for a reference to the given declaration.
245 unsigned getBasePriority(const NamedDecl *D);
246
247 /// Whether we should include code patterns in the completion
248 /// results.
249 bool includeCodePatterns() const {
250 return SemaRef.CodeCompletion().CodeCompleter &&
252 }
253
254 /// Set the filter used for code-completion results.
255 void setFilter(LookupFilter Filter) { this->Filter = Filter; }
256
257 Result *data() { return Results.empty() ? nullptr : &Results.front(); }
258 unsigned size() const { return Results.size(); }
259 bool empty() const { return Results.empty(); }
260
261 /// Specify the preferred type.
262 void setPreferredType(QualType T) {
263 PreferredType = SemaRef.Context.getCanonicalType(T);
264 }
265
266 /// Set the cv-qualifiers on the object type, for us in filtering
267 /// calls to member functions.
268 ///
269 /// When there are qualifiers in this set, they will be used to filter
270 /// out member functions that aren't available (because there will be a
271 /// cv-qualifier mismatch) or prefer functions with an exact qualifier
272 /// match.
273 void setObjectTypeQualifiers(Qualifiers Quals, ExprValueKind Kind) {
274 ObjectTypeQualifiers = Quals;
275 ObjectKind = Kind;
276 HasObjectTypeQualifiers = true;
277 }
278
279 /// Set the preferred selector.
280 ///
281 /// When an Objective-C method declaration result is added, and that
282 /// method's selector matches this preferred selector, we give that method
283 /// a slight priority boost.
284 void setPreferredSelector(Selector Sel) { PreferredSelector = Sel; }
285
286 /// Retrieve the code-completion context for which results are
287 /// being collected.
288 const CodeCompletionContext &getCompletionContext() const {
289 return CompletionContext;
290 }
291
292 /// Specify whether nested-name-specifiers are allowed.
293 void allowNestedNameSpecifiers(bool Allow = true) {
294 AllowNestedNameSpecifiers = Allow;
295 }
296
297 /// Return the semantic analysis object for which we are collecting
298 /// code completion results.
299 Sema &getSema() const { return SemaRef; }
300
301 /// Retrieve the allocator used to allocate code completion strings.
302 CodeCompletionAllocator &getAllocator() const { return Allocator; }
303
304 CodeCompletionTUInfo &getCodeCompletionTUInfo() const { return CCTUInfo; }
305
306 /// Determine whether the given declaration is at all interesting
307 /// as a code-completion result.
308 ///
309 /// \param ND the declaration that we are inspecting.
310 ///
311 /// \param AsNestedNameSpecifier will be set true if this declaration is
312 /// only interesting when it is a nested-name-specifier.
313 bool isInterestingDecl(const NamedDecl *ND,
314 bool &AsNestedNameSpecifier) const;
315
316 /// Decide whether or not a use of function Decl can be a call.
317 ///
318 /// \param ND the function declaration.
319 ///
320 /// \param BaseExprType the object type in a member access expression,
321 /// if any.
322 bool canFunctionBeCalled(const NamedDecl *ND, QualType BaseExprType) const;
323
324 /// Decide whether or not a use of member function Decl can be a call.
325 ///
326 /// \param Method the function declaration.
327 ///
328 /// \param BaseExprType the object type in a member access expression,
329 /// if any.
330 bool canCxxMethodBeCalled(const CXXMethodDecl *Method,
331 QualType BaseExprType) const;
332
333 /// Check whether the result is hidden by the Hiding declaration.
334 ///
335 /// \returns true if the result is hidden and cannot be found, false if
336 /// the hidden result could still be found. When false, \p R may be
337 /// modified to describe how the result can be found (e.g., via extra
338 /// qualification).
339 bool CheckHiddenResult(Result &R, DeclContext *CurContext,
340 const NamedDecl *Hiding);
341
342 /// Add a new result to this result set (if it isn't already in one
343 /// of the shadow maps), or replace an existing result (for, e.g., a
344 /// redeclaration).
345 ///
346 /// \param R the result to add (if it is unique).
347 ///
348 /// \param CurContext the context in which this result will be named.
349 void MaybeAddResult(Result R, DeclContext *CurContext = nullptr);
350
351 /// Add a new result to this result set, where we already know
352 /// the hiding declaration (if any).
353 ///
354 /// \param R the result to add (if it is unique).
355 ///
356 /// \param CurContext the context in which this result will be named.
357 ///
358 /// \param Hiding the declaration that hides the result.
359 ///
360 /// \param InBaseClass whether the result was found in a base
361 /// class of the searched context.
362 ///
363 /// \param BaseExprType the type of expression that precedes the "." or "->"
364 /// in a member access expression.
365 void AddResult(Result R, DeclContext *CurContext, NamedDecl *Hiding,
366 bool InBaseClass, QualType BaseExprType);
367
368 /// Add a new non-declaration result to this result set.
369 void AddResult(Result R);
370
371 /// Enter into a new scope.
372 void EnterNewScope();
373
374 /// Exit from the current scope.
375 void ExitScope();
376
377 /// Ignore this declaration, if it is seen again.
378 void Ignore(const Decl *D) { AllDeclsFound.insert(D->getCanonicalDecl()); }
379
380 /// Add a visited context.
381 void addVisitedContext(DeclContext *Ctx) {
382 CompletionContext.addVisitedContext(Ctx);
383 }
384
385 /// \name Name lookup predicates
386 ///
387 /// These predicates can be passed to the name lookup functions to filter the
388 /// results of name lookup. All of the predicates have the same type, so that
389 ///
390 //@{
391 bool IsOrdinaryName(const NamedDecl *ND) const;
392 bool IsOrdinaryNonTypeName(const NamedDecl *ND) const;
393 bool IsIntegralConstantValue(const NamedDecl *ND) const;
394 bool IsOrdinaryNonValueName(const NamedDecl *ND) const;
395 bool IsNestedNameSpecifier(const NamedDecl *ND) const;
396 bool IsEnum(const NamedDecl *ND) const;
397 bool IsClassOrStruct(const NamedDecl *ND) const;
398 bool IsUnion(const NamedDecl *ND) const;
399 bool IsNamespace(const NamedDecl *ND) const;
400 bool IsNamespaceOrAlias(const NamedDecl *ND) const;
401 bool IsType(const NamedDecl *ND) const;
402 bool IsMember(const NamedDecl *ND) const;
403 bool IsObjCIvar(const NamedDecl *ND) const;
404 bool IsObjCMessageReceiver(const NamedDecl *ND) const;
405 bool IsObjCMessageReceiverOrLambdaCapture(const NamedDecl *ND) const;
406 bool IsObjCCollection(const NamedDecl *ND) const;
407 bool IsImpossibleToSatisfy(const NamedDecl *ND) const;
408 //@}
409};
410} // namespace
411
413 if (!Enabled)
414 return;
415 if (isa<BlockDecl>(S.CurContext)) {
416 if (sema::BlockScopeInfo *BSI = S.getCurBlock()) {
417 ComputeType = nullptr;
418 Type = BSI->ReturnType;
419 ExpectedLoc = Tok;
420 }
421 } else if (const auto *Function = dyn_cast<FunctionDecl>(S.CurContext)) {
422 ComputeType = nullptr;
423 Type = Function->getReturnType();
424 ExpectedLoc = Tok;
425 } else if (const auto *Method = dyn_cast<ObjCMethodDecl>(S.CurContext)) {
426 ComputeType = nullptr;
427 Type = Method->getReturnType();
428 ExpectedLoc = Tok;
429 }
430}
431
433 if (!Enabled)
434 return;
435 auto *VD = llvm::dyn_cast_or_null<ValueDecl>(D);
436 ComputeType = nullptr;
437 Type = VD ? VD->getType() : QualType();
438 ExpectedLoc = Tok;
439}
440
441static QualType getDesignatedType(QualType BaseType, const Designation &Desig);
442
444 QualType BaseType,
445 const Designation &D) {
446 if (!Enabled)
447 return;
448 ComputeType = nullptr;
449 Type = getDesignatedType(BaseType, D);
450 ExpectedLoc = Tok;
451}
452
454 SourceLocation Tok, llvm::function_ref<QualType()> ComputeType) {
455 if (!Enabled)
456 return;
457 this->ComputeType = ComputeType;
458 Type = QualType();
459 ExpectedLoc = Tok;
460}
461
463 SourceLocation LParLoc) {
464 if (!Enabled)
465 return;
466 // expected type for parenthesized expression does not change.
467 if (ExpectedLoc == LParLoc)
468 ExpectedLoc = Tok;
469}
470
472 tok::TokenKind Op) {
473 if (!LHS)
474 return QualType();
475
476 QualType LHSType = LHS->getType();
477 if (LHSType->isPointerType()) {
478 if (Op == tok::plus || Op == tok::plusequal || Op == tok::minusequal)
480 // Pointer difference is more common than subtracting an int from a pointer.
481 if (Op == tok::minus)
482 return LHSType;
483 }
484
485 switch (Op) {
486 // No way to infer the type of RHS from LHS.
487 case tok::comma:
488 return QualType();
489 // Prefer the type of the left operand for all of these.
490 // Arithmetic operations.
491 case tok::plus:
492 case tok::plusequal:
493 case tok::minus:
494 case tok::minusequal:
495 case tok::percent:
496 case tok::percentequal:
497 case tok::slash:
498 case tok::slashequal:
499 case tok::star:
500 case tok::starequal:
501 // Assignment.
502 case tok::equal:
503 // Comparison operators.
504 case tok::equalequal:
505 case tok::exclaimequal:
506 case tok::less:
507 case tok::lessequal:
508 case tok::greater:
509 case tok::greaterequal:
510 case tok::spaceship:
511 return LHS->getType();
512 // Binary shifts are often overloaded, so don't try to guess those.
513 case tok::greatergreater:
514 case tok::greatergreaterequal:
515 case tok::lessless:
516 case tok::lesslessequal:
517 if (LHSType->isIntegralOrEnumerationType())
518 return S.getASTContext().IntTy;
519 return QualType();
520 // Logical operators, assume we want bool.
521 case tok::ampamp:
522 case tok::pipepipe:
523 case tok::caretcaret:
524 return S.getASTContext().BoolTy;
525 // Operators often used for bit manipulation are typically used with the type
526 // of the left argument.
527 case tok::pipe:
528 case tok::pipeequal:
529 case tok::caret:
530 case tok::caretequal:
531 case tok::amp:
532 case tok::ampequal:
533 if (LHSType->isIntegralOrEnumerationType())
534 return LHSType;
535 return QualType();
536 // RHS should be a pointer to a member of the 'LHS' type, but we can't give
537 // any particular type here.
538 case tok::periodstar:
539 case tok::arrowstar:
540 return QualType();
541 default:
542 // FIXME(ibiryukov): handle the missing op, re-add the assertion.
543 // assert(false && "unhandled binary op");
544 return QualType();
545 }
546}
547
548/// Get preferred type for an argument of an unary expression. \p ContextType is
549/// preferred type of the whole unary expression.
551 tok::TokenKind Op) {
552 switch (Op) {
553 case tok::exclaim:
554 return S.getASTContext().BoolTy;
555 case tok::amp:
556 if (!ContextType.isNull() && ContextType->isPointerType())
557 return ContextType->getPointeeType();
558 return QualType();
559 case tok::star:
560 if (ContextType.isNull())
561 return QualType();
562 return S.getASTContext().getPointerType(ContextType.getNonReferenceType());
563 case tok::plus:
564 case tok::minus:
565 case tok::tilde:
566 case tok::minusminus:
567 case tok::plusplus:
568 if (ContextType.isNull())
569 return S.getASTContext().IntTy;
570 // leave as is, these operators typically return the same type.
571 return ContextType;
572 case tok::kw___real:
573 case tok::kw___imag:
574 return QualType();
575 default:
576 assert(false && "unhandled unary op");
577 return QualType();
578 }
579}
580
582 tok::TokenKind Op) {
583 if (!Enabled)
584 return;
585 ComputeType = nullptr;
586 Type = getPreferredTypeOfBinaryRHS(S, LHS, Op);
587 ExpectedLoc = Tok;
588}
589
591 Expr *Base) {
592 if (!Enabled || !Base)
593 return;
594 // Do we have expected type for Base?
595 if (ExpectedLoc != Base->getBeginLoc())
596 return;
597 // Keep the expected type, only update the location.
598 ExpectedLoc = Tok;
599}
600
602 tok::TokenKind OpKind,
603 SourceLocation OpLoc) {
604 if (!Enabled)
605 return;
606 ComputeType = nullptr;
607 Type = getPreferredTypeOfUnaryArg(S, this->get(OpLoc), OpKind);
608 ExpectedLoc = Tok;
609}
610
612 Expr *LHS) {
613 if (!Enabled)
614 return;
615 ComputeType = nullptr;
617 ExpectedLoc = Tok;
618}
619
622 if (!Enabled)
623 return;
624 ComputeType = nullptr;
625 Type = !CastType.isNull() ? CastType.getCanonicalType() : QualType();
626 ExpectedLoc = Tok;
627}
628
630 if (!Enabled)
631 return;
632 ComputeType = nullptr;
634 ExpectedLoc = Tok;
635}
636
638 llvm::PointerUnion<const NamedDecl *, const DeclIndexPair *> DeclOrIterator;
639 unsigned SingleDeclIndex;
640
641public:
642 typedef DeclIndexPair value_type;
644 typedef std::ptrdiff_t difference_type;
645 typedef std::input_iterator_tag iterator_category;
646
647 class pointer {
648 DeclIndexPair Value;
649
650 public:
651 pointer(const DeclIndexPair &Value) : Value(Value) {}
652
653 const DeclIndexPair *operator->() const { return &Value; }
654 };
655
656 iterator() : DeclOrIterator((NamedDecl *)nullptr), SingleDeclIndex(0) {}
657
658 iterator(const NamedDecl *SingleDecl, unsigned Index)
659 : DeclOrIterator(SingleDecl), SingleDeclIndex(Index) {}
660
661 iterator(const DeclIndexPair *Iterator)
662 : DeclOrIterator(Iterator), SingleDeclIndex(0) {}
663
665 if (DeclOrIterator.is<const NamedDecl *>()) {
666 DeclOrIterator = (NamedDecl *)nullptr;
667 SingleDeclIndex = 0;
668 return *this;
669 }
670
671 const DeclIndexPair *I = DeclOrIterator.get<const DeclIndexPair *>();
672 ++I;
673 DeclOrIterator = I;
674 return *this;
675 }
676
677 /*iterator operator++(int) {
678 iterator tmp(*this);
679 ++(*this);
680 return tmp;
681 }*/
682
684 if (const NamedDecl *ND = DeclOrIterator.dyn_cast<const NamedDecl *>())
685 return reference(ND, SingleDeclIndex);
686
687 return *DeclOrIterator.get<const DeclIndexPair *>();
688 }
689
690 pointer operator->() const { return pointer(**this); }
691
692 friend bool operator==(const iterator &X, const iterator &Y) {
693 return X.DeclOrIterator.getOpaqueValue() ==
694 Y.DeclOrIterator.getOpaqueValue() &&
695 X.SingleDeclIndex == Y.SingleDeclIndex;
696 }
697
698 friend bool operator!=(const iterator &X, const iterator &Y) {
699 return !(X == Y);
700 }
701};
702
704ResultBuilder::ShadowMapEntry::begin() const {
705 if (DeclOrVector.isNull())
706 return iterator();
707
708 if (const NamedDecl *ND = DeclOrVector.dyn_cast<const NamedDecl *>())
709 return iterator(ND, SingleDeclIndex);
710
711 return iterator(DeclOrVector.get<DeclIndexPairVector *>()->begin());
712}
713
715ResultBuilder::ShadowMapEntry::end() const {
716 if (DeclOrVector.is<const NamedDecl *>() || DeclOrVector.isNull())
717 return iterator();
718
719 return iterator(DeclOrVector.get<DeclIndexPairVector *>()->end());
720}
721
722/// Compute the qualification required to get from the current context
723/// (\p CurContext) to the target context (\p TargetContext).
724///
725/// \param Context the AST context in which the qualification will be used.
726///
727/// \param CurContext the context where an entity is being named, which is
728/// typically based on the current scope.
729///
730/// \param TargetContext the context in which the named entity actually
731/// resides.
732///
733/// \returns a nested name specifier that refers into the target context, or
734/// NULL if no qualification is needed.
735static NestedNameSpecifier *
737 const DeclContext *TargetContext) {
739
740 for (const DeclContext *CommonAncestor = TargetContext;
741 CommonAncestor && !CommonAncestor->Encloses(CurContext);
742 CommonAncestor = CommonAncestor->getLookupParent()) {
743 if (CommonAncestor->isTransparentContext() ||
744 CommonAncestor->isFunctionOrMethod())
745 continue;
746
747 TargetParents.push_back(CommonAncestor);
748 }
749
750 NestedNameSpecifier *Result = nullptr;
751 while (!TargetParents.empty()) {
752 const DeclContext *Parent = TargetParents.pop_back_val();
753
754 if (const auto *Namespace = dyn_cast<NamespaceDecl>(Parent)) {
755 if (!Namespace->getIdentifier())
756 continue;
757
758 Result = NestedNameSpecifier::Create(Context, Result, Namespace);
759 } else if (const auto *TD = dyn_cast<TagDecl>(Parent))
761 Context, Result, false, Context.getTypeDeclType(TD).getTypePtr());
762 }
763 return Result;
764}
765
766// Some declarations have reserved names that we don't want to ever show.
767// Filter out names reserved for the implementation if they come from a
768// system header.
769static bool shouldIgnoreDueToReservedName(const NamedDecl *ND, Sema &SemaRef) {
770 // Debuggers want access to all identifiers, including reserved ones.
771 if (SemaRef.getLangOpts().DebuggerSupport)
772 return false;
773
774 ReservedIdentifierStatus Status = ND->isReserved(SemaRef.getLangOpts());
775 // Ignore reserved names for compiler provided decls.
776 if (isReservedInAllContexts(Status) && ND->getLocation().isInvalid())
777 return true;
778
779 // For system headers ignore only double-underscore names.
780 // This allows for system headers providing private symbols with a single
781 // underscore.
784 SemaRef.SourceMgr.getSpellingLoc(ND->getLocation())))
785 return true;
786
787 return false;
788}
789
790bool ResultBuilder::isInterestingDecl(const NamedDecl *ND,
791 bool &AsNestedNameSpecifier) const {
792 AsNestedNameSpecifier = false;
793
794 auto *Named = ND;
795 ND = ND->getUnderlyingDecl();
796
797 // Skip unnamed entities.
798 if (!ND->getDeclName())
799 return false;
800
801 // Friend declarations and declarations introduced due to friends are never
802 // added as results.
804 return false;
805
806 // Class template (partial) specializations are never added as results.
807 if (isa<ClassTemplateSpecializationDecl>(ND) ||
808 isa<ClassTemplatePartialSpecializationDecl>(ND))
809 return false;
810
811 // Using declarations themselves are never added as results.
812 if (isa<UsingDecl>(ND))
813 return false;
814
815 if (shouldIgnoreDueToReservedName(ND, SemaRef))
816 return false;
817
818 if (Filter == &ResultBuilder::IsNestedNameSpecifier ||
819 (isa<NamespaceDecl>(ND) && Filter != &ResultBuilder::IsNamespace &&
820 Filter != &ResultBuilder::IsNamespaceOrAlias && Filter != nullptr))
821 AsNestedNameSpecifier = true;
822
823 // Filter out any unwanted results.
824 if (Filter && !(this->*Filter)(Named)) {
825 // Check whether it is interesting as a nested-name-specifier.
826 if (AllowNestedNameSpecifiers && SemaRef.getLangOpts().CPlusPlus &&
827 IsNestedNameSpecifier(ND) &&
828 (Filter != &ResultBuilder::IsMember ||
829 (isa<CXXRecordDecl>(ND) &&
830 cast<CXXRecordDecl>(ND)->isInjectedClassName()))) {
831 AsNestedNameSpecifier = true;
832 return true;
833 }
834
835 return false;
836 }
837 // ... then it must be interesting!
838 return true;
839}
840
841bool ResultBuilder::CheckHiddenResult(Result &R, DeclContext *CurContext,
842 const NamedDecl *Hiding) {
843 // In C, there is no way to refer to a hidden name.
844 // FIXME: This isn't true; we can find a tag name hidden by an ordinary
845 // name if we introduce the tag type.
846 if (!SemaRef.getLangOpts().CPlusPlus)
847 return true;
848
849 const DeclContext *HiddenCtx =
850 R.Declaration->getDeclContext()->getRedeclContext();
851
852 // There is no way to qualify a name declared in a function or method.
853 if (HiddenCtx->isFunctionOrMethod())
854 return true;
855
856 if (HiddenCtx == Hiding->getDeclContext()->getRedeclContext())
857 return true;
858
859 // We can refer to the result with the appropriate qualification. Do it.
860 R.Hidden = true;
861 R.QualifierIsInformative = false;
862
863 if (!R.Qualifier)
864 R.Qualifier = getRequiredQualification(SemaRef.Context, CurContext,
865 R.Declaration->getDeclContext());
866 return false;
867}
868
869/// A simplified classification of types used to determine whether two
870/// types are "similar enough" when adjusting priorities.
872 switch (T->getTypeClass()) {
873 case Type::Builtin:
874 switch (cast<BuiltinType>(T)->getKind()) {
875 case BuiltinType::Void:
876 return STC_Void;
877
878 case BuiltinType::NullPtr:
879 return STC_Pointer;
880
881 case BuiltinType::Overload:
882 case BuiltinType::Dependent:
883 return STC_Other;
884
885 case BuiltinType::ObjCId:
886 case BuiltinType::ObjCClass:
887 case BuiltinType::ObjCSel:
888 return STC_ObjectiveC;
889
890 default:
891 return STC_Arithmetic;
892 }
893
894 case Type::Complex:
895 return STC_Arithmetic;
896
897 case Type::Pointer:
898 return STC_Pointer;
899
900 case Type::BlockPointer:
901 return STC_Block;
902
903 case Type::LValueReference:
904 case Type::RValueReference:
906
907 case Type::ConstantArray:
908 case Type::IncompleteArray:
909 case Type::VariableArray:
910 case Type::DependentSizedArray:
911 return STC_Array;
912
913 case Type::DependentSizedExtVector:
914 case Type::Vector:
915 case Type::ExtVector:
916 return STC_Arithmetic;
917
918 case Type::FunctionProto:
919 case Type::FunctionNoProto:
920 return STC_Function;
921
922 case Type::Record:
923 return STC_Record;
924
925 case Type::Enum:
926 return STC_Arithmetic;
927
928 case Type::ObjCObject:
929 case Type::ObjCInterface:
930 case Type::ObjCObjectPointer:
931 return STC_ObjectiveC;
932
933 default:
934 return STC_Other;
935 }
936}
937
938/// Get the type that a given expression will have if this declaration
939/// is used as an expression in its "typical" code-completion form.
941 ND = ND->getUnderlyingDecl();
942
943 if (const auto *Type = dyn_cast<TypeDecl>(ND))
944 return C.getTypeDeclType(Type);
945 if (const auto *Iface = dyn_cast<ObjCInterfaceDecl>(ND))
946 return C.getObjCInterfaceType(Iface);
947
948 QualType T;
949 if (const FunctionDecl *Function = ND->getAsFunction())
950 T = Function->getCallResultType();
951 else if (const auto *Method = dyn_cast<ObjCMethodDecl>(ND))
952 T = Method->getSendResultType();
953 else if (const auto *Enumerator = dyn_cast<EnumConstantDecl>(ND))
954 T = C.getTypeDeclType(cast<EnumDecl>(Enumerator->getDeclContext()));
955 else if (const auto *Property = dyn_cast<ObjCPropertyDecl>(ND))
956 T = Property->getType();
957 else if (const auto *Value = dyn_cast<ValueDecl>(ND))
958 T = Value->getType();
959
960 if (T.isNull())
961 return QualType();
962
963 // Dig through references, function pointers, and block pointers to
964 // get down to the likely type of an expression when the entity is
965 // used.
966 do {
967 if (const auto *Ref = T->getAs<ReferenceType>()) {
968 T = Ref->getPointeeType();
969 continue;
970 }
971
972 if (const auto *Pointer = T->getAs<PointerType>()) {
973 if (Pointer->getPointeeType()->isFunctionType()) {
974 T = Pointer->getPointeeType();
975 continue;
976 }
977
978 break;
979 }
980
981 if (const auto *Block = T->getAs<BlockPointerType>()) {
982 T = Block->getPointeeType();
983 continue;
984 }
985
986 if (const auto *Function = T->getAs<FunctionType>()) {
987 T = Function->getReturnType();
988 continue;
989 }
990
991 break;
992 } while (true);
993
994 return T;
995}
996
997unsigned ResultBuilder::getBasePriority(const NamedDecl *ND) {
998 if (!ND)
999 return CCP_Unlikely;
1000
1001 // Context-based decisions.
1002 const DeclContext *LexicalDC = ND->getLexicalDeclContext();
1003 if (LexicalDC->isFunctionOrMethod()) {
1004 // _cmd is relatively rare
1005 if (const auto *ImplicitParam = dyn_cast<ImplicitParamDecl>(ND))
1006 if (ImplicitParam->getIdentifier() &&
1007 ImplicitParam->getIdentifier()->isStr("_cmd"))
1008 return CCP_ObjC_cmd;
1009
1010 return CCP_LocalDeclaration;
1011 }
1012
1013 const DeclContext *DC = ND->getDeclContext()->getRedeclContext();
1014 if (DC->isRecord() || isa<ObjCContainerDecl>(DC)) {
1015 // Explicit destructor calls are very rare.
1016 if (isa<CXXDestructorDecl>(ND))
1017 return CCP_Unlikely;
1018 // Explicit operator and conversion function calls are also very rare.
1019 auto DeclNameKind = ND->getDeclName().getNameKind();
1020 if (DeclNameKind == DeclarationName::CXXOperatorName ||
1023 return CCP_Unlikely;
1024 return CCP_MemberDeclaration;
1025 }
1026
1027 // Content-based decisions.
1028 if (isa<EnumConstantDecl>(ND))
1029 return CCP_Constant;
1030
1031 // Use CCP_Type for type declarations unless we're in a statement, Objective-C
1032 // message receiver, or parenthesized expression context. There, it's as
1033 // likely that the user will want to write a type as other declarations.
1034 if ((isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) &&
1035 !(CompletionContext.getKind() == CodeCompletionContext::CCC_Statement ||
1036 CompletionContext.getKind() ==
1038 CompletionContext.getKind() ==
1040 return CCP_Type;
1041
1042 return CCP_Declaration;
1043}
1044
1045void ResultBuilder::AdjustResultPriorityForDecl(Result &R) {
1046 // If this is an Objective-C method declaration whose selector matches our
1047 // preferred selector, give it a priority boost.
1048 if (!PreferredSelector.isNull())
1049 if (const auto *Method = dyn_cast<ObjCMethodDecl>(R.Declaration))
1050 if (PreferredSelector == Method->getSelector())
1051 R.Priority += CCD_SelectorMatch;
1052
1053 // If we have a preferred type, adjust the priority for results with exactly-
1054 // matching or nearly-matching types.
1055 if (!PreferredType.isNull()) {
1056 QualType T = getDeclUsageType(SemaRef.Context, R.Declaration);
1057 if (!T.isNull()) {
1058 CanQualType TC = SemaRef.Context.getCanonicalType(T);
1059 // Check for exactly-matching types (modulo qualifiers).
1060 if (SemaRef.Context.hasSameUnqualifiedType(PreferredType, TC))
1061 R.Priority /= CCF_ExactTypeMatch;
1062 // Check for nearly-matching types, based on classification of each.
1063 else if ((getSimplifiedTypeClass(PreferredType) ==
1065 !(PreferredType->isEnumeralType() && TC->isEnumeralType()))
1066 R.Priority /= CCF_SimilarTypeMatch;
1067 }
1068 }
1069}
1070
1072 const CXXRecordDecl *Record) {
1073 QualType RecordTy = Context.getTypeDeclType(Record);
1074 DeclarationName ConstructorName =
1076 Context.getCanonicalType(RecordTy));
1077 return Record->lookup(ConstructorName);
1078}
1079
1080void ResultBuilder::MaybeAddConstructorResults(Result R) {
1081 if (!SemaRef.getLangOpts().CPlusPlus || !R.Declaration ||
1082 !CompletionContext.wantConstructorResults())
1083 return;
1084
1085 const NamedDecl *D = R.Declaration;
1086 const CXXRecordDecl *Record = nullptr;
1087 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D))
1088 Record = ClassTemplate->getTemplatedDecl();
1089 else if ((Record = dyn_cast<CXXRecordDecl>(D))) {
1090 // Skip specializations and partial specializations.
1091 if (isa<ClassTemplateSpecializationDecl>(Record))
1092 return;
1093 } else {
1094 // There are no constructors here.
1095 return;
1096 }
1097
1099 if (!Record)
1100 return;
1101
1102 for (NamedDecl *Ctor : getConstructors(SemaRef.Context, Record)) {
1103 R.Declaration = Ctor;
1104 R.CursorKind = getCursorKindForDecl(R.Declaration);
1105 Results.push_back(R);
1106 }
1107}
1108
1109static bool isConstructor(const Decl *ND) {
1110 if (const auto *Tmpl = dyn_cast<FunctionTemplateDecl>(ND))
1111 ND = Tmpl->getTemplatedDecl();
1112 return isa<CXXConstructorDecl>(ND);
1113}
1114
1115void ResultBuilder::MaybeAddResult(Result R, DeclContext *CurContext) {
1116 assert(!ShadowMaps.empty() && "Must enter into a results scope");
1117
1118 if (R.Kind != Result::RK_Declaration) {
1119 // For non-declaration results, just add the result.
1120 Results.push_back(R);
1121 return;
1122 }
1123
1124 // Look through using declarations.
1125 if (const UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
1126 CodeCompletionResult Result(Using->getTargetDecl(),
1127 getBasePriority(Using->getTargetDecl()),
1128 R.Qualifier, false,
1129 (R.Availability == CXAvailability_Available ||
1130 R.Availability == CXAvailability_Deprecated),
1131 std::move(R.FixIts));
1132 Result.ShadowDecl = Using;
1133 MaybeAddResult(Result, CurContext);
1134 return;
1135 }
1136
1137 const Decl *CanonDecl = R.Declaration->getCanonicalDecl();
1138 unsigned IDNS = CanonDecl->getIdentifierNamespace();
1139
1140 bool AsNestedNameSpecifier = false;
1141 if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
1142 return;
1143
1144 // C++ constructors are never found by name lookup.
1145 if (isConstructor(R.Declaration))
1146 return;
1147
1148 ShadowMap &SMap = ShadowMaps.back();
1149 ShadowMapEntry::iterator I, IEnd;
1150 ShadowMap::iterator NamePos = SMap.find(R.Declaration->getDeclName());
1151 if (NamePos != SMap.end()) {
1152 I = NamePos->second.begin();
1153 IEnd = NamePos->second.end();
1154 }
1155
1156 for (; I != IEnd; ++I) {
1157 const NamedDecl *ND = I->first;
1158 unsigned Index = I->second;
1159 if (ND->getCanonicalDecl() == CanonDecl) {
1160 // This is a redeclaration. Always pick the newer declaration.
1161 Results[Index].Declaration = R.Declaration;
1162
1163 // We're done.
1164 return;
1165 }
1166 }
1167
1168 // This is a new declaration in this scope. However, check whether this
1169 // declaration name is hidden by a similarly-named declaration in an outer
1170 // scope.
1171 std::list<ShadowMap>::iterator SM, SMEnd = ShadowMaps.end();
1172 --SMEnd;
1173 for (SM = ShadowMaps.begin(); SM != SMEnd; ++SM) {
1174 ShadowMapEntry::iterator I, IEnd;
1175 ShadowMap::iterator NamePos = SM->find(R.Declaration->getDeclName());
1176 if (NamePos != SM->end()) {
1177 I = NamePos->second.begin();
1178 IEnd = NamePos->second.end();
1179 }
1180 for (; I != IEnd; ++I) {
1181 // A tag declaration does not hide a non-tag declaration.
1182 if (I->first->hasTagIdentifierNamespace() &&
1185 continue;
1186
1187 // Protocols are in distinct namespaces from everything else.
1188 if (((I->first->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol) ||
1189 (IDNS & Decl::IDNS_ObjCProtocol)) &&
1190 I->first->getIdentifierNamespace() != IDNS)
1191 continue;
1192
1193 // The newly-added result is hidden by an entry in the shadow map.
1194 if (CheckHiddenResult(R, CurContext, I->first))
1195 return;
1196
1197 break;
1198 }
1199 }
1200
1201 // Make sure that any given declaration only shows up in the result set once.
1202 if (!AllDeclsFound.insert(CanonDecl).second)
1203 return;
1204
1205 // If the filter is for nested-name-specifiers, then this result starts a
1206 // nested-name-specifier.
1207 if (AsNestedNameSpecifier) {
1208 R.StartsNestedNameSpecifier = true;
1209 R.Priority = CCP_NestedNameSpecifier;
1210 } else
1211 AdjustResultPriorityForDecl(R);
1212
1213 // If this result is supposed to have an informative qualifier, add one.
1214 if (R.QualifierIsInformative && !R.Qualifier &&
1215 !R.StartsNestedNameSpecifier) {
1216 const DeclContext *Ctx = R.Declaration->getDeclContext();
1217 if (const NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
1218 R.Qualifier =
1219 NestedNameSpecifier::Create(SemaRef.Context, nullptr, Namespace);
1220 else if (const TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
1221 R.Qualifier = NestedNameSpecifier::Create(
1222 SemaRef.Context, nullptr, false,
1223 SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
1224 else
1225 R.QualifierIsInformative = false;
1226 }
1227
1228 // Insert this result into the set of results and into the current shadow
1229 // map.
1230 SMap[R.Declaration->getDeclName()].Add(R.Declaration, Results.size());
1231 Results.push_back(R);
1232
1233 if (!AsNestedNameSpecifier)
1234 MaybeAddConstructorResults(R);
1235}
1236
1239 R.InBaseClass = true;
1240}
1241
1243// Will Candidate ever be called on the object, when overloaded with Incumbent?
1244// Returns Dominates if Candidate is always called, Dominated if Incumbent is
1245// always called, BothViable if either may be called depending on arguments.
1246// Precondition: must actually be overloads!
1248 const CXXMethodDecl &Incumbent,
1249 const Qualifiers &ObjectQuals,
1250 ExprValueKind ObjectKind) {
1251 // Base/derived shadowing is handled elsewhere.
1252 if (Candidate.getDeclContext() != Incumbent.getDeclContext())
1253 return OverloadCompare::BothViable;
1254 if (Candidate.isVariadic() != Incumbent.isVariadic() ||
1255 Candidate.getNumParams() != Incumbent.getNumParams() ||
1256 Candidate.getMinRequiredArguments() !=
1257 Incumbent.getMinRequiredArguments())
1258 return OverloadCompare::BothViable;
1259 for (unsigned I = 0, E = Candidate.getNumParams(); I != E; ++I)
1260 if (Candidate.parameters()[I]->getType().getCanonicalType() !=
1261 Incumbent.parameters()[I]->getType().getCanonicalType())
1262 return OverloadCompare::BothViable;
1263 if (!Candidate.specific_attrs<EnableIfAttr>().empty() ||
1264 !Incumbent.specific_attrs<EnableIfAttr>().empty())
1265 return OverloadCompare::BothViable;
1266 // At this point, we know calls can't pick one or the other based on
1267 // arguments, so one of the two must win. (Or both fail, handled elsewhere).
1268 RefQualifierKind CandidateRef = Candidate.getRefQualifier();
1269 RefQualifierKind IncumbentRef = Incumbent.getRefQualifier();
1270 if (CandidateRef != IncumbentRef) {
1271 // If the object kind is LValue/RValue, there's one acceptable ref-qualifier
1272 // and it can't be mixed with ref-unqualified overloads (in valid code).
1273
1274 // For xvalue objects, we prefer the rvalue overload even if we have to
1275 // add qualifiers (which is rare, because const&& is rare).
1276 if (ObjectKind == clang::VK_XValue)
1277 return CandidateRef == RQ_RValue ? OverloadCompare::Dominates
1278 : OverloadCompare::Dominated;
1279 }
1280 // Now the ref qualifiers are the same (or we're in some invalid state).
1281 // So make some decision based on the qualifiers.
1282 Qualifiers CandidateQual = Candidate.getMethodQualifiers();
1283 Qualifiers IncumbentQual = Incumbent.getMethodQualifiers();
1284 bool CandidateSuperset = CandidateQual.compatiblyIncludes(IncumbentQual);
1285 bool IncumbentSuperset = IncumbentQual.compatiblyIncludes(CandidateQual);
1286 if (CandidateSuperset == IncumbentSuperset)
1287 return OverloadCompare::BothViable;
1288 return IncumbentSuperset ? OverloadCompare::Dominates
1289 : OverloadCompare::Dominated;
1290}
1291
1292bool ResultBuilder::canCxxMethodBeCalled(const CXXMethodDecl *Method,
1293 QualType BaseExprType) const {
1294 // Find the class scope that we're currently in.
1295 // We could e.g. be inside a lambda, so walk up the DeclContext until we
1296 // find a CXXMethodDecl.
1297 DeclContext *CurContext = SemaRef.CurContext;
1298 const auto *CurrentClassScope = [&]() -> const CXXRecordDecl * {
1299 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getParent()) {
1300 const auto *CtxMethod = llvm::dyn_cast<CXXMethodDecl>(Ctx);
1301 if (CtxMethod && !CtxMethod->getParent()->isLambda()) {
1302 return CtxMethod->getParent();
1303 }
1304 }
1305 return nullptr;
1306 }();
1307
1308 // If we're not inside the scope of the method's class, it can't be a call.
1309 bool FunctionCanBeCall =
1310 CurrentClassScope &&
1311 (CurrentClassScope == Method->getParent() ||
1312 CurrentClassScope->isDerivedFrom(Method->getParent()));
1313
1314 // We skip the following calculation for exceptions if it's already true.
1315 if (FunctionCanBeCall)
1316 return true;
1317
1318 // Exception: foo->FooBase::bar() or foo->Foo::bar() *is* a call.
1319 if (const CXXRecordDecl *MaybeDerived =
1320 BaseExprType.isNull() ? nullptr
1321 : BaseExprType->getAsCXXRecordDecl()) {
1322 auto *MaybeBase = Method->getParent();
1323 FunctionCanBeCall =
1324 MaybeDerived == MaybeBase || MaybeDerived->isDerivedFrom(MaybeBase);
1325 }
1326
1327 return FunctionCanBeCall;
1328}
1329
1330bool ResultBuilder::canFunctionBeCalled(const NamedDecl *ND,
1331 QualType BaseExprType) const {
1332 // We apply heuristics only to CCC_Symbol:
1333 // * CCC_{Arrow,Dot}MemberAccess reflect member access expressions:
1334 // f.method() and f->method(). These are always calls.
1335 // * A qualified name to a member function may *not* be a call. We have to
1336 // subdivide the cases: For example, f.Base::method(), which is regarded as
1337 // CCC_Symbol, should be a call.
1338 // * Non-member functions and static member functions are always considered
1339 // calls.
1340 if (CompletionContext.getKind() == clang::CodeCompletionContext::CCC_Symbol) {
1341 if (const auto *FuncTmpl = dyn_cast<FunctionTemplateDecl>(ND)) {
1342 ND = FuncTmpl->getTemplatedDecl();
1343 }
1344 const auto *Method = dyn_cast<CXXMethodDecl>(ND);
1345 if (Method && !Method->isStatic()) {
1346 return canCxxMethodBeCalled(Method, BaseExprType);
1347 }
1348 }
1349 return true;
1350}
1351
1352void ResultBuilder::AddResult(Result R, DeclContext *CurContext,
1353 NamedDecl *Hiding, bool InBaseClass = false,
1354 QualType BaseExprType = QualType()) {
1355 if (R.Kind != Result::RK_Declaration) {
1356 // For non-declaration results, just add the result.
1357 Results.push_back(R);
1358 return;
1359 }
1360
1361 // Look through using declarations.
1362 if (const auto *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
1363 CodeCompletionResult Result(Using->getTargetDecl(),
1364 getBasePriority(Using->getTargetDecl()),
1365 R.Qualifier, false,
1366 (R.Availability == CXAvailability_Available ||
1367 R.Availability == CXAvailability_Deprecated),
1368 std::move(R.FixIts));
1369 Result.ShadowDecl = Using;
1370 AddResult(Result, CurContext, Hiding, /*InBaseClass=*/false,
1371 /*BaseExprType=*/BaseExprType);
1372 return;
1373 }
1374
1375 bool AsNestedNameSpecifier = false;
1376 if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
1377 return;
1378
1379 // C++ constructors are never found by name lookup.
1380 if (isConstructor(R.Declaration))
1381 return;
1382
1383 if (Hiding && CheckHiddenResult(R, CurContext, Hiding))
1384 return;
1385
1386 // Make sure that any given declaration only shows up in the result set once.
1387 if (!AllDeclsFound.insert(R.Declaration->getCanonicalDecl()).second)
1388 return;
1389
1390 // If the filter is for nested-name-specifiers, then this result starts a
1391 // nested-name-specifier.
1392 if (AsNestedNameSpecifier) {
1393 R.StartsNestedNameSpecifier = true;
1394 R.Priority = CCP_NestedNameSpecifier;
1395 } else if (Filter == &ResultBuilder::IsMember && !R.Qualifier &&
1396 InBaseClass &&
1397 isa<CXXRecordDecl>(
1398 R.Declaration->getDeclContext()->getRedeclContext()))
1399 R.QualifierIsInformative = true;
1400
1401 // If this result is supposed to have an informative qualifier, add one.
1402 if (R.QualifierIsInformative && !R.Qualifier &&
1403 !R.StartsNestedNameSpecifier) {
1404 const DeclContext *Ctx = R.Declaration->getDeclContext();
1405 if (const auto *Namespace = dyn_cast<NamespaceDecl>(Ctx))
1406 R.Qualifier =
1407 NestedNameSpecifier::Create(SemaRef.Context, nullptr, Namespace);
1408 else if (const auto *Tag = dyn_cast<TagDecl>(Ctx))
1409 R.Qualifier = NestedNameSpecifier::Create(
1410 SemaRef.Context, nullptr, false,
1411 SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
1412 else
1413 R.QualifierIsInformative = false;
1414 }
1415
1416 // Adjust the priority if this result comes from a base class.
1417 if (InBaseClass)
1418 setInBaseClass(R);
1419
1420 AdjustResultPriorityForDecl(R);
1421
1422 if (HasObjectTypeQualifiers)
1423 if (const auto *Method = dyn_cast<CXXMethodDecl>(R.Declaration))
1424 if (Method->isInstance()) {
1425 Qualifiers MethodQuals = Method->getMethodQualifiers();
1426 if (ObjectTypeQualifiers == MethodQuals)
1427 R.Priority += CCD_ObjectQualifierMatch;
1428 else if (ObjectTypeQualifiers - MethodQuals) {
1429 // The method cannot be invoked, because doing so would drop
1430 // qualifiers.
1431 return;
1432 }
1433 // Detect cases where a ref-qualified method cannot be invoked.
1434 switch (Method->getRefQualifier()) {
1435 case RQ_LValue:
1436 if (ObjectKind != VK_LValue && !MethodQuals.hasConst())
1437 return;
1438 break;
1439 case RQ_RValue:
1440 if (ObjectKind == VK_LValue)
1441 return;
1442 break;
1443 case RQ_None:
1444 break;
1445 }
1446
1447 /// Check whether this dominates another overloaded method, which should
1448 /// be suppressed (or vice versa).
1449 /// Motivating case is const_iterator begin() const vs iterator begin().
1450 auto &OverloadSet = OverloadMap[std::make_pair(
1451 CurContext, Method->getDeclName().getAsOpaqueInteger())];
1452 for (const DeclIndexPair Entry : OverloadSet) {
1453 Result &Incumbent = Results[Entry.second];
1454 switch (compareOverloads(*Method,
1455 *cast<CXXMethodDecl>(Incumbent.Declaration),
1456 ObjectTypeQualifiers, ObjectKind)) {
1457 case OverloadCompare::Dominates:
1458 // Replace the dominated overload with this one.
1459 // FIXME: if the overload dominates multiple incumbents then we
1460 // should remove all. But two overloads is by far the common case.
1461 Incumbent = std::move(R);
1462 return;
1463 case OverloadCompare::Dominated:
1464 // This overload can't be called, drop it.
1465 return;
1466 case OverloadCompare::BothViable:
1467 break;
1468 }
1469 }
1470 OverloadSet.Add(Method, Results.size());
1471 }
1472
1473 R.FunctionCanBeCall = canFunctionBeCalled(R.getDeclaration(), BaseExprType);
1474
1475 // Insert this result into the set of results.
1476 Results.push_back(R);
1477
1478 if (!AsNestedNameSpecifier)
1479 MaybeAddConstructorResults(R);
1480}
1481
1482void ResultBuilder::AddResult(Result R) {
1483 assert(R.Kind != Result::RK_Declaration &&
1484 "Declaration results need more context");
1485 Results.push_back(R);
1486}
1487
1488/// Enter into a new scope.
1489void ResultBuilder::EnterNewScope() { ShadowMaps.emplace_back(); }
1490
1491/// Exit from the current scope.
1492void ResultBuilder::ExitScope() {
1493 ShadowMaps.pop_back();
1494}
1495
1496/// Determines whether this given declaration will be found by
1497/// ordinary name lookup.
1498bool ResultBuilder::IsOrdinaryName(const NamedDecl *ND) const {
1499 ND = ND->getUnderlyingDecl();
1500
1501 // If name lookup finds a local extern declaration, then we are in a
1502 // context where it behaves like an ordinary name.
1504 if (SemaRef.getLangOpts().CPlusPlus)
1506 else if (SemaRef.getLangOpts().ObjC) {
1507 if (isa<ObjCIvarDecl>(ND))
1508 return true;
1509 }
1510
1511 return ND->getIdentifierNamespace() & IDNS;
1512}
1513
1514/// Determines whether this given declaration will be found by
1515/// ordinary name lookup but is not a type name.
1516bool ResultBuilder::IsOrdinaryNonTypeName(const NamedDecl *ND) const {
1517 ND = ND->getUnderlyingDecl();
1518 if (isa<TypeDecl>(ND))
1519 return false;
1520 // Objective-C interfaces names are not filtered by this method because they
1521 // can be used in a class property expression. We can still filter out
1522 // @class declarations though.
1523 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND)) {
1524 if (!ID->getDefinition())
1525 return false;
1526 }
1527
1529 if (SemaRef.getLangOpts().CPlusPlus)
1531 else if (SemaRef.getLangOpts().ObjC) {
1532 if (isa<ObjCIvarDecl>(ND))
1533 return true;
1534 }
1535
1536 return ND->getIdentifierNamespace() & IDNS;
1537}
1538
1539bool ResultBuilder::IsIntegralConstantValue(const NamedDecl *ND) const {
1540 if (!IsOrdinaryNonTypeName(ND))
1541 return false;
1542
1543 if (const auto *VD = dyn_cast<ValueDecl>(ND->getUnderlyingDecl()))
1544 if (VD->getType()->isIntegralOrEnumerationType())
1545 return true;
1546
1547 return false;
1548}
1549
1550/// Determines whether this given declaration will be found by
1551/// ordinary name lookup.
1552bool ResultBuilder::IsOrdinaryNonValueName(const NamedDecl *ND) const {
1553 ND = ND->getUnderlyingDecl();
1554
1556 if (SemaRef.getLangOpts().CPlusPlus)
1558
1559 return (ND->getIdentifierNamespace() & IDNS) && !isa<ValueDecl>(ND) &&
1560 !isa<FunctionTemplateDecl>(ND) && !isa<ObjCPropertyDecl>(ND);
1561}
1562
1563/// Determines whether the given declaration is suitable as the
1564/// start of a C++ nested-name-specifier, e.g., a class or namespace.
1565bool ResultBuilder::IsNestedNameSpecifier(const NamedDecl *ND) const {
1566 // Allow us to find class templates, too.
1567 if (const auto *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
1568 ND = ClassTemplate->getTemplatedDecl();
1569
1570 return SemaRef.isAcceptableNestedNameSpecifier(ND);
1571}
1572
1573/// Determines whether the given declaration is an enumeration.
1574bool ResultBuilder::IsEnum(const NamedDecl *ND) const {
1575 return isa<EnumDecl>(ND);
1576}
1577
1578/// Determines whether the given declaration is a class or struct.
1579bool ResultBuilder::IsClassOrStruct(const NamedDecl *ND) const {
1580 // Allow us to find class templates, too.
1581 if (const auto *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
1582 ND = ClassTemplate->getTemplatedDecl();
1583
1584 // For purposes of this check, interfaces match too.
1585 if (const auto *RD = dyn_cast<RecordDecl>(ND))
1586 return RD->getTagKind() == TagTypeKind::Class ||
1587 RD->getTagKind() == TagTypeKind::Struct ||
1588 RD->getTagKind() == TagTypeKind::Interface;
1589
1590 return false;
1591}
1592
1593/// Determines whether the given declaration is a union.
1594bool ResultBuilder::IsUnion(const NamedDecl *ND) const {
1595 // Allow us to find class templates, too.
1596 if (const auto *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
1597 ND = ClassTemplate->getTemplatedDecl();
1598
1599 if (const auto *RD = dyn_cast<RecordDecl>(ND))
1600 return RD->getTagKind() == TagTypeKind::Union;
1601
1602 return false;
1603}
1604
1605/// Determines whether the given declaration is a namespace.
1606bool ResultBuilder::IsNamespace(const NamedDecl *ND) const {
1607 return isa<NamespaceDecl>(ND);
1608}
1609
1610/// Determines whether the given declaration is a namespace or
1611/// namespace alias.
1612bool ResultBuilder::IsNamespaceOrAlias(const NamedDecl *ND) const {
1613 return isa<NamespaceDecl>(ND->getUnderlyingDecl());
1614}
1615
1616/// Determines whether the given declaration is a type.
1617bool ResultBuilder::IsType(const NamedDecl *ND) const {
1618 ND = ND->getUnderlyingDecl();
1619 return isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
1620}
1621
1622/// Determines which members of a class should be visible via
1623/// "." or "->". Only value declarations, nested name specifiers, and
1624/// using declarations thereof should show up.
1625bool ResultBuilder::IsMember(const NamedDecl *ND) const {
1626 ND = ND->getUnderlyingDecl();
1627 return isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND) ||
1628 isa<ObjCPropertyDecl>(ND);
1629}
1630
1632 T = C.getCanonicalType(T);
1633 switch (T->getTypeClass()) {
1634 case Type::ObjCObject:
1635 case Type::ObjCInterface:
1636 case Type::ObjCObjectPointer:
1637 return true;
1638
1639 case Type::Builtin:
1640 switch (cast<BuiltinType>(T)->getKind()) {
1641 case BuiltinType::ObjCId:
1642 case BuiltinType::ObjCClass:
1643 case BuiltinType::ObjCSel:
1644 return true;
1645
1646 default:
1647 break;
1648 }
1649 return false;
1650
1651 default:
1652 break;
1653 }
1654
1655 if (!C.getLangOpts().CPlusPlus)
1656 return false;
1657
1658 // FIXME: We could perform more analysis here to determine whether a
1659 // particular class type has any conversions to Objective-C types. For now,
1660 // just accept all class types.
1661 return T->isDependentType() || T->isRecordType();
1662}
1663
1664bool ResultBuilder::IsObjCMessageReceiver(const NamedDecl *ND) const {
1665 QualType T = getDeclUsageType(SemaRef.Context, ND);
1666 if (T.isNull())
1667 return false;
1668
1669 T = SemaRef.Context.getBaseElementType(T);
1670 return isObjCReceiverType(SemaRef.Context, T);
1671}
1672
1673bool ResultBuilder::IsObjCMessageReceiverOrLambdaCapture(
1674 const NamedDecl *ND) const {
1675 if (IsObjCMessageReceiver(ND))
1676 return true;
1677
1678 const auto *Var = dyn_cast<VarDecl>(ND);
1679 if (!Var)
1680 return false;
1681
1682 return Var->hasLocalStorage() && !Var->hasAttr<BlocksAttr>();
1683}
1684
1685bool ResultBuilder::IsObjCCollection(const NamedDecl *ND) const {
1686 if ((SemaRef.getLangOpts().CPlusPlus && !IsOrdinaryName(ND)) ||
1687 (!SemaRef.getLangOpts().CPlusPlus && !IsOrdinaryNonTypeName(ND)))
1688 return false;
1689
1690 QualType T = getDeclUsageType(SemaRef.Context, ND);
1691 if (T.isNull())
1692 return false;
1693
1694 T = SemaRef.Context.getBaseElementType(T);
1695 return T->isObjCObjectType() || T->isObjCObjectPointerType() ||
1696 T->isObjCIdType() ||
1697 (SemaRef.getLangOpts().CPlusPlus && T->isRecordType());
1698}
1699
1700bool ResultBuilder::IsImpossibleToSatisfy(const NamedDecl *ND) const {
1701 return false;
1702}
1703
1704/// Determines whether the given declaration is an Objective-C
1705/// instance variable.
1706bool ResultBuilder::IsObjCIvar(const NamedDecl *ND) const {
1707 return isa<ObjCIvarDecl>(ND);
1708}
1709
1710namespace {
1711
1712/// Visible declaration consumer that adds a code-completion result
1713/// for each visible declaration.
1714class CodeCompletionDeclConsumer : public VisibleDeclConsumer {
1715 ResultBuilder &Results;
1716 DeclContext *InitialLookupCtx;
1717 // NamingClass and BaseType are used for access-checking. See
1718 // Sema::IsSimplyAccessible for details.
1719 CXXRecordDecl *NamingClass;
1720 QualType BaseType;
1721 std::vector<FixItHint> FixIts;
1722
1723public:
1724 CodeCompletionDeclConsumer(
1725 ResultBuilder &Results, DeclContext *InitialLookupCtx,
1726 QualType BaseType = QualType(),
1727 std::vector<FixItHint> FixIts = std::vector<FixItHint>())
1728 : Results(Results), InitialLookupCtx(InitialLookupCtx),
1729 FixIts(std::move(FixIts)) {
1730 NamingClass = llvm::dyn_cast<CXXRecordDecl>(InitialLookupCtx);
1731 // If BaseType was not provided explicitly, emulate implicit 'this->'.
1732 if (BaseType.isNull()) {
1733 auto ThisType = Results.getSema().getCurrentThisType();
1734 if (!ThisType.isNull()) {
1735 assert(ThisType->isPointerType());
1736 BaseType = ThisType->getPointeeType();
1737 if (!NamingClass)
1738 NamingClass = BaseType->getAsCXXRecordDecl();
1739 }
1740 }
1741 this->BaseType = BaseType;
1742 }
1743
1744 void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
1745 bool InBaseClass) override {
1746 ResultBuilder::Result Result(ND, Results.getBasePriority(ND), nullptr,
1747 false, IsAccessible(ND, Ctx), FixIts);
1748 Results.AddResult(Result, InitialLookupCtx, Hiding, InBaseClass, BaseType);
1749 }
1750
1751 void EnteredContext(DeclContext *Ctx) override {
1752 Results.addVisitedContext(Ctx);
1753 }
1754
1755private:
1756 bool IsAccessible(NamedDecl *ND, DeclContext *Ctx) {
1757 // Naming class to use for access check. In most cases it was provided
1758 // explicitly (e.g. member access (lhs.foo) or qualified lookup (X::)),
1759 // for unqualified lookup we fallback to the \p Ctx in which we found the
1760 // member.
1761 auto *NamingClass = this->NamingClass;
1762 QualType BaseType = this->BaseType;
1763 if (auto *Cls = llvm::dyn_cast_or_null<CXXRecordDecl>(Ctx)) {
1764 if (!NamingClass)
1765 NamingClass = Cls;
1766 // When we emulate implicit 'this->' in an unqualified lookup, we might
1767 // end up with an invalid naming class. In that case, we avoid emulating
1768 // 'this->' qualifier to satisfy preconditions of the access checking.
1769 if (NamingClass->getCanonicalDecl() != Cls->getCanonicalDecl() &&
1770 !NamingClass->isDerivedFrom(Cls)) {
1771 NamingClass = Cls;
1772 BaseType = QualType();
1773 }
1774 } else {
1775 // The decl was found outside the C++ class, so only ObjC access checks
1776 // apply. Those do not rely on NamingClass and BaseType, so we clear them
1777 // out.
1778 NamingClass = nullptr;
1779 BaseType = QualType();
1780 }
1781 return Results.getSema().IsSimplyAccessible(ND, NamingClass, BaseType);
1782 }
1783};
1784} // namespace
1785
1786/// Add type specifiers for the current language as keyword results.
1787static void AddTypeSpecifierResults(const LangOptions &LangOpts,
1788 ResultBuilder &Results) {
1790 Results.AddResult(Result("short", CCP_Type));
1791 Results.AddResult(Result("long", CCP_Type));
1792 Results.AddResult(Result("signed", CCP_Type));
1793 Results.AddResult(Result("unsigned", CCP_Type));
1794 Results.AddResult(Result("void", CCP_Type));
1795 Results.AddResult(Result("char", CCP_Type));
1796 Results.AddResult(Result("int", CCP_Type));
1797 Results.AddResult(Result("float", CCP_Type));
1798 Results.AddResult(Result("double", CCP_Type));
1799 Results.AddResult(Result("enum", CCP_Type));
1800 Results.AddResult(Result("struct", CCP_Type));
1801 Results.AddResult(Result("union", CCP_Type));
1802 Results.AddResult(Result("const", CCP_Type));
1803 Results.AddResult(Result("volatile", CCP_Type));
1804
1805 if (LangOpts.C99) {
1806 // C99-specific
1807 Results.AddResult(Result("_Complex", CCP_Type));
1808 Results.AddResult(Result("_Imaginary", CCP_Type));
1809 Results.AddResult(Result("_Bool", CCP_Type));
1810 Results.AddResult(Result("restrict", CCP_Type));
1811 }
1812
1813 CodeCompletionBuilder Builder(Results.getAllocator(),
1814 Results.getCodeCompletionTUInfo());
1815 if (LangOpts.CPlusPlus) {
1816 // C++-specific
1817 Results.AddResult(
1818 Result("bool", CCP_Type + (LangOpts.ObjC ? CCD_bool_in_ObjC : 0)));
1819 Results.AddResult(Result("class", CCP_Type));
1820 Results.AddResult(Result("wchar_t", CCP_Type));
1821
1822 // typename name
1823 Builder.AddTypedTextChunk("typename");
1825 Builder.AddPlaceholderChunk("name");
1826 Results.AddResult(Result(Builder.TakeString()));
1827
1828 if (LangOpts.CPlusPlus11) {
1829 Results.AddResult(Result("auto", CCP_Type));
1830 Results.AddResult(Result("char16_t", CCP_Type));
1831 Results.AddResult(Result("char32_t", CCP_Type));
1832
1833 Builder.AddTypedTextChunk("decltype");
1834 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1835 Builder.AddPlaceholderChunk("expression");
1836 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1837 Results.AddResult(Result(Builder.TakeString()));
1838 }
1839 } else
1840 Results.AddResult(Result("__auto_type", CCP_Type));
1841
1842 // GNU keywords
1843 if (LangOpts.GNUKeywords) {
1844 // FIXME: Enable when we actually support decimal floating point.
1845 // Results.AddResult(Result("_Decimal32"));
1846 // Results.AddResult(Result("_Decimal64"));
1847 // Results.AddResult(Result("_Decimal128"));
1848
1849 Builder.AddTypedTextChunk("typeof");
1851 Builder.AddPlaceholderChunk("expression");
1852 Results.AddResult(Result(Builder.TakeString()));
1853
1854 Builder.AddTypedTextChunk("typeof");
1855 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1856 Builder.AddPlaceholderChunk("type");
1857 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1858 Results.AddResult(Result(Builder.TakeString()));
1859 }
1860
1861 // Nullability
1862 Results.AddResult(Result("_Nonnull", CCP_Type));
1863 Results.AddResult(Result("_Null_unspecified", CCP_Type));
1864 Results.AddResult(Result("_Nullable", CCP_Type));
1865}
1866
1867static void
1869 const LangOptions &LangOpts, ResultBuilder &Results) {
1871 // Note: we don't suggest either "auto" or "register", because both
1872 // are pointless as storage specifiers. Elsewhere, we suggest "auto"
1873 // in C++0x as a type specifier.
1874 Results.AddResult(Result("extern"));
1875 Results.AddResult(Result("static"));
1876
1877 if (LangOpts.CPlusPlus11) {
1878 CodeCompletionAllocator &Allocator = Results.getAllocator();
1879 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
1880
1881 // alignas
1882 Builder.AddTypedTextChunk("alignas");
1883 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1884 Builder.AddPlaceholderChunk("expression");
1885 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1886 Results.AddResult(Result(Builder.TakeString()));
1887
1888 Results.AddResult(Result("constexpr"));
1889 Results.AddResult(Result("thread_local"));
1890 }
1891}
1892
1893static void
1895 const LangOptions &LangOpts, ResultBuilder &Results) {
1897 switch (CCC) {
1900 if (LangOpts.CPlusPlus) {
1901 Results.AddResult(Result("explicit"));
1902 Results.AddResult(Result("friend"));
1903 Results.AddResult(Result("mutable"));
1904 Results.AddResult(Result("virtual"));
1905 }
1906 [[fallthrough]];
1907
1912 if (LangOpts.CPlusPlus || LangOpts.C99)
1913 Results.AddResult(Result("inline"));
1914 break;
1915
1926 break;
1927 }
1928}
1929
1930static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt);
1931static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt);
1932static void AddObjCVisibilityResults(const LangOptions &LangOpts,
1933 ResultBuilder &Results, bool NeedAt);
1934static void AddObjCImplementationResults(const LangOptions &LangOpts,
1935 ResultBuilder &Results, bool NeedAt);
1936static void AddObjCInterfaceResults(const LangOptions &LangOpts,
1937 ResultBuilder &Results, bool NeedAt);
1938static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt);
1939
1940static void AddTypedefResult(ResultBuilder &Results) {
1941 CodeCompletionBuilder Builder(Results.getAllocator(),
1942 Results.getCodeCompletionTUInfo());
1943 Builder.AddTypedTextChunk("typedef");
1945 Builder.AddPlaceholderChunk("type");
1947 Builder.AddPlaceholderChunk("name");
1948 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
1949 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
1950}
1951
1952// using name = type
1954 ResultBuilder &Results) {
1955 Builder.AddTypedTextChunk("using");
1957 Builder.AddPlaceholderChunk("name");
1958 Builder.AddChunk(CodeCompletionString::CK_Equal);
1959 Builder.AddPlaceholderChunk("type");
1960 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
1961 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
1962}
1963
1965 const LangOptions &LangOpts) {
1966 switch (CCC) {
1978 return true;
1979
1982 return LangOpts.CPlusPlus;
1983
1986 return false;
1987
1989 return LangOpts.CPlusPlus || LangOpts.ObjC || LangOpts.C99;
1990 }
1991
1992 llvm_unreachable("Invalid ParserCompletionContext!");
1993}
1994
1996 const Preprocessor &PP) {
1997 PrintingPolicy Policy = Sema::getPrintingPolicy(Context, PP);
1998 Policy.AnonymousTagLocations = false;
1999 Policy.SuppressStrongLifetime = true;
2000 Policy.SuppressUnwrittenScope = true;
2001 Policy.SuppressScope = true;
2002 Policy.CleanUglifiedParameters = true;
2003 return Policy;
2004}
2005
2006/// Retrieve a printing policy suitable for code completion.
2009}
2010
2011/// Retrieve the string representation of the given type as a string
2012/// that has the appropriate lifetime for code completion.
2013///
2014/// This routine provides a fast path where we provide constant strings for
2015/// common type names.
2016static const char *GetCompletionTypeString(QualType T, ASTContext &Context,
2017 const PrintingPolicy &Policy,
2018 CodeCompletionAllocator &Allocator) {
2019 if (!T.getLocalQualifiers()) {
2020 // Built-in type names are constant strings.
2021 if (const BuiltinType *BT = dyn_cast<BuiltinType>(T))
2022 return BT->getNameAsCString(Policy);
2023
2024 // Anonymous tag types are constant strings.
2025 if (const TagType *TagT = dyn_cast<TagType>(T))
2026 if (TagDecl *Tag = TagT->getDecl())
2027 if (!Tag->hasNameForLinkage()) {
2028 switch (Tag->getTagKind()) {
2030 return "struct <anonymous>";
2032 return "__interface <anonymous>";
2033 case TagTypeKind::Class:
2034 return "class <anonymous>";
2035 case TagTypeKind::Union:
2036 return "union <anonymous>";
2037 case TagTypeKind::Enum:
2038 return "enum <anonymous>";
2039 }
2040 }
2041 }
2042
2043 // Slow path: format the type as a string.
2044 std::string Result;
2045 T.getAsStringInternal(Result, Policy);
2046 return Allocator.CopyString(Result);
2047}
2048
2049/// Add a completion for "this", if we're in a member function.
2050static void addThisCompletion(Sema &S, ResultBuilder &Results) {
2051 QualType ThisTy = S.getCurrentThisType();
2052 if (ThisTy.isNull())
2053 return;
2054
2055 CodeCompletionAllocator &Allocator = Results.getAllocator();
2056 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
2058 Builder.AddResultTypeChunk(
2059 GetCompletionTypeString(ThisTy, S.Context, Policy, Allocator));
2060 Builder.AddTypedTextChunk("this");
2061 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
2062}
2063
2065 ResultBuilder &Results,
2066 const LangOptions &LangOpts) {
2067 if (!LangOpts.CPlusPlus11)
2068 return;
2069
2070 Builder.AddTypedTextChunk("static_assert");
2071 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2072 Builder.AddPlaceholderChunk("expression");
2073 Builder.AddChunk(CodeCompletionString::CK_Comma);
2074 Builder.AddPlaceholderChunk("message");
2075 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2076 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2077 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
2078}
2079
2080static void AddOverrideResults(ResultBuilder &Results,
2081 const CodeCompletionContext &CCContext,
2082 CodeCompletionBuilder &Builder) {
2083 Sema &S = Results.getSema();
2084 const auto *CR = llvm::dyn_cast<CXXRecordDecl>(S.CurContext);
2085 // If not inside a class/struct/union return empty.
2086 if (!CR)
2087 return;
2088 // First store overrides within current class.
2089 // These are stored by name to make querying fast in the later step.
2090 llvm::StringMap<std::vector<FunctionDecl *>> Overrides;
2091 for (auto *Method : CR->methods()) {
2092 if (!Method->isVirtual() || !Method->getIdentifier())
2093 continue;
2094 Overrides[Method->getName()].push_back(Method);
2095 }
2096
2097 for (const auto &Base : CR->bases()) {
2098 const auto *BR = Base.getType().getTypePtr()->getAsCXXRecordDecl();
2099 if (!BR)
2100 continue;
2101 for (auto *Method : BR->methods()) {
2102 if (!Method->isVirtual() || !Method->getIdentifier())
2103 continue;
2104 const auto it = Overrides.find(Method->getName());
2105 bool IsOverriden = false;
2106 if (it != Overrides.end()) {
2107 for (auto *MD : it->second) {
2108 // If the method in current body is not an overload of this virtual
2109 // function, then it overrides this one.
2110 if (!S.IsOverload(MD, Method, false)) {
2111 IsOverriden = true;
2112 break;
2113 }
2114 }
2115 }
2116 if (!IsOverriden) {
2117 // Generates a new CodeCompletionResult by taking this function and
2118 // converting it into an override declaration with only one chunk in the
2119 // final CodeCompletionString as a TypedTextChunk.
2120 std::string OverrideSignature;
2121 llvm::raw_string_ostream OS(OverrideSignature);
2122 CodeCompletionResult CCR(Method, 0);
2123 PrintingPolicy Policy =
2126 S.getPreprocessor(), S.getASTContext(), Builder,
2127 /*IncludeBriefComments=*/false, CCContext, Policy);
2128 Results.AddResult(CodeCompletionResult(CCS, Method, CCP_CodePattern));
2129 }
2130 }
2131 }
2132}
2133
2134/// Add language constructs that show up for "ordinary" names.
2135static void
2137 Scope *S, Sema &SemaRef, ResultBuilder &Results) {
2138 CodeCompletionAllocator &Allocator = Results.getAllocator();
2139 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
2140
2142 switch (CCC) {
2144 if (SemaRef.getLangOpts().CPlusPlus) {
2145 if (Results.includeCodePatterns()) {
2146 // namespace <identifier> { declarations }
2147 Builder.AddTypedTextChunk("namespace");
2149 Builder.AddPlaceholderChunk("identifier");
2151 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
2153 Builder.AddPlaceholderChunk("declarations");
2155 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
2156 Results.AddResult(Result(Builder.TakeString()));
2157 }
2158
2159 // namespace identifier = identifier ;
2160 Builder.AddTypedTextChunk("namespace");
2162 Builder.AddPlaceholderChunk("name");
2163 Builder.AddChunk(CodeCompletionString::CK_Equal);
2164 Builder.AddPlaceholderChunk("namespace");
2165 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2166 Results.AddResult(Result(Builder.TakeString()));
2167
2168 // Using directives
2169 Builder.AddTypedTextChunk("using namespace");
2171 Builder.AddPlaceholderChunk("identifier");
2172 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2173 Results.AddResult(Result(Builder.TakeString()));
2174
2175 // asm(string-literal)
2176 Builder.AddTypedTextChunk("asm");
2177 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2178 Builder.AddPlaceholderChunk("string-literal");
2179 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2180 Results.AddResult(Result(Builder.TakeString()));
2181
2182 if (Results.includeCodePatterns()) {
2183 // Explicit template instantiation
2184 Builder.AddTypedTextChunk("template");
2186 Builder.AddPlaceholderChunk("declaration");
2187 Results.AddResult(Result(Builder.TakeString()));
2188 } else {
2189 Results.AddResult(Result("template", CodeCompletionResult::RK_Keyword));
2190 }
2191 }
2192
2193 if (SemaRef.getLangOpts().ObjC)
2194 AddObjCTopLevelResults(Results, true);
2195
2196 AddTypedefResult(Results);
2197 [[fallthrough]];
2198
2200 if (SemaRef.getLangOpts().CPlusPlus) {
2201 // Using declaration
2202 Builder.AddTypedTextChunk("using");
2204 Builder.AddPlaceholderChunk("qualifier");
2205 Builder.AddTextChunk("::");
2206 Builder.AddPlaceholderChunk("name");
2207 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2208 Results.AddResult(Result(Builder.TakeString()));
2209
2210 if (SemaRef.getLangOpts().CPlusPlus11)
2211 AddUsingAliasResult(Builder, Results);
2212
2213 // using typename qualifier::name (only in a dependent context)
2214 if (SemaRef.CurContext->isDependentContext()) {
2215 Builder.AddTypedTextChunk("using typename");
2217 Builder.AddPlaceholderChunk("qualifier");
2218 Builder.AddTextChunk("::");
2219 Builder.AddPlaceholderChunk("name");
2220 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2221 Results.AddResult(Result(Builder.TakeString()));
2222 }
2223
2224 AddStaticAssertResult(Builder, Results, SemaRef.getLangOpts());
2225
2226 if (CCC == SemaCodeCompletion::PCC_Class) {
2227 AddTypedefResult(Results);
2228
2229 bool IsNotInheritanceScope = !S->isClassInheritanceScope();
2230 // public:
2231 Builder.AddTypedTextChunk("public");
2232 if (IsNotInheritanceScope && Results.includeCodePatterns())
2233 Builder.AddChunk(CodeCompletionString::CK_Colon);
2234 Results.AddResult(Result(Builder.TakeString()));
2235
2236 // protected:
2237 Builder.AddTypedTextChunk("protected");
2238 if (IsNotInheritanceScope && Results.includeCodePatterns())
2239 Builder.AddChunk(CodeCompletionString::CK_Colon);
2240 Results.AddResult(Result(Builder.TakeString()));
2241
2242 // private:
2243 Builder.AddTypedTextChunk("private");
2244 if (IsNotInheritanceScope && Results.includeCodePatterns())
2245 Builder.AddChunk(CodeCompletionString::CK_Colon);
2246 Results.AddResult(Result(Builder.TakeString()));
2247
2248 // FIXME: This adds override results only if we are at the first word of
2249 // the declaration/definition. Also call this from other sides to have
2250 // more use-cases.
2252 Builder);
2253 }
2254 }
2255 [[fallthrough]];
2256
2259 if (SemaRef.getLangOpts().CPlusPlus && Results.includeCodePatterns()) {
2260 // template < parameters >
2261 Builder.AddTypedTextChunk("template");
2262 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
2263 Builder.AddPlaceholderChunk("parameters");
2264 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
2265 Results.AddResult(Result(Builder.TakeString()));
2266 } else {
2267 Results.AddResult(Result("template", CodeCompletionResult::RK_Keyword));
2268 }
2269
2270 AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
2271 AddFunctionSpecifiers(CCC, SemaRef.getLangOpts(), Results);
2272 break;
2273
2275 AddObjCInterfaceResults(SemaRef.getLangOpts(), Results, true);
2276 AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
2277 AddFunctionSpecifiers(CCC, SemaRef.getLangOpts(), Results);
2278 break;
2279
2281 AddObjCImplementationResults(SemaRef.getLangOpts(), Results, true);
2282 AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
2283 AddFunctionSpecifiers(CCC, SemaRef.getLangOpts(), Results);
2284 break;
2285
2287 AddObjCVisibilityResults(SemaRef.getLangOpts(), Results, true);
2288 break;
2289
2293 if (SemaRef.getLangOpts().CPlusPlus11)
2294 AddUsingAliasResult(Builder, Results);
2295
2296 AddTypedefResult(Results);
2297
2298 if (SemaRef.getLangOpts().CPlusPlus && Results.includeCodePatterns() &&
2299 SemaRef.getLangOpts().CXXExceptions) {
2300 Builder.AddTypedTextChunk("try");
2302 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
2304 Builder.AddPlaceholderChunk("statements");
2306 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
2308 Builder.AddTextChunk("catch");
2310 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2311 Builder.AddPlaceholderChunk("declaration");
2312 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2314 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
2316 Builder.AddPlaceholderChunk("statements");
2318 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
2319 Results.AddResult(Result(Builder.TakeString()));
2320 }
2321 if (SemaRef.getLangOpts().ObjC)
2322 AddObjCStatementResults(Results, true);
2323
2324 if (Results.includeCodePatterns()) {
2325 // if (condition) { statements }
2326 Builder.AddTypedTextChunk("if");
2328 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2329 if (SemaRef.getLangOpts().CPlusPlus)
2330 Builder.AddPlaceholderChunk("condition");
2331 else
2332 Builder.AddPlaceholderChunk("expression");
2333 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2335 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
2337 Builder.AddPlaceholderChunk("statements");
2339 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
2340 Results.AddResult(Result(Builder.TakeString()));
2341
2342 // switch (condition) { }
2343 Builder.AddTypedTextChunk("switch");
2345 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2346 if (SemaRef.getLangOpts().CPlusPlus)
2347 Builder.AddPlaceholderChunk("condition");
2348 else
2349 Builder.AddPlaceholderChunk("expression");
2350 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2352 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
2354 Builder.AddPlaceholderChunk("cases");
2356 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
2357 Results.AddResult(Result(Builder.TakeString()));
2358 }
2359
2360 // Switch-specific statements.
2361 if (SemaRef.getCurFunction() &&
2362 !SemaRef.getCurFunction()->SwitchStack.empty()) {
2363 // case expression:
2364 Builder.AddTypedTextChunk("case");
2366 Builder.AddPlaceholderChunk("expression");
2367 Builder.AddChunk(CodeCompletionString::CK_Colon);
2368 Results.AddResult(Result(Builder.TakeString()));
2369
2370 // default:
2371 Builder.AddTypedTextChunk("default");
2372 Builder.AddChunk(CodeCompletionString::CK_Colon);
2373 Results.AddResult(Result(Builder.TakeString()));
2374 }
2375
2376 if (Results.includeCodePatterns()) {
2377 /// while (condition) { statements }
2378 Builder.AddTypedTextChunk("while");
2380 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2381 if (SemaRef.getLangOpts().CPlusPlus)
2382 Builder.AddPlaceholderChunk("condition");
2383 else
2384 Builder.AddPlaceholderChunk("expression");
2385 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2387 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
2389 Builder.AddPlaceholderChunk("statements");
2391 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
2392 Results.AddResult(Result(Builder.TakeString()));
2393
2394 // do { statements } while ( expression );
2395 Builder.AddTypedTextChunk("do");
2397 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
2399 Builder.AddPlaceholderChunk("statements");
2401 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
2402 Builder.AddTextChunk("while");
2404 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2405 Builder.AddPlaceholderChunk("expression");
2406 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2407 Results.AddResult(Result(Builder.TakeString()));
2408
2409 // for ( for-init-statement ; condition ; expression ) { statements }
2410 Builder.AddTypedTextChunk("for");
2412 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2413 if (SemaRef.getLangOpts().CPlusPlus || SemaRef.getLangOpts().C99)
2414 Builder.AddPlaceholderChunk("init-statement");
2415 else
2416 Builder.AddPlaceholderChunk("init-expression");
2417 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2419 Builder.AddPlaceholderChunk("condition");
2420 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2422 Builder.AddPlaceholderChunk("inc-expression");
2423 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2425 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
2427 Builder.AddPlaceholderChunk("statements");
2429 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
2430 Results.AddResult(Result(Builder.TakeString()));
2431
2432 if (SemaRef.getLangOpts().CPlusPlus11 || SemaRef.getLangOpts().ObjC) {
2433 // for ( range_declaration (:|in) range_expression ) { statements }
2434 Builder.AddTypedTextChunk("for");
2436 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2437 Builder.AddPlaceholderChunk("range-declaration");
2439 if (SemaRef.getLangOpts().ObjC)
2440 Builder.AddTextChunk("in");
2441 else
2442 Builder.AddChunk(CodeCompletionString::CK_Colon);
2444 Builder.AddPlaceholderChunk("range-expression");
2445 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2447 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
2449 Builder.AddPlaceholderChunk("statements");
2451 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
2452 Results.AddResult(Result(Builder.TakeString()));
2453 }
2454 }
2455
2456 if (S->getContinueParent()) {
2457 // continue ;
2458 Builder.AddTypedTextChunk("continue");
2459 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2460 Results.AddResult(Result(Builder.TakeString()));
2461 }
2462
2463 if (S->getBreakParent()) {
2464 // break ;
2465 Builder.AddTypedTextChunk("break");
2466 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2467 Results.AddResult(Result(Builder.TakeString()));
2468 }
2469
2470 // "return expression ;" or "return ;", depending on the return type.
2471 QualType ReturnType;
2472 if (const auto *Function = dyn_cast<FunctionDecl>(SemaRef.CurContext))
2473 ReturnType = Function->getReturnType();
2474 else if (const auto *Method = dyn_cast<ObjCMethodDecl>(SemaRef.CurContext))
2475 ReturnType = Method->getReturnType();
2476 else if (SemaRef.getCurBlock() &&
2477 !SemaRef.getCurBlock()->ReturnType.isNull())
2478 ReturnType = SemaRef.getCurBlock()->ReturnType;;
2479 if (ReturnType.isNull() || ReturnType->isVoidType()) {
2480 Builder.AddTypedTextChunk("return");
2481 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2482 Results.AddResult(Result(Builder.TakeString()));
2483 } else {
2484 assert(!ReturnType.isNull());
2485 // "return expression ;"
2486 Builder.AddTypedTextChunk("return");
2488 Builder.AddPlaceholderChunk("expression");
2489 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2490 Results.AddResult(Result(Builder.TakeString()));
2491 // When boolean, also add 'return true;' and 'return false;'.
2492 if (ReturnType->isBooleanType()) {
2493 Builder.AddTypedTextChunk("return true");
2494 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2495 Results.AddResult(Result(Builder.TakeString()));
2496
2497 Builder.AddTypedTextChunk("return false");
2498 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2499 Results.AddResult(Result(Builder.TakeString()));
2500 }
2501 // For pointers, suggest 'return nullptr' in C++.
2502 if (SemaRef.getLangOpts().CPlusPlus11 &&
2503 (ReturnType->isPointerType() || ReturnType->isMemberPointerType())) {
2504 Builder.AddTypedTextChunk("return nullptr");
2505 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2506 Results.AddResult(Result(Builder.TakeString()));
2507 }
2508 }
2509
2510 // goto identifier ;
2511 Builder.AddTypedTextChunk("goto");
2513 Builder.AddPlaceholderChunk("label");
2514 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2515 Results.AddResult(Result(Builder.TakeString()));
2516
2517 // Using directives
2518 Builder.AddTypedTextChunk("using namespace");
2520 Builder.AddPlaceholderChunk("identifier");
2521 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2522 Results.AddResult(Result(Builder.TakeString()));
2523
2524 AddStaticAssertResult(Builder, Results, SemaRef.getLangOpts());
2525 }
2526 [[fallthrough]];
2527
2528 // Fall through (for statement expressions).
2531 AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
2532 // Fall through: conditions and statements can have expressions.
2533 [[fallthrough]];
2534
2536 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
2538 // (__bridge <type>)<expression>
2539 Builder.AddTypedTextChunk("__bridge");
2541 Builder.AddPlaceholderChunk("type");
2542 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2543 Builder.AddPlaceholderChunk("expression");
2544 Results.AddResult(Result(Builder.TakeString()));
2545
2546 // (__bridge_transfer <Objective-C type>)<expression>
2547 Builder.AddTypedTextChunk("__bridge_transfer");
2549 Builder.AddPlaceholderChunk("Objective-C type");
2550 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2551 Builder.AddPlaceholderChunk("expression");
2552 Results.AddResult(Result(Builder.TakeString()));
2553
2554 // (__bridge_retained <CF type>)<expression>
2555 Builder.AddTypedTextChunk("__bridge_retained");
2557 Builder.AddPlaceholderChunk("CF type");
2558 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2559 Builder.AddPlaceholderChunk("expression");
2560 Results.AddResult(Result(Builder.TakeString()));
2561 }
2562 // Fall through
2563 [[fallthrough]];
2564
2566 if (SemaRef.getLangOpts().CPlusPlus) {
2567 // 'this', if we're in a non-static member function.
2568 addThisCompletion(SemaRef, Results);
2569
2570 // true
2571 Builder.AddResultTypeChunk("bool");
2572 Builder.AddTypedTextChunk("true");
2573 Results.AddResult(Result(Builder.TakeString()));
2574
2575 // false
2576 Builder.AddResultTypeChunk("bool");
2577 Builder.AddTypedTextChunk("false");
2578 Results.AddResult(Result(Builder.TakeString()));
2579
2580 if (SemaRef.getLangOpts().RTTI) {
2581 // dynamic_cast < type-id > ( expression )
2582 Builder.AddTypedTextChunk("dynamic_cast");
2583 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
2584 Builder.AddPlaceholderChunk("type");
2585 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
2586 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2587 Builder.AddPlaceholderChunk("expression");
2588 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2589 Results.AddResult(Result(Builder.TakeString()));
2590 }
2591
2592 // static_cast < type-id > ( expression )
2593 Builder.AddTypedTextChunk("static_cast");
2594 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
2595 Builder.AddPlaceholderChunk("type");
2596 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
2597 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2598 Builder.AddPlaceholderChunk("expression");
2599 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2600 Results.AddResult(Result(Builder.TakeString()));
2601
2602 // reinterpret_cast < type-id > ( expression )
2603 Builder.AddTypedTextChunk("reinterpret_cast");
2604 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
2605 Builder.AddPlaceholderChunk("type");
2606 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
2607 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2608 Builder.AddPlaceholderChunk("expression");
2609 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2610 Results.AddResult(Result(Builder.TakeString()));
2611
2612 // const_cast < type-id > ( expression )
2613 Builder.AddTypedTextChunk("const_cast");
2614 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
2615 Builder.AddPlaceholderChunk("type");
2616 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
2617 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2618 Builder.AddPlaceholderChunk("expression");
2619 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2620 Results.AddResult(Result(Builder.TakeString()));
2621
2622 if (SemaRef.getLangOpts().RTTI) {
2623 // typeid ( expression-or-type )
2624 Builder.AddResultTypeChunk("std::type_info");
2625 Builder.AddTypedTextChunk("typeid");
2626 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2627 Builder.AddPlaceholderChunk("expression-or-type");
2628 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2629 Results.AddResult(Result(Builder.TakeString()));
2630 }
2631
2632 // new T ( ... )
2633 Builder.AddTypedTextChunk("new");
2635 Builder.AddPlaceholderChunk("type");
2636 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2637 Builder.AddPlaceholderChunk("expressions");
2638 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2639 Results.AddResult(Result(Builder.TakeString()));
2640
2641 // new T [ ] ( ... )
2642 Builder.AddTypedTextChunk("new");
2644 Builder.AddPlaceholderChunk("type");
2645 Builder.AddChunk(CodeCompletionString::CK_LeftBracket);
2646 Builder.AddPlaceholderChunk("size");
2647 Builder.AddChunk(CodeCompletionString::CK_RightBracket);
2648 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2649 Builder.AddPlaceholderChunk("expressions");
2650 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2651 Results.AddResult(Result(Builder.TakeString()));
2652
2653 // delete expression
2654 Builder.AddResultTypeChunk("void");
2655 Builder.AddTypedTextChunk("delete");
2657 Builder.AddPlaceholderChunk("expression");
2658 Results.AddResult(Result(Builder.TakeString()));
2659
2660 // delete [] expression
2661 Builder.AddResultTypeChunk("void");
2662 Builder.AddTypedTextChunk("delete");
2664 Builder.AddChunk(CodeCompletionString::CK_LeftBracket);
2665 Builder.AddChunk(CodeCompletionString::CK_RightBracket);
2667 Builder.AddPlaceholderChunk("expression");
2668 Results.AddResult(Result(Builder.TakeString()));
2669
2670 if (SemaRef.getLangOpts().CXXExceptions) {
2671 // throw expression
2672 Builder.AddResultTypeChunk("void");
2673 Builder.AddTypedTextChunk("throw");
2675 Builder.AddPlaceholderChunk("expression");
2676 Results.AddResult(Result(Builder.TakeString()));
2677 }
2678
2679 // FIXME: Rethrow?
2680
2681 if (SemaRef.getLangOpts().CPlusPlus11) {
2682 // nullptr
2683 Builder.AddResultTypeChunk("std::nullptr_t");
2684 Builder.AddTypedTextChunk("nullptr");
2685 Results.AddResult(Result(Builder.TakeString()));
2686
2687 // alignof
2688 Builder.AddResultTypeChunk("size_t");
2689 Builder.AddTypedTextChunk("alignof");
2690 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2691 Builder.AddPlaceholderChunk("type");
2692 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2693 Results.AddResult(Result(Builder.TakeString()));
2694
2695 // noexcept
2696 Builder.AddResultTypeChunk("bool");
2697 Builder.AddTypedTextChunk("noexcept");
2698 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2699 Builder.AddPlaceholderChunk("expression");
2700 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2701 Results.AddResult(Result(Builder.TakeString()));
2702
2703 // sizeof... expression
2704 Builder.AddResultTypeChunk("size_t");
2705 Builder.AddTypedTextChunk("sizeof...");
2706 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2707 Builder.AddPlaceholderChunk("parameter-pack");
2708 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2709 Results.AddResult(Result(Builder.TakeString()));
2710 }
2711 }
2712
2713 if (SemaRef.getLangOpts().ObjC) {
2714 // Add "super", if we're in an Objective-C class with a superclass.
2715 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
2716 // The interface can be NULL.
2717 if (ObjCInterfaceDecl *ID = Method->getClassInterface())
2718 if (ID->getSuperClass()) {
2719 std::string SuperType;
2720 SuperType = ID->getSuperClass()->getNameAsString();
2721 if (Method->isInstanceMethod())
2722 SuperType += " *";
2723
2724 Builder.AddResultTypeChunk(Allocator.CopyString(SuperType));
2725 Builder.AddTypedTextChunk("super");
2726 Results.AddResult(Result(Builder.TakeString()));
2727 }
2728 }
2729
2730 AddObjCExpressionResults(Results, true);
2731 }
2732
2733 if (SemaRef.getLangOpts().C11) {
2734 // _Alignof
2735 Builder.AddResultTypeChunk("size_t");
2736 if (SemaRef.PP.isMacroDefined("alignof"))
2737 Builder.AddTypedTextChunk("alignof");
2738 else
2739 Builder.AddTypedTextChunk("_Alignof");
2740 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2741 Builder.AddPlaceholderChunk("type");
2742 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2743 Results.AddResult(Result(Builder.TakeString()));
2744 }
2745
2746 if (SemaRef.getLangOpts().C23) {
2747 // nullptr
2748 Builder.AddResultTypeChunk("nullptr_t");
2749 Builder.AddTypedTextChunk("nullptr");
2750 Results.AddResult(Result(Builder.TakeString()));
2751 }
2752
2753 // sizeof expression
2754 Builder.AddResultTypeChunk("size_t");
2755 Builder.AddTypedTextChunk("sizeof");
2756 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2757 Builder.AddPlaceholderChunk("expression-or-type");
2758 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2759 Results.AddResult(Result(Builder.TakeString()));
2760 break;
2761 }
2762
2765 break;
2766 }
2767
2768 if (WantTypesInContext(CCC, SemaRef.getLangOpts()))
2769 AddTypeSpecifierResults(SemaRef.getLangOpts(), Results);
2770
2771 if (SemaRef.getLangOpts().CPlusPlus && CCC != SemaCodeCompletion::PCC_Type)
2772 Results.AddResult(Result("operator"));
2773}
2774
2775/// If the given declaration has an associated type, add it as a result
2776/// type chunk.
2777static void AddResultTypeChunk(ASTContext &Context,
2778 const PrintingPolicy &Policy,
2779 const NamedDecl *ND, QualType BaseType,
2781 if (!ND)
2782 return;
2783
2784 // Skip constructors and conversion functions, which have their return types
2785 // built into their names.
2786 if (isConstructor(ND) || isa<CXXConversionDecl>(ND))
2787 return;
2788
2789 // Determine the type of the declaration (if it has a type).
2790 QualType T;
2791 if (const FunctionDecl *Function = ND->getAsFunction())
2792 T = Function->getReturnType();
2793 else if (const auto *Method = dyn_cast<ObjCMethodDecl>(ND)) {
2794 if (!BaseType.isNull())
2795 T = Method->getSendResultType(BaseType);
2796 else
2797 T = Method->getReturnType();
2798 } else if (const auto *Enumerator = dyn_cast<EnumConstantDecl>(ND)) {
2799 T = Context.getTypeDeclType(cast<TypeDecl>(Enumerator->getDeclContext()));
2801 } else if (isa<UnresolvedUsingValueDecl>(ND)) {
2802 /* Do nothing: ignore unresolved using declarations*/
2803 } else if (const auto *Ivar = dyn_cast<ObjCIvarDecl>(ND)) {
2804 if (!BaseType.isNull())
2805 T = Ivar->getUsageType(BaseType);
2806 else
2807 T = Ivar->getType();
2808 } else if (const auto *Value = dyn_cast<ValueDecl>(ND)) {
2809 T = Value->getType();
2810 } else if (const auto *Property = dyn_cast<ObjCPropertyDecl>(ND)) {
2811 if (!BaseType.isNull())
2812 T = Property->getUsageType(BaseType);
2813 else
2814 T = Property->getType();
2815 }
2816
2817 if (T.isNull() || Context.hasSameType(T, Context.DependentTy))
2818 return;
2819
2820 Result.AddResultTypeChunk(
2821 GetCompletionTypeString(T, Context, Policy, Result.getAllocator()));
2822}
2823
2825 const NamedDecl *FunctionOrMethod,
2827 if (SentinelAttr *Sentinel = FunctionOrMethod->getAttr<SentinelAttr>())
2828 if (Sentinel->getSentinel() == 0) {
2829 if (PP.getLangOpts().ObjC && PP.isMacroDefined("nil"))
2830 Result.AddTextChunk(", nil");
2831 else if (PP.isMacroDefined("NULL"))
2832 Result.AddTextChunk(", NULL");
2833 else
2834 Result.AddTextChunk(", (void*)0");
2835 }
2836}
2837
2838static std::string formatObjCParamQualifiers(unsigned ObjCQuals,
2839 QualType &Type) {
2840 std::string Result;
2841 if (ObjCQuals & Decl::OBJC_TQ_In)
2842 Result += "in ";
2843 else if (ObjCQuals & Decl::OBJC_TQ_Inout)
2844 Result += "inout ";
2845 else if (ObjCQuals & Decl::OBJC_TQ_Out)
2846 Result += "out ";
2847 if (ObjCQuals & Decl::OBJC_TQ_Bycopy)
2848 Result += "bycopy ";
2849 else if (ObjCQuals & Decl::OBJC_TQ_Byref)
2850 Result += "byref ";
2851 if (ObjCQuals & Decl::OBJC_TQ_Oneway)
2852 Result += "oneway ";
2853 if (ObjCQuals & Decl::OBJC_TQ_CSNullability) {
2854 if (auto nullability = AttributedType::stripOuterNullability(Type)) {
2855 switch (*nullability) {
2857 Result += "nonnull ";
2858 break;
2859
2861 Result += "nullable ";
2862 break;
2863
2865 Result += "null_unspecified ";
2866 break;
2867
2869 llvm_unreachable("Not supported as a context-sensitive keyword!");
2870 break;
2871 }
2872 }
2873 }
2874 return Result;
2875}
2876
2877/// Tries to find the most appropriate type location for an Objective-C
2878/// block placeholder.
2879///
2880/// This function ignores things like typedefs and qualifiers in order to
2881/// present the most relevant and accurate block placeholders in code completion
2882/// results.
2885 FunctionProtoTypeLoc &BlockProto,
2886 bool SuppressBlock = false) {
2887 if (!TSInfo)
2888 return;
2889 TypeLoc TL = TSInfo->getTypeLoc().getUnqualifiedLoc();
2890 while (true) {
2891 // Look through typedefs.
2892 if (!SuppressBlock) {
2893 if (TypedefTypeLoc TypedefTL = TL.getAsAdjusted<TypedefTypeLoc>()) {
2894 if (TypeSourceInfo *InnerTSInfo =
2895 TypedefTL.getTypedefNameDecl()->getTypeSourceInfo()) {
2896 TL = InnerTSInfo->getTypeLoc().getUnqualifiedLoc();
2897 continue;
2898 }
2899 }
2900
2901 // Look through qualified types
2902 if (QualifiedTypeLoc QualifiedTL = TL.getAs<QualifiedTypeLoc>()) {
2903 TL = QualifiedTL.getUnqualifiedLoc();
2904 continue;
2905 }
2906
2907 if (AttributedTypeLoc AttrTL = TL.getAs<AttributedTypeLoc>()) {
2908 TL = AttrTL.getModifiedLoc();
2909 continue;
2910 }
2911 }
2912
2913 // Try to get the function prototype behind the block pointer type,
2914 // then we're done.
2915 if (BlockPointerTypeLoc BlockPtr = TL.getAs<BlockPointerTypeLoc>()) {
2916 TL = BlockPtr.getPointeeLoc().IgnoreParens();
2917 Block = TL.getAs<FunctionTypeLoc>();
2918 BlockProto = TL.getAs<FunctionProtoTypeLoc>();
2919 }
2920 break;
2921 }
2922}
2923
2924static std::string formatBlockPlaceholder(
2925 const PrintingPolicy &Policy, const NamedDecl *BlockDecl,
2927 bool SuppressBlockName = false, bool SuppressBlock = false,
2928 std::optional<ArrayRef<QualType>> ObjCSubsts = std::nullopt);
2929
2930static std::string FormatFunctionParameter(
2931 const PrintingPolicy &Policy, const DeclaratorDecl *Param,
2932 bool SuppressName = false, bool SuppressBlock = false,
2933 std::optional<ArrayRef<QualType>> ObjCSubsts = std::nullopt) {
2934 // Params are unavailable in FunctionTypeLoc if the FunctionType is invalid.
2935 // It would be better to pass in the param Type, which is usually available.
2936 // But this case is rare, so just pretend we fell back to int as elsewhere.
2937 if (!Param)
2938 return "int";
2940 if (const auto *PVD = dyn_cast<ParmVarDecl>(Param))
2941 ObjCQual = PVD->getObjCDeclQualifier();
2942 bool ObjCMethodParam = isa<ObjCMethodDecl>(Param->getDeclContext());
2943 if (Param->getType()->isDependentType() ||
2944 !Param->getType()->isBlockPointerType()) {
2945 // The argument for a dependent or non-block parameter is a placeholder
2946 // containing that parameter's type.
2947 std::string Result;
2948
2949 if (Param->getIdentifier() && !ObjCMethodParam && !SuppressName)
2950 Result = std::string(Param->getIdentifier()->deuglifiedName());
2951
2952 QualType Type = Param->getType();
2953 if (ObjCSubsts)
2954 Type = Type.substObjCTypeArgs(Param->getASTContext(), *ObjCSubsts,
2956 if (ObjCMethodParam) {
2957 Result = "(" + formatObjCParamQualifiers(ObjCQual, Type);
2958 Result += Type.getAsString(Policy) + ")";
2959 if (Param->getIdentifier() && !SuppressName)
2960 Result += Param->getIdentifier()->deuglifiedName();
2961 } else {
2962 Type.getAsStringInternal(Result, Policy);
2963 }
2964 return Result;
2965 }
2966
2967 // The argument for a block pointer parameter is a block literal with
2968 // the appropriate type.
2970 FunctionProtoTypeLoc BlockProto;
2972 SuppressBlock);
2973 // Try to retrieve the block type information from the property if this is a
2974 // parameter in a setter.
2975 if (!Block && ObjCMethodParam &&
2976 cast<ObjCMethodDecl>(Param->getDeclContext())->isPropertyAccessor()) {
2977 if (const auto *PD = cast<ObjCMethodDecl>(Param->getDeclContext())
2978 ->findPropertyDecl(/*CheckOverrides=*/false))
2979 findTypeLocationForBlockDecl(PD->getTypeSourceInfo(), Block, BlockProto,
2980 SuppressBlock);
2981 }
2982
2983 if (!Block) {
2984 // We were unable to find a FunctionProtoTypeLoc with parameter names
2985 // for the block; just use the parameter type as a placeholder.
2986 std::string Result;
2987 if (!ObjCMethodParam && Param->getIdentifier())
2988 Result = std::string(Param->getIdentifier()->deuglifiedName());
2989
2991
2992 if (ObjCMethodParam) {
2993 Result = Type.getAsString(Policy);
2994 std::string Quals = formatObjCParamQualifiers(ObjCQual, Type);
2995 if (!Quals.empty())
2996 Result = "(" + Quals + " " + Result + ")";
2997 if (Result.back() != ')')
2998 Result += " ";
2999 if (Param->getIdentifier())
3000 Result += Param->getIdentifier()->deuglifiedName();
3001 } else {
3002 Type.getAsStringInternal(Result, Policy);
3003 }
3004
3005 return Result;
3006 }
3007
3008 // We have the function prototype behind the block pointer type, as it was
3009 // written in the source.
3010 return formatBlockPlaceholder(Policy, Param, Block, BlockProto,
3011 /*SuppressBlockName=*/false, SuppressBlock,
3012 ObjCSubsts);
3013}
3014
3015/// Returns a placeholder string that corresponds to an Objective-C block
3016/// declaration.
3017///
3018/// \param BlockDecl A declaration with an Objective-C block type.
3019///
3020/// \param Block The most relevant type location for that block type.
3021///
3022/// \param SuppressBlockName Determines whether or not the name of the block
3023/// declaration is included in the resulting string.
3024static std::string
3027 bool SuppressBlockName, bool SuppressBlock,
3028 std::optional<ArrayRef<QualType>> ObjCSubsts) {
3029 std::string Result;
3030 QualType ResultType = Block.getTypePtr()->getReturnType();
3031 if (ObjCSubsts)
3032 ResultType =
3033 ResultType.substObjCTypeArgs(BlockDecl->getASTContext(), *ObjCSubsts,
3035 if (!ResultType->isVoidType() || SuppressBlock)
3036 ResultType.getAsStringInternal(Result, Policy);
3037
3038 // Format the parameter list.
3039 std::string Params;
3040 if (!BlockProto || Block.getNumParams() == 0) {
3041 if (BlockProto && BlockProto.getTypePtr()->isVariadic())
3042 Params = "(...)";
3043 else
3044 Params = "(void)";
3045 } else {
3046 Params += "(";
3047 for (unsigned I = 0, N = Block.getNumParams(); I != N; ++I) {
3048 if (I)
3049 Params += ", ";
3050 Params += FormatFunctionParameter(Policy, Block.getParam(I),
3051 /*SuppressName=*/false,
3052 /*SuppressBlock=*/true, ObjCSubsts);
3053
3054 if (I == N - 1 && BlockProto.getTypePtr()->isVariadic())
3055 Params += ", ...";
3056 }
3057 Params += ")";
3058 }
3059
3060 if (SuppressBlock) {
3061 // Format as a parameter.
3062 Result = Result + " (^";
3063 if (!SuppressBlockName && BlockDecl->getIdentifier())
3064 Result += BlockDecl->getIdentifier()->getName();
3065 Result += ")";
3066 Result += Params;
3067 } else {
3068 // Format as a block literal argument.
3069 Result = '^' + Result;
3070 Result += Params;
3071
3072 if (!SuppressBlockName && BlockDecl->getIdentifier())
3073 Result += BlockDecl->getIdentifier()->getName();
3074 }
3075
3076 return Result;
3077}
3078
3079static std::string GetDefaultValueString(const ParmVarDecl *Param,
3080 const SourceManager &SM,
3081 const LangOptions &LangOpts) {
3082 const SourceRange SrcRange = Param->getDefaultArgRange();
3083 CharSourceRange CharSrcRange = CharSourceRange::getTokenRange(SrcRange);
3084 bool Invalid = CharSrcRange.isInvalid();
3085 if (Invalid)
3086 return "";
3087 StringRef srcText =
3088 Lexer::getSourceText(CharSrcRange, SM, LangOpts, &Invalid);
3089 if (Invalid)
3090 return "";
3091
3092 if (srcText.empty() || srcText == "=") {
3093 // Lexer can't determine the value.
3094 // This happens if the code is incorrect (for example class is forward
3095 // declared).
3096 return "";
3097 }
3098 std::string DefValue(srcText.str());
3099 // FIXME: remove this check if the Lexer::getSourceText value is fixed and
3100 // this value always has (or always does not have) '=' in front of it
3101 if (DefValue.at(0) != '=') {
3102 // If we don't have '=' in front of value.
3103 // Lexer returns built-in types values without '=' and user-defined types
3104 // values with it.
3105 return " = " + DefValue;
3106 }
3107 return " " + DefValue;
3108}
3109
3110/// Add function parameter chunks to the given code completion string.
3112 const PrintingPolicy &Policy,
3113 const FunctionDecl *Function,
3115 unsigned Start = 0,
3116 bool InOptional = false) {
3117 bool FirstParameter = true;
3118
3119 for (unsigned P = Start, N = Function->getNumParams(); P != N; ++P) {
3120 const ParmVarDecl *Param = Function->getParamDecl(P);
3121
3122 if (Param->hasDefaultArg() && !InOptional) {
3123 // When we see an optional default argument, put that argument and
3124 // the remaining default arguments into a new, optional string.
3125 CodeCompletionBuilder Opt(Result.getAllocator(),
3126 Result.getCodeCompletionTUInfo());
3127 if (!FirstParameter)
3129 AddFunctionParameterChunks(PP, Policy, Function, Opt, P, true);
3130 Result.AddOptionalChunk(Opt.TakeString());
3131 break;
3132 }
3133
3134 if (FirstParameter)
3135 FirstParameter = false;
3136 else
3138
3139 InOptional = false;
3140
3141 // Format the placeholder string.
3142 std::string PlaceholderStr = FormatFunctionParameter(Policy, Param);
3143 if (Param->hasDefaultArg())
3144 PlaceholderStr +=
3146
3147 if (Function->isVariadic() && P == N - 1)
3148 PlaceholderStr += ", ...";
3149
3150 // Add the placeholder string.
3151 Result.AddPlaceholderChunk(
3152 Result.getAllocator().CopyString(PlaceholderStr));
3153 }
3154
3155 if (const auto *Proto = Function->getType()->getAs<FunctionProtoType>())
3156 if (Proto->isVariadic()) {
3157 if (Proto->getNumParams() == 0)
3158 Result.AddPlaceholderChunk("...");
3159
3161 }
3162}
3163
3164/// Add template parameter chunks to the given code completion string.
3166 ASTContext &Context, const PrintingPolicy &Policy,
3167 const TemplateDecl *Template, CodeCompletionBuilder &Result,
3168 unsigned MaxParameters = 0, unsigned Start = 0, bool InDefaultArg = false) {
3169 bool FirstParameter = true;
3170
3171 // Prefer to take the template parameter names from the first declaration of
3172 // the template.
3173 Template = cast<TemplateDecl>(Template->getCanonicalDecl());
3174
3175 TemplateParameterList *Params = Template->getTemplateParameters();
3176 TemplateParameterList::iterator PEnd = Params->end();
3177 if (MaxParameters)
3178 PEnd = Params->begin() + MaxParameters;
3179 for (TemplateParameterList::iterator P = Params->begin() + Start; P != PEnd;
3180 ++P) {
3181 bool HasDefaultArg = false;
3182 std::string PlaceholderStr;
3183 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
3184 if (TTP->wasDeclaredWithTypename())
3185 PlaceholderStr = "typename";
3186 else if (const auto *TC = TTP->getTypeConstraint()) {
3187 llvm::raw_string_ostream OS(PlaceholderStr);
3188 TC->print(OS, Policy);
3189 OS.flush();
3190 } else
3191 PlaceholderStr = "class";
3192
3193 if (TTP->getIdentifier()) {
3194 PlaceholderStr += ' ';
3195 PlaceholderStr += TTP->getIdentifier()->deuglifiedName();
3196 }
3197
3198 HasDefaultArg = TTP->hasDefaultArgument();
3199 } else if (NonTypeTemplateParmDecl *NTTP =
3200 dyn_cast<NonTypeTemplateParmDecl>(*P)) {
3201 if (NTTP->getIdentifier())
3202 PlaceholderStr = std::string(NTTP->getIdentifier()->deuglifiedName());
3203 NTTP->getType().getAsStringInternal(PlaceholderStr, Policy);
3204 HasDefaultArg = NTTP->hasDefaultArgument();
3205 } else {
3206 assert(isa<TemplateTemplateParmDecl>(*P));
3207 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
3208
3209 // Since putting the template argument list into the placeholder would
3210 // be very, very long, we just use an abbreviation.
3211 PlaceholderStr = "template<...> class";
3212 if (TTP->getIdentifier()) {
3213 PlaceholderStr += ' ';
3214 PlaceholderStr += TTP->getIdentifier()->deuglifiedName();
3215 }
3216
3217 HasDefaultArg = TTP->hasDefaultArgument();
3218 }
3219
3220 if (HasDefaultArg && !InDefaultArg) {
3221 // When we see an optional default argument, put that argument and
3222 // the remaining default arguments into a new, optional string.
3223 CodeCompletionBuilder Opt(Result.getAllocator(),
3224 Result.getCodeCompletionTUInfo());
3225 if (!FirstParameter)
3227 AddTemplateParameterChunks(Context, Policy, Template, Opt, MaxParameters,
3228 P - Params->begin(), true);
3229 Result.AddOptionalChunk(Opt.TakeString());
3230 break;
3231 }
3232
3233 InDefaultArg = false;
3234
3235 if (FirstParameter)
3236 FirstParameter = false;
3237 else
3239
3240 // Add the placeholder string.
3241 Result.AddPlaceholderChunk(
3242 Result.getAllocator().CopyString(PlaceholderStr));
3243 }
3244}
3245
3246/// Add a qualifier to the given code-completion string, if the
3247/// provided nested-name-specifier is non-NULL.
3249 NestedNameSpecifier *Qualifier,
3250 bool QualifierIsInformative,
3251 ASTContext &Context,
3252 const PrintingPolicy &Policy) {
3253 if (!Qualifier)
3254 return;
3255
3256 std::string PrintedNNS;
3257 {
3258 llvm::raw_string_ostream OS(PrintedNNS);
3259 Qualifier->print(OS, Policy);
3260 }
3261 if (QualifierIsInformative)
3262 Result.AddInformativeChunk(Result.getAllocator().CopyString(PrintedNNS));
3263 else
3264 Result.AddTextChunk(Result.getAllocator().CopyString(PrintedNNS));
3265}
3266
3267static void
3269 const FunctionDecl *Function) {
3270 const auto *Proto = Function->getType()->getAs<FunctionProtoType>();
3271 if (!Proto || !Proto->getMethodQuals())
3272 return;
3273
3274 // FIXME: Add ref-qualifier!
3275
3276 // Handle single qualifiers without copying
3277 if (Proto->getMethodQuals().hasOnlyConst()) {
3278 Result.AddInformativeChunk(" const");
3279 return;
3280 }
3281
3282 if (Proto->getMethodQuals().hasOnlyVolatile()) {
3283 Result.AddInformativeChunk(" volatile");
3284 return;
3285 }
3286
3287 if (Proto->getMethodQuals().hasOnlyRestrict()) {
3288 Result.AddInformativeChunk(" restrict");
3289 return;
3290 }
3291
3292 // Handle multiple qualifiers.
3293 std::string QualsStr;
3294 if (Proto->isConst())
3295 QualsStr += " const";
3296 if (Proto->isVolatile())
3297 QualsStr += " volatile";
3298 if (Proto->isRestrict())
3299 QualsStr += " restrict";
3300 Result.AddInformativeChunk(Result.getAllocator().CopyString(QualsStr));
3301}
3302
3303/// Add the name of the given declaration
3304static void AddTypedNameChunk(ASTContext &Context, const PrintingPolicy &Policy,
3305 const NamedDecl *ND,
3307 DeclarationName Name = ND->getDeclName();
3308 if (!Name)
3309 return;
3310
3311 switch (Name.getNameKind()) {
3313 const char *OperatorName = nullptr;
3314 switch (Name.getCXXOverloadedOperator()) {
3315 case OO_None:
3316 case OO_Conditional:
3318 OperatorName = "operator";
3319 break;
3320
3321#define OVERLOADED_OPERATOR(Name, Spelling, Token, Unary, Binary, MemberOnly) \
3322 case OO_##Name: \
3323 OperatorName = "operator" Spelling; \
3324 break;
3325#define OVERLOADED_OPERATOR_MULTI(Name, Spelling, Unary, Binary, MemberOnly)
3326#include "clang/Basic/OperatorKinds.def"
3327
3328 case OO_New:
3329 OperatorName = "operator new";
3330 break;
3331 case OO_Delete:
3332 OperatorName = "operator delete";
3333 break;
3334 case OO_Array_New:
3335 OperatorName = "operator new[]";
3336 break;
3337 case OO_Array_Delete:
3338 OperatorName = "operator delete[]";
3339 break;
3340 case OO_Call:
3341 OperatorName = "operator()";
3342 break;
3343 case OO_Subscript:
3344 OperatorName = "operator[]";
3345 break;
3346 }
3347 Result.AddTypedTextChunk(OperatorName);
3348 break;
3349 }
3350
3355 Result.AddTypedTextChunk(
3356 Result.getAllocator().CopyString(ND->getNameAsString()));
3357 break;
3358
3364 break;
3365
3367 CXXRecordDecl *Record = nullptr;
3368 QualType Ty = Name.getCXXNameType();
3369 if (const auto *RecordTy = Ty->getAs<RecordType>())
3370 Record = cast<CXXRecordDecl>(RecordTy->getDecl());
3371 else if (const auto *InjectedTy = Ty->getAs<InjectedClassNameType>())
3372 Record = InjectedTy->getDecl();
3373 else {
3374 Result.AddTypedTextChunk(
3375 Result.getAllocator().CopyString(ND->getNameAsString()));
3376 break;
3377 }
3378
3379 Result.AddTypedTextChunk(
3380 Result.getAllocator().CopyString(Record->getNameAsString()));
3381 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) {
3383 AddTemplateParameterChunks(Context, Policy, Template, Result);
3385 }
3386 break;
3387 }
3388 }
3389}
3390
3392 Sema &S, const CodeCompletionContext &CCContext,
3393 CodeCompletionAllocator &Allocator, CodeCompletionTUInfo &CCTUInfo,
3394 bool IncludeBriefComments) {
3395 return CreateCodeCompletionString(S.Context, S.PP, CCContext, Allocator,
3396 CCTUInfo, IncludeBriefComments);
3397}
3398
3400 Preprocessor &PP, CodeCompletionAllocator &Allocator,
3401 CodeCompletionTUInfo &CCTUInfo) {
3402 assert(Kind == RK_Macro);
3403 CodeCompletionBuilder Result(Allocator, CCTUInfo, Priority, Availability);
3404 const MacroInfo *MI = PP.getMacroInfo(Macro);
3405 Result.AddTypedTextChunk(Result.getAllocator().CopyString(Macro->getName()));
3406
3407 if (!MI || !MI->isFunctionLike())
3408 return Result.TakeString();
3409
3410 // Format a function-like macro with placeholders for the arguments.
3412 MacroInfo::param_iterator A = MI->param_begin(), AEnd = MI->param_end();
3413
3414 // C99 variadic macros add __VA_ARGS__ at the end. Skip it.
3415 if (MI->isC99Varargs()) {
3416 --AEnd;
3417
3418 if (A == AEnd) {
3419 Result.AddPlaceholderChunk("...");
3420 }
3421 }
3422
3423 for (MacroInfo::param_iterator A = MI->param_begin(); A != AEnd; ++A) {
3424 if (A != MI->param_begin())
3426
3427 if (MI->isVariadic() && (A + 1) == AEnd) {
3428 SmallString<32> Arg = (*A)->getName();
3429 if (MI->isC99Varargs())
3430 Arg += ", ...";
3431 else
3432 Arg += "...";
3433 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
3434 break;
3435 }
3436
3437 // Non-variadic macros are simple.
3438 Result.AddPlaceholderChunk(
3439 Result.getAllocator().CopyString((*A)->getName()));
3440 }
3442 return Result.TakeString();
3443}
3444
3445/// If possible, create a new code completion string for the given
3446/// result.
3447///
3448/// \returns Either a new, heap-allocated code completion string describing
3449/// how to use this result, or NULL to indicate that the string or name of the
3450/// result is all that is needed.
3452 ASTContext &Ctx, Preprocessor &PP, const CodeCompletionContext &CCContext,
3453 CodeCompletionAllocator &Allocator, CodeCompletionTUInfo &CCTUInfo,
3454 bool IncludeBriefComments) {
3455 if (Kind == RK_Macro)
3456 return CreateCodeCompletionStringForMacro(PP, Allocator, CCTUInfo);
3457
3458 CodeCompletionBuilder Result(Allocator, CCTUInfo, Priority, Availability);
3459
3461 if (Kind == RK_Pattern) {
3462 Pattern->Priority = Priority;
3463 Pattern->Availability = Availability;
3464
3465 if (Declaration) {
3466 Result.addParentContext(Declaration->getDeclContext());
3467 Pattern->ParentName = Result.getParentName();
3468 if (const RawComment *RC =
3470 Result.addBriefComment(RC->getBriefText(Ctx));
3471 Pattern->BriefComment = Result.getBriefComment();
3472 }
3473 }
3474
3475 return Pattern;
3476 }
3477
3478 if (Kind == RK_Keyword) {
3479 Result.AddTypedTextChunk(Keyword);
3480 return Result.TakeString();
3481 }
3482 assert(Kind == RK_Declaration && "Missed a result kind?");
3484 PP, Ctx, Result, IncludeBriefComments, CCContext, Policy);
3485}
3486
3488 std::string &BeforeName,
3489 std::string &NameAndSignature) {
3490 bool SeenTypedChunk = false;
3491 for (auto &Chunk : CCS) {
3492 if (Chunk.Kind == CodeCompletionString::CK_Optional) {
3493 assert(SeenTypedChunk && "optional parameter before name");
3494 // Note that we put all chunks inside into NameAndSignature.
3495 printOverrideString(*Chunk.Optional, NameAndSignature, NameAndSignature);
3496 continue;
3497 }
3498 SeenTypedChunk |= Chunk.Kind == CodeCompletionString::CK_TypedText;
3499 if (SeenTypedChunk)
3500 NameAndSignature += Chunk.Text;
3501 else
3502 BeforeName += Chunk.Text;
3503 }
3504}
3505
3509 bool IncludeBriefComments, const CodeCompletionContext &CCContext,
3510 PrintingPolicy &Policy) {
3511 auto *CCS = createCodeCompletionStringForDecl(PP, Ctx, Result,
3512 /*IncludeBriefComments=*/false,
3513 CCContext, Policy);
3514 std::string BeforeName;
3515 std::string NameAndSignature;
3516 // For overrides all chunks go into the result, none are informative.
3517 printOverrideString(*CCS, BeforeName, NameAndSignature);
3518 NameAndSignature += " override";
3519
3520 Result.AddTextChunk(Result.getAllocator().CopyString(BeforeName));
3522 Result.AddTypedTextChunk(Result.getAllocator().CopyString(NameAndSignature));
3523 return Result.TakeString();
3524}
3525
3526// FIXME: Right now this works well with lambdas. Add support for other functor
3527// types like std::function.
3529 const auto *VD = dyn_cast<VarDecl>(ND);
3530 if (!VD)
3531 return nullptr;
3532 const auto *RecordDecl = VD->getType()->getAsCXXRecordDecl();
3533 if (!RecordDecl || !RecordDecl->isLambda())
3534 return nullptr;
3535 return RecordDecl->getLambdaCallOperator();
3536}
3537
3540 bool IncludeBriefComments, const CodeCompletionContext &CCContext,
3541 PrintingPolicy &Policy) {
3542 const NamedDecl *ND = Declaration;
3543 Result.addParentContext(ND->getDeclContext());
3544
3545 if (IncludeBriefComments) {
3546 // Add documentation comment, if it exists.
3547 if (const RawComment *RC = getCompletionComment(Ctx, Declaration)) {
3548 Result.addBriefComment(RC->getBriefText(Ctx));
3549 }
3550 }
3551
3553 Result.AddTypedTextChunk(
3554 Result.getAllocator().CopyString(ND->getNameAsString()));
3555 Result.AddTextChunk("::");
3556 return Result.TakeString();
3557 }
3558
3559 for (const auto *I : ND->specific_attrs<AnnotateAttr>())
3560 Result.AddAnnotation(Result.getAllocator().CopyString(I->getAnnotation()));
3561
3562 auto AddFunctionTypeAndResult = [&](const FunctionDecl *Function) {
3563 AddResultTypeChunk(Ctx, Policy, Function, CCContext.getBaseType(), Result);
3565 Ctx, Policy);
3566 AddTypedNameChunk(Ctx, Policy, ND, Result);
3571 };
3572
3573 if (const auto *Function = dyn_cast<FunctionDecl>(ND)) {
3574 AddFunctionTypeAndResult(Function);
3575 return Result.TakeString();
3576 }
3577
3578 if (const auto *CallOperator =
3579 dyn_cast_or_null<FunctionDecl>(extractFunctorCallOperator(ND))) {
3580 AddFunctionTypeAndResult(CallOperator);
3581 return Result.TakeString();
3582 }
3583
3584 AddResultTypeChunk(Ctx, Policy, ND, CCContext.getBaseType(), Result);
3585
3586 if (const FunctionTemplateDecl *FunTmpl =
3587 dyn_cast<FunctionTemplateDecl>(ND)) {
3589 Ctx, Policy);
3590 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
3591 AddTypedNameChunk(Ctx, Policy, Function, Result);
3592
3593 // Figure out which template parameters are deduced (or have default
3594 // arguments).
3595 // Note that we're creating a non-empty bit vector so that we can go
3596 // through the loop below to omit default template parameters for non-call
3597 // cases.
3598 llvm::SmallBitVector Deduced(FunTmpl->getTemplateParameters()->size());
3599 // Avoid running it if this is not a call: We should emit *all* template
3600 // parameters.
3602 Sema::MarkDeducedTemplateParameters(Ctx, FunTmpl, Deduced);
3603 unsigned LastDeducibleArgument;
3604 for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0;
3605 --LastDeducibleArgument) {
3606 if (!Deduced[LastDeducibleArgument - 1]) {
3607 // C++0x: Figure out if the template argument has a default. If so,
3608 // the user doesn't need to type this argument.
3609 // FIXME: We need to abstract template parameters better!
3610 bool HasDefaultArg = false;
3611 NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam(
3612 LastDeducibleArgument - 1);
3613 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
3614 HasDefaultArg = TTP->hasDefaultArgument();
3615 else if (NonTypeTemplateParmDecl *NTTP =
3616 dyn_cast<NonTypeTemplateParmDecl>(Param))
3617 HasDefaultArg = NTTP->hasDefaultArgument();
3618 else {
3619 assert(isa<TemplateTemplateParmDecl>(Param));
3620 HasDefaultArg =
3621 cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument();
3622 }
3623
3624 if (!HasDefaultArg)
3625 break;
3626 }
3627 }
3628
3629 if (LastDeducibleArgument || !FunctionCanBeCall) {
3630 // Some of the function template arguments cannot be deduced from a
3631 // function call, so we introduce an explicit template argument list
3632 // containing all of the arguments up to the first deducible argument.
3633 //
3634 // Or, if this isn't a call, emit all the template arguments
3635 // to disambiguate the (potential) overloads.
3636 //
3637 // FIXME: Detect cases where the function parameters can be deduced from
3638 // the surrounding context, as per [temp.deduct.funcaddr].
3639 // e.g.,
3640 // template <class T> void foo(T);
3641 // void (*f)(int) = foo;
3643 AddTemplateParameterChunks(Ctx, Policy, FunTmpl, Result,
3644 LastDeducibleArgument);
3646 }
3647
3648 // Add the function parameters
3653 return Result.TakeString();
3654 }
3655
3656 if (const auto *Template = dyn_cast<TemplateDecl>(ND)) {
3658 Ctx, Policy);
3659 Result.AddTypedTextChunk(
3660 Result.getAllocator().CopyString(Template->getNameAsString()));
3662 AddTemplateParameterChunks(Ctx, Policy, Template, Result);
3664 return Result.TakeString();
3665 }
3666
3667 if (const auto *Method = dyn_cast<ObjCMethodDecl>(ND)) {
3668 Selector Sel = Method->getSelector();
3669 if (Sel.isUnarySelector()) {
3670 Result.AddTypedTextChunk(
3671 Result.getAllocator().CopyString(Sel.getNameForSlot(0)));
3672 return Result.TakeString();
3673 }
3674
3675 std::string SelName = Sel.getNameForSlot(0).str();
3676 SelName += ':';
3677 if (StartParameter == 0)
3678 Result.AddTypedTextChunk(Result.getAllocator().CopyString(SelName));
3679 else {
3680 Result.AddInformativeChunk(Result.getAllocator().CopyString(SelName));
3681
3682 // If there is only one parameter, and we're past it, add an empty
3683 // typed-text chunk since there is nothing to type.
3684 if (Method->param_size() == 1)
3685 Result.AddTypedTextChunk("");
3686 }
3687 unsigned Idx = 0;
3688 // The extra Idx < Sel.getNumArgs() check is needed due to legacy C-style
3689 // method parameters.
3691 PEnd = Method->param_end();
3692 P != PEnd && Idx < Sel.getNumArgs(); (void)++P, ++Idx) {
3693 if (Idx > 0) {
3694 std::string Keyword;
3695 if (Idx > StartParameter)
3697 if (const IdentifierInfo *II = Sel.getIdentifierInfoForSlot(Idx))
3698 Keyword += II->getName();
3699 Keyword += ":";
3701 Result.AddInformativeChunk(Result.getAllocator().CopyString(Keyword));
3702 else
3703 Result.AddTypedTextChunk(Result.getAllocator().CopyString(Keyword));
3704 }
3705
3706 // If we're before the starting parameter, skip the placeholder.
3707 if (Idx < StartParameter)
3708 continue;
3709
3710 std::string Arg;
3711 QualType ParamType = (*P)->getType();
3712 std::optional<ArrayRef<QualType>> ObjCSubsts;
3713 if (!CCContext.getBaseType().isNull())
3714 ObjCSubsts = CCContext.getBaseType()->getObjCSubstitutions(Method);
3715
3716 if (ParamType->isBlockPointerType() && !DeclaringEntity)
3717 Arg = FormatFunctionParameter(Policy, *P, true,
3718 /*SuppressBlock=*/false, ObjCSubsts);
3719 else {
3720 if (ObjCSubsts)
3721 ParamType = ParamType.substObjCTypeArgs(
3722 Ctx, *ObjCSubsts, ObjCSubstitutionContext::Parameter);
3723 Arg = "(" + formatObjCParamQualifiers((*P)->getObjCDeclQualifier(),
3724 ParamType);
3725 Arg += ParamType.getAsString(Policy) + ")";
3726 if (const IdentifierInfo *II = (*P)->getIdentifier())
3728 Arg += II->getName();
3729 }
3730
3731 if (Method->isVariadic() && (P + 1) == PEnd)
3732 Arg += ", ...";
3733
3734 if (DeclaringEntity)
3735 Result.AddTextChunk(Result.getAllocator().CopyString(Arg));
3737 Result.AddInformativeChunk(Result.getAllocator().CopyString(Arg));
3738 else
3739 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
3740 }
3741
3742 if (Method->isVariadic()) {
3743 if (Method->param_size() == 0) {
3744 if (DeclaringEntity)
3745 Result.AddTextChunk(", ...");
3747 Result.AddInformativeChunk(", ...");
3748 else
3749 Result.AddPlaceholderChunk(", ...");
3750 }
3751
3752 MaybeAddSentinel(PP, Method, Result);
3753 }
3754
3755 return Result.TakeString();
3756 }
3757
3758 if (Qualifier)
3760 Ctx, Policy);
3761
3762 Result.AddTypedTextChunk(
3763 Result.getAllocator().CopyString(ND->getNameAsString()));
3764 return Result.TakeString();
3765}
3766
3768 const NamedDecl *ND) {
3769 if (!ND)
3770 return nullptr;
3771 if (auto *RC = Ctx.getRawCommentForAnyRedecl(ND))
3772 return RC;
3773
3774 // Try to find comment from a property for ObjC methods.
3775 const auto *M = dyn_cast<ObjCMethodDecl>(ND);
3776 if (!M)
3777 return nullptr;
3778 const ObjCPropertyDecl *PDecl = M->findPropertyDecl();
3779 if (!PDecl)
3780 return nullptr;
3781
3782 return Ctx.getRawCommentForAnyRedecl(PDecl);
3783}
3784
3786 const NamedDecl *ND) {
3787 const auto *M = dyn_cast_or_null<ObjCMethodDecl>(ND);
3788 if (!M || !M->isPropertyAccessor())
3789 return nullptr;
3790
3791 // Provide code completion comment for self.GetterName where
3792 // GetterName is the getter method for a property with name
3793 // different from the property name (declared via a property
3794 // getter attribute.
3795 const ObjCPropertyDecl *PDecl = M->findPropertyDecl();
3796 if (!PDecl)
3797 return nullptr;
3798 if (PDecl->getGetterName() == M->getSelector() &&
3799 PDecl->getIdentifier() != M->getIdentifier()) {
3800 if (auto *RC = Ctx.getRawCommentForAnyRedecl(M))
3801 return RC;
3802 if (auto *RC = Ctx.getRawCommentForAnyRedecl(PDecl))
3803 return RC;
3804 }
3805 return nullptr;
3806}
3807
3809 const ASTContext &Ctx,
3810 const CodeCompleteConsumer::OverloadCandidate &Result, unsigned ArgIndex) {
3811 auto FDecl = Result.getFunction();
3812 if (!FDecl)
3813 return nullptr;
3814 if (ArgIndex < FDecl->getNumParams())
3815 return Ctx.getRawCommentForAnyRedecl(FDecl->getParamDecl(ArgIndex));
3816 return nullptr;
3817}
3818
3820 const PrintingPolicy &Policy,
3822 unsigned CurrentArg) {
3823 unsigned ChunkIndex = 0;
3824 auto AddChunk = [&](llvm::StringRef Placeholder) {
3825 if (ChunkIndex > 0)
3827 const char *Copy = Result.getAllocator().CopyString(Placeholder);
3828 if (ChunkIndex == CurrentArg)
3829 Result.AddCurrentParameterChunk(Copy);
3830 else
3831 Result.AddPlaceholderChunk(Copy);
3832 ++ChunkIndex;
3833 };
3834 // Aggregate initialization has all bases followed by all fields.
3835 // (Bases are not legal in C++11 but in that case we never get here).
3836 if (auto *CRD = llvm::dyn_cast<CXXRecordDecl>(RD)) {
3837 for (const auto &Base : CRD->bases())
3838 AddChunk(Base.getType().getAsString(Policy));
3839 }
3840 for (const auto &Field : RD->fields())
3841 AddChunk(FormatFunctionParameter(Policy, Field));
3842}
3843
3844/// Add function overload parameter chunks to the given code completion
3845/// string.
3847 ASTContext &Context, const PrintingPolicy &Policy,
3850 unsigned CurrentArg, unsigned Start = 0, bool InOptional = false) {
3851 if (!Function && !Prototype) {
3853 return;
3854 }
3855
3856 bool FirstParameter = true;
3857 unsigned NumParams =
3858 Function ? Function->getNumParams() : Prototype->getNumParams();
3859
3860 for (unsigned P = Start; P != NumParams; ++P) {
3861 if (Function && Function->getParamDecl(P)->hasDefaultArg() && !InOptional) {
3862 // When we see an optional default argument, put that argument and
3863 // the remaining default arguments into a new, optional string.
3864 CodeCompletionBuilder Opt(Result.getAllocator(),
3865 Result.getCodeCompletionTUInfo());
3866 if (!FirstParameter)
3868 // Optional sections are nested.
3870 PrototypeLoc, Opt, CurrentArg, P,
3871 /*InOptional=*/true);
3872 Result.AddOptionalChunk(Opt.TakeString());
3873 return;
3874 }
3875
3876 if (FirstParameter)
3877 FirstParameter = false;
3878 else
3880
3881 InOptional = false;
3882
3883 // Format the placeholder string.
3884 std::string Placeholder;
3885 assert(P < Prototype->getNumParams());
3886 if (Function || PrototypeLoc) {
3887 const ParmVarDecl *Param =
3888 Function ? Function->getParamDecl(P) : PrototypeLoc.getParam(P);
3889 Placeholder = FormatFunctionParameter(Policy, Param);
3890 if (Param->hasDefaultArg())
3891 Placeholder += GetDefaultValueString(Param, Context.getSourceManager(),
3892 Context.getLangOpts());
3893 } else {
3894 Placeholder = Prototype->getParamType(P).getAsString(Policy);
3895 }
3896
3897 if (P == CurrentArg)
3898 Result.AddCurrentParameterChunk(
3899 Result.getAllocator().CopyString(Placeholder));
3900 else
3901 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Placeholder));
3902 }
3903
3904 if (Prototype && Prototype->isVariadic()) {
3905 CodeCompletionBuilder Opt(Result.getAllocator(),
3906 Result.getCodeCompletionTUInfo());
3907 if (!FirstParameter)
3909
3910 if (CurrentArg < NumParams)
3911 Opt.AddPlaceholderChunk("...");
3912 else
3913 Opt.AddCurrentParameterChunk("...");
3914
3915 Result.AddOptionalChunk(Opt.TakeString());
3916 }
3917}
3918
3919static std::string
3921 const PrintingPolicy &Policy) {
3922 if (const auto *Type = dyn_cast<TemplateTypeParmDecl>(Param)) {
3923 Optional = Type->hasDefaultArgument();
3924 } else if (const auto *NonType = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3925 Optional = NonType->hasDefaultArgument();
3926 } else if (const auto *Template = dyn_cast<TemplateTemplateParmDecl>(Param)) {
3927 Optional = Template->hasDefaultArgument();
3928 }
3929 std::string Result;
3930 llvm::raw_string_ostream OS(Result);
3931 Param->print(OS, Policy);
3932 return Result;
3933}
3934
3935static std::string templateResultType(const TemplateDecl *TD,
3936 const PrintingPolicy &Policy) {
3937 if (const auto *CTD = dyn_cast<ClassTemplateDecl>(TD))
3938 return CTD->getTemplatedDecl()->getKindName().str();
3939 if (const auto *VTD = dyn_cast<VarTemplateDecl>(TD))
3940 return VTD->getTemplatedDecl()->getType().getAsString(Policy);
3941 if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(TD))
3942 return FTD->getTemplatedDecl()->getReturnType().getAsString(Policy);
3943 if (isa<TypeAliasTemplateDecl>(TD))
3944 return "type";
3945 if (isa<TemplateTemplateParmDecl>(TD))
3946 return "class";
3947 if (isa<ConceptDecl>(TD))
3948 return "concept";
3949 return "";
3950}
3951
3953 const TemplateDecl *TD, CodeCompletionBuilder &Builder, unsigned CurrentArg,
3954 const PrintingPolicy &Policy) {
3956 CodeCompletionBuilder OptionalBuilder(Builder.getAllocator(),
3957 Builder.getCodeCompletionTUInfo());
3958 std::string ResultType = templateResultType(TD, Policy);
3959 if (!ResultType.empty())
3960 Builder.AddResultTypeChunk(Builder.getAllocator().CopyString(ResultType));
3961 Builder.AddTextChunk(
3962 Builder.getAllocator().CopyString(TD->getNameAsString()));
3963 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
3964 // Initially we're writing into the main string. Once we see an optional arg
3965 // (with default), we're writing into the nested optional chunk.
3966 CodeCompletionBuilder *Current = &Builder;
3967 for (unsigned I = 0; I < Params.size(); ++I) {
3968 bool Optional = false;
3969 std::string Placeholder =
3970 formatTemplateParameterPlaceholder(Params[I], Optional, Policy);
3971 if (Optional)
3972 Current = &OptionalBuilder;
3973 if (I > 0)
3974 Current->AddChunk(CodeCompletionString::CK_Comma);
3975 Current->AddChunk(I == CurrentArg
3978 Current->getAllocator().CopyString(Placeholder));
3979 }
3980 // Add the optional chunk to the main string if we ever used it.
3981 if (Current == &OptionalBuilder)
3982 Builder.AddOptionalChunk(OptionalBuilder.TakeString());
3983 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
3984 // For function templates, ResultType was the function's return type.
3985 // Give some clue this is a function. (Don't show the possibly-bulky params).
3986 if (isa<FunctionTemplateDecl>(TD))
3987 Builder.AddInformativeChunk("()");
3988 return Builder.TakeString();
3989}
3990
3993 unsigned CurrentArg, Sema &S, CodeCompletionAllocator &Allocator,
3994 CodeCompletionTUInfo &CCTUInfo, bool IncludeBriefComments,
3995 bool Braced) const {
3997 // Show signatures of constructors as they are declared:
3998 // vector(int n) rather than vector<string>(int n)
3999 // This is less noisy without being less clear, and avoids tricky cases.
4001
4002 // FIXME: Set priority, availability appropriately.
4003 CodeCompletionBuilder Result(Allocator, CCTUInfo, 1,
4005
4006 if (getKind() == CK_Template)
4007 return createTemplateSignatureString(getTemplate(), Result, CurrentArg,
4008 Policy);
4009
4010 FunctionDecl *FDecl = getFunction();
4011 const FunctionProtoType *Proto =
4012 dyn_cast_or_null<FunctionProtoType>(getFunctionType());
4013
4014 // First, the name/type of the callee.
4015 if (getKind() == CK_Aggregate) {
4016 Result.AddTextChunk(
4017 Result.getAllocator().CopyString(getAggregate()->getName()));
4018 } else if (FDecl) {
4019 if (IncludeBriefComments) {
4020 if (auto RC = getParameterComment(S.getASTContext(), *this, CurrentArg))
4021 Result.addBriefComment(RC->getBriefText(S.getASTContext()));
4022 }
4023 AddResultTypeChunk(S.Context, Policy, FDecl, QualType(), Result);
4024
4025 std::string Name;
4026 llvm::raw_string_ostream OS(Name);
4027 FDecl->getDeclName().print(OS, Policy);
4028 Result.AddTextChunk(Result.getAllocator().CopyString(OS.str()));
4029 } else {
4030 // Function without a declaration. Just give the return type.
4031 Result.AddResultTypeChunk(Result.getAllocator().CopyString(
4032 getFunctionType()->getReturnType().getAsString(Policy)));
4033 }
4034
4035 // Next, the brackets and parameters.
4038 if (getKind() == CK_Aggregate)
4039 AddOverloadAggregateChunks(getAggregate(), Policy, Result, CurrentArg);
4040 else
4041 AddOverloadParameterChunks(S.getASTContext(), Policy, FDecl, Proto,
4042 getFunctionProtoTypeLoc(), Result, CurrentArg);
4045
4046 return Result.TakeString();
4047}
4048
4049unsigned clang::getMacroUsagePriority(StringRef MacroName,
4050 const LangOptions &LangOpts,
4051 bool PreferredTypeIsPointer) {
4052 unsigned Priority = CCP_Macro;
4053
4054 // Treat the "nil", "Nil" and "NULL" macros as null pointer constants.
4055 if (MacroName == "nil" || MacroName == "NULL" || MacroName == "Nil") {
4057 if (PreferredTypeIsPointer)
4059 }
4060 // Treat "YES", "NO", "true", and "false" as constants.
4061 else if (MacroName == "YES" || MacroName == "NO" || MacroName == "true" ||
4062 MacroName == "false")
4064 // Treat "bool" as a type.
4065 else if (MacroName == "bool")
4066 Priority = CCP_Type + (LangOpts.ObjC ? CCD_bool_in_ObjC : 0);
4067
4068 return Priority;
4069}
4070
4072 if (!D)
4074
4075 switch (D->getKind()) {
4076 case Decl::Enum:
4077 return CXCursor_EnumDecl;
4078 case Decl::EnumConstant:
4080 case Decl::Field:
4081 return CXCursor_FieldDecl;
4082 case Decl::Function:
4083 return CXCursor_FunctionDecl;
4084 case Decl::ObjCCategory:
4086 case Decl::ObjCCategoryImpl:
4088 case Decl::ObjCImplementation:
4090
4091 case Decl::ObjCInterface:
4093 case Decl::ObjCIvar:
4094 return CXCursor_ObjCIvarDecl;
4095 case Decl::ObjCMethod:
4096 return cast<ObjCMethodDecl>(D)->isInstanceMethod()
4099 case Decl::CXXMethod:
4100 return CXCursor_CXXMethod;
4101 case Decl::CXXConstructor:
4102 return CXCursor_Constructor;
4103 case Decl::CXXDestructor:
4104 return CXCursor_Destructor;
4105 case Decl::CXXConversion:
4107 case Decl::ObjCProperty:
4109 case Decl::ObjCProtocol:
4111 case Decl::ParmVar:
4112 return CXCursor_ParmDecl;
4113 case Decl::Typedef:
4114 return CXCursor_TypedefDecl;
4115 case Decl::TypeAlias:
4117 case Decl::TypeAliasTemplate:
4119 case Decl::Var:
4120 return CXCursor_VarDecl;
4121 case Decl::Namespace:
4122 return CXCursor_Namespace;
4123 case Decl::NamespaceAlias:
4125 case Decl::TemplateTypeParm:
4127 case Decl::NonTypeTemplateParm:
4129 case Decl::TemplateTemplateParm:
4131 case Decl::FunctionTemplate:
4133 case Decl::ClassTemplate:
4135 case Decl::AccessSpec:
4137 case Decl::ClassTemplatePartialSpecialization:
4139 case Decl::UsingDirective:
4141 case Decl::StaticAssert:
4142 return CXCursor_StaticAssert;
4143 case Decl::Friend:
4144 return CXCursor_FriendDecl;
4145 case Decl::TranslationUnit:
4147
4148 case Decl::Using:
4149 case Decl::UnresolvedUsingValue:
4150 case Decl::UnresolvedUsingTypename:
4152
4153 case Decl::UsingEnum:
4154 return CXCursor_EnumDecl;
4155
4156 case Decl::ObjCPropertyImpl:
4157 switch (cast<ObjCPropertyImplDecl>(D)->getPropertyImplementation()) {
4160
4163 }
4164 llvm_unreachable("Unexpected Kind!");
4165
4166 case Decl::Import:
4168
4169 case Decl::ObjCTypeParam:
4171
4172 case Decl::Concept:
4173 return CXCursor_ConceptDecl;
4174
4175 case Decl::LinkageSpec:
4176 return CXCursor_LinkageSpec;
4177
4178 default:
4179 if (const auto *TD = dyn_cast<TagDecl>(D)) {
4180 switch (TD->getTagKind()) {
4181 case TagTypeKind::Interface: // fall through
4183 return CXCursor_StructDecl;
4184 case TagTypeKind::Class:
4185 return CXCursor_ClassDecl;
4186 case TagTypeKind::Union:
4187 return CXCursor_UnionDecl;
4188 case TagTypeKind::Enum:
4189 return CXCursor_EnumDecl;
4190 }
4191 }
4192 }
4193
4195}
4196
4197static void AddMacroResults(Preprocessor &PP, ResultBuilder &Results,
4198 bool LoadExternal, bool IncludeUndefined,
4199 bool TargetTypeIsPointer = false) {
4201
4202 Results.EnterNewScope();
4203
4204 for (Preprocessor::macro_iterator M = PP.macro_begin(LoadExternal),
4205 MEnd = PP.macro_end(LoadExternal);
4206 M != MEnd; ++M) {
4207 auto MD = PP.getMacroDefinition(M->first);
4208 if (IncludeUndefined || MD) {
4209 MacroInfo *MI = MD.getMacroInfo();
4210 if (MI && MI->isUsedForHeaderGuard())
4211 continue;
4212
4213 Results.AddResult(
4214 Result(M->first, MI,
4215 getMacroUsagePriority(M->first->getName(), PP.getLangOpts(),
4216 TargetTypeIsPointer)));
4217 }
4218 }
4219
4220 Results.ExitScope();
4221}
4222
4223static void AddPrettyFunctionResults(const LangOptions &LangOpts,
4224 ResultBuilder &Results) {
4226
4227 Results.EnterNewScope();
4228
4229 Results.AddResult(Result("__PRETTY_FUNCTION__", CCP_Constant));
4230 Results.AddResult(Result("__FUNCTION__", CCP_Constant));
4231 if (LangOpts.C99 || LangOpts.CPlusPlus11)
4232 Results.AddResult(Result("__func__", CCP_Constant));
4233 Results.ExitScope();
4234}
4235
4237 CodeCompleteConsumer *CodeCompleter,
4238 const CodeCompletionContext &Context,
4239 CodeCompletionResult *Results,
4240 unsigned NumResults) {
4241 if (CodeCompleter)
4242 CodeCompleter->ProcessCodeCompleteResults(*S, Context, Results, NumResults);
4243}
4244
4248 switch (PCC) {
4251
4254
4257
4260
4263
4266 if (S.CurContext->isFileContext())
4268 if (S.CurContext->isRecord())
4271
4274
4276 if (S.getLangOpts().CPlusPlus || S.getLangOpts().C99 ||
4277 S.getLangOpts().ObjC)
4279 else
4281
4286 S.getASTContext().BoolTy);
4287
4290
4293
4296
4301 }
4302
4303 llvm_unreachable("Invalid ParserCompletionContext!");
4304}
4305
4306/// If we're in a C++ virtual member function, add completion results
4307/// that invoke the functions we override, since it's common to invoke the
4308/// overridden function as well as adding new functionality.
4309///
4310/// \param S The semantic analysis object for which we are generating results.
4311///
4312/// \param InContext This context in which the nested-name-specifier preceding
4313/// the code-completion point
4314static void MaybeAddOverrideCalls(Sema &S, DeclContext *InContext,
4315 ResultBuilder &Results) {
4316 // Look through blocks.
4317 DeclContext *CurContext = S.CurContext;
4318 while (isa<BlockDecl>(CurContext))
4319 CurContext = CurContext->getParent();
4320
4321 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(CurContext);
4322 if (!Method || !Method->isVirtual())
4323 return;
4324
4325 // We need to have names for all of the parameters, if we're going to
4326 // generate a forwarding call.
4327 for (auto *P : Method->parameters())
4328 if (!P->getDeclName())
4329 return;
4330
4332 for (const CXXMethodDecl *Overridden : Method->overridden_methods()) {
4333 CodeCompletionBuilder Builder(Results.getAllocator(),
4334 Results.getCodeCompletionTUInfo());
4335 if (Overridden->getCanonicalDecl() == Method->getCanonicalDecl())
4336 continue;
4337
4338 // If we need a nested-name-specifier, add one now.
4339 if (!InContext) {
4341 S.Context, CurContext, Overridden->getDeclContext());
4342 if (NNS) {
4343 std::string Str;
4344 llvm::raw_string_ostream OS(Str);
4345 NNS->print(OS, Policy);
4346 Builder.AddTextChunk(Results.getAllocator().CopyString(OS.str()));
4347 }
4348 } else if (!InContext->Equals(Overridden->getDeclContext()))
4349 continue;
4350
4351 Builder.AddTypedTextChunk(
4352 Results.getAllocator().CopyString(Overridden->getNameAsString()));
4353 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4354 bool FirstParam = true;
4355 for (auto *P : Method->parameters()) {
4356 if (FirstParam)
4357 FirstParam = false;
4358 else
4359 Builder.AddChunk(CodeCompletionString::CK_Comma);
4360
4361 Builder.AddPlaceholderChunk(
4362 Results.getAllocator().CopyString(P->getIdentifier()->getName()));
4363 }
4364 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4365 Results.AddResult(CodeCompletionResult(
4366 Builder.TakeString(), CCP_SuperCompletion, CXCursor_CXXMethod,
4367 CXAvailability_Available, Overridden));
4368 Results.Ignore(Overridden);
4369 }
4370}
4371
4373 ModuleIdPath Path) {
4375 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(),
4376 CodeCompleter->getCodeCompletionTUInfo(),
4378 Results.EnterNewScope();
4379
4380 CodeCompletionAllocator &Allocator = Results.getAllocator();
4381 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
4383 if (Path.empty()) {
4384 // Enumerate all top-level modules.
4386 SemaRef.PP.getHeaderSearchInfo().collectAllModules(Modules);
4387 for (unsigned I = 0, N = Modules.size(); I != N; ++I) {
4388 Builder.AddTypedTextChunk(
4389 Builder.getAllocator().CopyString(Modules[I]->Name));
4390 Results.AddResult(Result(
4391 Builder.TakeString(), CCP_Declaration, CXCursor_ModuleImportDecl,
4392 Modules[I]->isAvailable() ? CXAvailability_Available
4394 }
4395 } else if (getLangOpts().Modules) {
4396 // Load the named module.
4397 Module *Mod = SemaRef.PP.getModuleLoader().loadModule(
4398 ImportLoc, Path, Module::AllVisible,
4399 /*IsInclusionDirective=*/false);
4400 // Enumerate submodules.
4401 if (Mod) {
4402 for (auto *Submodule : Mod->submodules()) {
4403 Builder.AddTypedTextChunk(
4404 Builder.getAllocator().CopyString(Submodule->Name));
4405 Results.AddResult(Result(
4406 Builder.TakeString(), CCP_Declaration, CXCursor_ModuleImportDecl,
4407 Submodule->isAvailable() ? CXAvailability_Available
4409 }
4410 }
4411 }
4412 Results.ExitScope();
4413 HandleCodeCompleteResults(&SemaRef, CodeCompleter,
4414 Results.getCompletionContext(), Results.data(),
4415 Results.size());
4416}
4417
4419 Scope *S, SemaCodeCompletion::ParserCompletionContext CompletionContext) {
4420 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(),
4421 CodeCompleter->getCodeCompletionTUInfo(),
4422 mapCodeCompletionContext(SemaRef, CompletionContext));
4423 Results.EnterNewScope();
4424
4425 // Determine how to filter results, e.g., so that the names of
4426 // values (functions, enumerators, function templates, etc.) are
4427 // only allowed where we can have an expression.
4428 switch (CompletionContext) {
4429 case PCC_Namespace:
4430 case PCC_Class:
4431 case PCC_ObjCInterface:
4432 case PCC_ObjCImplementation:
4433 case PCC_ObjCInstanceVariableList:
4434 case PCC_Template:
4435 case PCC_MemberTemplate:
4436 case PCC_Type:
4437 case PCC_LocalDeclarationSpecifiers:
4438 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
4439 break;
4440
4441 case PCC_Statement:
4442 case PCC_TopLevelOrExpression:
4443 case PCC_ParenthesizedExpression:
4444 case PCC_Expression:
4445 case PCC_ForInit:
4446 case PCC_Condition:
4447 if (WantTypesInContext(CompletionContext, getLangOpts()))
4448 Results.setFilter(&ResultBuilder::IsOrdinaryName);
4449 else
4450 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
4451
4452 if (getLangOpts().CPlusPlus)
4453 MaybeAddOverrideCalls(SemaRef, /*InContext=*/nullptr, Results);
4454 break;
4455
4456 case PCC_RecoveryInFunction:
4457 // Unfiltered
4458 break;
4459 }
4460
4461 // If we are in a C++ non-static member function, check the qualifiers on
4462 // the member function to filter/prioritize the results list.
4463 auto ThisType = SemaRef.getCurrentThisType();
4464 if (!ThisType.isNull())
4465 Results.setObjectTypeQualifiers(ThisType->getPointeeType().getQualifiers(),
4466 VK_LValue);
4467
4468 CodeCompletionDeclConsumer Consumer(Results, SemaRef.CurContext);
4469 SemaRef.LookupVisibleDecls(S, SemaRef.LookupOrdinaryName, Consumer,
4470 CodeCompleter->includeGlobals(),
4471 CodeCompleter->loadExternal());
4472
4473 AddOrdinaryNameResults(CompletionContext, S, SemaRef, Results);
4474 Results.ExitScope();
4475
4476 switch (CompletionContext) {
4477 case PCC_ParenthesizedExpression:
4478 case PCC_Expression:
4479 case PCC_Statement:
4480 case PCC_TopLevelOrExpression:
4481 case PCC_RecoveryInFunction:
4482 if (S->getFnParent())
4483 AddPrettyFunctionResults(getLangOpts(), Results);
4484 break;
4485
4486 case PCC_Namespace:
4487 case PCC_Class:
4488 case PCC_ObjCInterface:
4489 case PCC_ObjCImplementation:
4490 case PCC_ObjCInstanceVariableList:
4491 case PCC_Template:
4492 case PCC_MemberTemplate:
4493 case PCC_ForInit:
4494 case PCC_Condition:
4495 case PCC_Type:
4496 case PCC_LocalDeclarationSpecifiers:
4497 break;
4498 }
4499
4500 if (CodeCompleter->includeMacros())
4501 AddMacroResults(SemaRef.PP, Results, CodeCompleter->loadExternal(), false);
4502
4503 HandleCodeCompleteResults(&SemaRef, CodeCompleter,
4504 Results.getCompletionContext(), Results.data(),
4505 Results.size());
4506}
4507
4508static void
4509AddClassMessageCompletions(Sema &SemaRef, Scope *S, ParsedType Receiver,
4511 bool AtArgumentExpression, bool IsSuper,
4512 ResultBuilder &Results);
4513
4515 bool AllowNonIdentifiers,
4516 bool AllowNestedNameSpecifiers) {
4518 ResultBuilder Results(
4519 SemaRef, CodeCompleter->getAllocator(),
4520 CodeCompleter->getCodeCompletionTUInfo(),
4521 AllowNestedNameSpecifiers
4522 // FIXME: Try to separate codepath leading here to deduce whether we
4523 // need an existing symbol or a new one.
4526 Results.EnterNewScope();
4527
4528 // Type qualifiers can come after names.
4529 Results.AddResult(Result("const"));
4530 Results.AddResult(Result("volatile"));
4531 if (getLangOpts().C99)
4532 Results.AddResult(Result("restrict"));
4533
4534 if (getLangOpts().CPlusPlus) {
4535 if (getLangOpts().CPlusPlus11 &&
4538 Results.AddResult("final");
4539
4540 if (AllowNonIdentifiers) {
4541 Results.AddResult(Result("operator"));
4542 }
4543
4544 // Add nested-name-specifiers.
4545 if (AllowNestedNameSpecifiers) {
4546 Results.allowNestedNameSpecifiers();
4547 Results.setFilter(&ResultBuilder::IsImpossibleToSatisfy);
4548 CodeCompletionDeclConsumer Consumer(Results, SemaRef.CurContext);
4550 Consumer, CodeCompleter->includeGlobals(),
4551 CodeCompleter->loadExternal());
4552 Results.setFilter(nullptr);
4553 }
4554 }
4555 Results.ExitScope();
4556
4557 // If we're in a context where we might have an expression (rather than a
4558 // declaration), and what we've seen so far is an Objective-C type that could
4559 // be a receiver of a class message, this may be a class message send with
4560 // the initial opening bracket '[' missing. Add appropriate completions.
4561 if (AllowNonIdentifiers && !AllowNestedNameSpecifiers &&
4566 !DS.isTypeAltiVecVector() && S &&
4567 (S->getFlags() & Scope::DeclScope) != 0 &&
4568 (S->getFlags() & (Scope::ClassScope | Scope::TemplateParamScope |
4570 0) {
4571 ParsedType T = DS.getRepAsType();
4572 if (!T.get().isNull() && T.get()->isObjCObjectOrInterfaceType())
4573 AddClassMessageCompletions(SemaRef, S, T, std::nullopt, false, false,
4574 Results);
4575 }
4576
4577 // Note that we intentionally suppress macro results here, since we do not
4578 // encourage using macros to produce the names of entities.
4579
4580 HandleCodeCompleteResults(&SemaRef, CodeCompleter,
4581 Results.getCompletionContext(), Results.data(),
4582 Results.size());
4583}
4584
4585static const char *underscoreAttrScope(llvm::StringRef Scope) {
4586 if (Scope == "clang")
4587 return "_Clang";
4588 if (Scope == "gnu")
4589 return "__gnu__";
4590 return nullptr;
4591}
4592
4593static const char *noUnderscoreAttrScope(llvm::StringRef Scope) {
4594 if (Scope == "_Clang")
4595 return "clang";
4596 if (Scope == "__gnu__")
4597 return "gnu";
4598 return nullptr;
4599}
4600
4603 const IdentifierInfo *InScope) {
4604 if (Completion == AttributeCompletion::None)
4605 return;
4606 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(),
4607 CodeCompleter->getCodeCompletionTUInfo(),
4609
4610 // We're going to iterate over the normalized spellings of the attribute.
4611 // These don't include "underscore guarding": the normalized spelling is
4612 // clang::foo but you can also write _Clang::__foo__.
4613 //
4614 // (Clang supports a mix like clang::__foo__ but we won't suggest it: either
4615 // you care about clashing with macros or you don't).
4616 //
4617 // So if we're already in a scope, we determine its canonical spellings
4618 // (for comparison with normalized attr spelling) and remember whether it was
4619 // underscore-guarded (so we know how to spell contained attributes).
4620 llvm::StringRef InScopeName;
4621 bool InScopeUnderscore = false;
4622 if (InScope) {
4623 InScopeName = InScope->getName();
4624 if (const char *NoUnderscore = noUnderscoreAttrScope(InScopeName)) {
4625 InScopeName = NoUnderscore;
4626 InScopeUnderscore = true;
4627 }
4628 }
4629 bool SyntaxSupportsGuards = Syntax == AttributeCommonInfo::AS_GNU ||
4632
4634 auto AddCompletions = [&](const ParsedAttrInfo &A) {
4635 if (A.IsTargetSpecific &&
4636 !A.existsInTarget(getASTContext().getTargetInfo()))
4637 return;
4638 if (!A.acceptsLangOpts(getLangOpts()))
4639 return;
4640 for (const auto &S : A.Spellings) {
4641 if (S.Syntax != Syntax)
4642 continue;
4643 llvm::StringRef Name = S.NormalizedFullName;
4644 llvm::StringRef Scope;
4645 if ((Syntax == AttributeCommonInfo::AS_CXX11 ||
4646 Syntax == AttributeCommonInfo::AS_C23)) {
4647 std::tie(Scope, Name) = Name.split("::");
4648 if (Name.empty()) // oops, unscoped
4649 std::swap(Name, Scope);
4650 }
4651
4652 // Do we just want a list of scopes rather than attributes?
4653 if (Completion == AttributeCompletion::Scope) {
4654 // Make sure to emit each scope only once.
4655 if (!Scope.empty() && FoundScopes.insert(Scope).second) {
4656 Results.AddResult(
4657 CodeCompletionResult(Results.getAllocator().CopyString(Scope)));
4658 // Include alternate form (__gnu__ instead of gnu).
4659 if (const char *Scope2 = underscoreAttrScope(Scope))
4660 Results.AddResult(CodeCompletionResult(Scope2));
4661 }
4662 continue;
4663 }
4664
4665 // If a scope was specified, it must match but we don't need to print it.
4666 if (!InScopeName.empty()) {
4667 if (Scope != InScopeName)
4668 continue;
4669 Scope = "";
4670 }
4671
4672 auto Add = [&](llvm::StringRef Scope, llvm::StringRef Name,
4673 bool Underscores) {
4674 CodeCompletionBuilder Builder(Results.getAllocator(),
4675 Results.getCodeCompletionTUInfo());
4677 if (!Scope.empty()) {
4678 Text.append(Scope);
4679 Text.append("::");
4680 }
4681 if (Underscores)
4682 Text.append("__");
4683 Text.append(Name);
4684 if (Underscores)
4685 Text.append("__");
4686 Builder.AddTypedTextChunk(Results.getAllocator().CopyString(Text));
4687
4688 if (!A.ArgNames.empty()) {
4689 Builder.AddChunk(CodeCompletionString::CK_LeftParen, "(");
4690 bool First = true;
4691 for (const char *Arg : A.ArgNames) {
4692 if (!First)
4693 Builder.AddChunk(CodeCompletionString::CK_Comma, ", ");
4694 First = false;
4695 Builder.AddPlaceholderChunk(Arg);
4696 }
4697 Builder.AddChunk(CodeCompletionString::CK_RightParen, ")");
4698 }
4699
4700 Results.AddResult(Builder.TakeString());
4701 };
4702
4703 // Generate the non-underscore-guarded result.
4704 // Note this is (a suffix of) the NormalizedFullName, no need to copy.
4705 // If an underscore-guarded scope was specified, only the
4706 // underscore-guarded attribute name is relevant.
4707 if (!InScopeUnderscore)
4708 Add(Scope, Name, /*Underscores=*/false);
4709
4710 // Generate the underscore-guarded version, for syntaxes that support it.
4711 // We skip this if the scope was already spelled and not guarded, or
4712 // we must spell it and can't guard it.
4713 if (!(InScope && !InScopeUnderscore) && SyntaxSupportsGuards) {
4714 llvm::SmallString<32> Guarded;
4715 if (Scope.empty()) {
4716 Add(Scope, Name, /*Underscores=*/true);
4717 } else {
4718 const char *GuardedScope = underscoreAttrScope(Scope);
4719 if (!GuardedScope)
4720 continue;
4721 Add(GuardedScope, Name, /*Underscores=*/true);
4722 }
4723 }
4724
4725 // It may be nice to include the Kind so we can look up the docs later.
4726 }
4727 };
4728
4729 for (const auto *A : ParsedAttrInfo::getAllBuiltin())
4730 AddCompletions(*A);
4731 for (const auto &Entry : ParsedAttrInfoRegistry::entries())
4732 AddCompletions(*Entry.instantiate());
4733
4734 HandleCodeCompleteResults(&SemaRef, CodeCompleter,
4735 Results.getCompletionContext(), Results.data(),
4736 Results.size());
4737}
4738
4741 bool IsParenthesized = false)
4742 : PreferredType(PreferredType), IntegralConstantExpression(false),
4743 ObjCCollection(false), IsParenthesized(IsParenthesized) {}
4744
4750};
4751
4752namespace {
4753/// Information that allows to avoid completing redundant enumerators.
4754struct CoveredEnumerators {
4756 NestedNameSpecifier *SuggestedQualifier = nullptr;
4757};
4758} // namespace
4759
4760static void AddEnumerators(ResultBuilder &Results, ASTContext &Context,
4761 EnumDecl *Enum, DeclContext *CurContext,
4762 const CoveredEnumerators &Enumerators) {
4763 NestedNameSpecifier *Qualifier = Enumerators.SuggestedQualifier;
4764 if (Context.getLangOpts().CPlusPlus && !Qualifier && Enumerators.Seen.empty()) {
4765 // If there are no prior enumerators in C++, check whether we have to
4766 // qualify the names of the enumerators that we suggest, because they
4767 // may not be visible in this scope.
4768 Qualifier = getRequiredQualification(Context, CurContext, Enum);
4769 }
4770
4771 Results.EnterNewScope();
4772 for (auto *E : Enum->enumerators()) {
4773 if (Enumerators.Seen.count(E))
4774 continue;
4775
4776 CodeCompletionResult R(E, CCP_EnumInCase, Qualifier);
4777 Results.AddResult(R, CurContext, nullptr, false);
4778 }
4779 Results.ExitScope();
4780}
4781
4782/// Try to find a corresponding FunctionProtoType for function-like types (e.g.
4783/// function pointers, std::function, etc).
4785 assert(!T.isNull());
4786 // Try to extract first template argument from std::function<> and similar.
4787 // Note we only handle the sugared types, they closely match what users wrote.
4788 // We explicitly choose to not handle ClassTemplateSpecializationDecl.
4790 if (Specialization->template_arguments().size() != 1)
4791 return nullptr;
4792 const TemplateArgument &Argument = Specialization->template_arguments()[0];
4793 if (Argument.getKind() != TemplateArgument::Type)
4794 return nullptr;
4795 return Argument.getAsType()->getAs<FunctionProtoType>();
4796 }
4797 // Handle other cases.
4798 if (T->isPointerType())
4799 T = T->getPointeeType();
4800 return T->getAs<FunctionProtoType>();
4801}
4802
4803/// Adds a pattern completion for a lambda expression with the specified
4804/// parameter types and placeholders for parameter names.
4805static void AddLambdaCompletion(ResultBuilder &Results,
4806 llvm::ArrayRef<QualType> Parameters,
4807 const LangOptions &LangOpts) {
4808 if (!Results.includeCodePatterns())
4809 return;
4810 CodeCompletionBuilder Completion(Results.getAllocator(),
4811 Results.getCodeCompletionTUInfo());
4812 // [](<parameters>) {}
4814 Completion.AddPlaceholderChunk("=");
4816 if (!Parameters.empty()) {
4818 bool First = true;
4819 for (auto Parameter : Parameters) {
4820 if (!First)
4822 else
4823 First = false;
4824
4825 constexpr llvm::StringLiteral NamePlaceholder = "!#!NAME_GOES_HERE!#!";
4826 std::string Type = std::string(NamePlaceholder);
4827 Parameter.getAsStringInternal(Type, PrintingPolicy(LangOpts));
4828 llvm::StringRef Prefix, Suffix;
4829 std::tie(Prefix, Suffix) = llvm::StringRef(Type).split(NamePlaceholder);
4830 Prefix = Prefix.rtrim();
4831 Suffix = Suffix.ltrim();
4832
4833 Completion.AddTextChunk(Completion.getAllocator().CopyString(Prefix));
4835 Completion.AddPlaceholderChunk("parameter");
4836 Completion.AddTextChunk(Completion.getAllocator().CopyString(Suffix));
4837 };
4839 }
4843 Completion.AddPlaceholderChunk("body");
4846
4847 Results.AddResult(Completion.TakeString());
4848}
4849
4850/// Perform code-completion in an expression context when we know what
4851/// type we're looking for.
4854 ResultBuilder Results(
4855 SemaRef, CodeCompleter->getAllocator(),
4856 CodeCompleter->getCodeCompletionTUInfo(),
4858 Data.IsParenthesized
4861 Data.PreferredType));
4862 auto PCC =
4863 Data.IsParenthesized ? PCC_ParenthesizedExpression : PCC_Expression;
4864 if (Data.ObjCCollection)
4865 Results.setFilter(&ResultBuilder::IsObjCCollection);
4866 else if (Data.IntegralConstantExpression)
4867 Results.setFilter(&ResultBuilder::IsIntegralConstantValue);
4868 else if (WantTypesInContext(PCC, getLangOpts()))
4869 Results.setFilter(&ResultBuilder::IsOrdinaryName);
4870 else
4871 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
4872
4873 if (!Data.PreferredType.isNull())
4874 Results.setPreferredType(Data.PreferredType.getNonReferenceType());
4875
4876 // Ignore any declarations that we were told that we don't care about.
4877 for (unsigned I = 0, N = Data.IgnoreDecls.size(); I != N; ++I)
4878 Results.Ignore(Data.IgnoreDecls[I]);
4879
4880 CodeCompletionDeclConsumer Consumer(Results, SemaRef.CurContext);
4881 SemaRef.LookupVisibleDecls(S, Sema::LookupOrdinaryName, Consumer,
4882 CodeCompleter->includeGlobals(),
4883 CodeCompleter->loadExternal());
4884
4885 Results.EnterNewScope();
4886 AddOrdinaryNameResults(PCC, S, SemaRef, Results);
4887 Results.ExitScope();
4888
4889 bool PreferredTypeIsPointer = false;
4890 if (!Data.PreferredType.isNull()) {
4891 PreferredTypeIsPointer = Data.PreferredType->isAnyPointerType() ||
4892 Data.PreferredType->isMemberPointerType() ||
4893 Data.PreferredType->isBlockPointerType();
4894 if (Data.PreferredType->isEnumeralType()) {
4895 EnumDecl *Enum = Data.PreferredType->castAs<EnumType>()->getDecl();
4896 if (auto *Def = Enum->getDefinition())
4897 Enum = Def;
4898 // FIXME: collect covered enumerators in cases like:
4899 // if (x == my_enum::one) { ... } else if (x == ^) {}
4900 AddEnumerators(Results, getASTContext(), Enum, SemaRef.CurContext,
4901 CoveredEnumerators());
4902 }
4903 }
4904
4905 if (S->getFnParent() && !Data.ObjCCollection &&
4906 !Data.IntegralConstantExpression)
4907 AddPrettyFunctionResults(getLangOpts(), Results);
4908
4909 if (CodeCompleter->includeMacros())
4910 AddMacroResults(SemaRef.PP, Results, CodeCompleter->loadExternal(), false,
4911 PreferredTypeIsPointer);
4912
4913 // Complete a lambda expression when preferred type is a function.
4914 if (!Data.PreferredType.isNull() && getLangOpts().CPlusPlus11) {
4915 if (const FunctionProtoType *F =
4916 TryDeconstructFunctionLike(Data.PreferredType))
4917 AddLambdaCompletion(Results, F->getParamTypes(), getLangOpts());
4918 }
4919
4920 HandleCodeCompleteResults(&SemaRef, CodeCompleter,
4921 Results.getCompletionContext(), Results.data(),
4922 Results.size());
4923}
4924
4926 QualType PreferredType,
4927 bool IsParenthesized) {
4928 return CodeCompleteExpression(
4929 S, CodeCompleteExpressionData(PreferredType, IsParenthesized));
4930}
4931
4933 QualType PreferredType) {
4934 if (E.isInvalid())
4935 CodeCompleteExpression(S, PreferredType);
4936 else if (getLangOpts().ObjC)
4937 CodeCompleteObjCInstanceMessage(S, E.get(), std::nullopt, false);
4938}
4939
4940/// The set of properties that have already been added, referenced by
4941/// property name.
4943
4944/// Retrieve the container definition, if any?
4946 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
4947 if (Interface->hasDefinition())
4948 return Interface->getDefinition();
4949
4950 return Interface;
4951 }
4952
4953 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4954 if (Protocol->hasDefinition())
4955 return Protocol->getDefinition();
4956
4957 return Protocol;
4958 }
4959 return Container;
4960}
4961
4962/// Adds a block invocation code completion result for the given block
4963/// declaration \p BD.
4964static void AddObjCBlockCall(ASTContext &Context, const PrintingPolicy &Policy,
4965 CodeCompletionBuilder &Builder,
4966 const NamedDecl *BD,
4967 const FunctionTypeLoc &BlockLoc,
4968 const FunctionProtoTypeLoc &BlockProtoLoc) {
4969 Builder.AddResultTypeChunk(
4970 GetCompletionTypeString(BlockLoc.getReturnLoc().getType(), Context,
4971 Policy, Builder.getAllocator()));
4972
4973 AddTypedNameChunk(Context, Policy, BD, Builder);
4974 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4975
4976 if (BlockProtoLoc && BlockProtoLoc.getTypePtr()->isVariadic()) {
4977 Builder.AddPlaceholderChunk("...");
4978 } else {
4979 for (unsigned I = 0, N = BlockLoc.getNumParams(); I != N; ++I) {
4980 if (I)
4981 Builder.AddChunk(CodeCompletionString::CK_Comma);
4982
4983 // Format the placeholder string.
4984 std::string PlaceholderStr =
4985 FormatFunctionParameter(Policy, BlockLoc.getParam(I));
4986
4987 if (I == N - 1 && BlockProtoLoc &&
4988 BlockProtoLoc.getTypePtr()->isVariadic())
4989 PlaceholderStr += ", ...";
4990
4991 // Add the placeholder string.
4992 Builder.AddPlaceholderChunk(
4993 Builder.getAllocator().CopyString(PlaceholderStr));
4994 }
4995 }
4996
4997 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4998}
4999
5000static void
5002 ObjCContainerDecl *Container, bool AllowCategories,
5003 bool AllowNullaryMethods, DeclContext *CurContext,
5004 AddedPropertiesSet &AddedProperties, ResultBuilder &Results,
5005 bool IsBaseExprStatement = false,
5006 bool IsClassProperty = false, bool InOriginalClass = true) {
5008
5009 // Retrieve the definition.
5010 Container = getContainerDef(Container);
5011
5012 // Add properties in this container.
5013 const auto AddProperty = [&](const ObjCPropertyDecl *P) {
5014 if (!AddedProperties.insert(P->getIdentifier()).second)
5015 return;
5016
5017 // FIXME: Provide block invocation completion for non-statement
5018 // expressions.
5019 if (!P->getType().getTypePtr()->isBlockPointerType() ||
5020 !IsBaseExprStatement) {
5021 Result R = Result(P, Results.getBasePriority(P), nullptr);
5022 if (!InOriginalClass)
5023 setInBaseClass(R);
5024 Results.MaybeAddResult(R, CurContext);
5025 return;
5026 }
5027
5028 // Block setter and invocation completion is provided only when we are able
5029 // to find the FunctionProtoTypeLoc with parameter names for the block.
5030 FunctionTypeLoc BlockLoc;
5031 FunctionProtoTypeLoc BlockProtoLoc;
5032 findTypeLocationForBlockDecl(P->getTypeSourceInfo(), BlockLoc,
5033 BlockProtoLoc);
5034 if (!BlockLoc) {
5035 Result R = Result(P, Results.getBasePriority(P), nullptr);
5036 if (!InOriginalClass)
5037 setInBaseClass(R);
5038 Results.MaybeAddResult(R, CurContext);
5039 return;
5040 }
5041
5042 // The default completion result for block properties should be the block
5043 // invocation completion when the base expression is a statement.
5044 CodeCompletionBuilder Builder(Results.getAllocator(),
5045 Results.getCodeCompletionTUInfo());
5046 AddObjCBlockCall(Container->getASTContext(),
5047 getCompletionPrintingPolicy(Results.getSema()), Builder, P,
5048 BlockLoc, BlockProtoLoc);
5049 Result R = Result(Builder.TakeString(), P, Results.getBasePriority(P));
5050 if (!InOriginalClass)
5051 setInBaseClass(R);
5052 Results.MaybeAddResult(R, CurContext);
5053
5054 // Provide additional block setter completion iff the base expression is a
5055 // statement and the block property is mutable.
5056 if (!P->isReadOnly()) {
5057 CodeCompletionBuilder Builder(Results.getAllocator(),
5058 Results.getCodeCompletionTUInfo());
5059 AddResultTypeChunk(Container->getASTContext(),
5060 getCompletionPrintingPolicy(Results.getSema()), P,
5061 CCContext.getBaseType(), Builder);
5062 Builder.AddTypedTextChunk(
5063 Results.getAllocator().CopyString(P->getName()));
5064 Builder.AddChunk(CodeCompletionString::CK_Equal);
5065
5066 std::string PlaceholderStr = formatBlockPlaceholder(
5067 getCompletionPrintingPolicy(Results.getSema()), P, BlockLoc,
5068 BlockProtoLoc, /*SuppressBlockName=*/true);
5069 // Add the placeholder string.
5070 Builder.AddPlaceholderChunk(
5071 Builder.getAllocator().CopyString(PlaceholderStr));
5072
5073 // When completing blocks properties that return void the default
5074 // property completion result should show up before the setter,
5075 // otherwise the setter completion should show up before the default
5076 // property completion, as we normally want to use the result of the
5077 // call.
5078 Result R =
5079 Result(Builder.TakeString(), P,
5080 Results.getBasePriority(P) +
5081 (BlockLoc.getTypePtr()->getReturnType()->isVoidType()
5084 if (!InOriginalClass)
5085 setInBaseClass(R);
5086 Results.MaybeAddResult(R, CurContext);
5087 }
5088 };
5089
5090 if (IsClassProperty) {
5091 for (const auto *P : Container->class_properties())
5092 AddProperty(P);
5093 } else {
5094 for (const auto *P : Container->instance_properties())
5095 AddProperty(P);
5096 }
5097
5098 // Add nullary methods or implicit class properties
5099 if (AllowNullaryMethods) {
5100 ASTContext &Context = Container->getASTContext();
5101 PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema());
5102 // Adds a method result
5103 const auto AddMethod = [&](const ObjCMethodDecl *M) {
5104 const IdentifierInfo *Name = M->getSelector().getIdentifierInfoForSlot(0);
5105 if (!Name)
5106 return;
5107 if (!AddedProperties.insert(Name).second)
5108 return;
5109 CodeCompletionBuilder Builder(Results.getAllocator(),
5110 Results.getCodeCompletionTUInfo());
5111 AddResultTypeChunk(Context, Policy, M, CCContext.getBaseType(), Builder);
5112 Builder.AddTypedTextChunk(
5113 Results.getAllocator().CopyString(Name->getName()));
5114 Result R = Result(Builder.TakeString(), M,
5116 if (!InOriginalClass)
5117 setInBaseClass(R);
5118 Results.MaybeAddResult(R, CurContext);
5119 };
5120
5121 if (IsClassProperty) {
5122 for (const auto *M : Container->methods()) {
5123 // Gather the class method that can be used as implicit property
5124 // getters. Methods with arguments or methods that return void aren't
5125 // added to the results as they can't be used as a getter.
5126 if (!M->getSelector().isUnarySelector() ||
5127 M->getReturnType()->isVoidType() || M->isInstanceMethod())
5128 continue;
5129 AddMethod(M);
5130 }
5131 } else {
5132 for (auto *M : Container->methods()) {
5133 if (M->getSelector().isUnarySelector())
5134 AddMethod(M);
5135 }
5136 }
5137 }
5138
5139 // Add properties in referenced protocols.
5140 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
5141 for (auto *P : Protocol->protocols())
5142 AddObjCProperties(CCContext, P, AllowCategories, AllowNullaryMethods,
5143 CurContext, AddedProperties, Results,
5144 IsBaseExprStatement, IsClassProperty,
5145 /*InOriginalClass*/ false);
5146 } else if (ObjCInterfaceDecl *IFace =
5147 dyn_cast<ObjCInterfaceDecl>(Container)) {
5148 if (AllowCategories) {
5149 // Look through categories.
5150 for (auto *Cat : IFace->known_categories())
5151 AddObjCProperties(CCContext, Cat, AllowCategories, AllowNullaryMethods,
5152 CurContext, AddedProperties, Results,
5153 IsBaseExprStatement, IsClassProperty,
5154 InOriginalClass);
5155 }
5156
5157 // Look through protocols.
5158 for (auto *I : IFace->all_referenced_protocols())
5159 AddObjCProperties(CCContext, I, AllowCategories, AllowNullaryMethods,
5160 CurContext, AddedProperties, Results,
5161 IsBaseExprStatement, IsClassProperty,
5162 /*InOriginalClass*/ false);
5163
5164 // Look in the superclass.
5165 if (IFace->getSuperClass())
5166 AddObjCProperties(CCContext, IFace->getSuperClass(), AllowCategories,
5167 AllowNullaryMethods, CurContext, AddedProperties,
5168 Results, IsBaseExprStatement, IsClassProperty,
5169 /*InOriginalClass*/ false);
5170 } else if (const auto *Category =
5171 dyn_cast<ObjCCategoryDecl>(Container)) {
5172 // Look through protocols.
5173 for (auto *P : Category->protocols())
5174 AddObjCProperties(CCContext, P, AllowCategories, AllowNullaryMethods,
5175 CurContext, AddedProperties, Results,
5176 IsBaseExprStatement, IsClassProperty,
5177 /*InOriginalClass*/ false);
5178 }
5179}
5180
5181static void
5182AddRecordMembersCompletionResults(Sema &SemaRef, ResultBuilder &Results,
5183 Scope *S, QualType BaseType,
5184 ExprValueKind BaseKind, RecordDecl *RD,
5185 std::optional<FixItHint> AccessOpFixIt) {
5186 // Indicate that we are performing a member access, and the cv-qualifiers
5187 // for the base object type.
5188 Results.setObjectTypeQualifiers(BaseType.getQualifiers(), BaseKind);
5189
5190 // Access to a C/C++ class, struct, or union.
5191 Results.allowNestedNameSpecifiers();
5192 std::vector<FixItHint> FixIts;
5193 if (AccessOpFixIt)
5194 FixIts.emplace_back(*AccessOpFixIt);
5195 CodeCompletionDeclConsumer Consumer(Results, RD, BaseType, std::move(FixIts));
5196 SemaRef.LookupVisibleDecls(
5197 RD, Sema::LookupMemberName, Consumer,
5199 /*IncludeDependentBases=*/true,
5201
5202 if (SemaRef.getLangOpts().CPlusPlus) {
5203 if (!Results.empty()) {
5204 // The "template" keyword can follow "->" or "." in the grammar.
5205 // However, we only want to suggest the template keyword if something
5206 // is dependent.
5207 bool IsDependent = BaseType->isDependentType();
5208 if (!IsDependent) {
5209 for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent())
5210 if (DeclContext *Ctx = DepScope->getEntity()) {
5211 IsDependent = Ctx->isDependentContext();
5212 break;
5213 }
5214 }
5215
5216 if (IsDependent)
5217 Results.AddResult(CodeCompletionResult("template"));
5218 }
5219 }
5220}
5221
5222// Returns the RecordDecl inside the BaseType, falling back to primary template
5223// in case of specializations. Since we might not have a decl for the
5224// instantiation/specialization yet, e.g. dependent code.
5226 BaseType = BaseType.getNonReferenceType();
5227 if (auto *RD = BaseType->getAsRecordDecl()) {
5228 if (const auto *CTSD =
5229 llvm::dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
5230 // Template might not be instantiated yet, fall back to primary template
5231 // in such cases.
5232 if (CTSD->getTemplateSpecializationKind() == TSK_Undeclared)
5233 RD = CTSD->getSpecializedTemplate()->getTemplatedDecl();
5234 }
5235 return RD;
5236 }
5237
5238 if (const auto *TST = BaseType->getAs<TemplateSpecializationType>()) {
5239 if (const auto *TD = dyn_cast_or_null<ClassTemplateDecl>(
5240 TST->getTemplateName().getAsTemplateDecl())) {
5241 return TD->getTemplatedDecl();
5242 }
5243 }
5244
5245 return nullptr;
5246}
5247
5248namespace {
5249// Collects completion-relevant information about a concept-constrainted type T.
5250// In particular, examines the constraint expressions to find members of T.
5251//
5252// The design is very simple: we walk down each constraint looking for
5253// expressions of the form T.foo().
5254// If we're extra lucky, the return type is specified.
5255// We don't do any clever handling of && or || in constraint expressions, we
5256// take members from both branches.
5257//
5258// For example, given:
5259// template <class T> concept X = requires (T t, string& s) { t.print(s); };
5260// template <X U> void foo(U u) { u.^ }
5261// We want to suggest the inferred member function 'print(string)'.
5262// We see that u has type U, so X<U> holds.
5263// X<U> requires t.print(s) to be valid, where t has type U (substituted for T).
5264// By looking at the CallExpr we find the signature of print().
5265//
5266// While we tend to know in advance which kind of members (access via . -> ::)
5267// we want, it's simpler just to gather them all and post-filter.
5268//
5269// FIXME: some of this machinery could be used for non-concept type-parms too,
5270// enabling completion for type parameters based on other uses of that param.
5271//
5272// FIXME: there are other cases where a type can be constrained by a concept,
5273// e.g. inside `if constexpr(ConceptSpecializationExpr) { ... }`
5274class ConceptInfo {
5275public:
5276 // Describes a likely member of a type, inferred by concept constraints.
5277 // Offered as a code completion for T. T-> and T:: contexts.
5278 struct Member {
5279 // Always non-null: we only handle members with ordinary identifier names.
5280 const IdentifierInfo *Name = nullptr;
5281 // Set for functions we've seen called.
5282 // We don't have the declared parameter types, only the actual types of
5283 // arguments we've seen. These are still valuable, as it's hard to render
5284 // a useful function completion with neither parameter types nor names!
5285 std::optional<SmallVector<QualType, 1>> ArgTypes;
5286 // Whether this is accessed as T.member, T->member, or T::member.
5287 enum AccessOperator {
5288 Colons,
5289 Arrow,
5290 Dot,
5291 } Operator = Dot;
5292 // What's known about the type of a variable or return type of a function.
5293 const TypeConstraint *ResultType = nullptr;
5294 // FIXME: also track:
5295 // - kind of entity (function/variable/type), to expose structured results
5296 // - template args kinds/types, as a proxy for template params
5297
5298 // For now we simply return these results as "pattern" strings.
5300 CodeCompletionTUInfo &Info) const {
5301 CodeCompletionBuilder B(Alloc, Info);
5302 // Result type
5303 if (ResultType) {
5304 std::string AsString;
5305 {
5306 llvm::raw_string_ostream OS(AsString);
5307 QualType ExactType = deduceType(*ResultType);
5308 if (!ExactType.isNull())
5309 ExactType.print(OS, getCompletionPrintingPolicy(S));
5310 else
5311 ResultType->print(OS, getCompletionPrintingPolicy(S));
5312 }
5313 B.AddResultTypeChunk(Alloc.CopyString(AsString));
5314 }
5315 // Member name
5316 B.AddTypedTextChunk(Alloc.CopyString(Name->getName()));
5317 // Function argument list
5318 if (ArgTypes) {
5320 bool First = true;
5321 for (QualType Arg : *ArgTypes) {
5322 if (First)
5323 First = false;
5324 else {
5327 }
5328 B.AddPlaceholderChunk(Alloc.CopyString(
5329 Arg.getAsString(getCompletionPrintingPolicy(S))));
5330 }
5332 }
5333 return B.TakeString();
5334 }
5335 };
5336
5337 // BaseType is the type parameter T to infer members from.
5338 // T must be accessible within S, as we use it to find the template entity
5339 // that T is attached to in order to gather the relevant constraints.
5340 ConceptInfo(const TemplateTypeParmType &BaseType, Scope *S) {
5341 auto *TemplatedEntity = getTemplatedEntity(BaseType.getDecl(), S);
5342 for (const Expr *E : constraintsForTemplatedEntity(TemplatedEntity))
5343 believe(E, &BaseType);
5344 }
5345
5346 std::vector<Member> members() {
5347 std::vector<Member> Results;
5348 for (const auto &E : this->Results)
5349 Results.push_back(E.second);
5350 llvm::sort(Results, [](const Member &L, const Member &R) {
5351 return L.Name->getName() < R.Name->getName();
5352 });
5353 return Results;
5354 }
5355
5356private:
5357 // Infer members of T, given that the expression E (dependent on T) is true.
5358 void believe(const Expr *E, const TemplateTypeParmType *T) {
5359 if (!E || !T)
5360 return;
5361 if (auto *CSE = dyn_cast<ConceptSpecializationExpr>(E)) {
5362 // If the concept is
5363 // template <class A, class B> concept CD = f<A, B>();
5364 // And the concept specialization is
5365 // CD<int, T>
5366 // Then we're substituting T for B, so we want to make f<A, B>() true
5367 // by adding members to B - i.e. believe(f<A, B>(), B);
5368 //
5369 // For simplicity:
5370 // - we don't attempt to substitute int for A
5371 // - when T is used in other ways (like CD<T*>) we ignore it
5372 ConceptDecl *CD = CSE->getNamedConcept();
5374 unsigned Index = 0;
5375 for (const auto &Arg : CSE->getTemplateArguments()) {
5376 if (Index >= Params->size())
5377 break; // Won't happen in valid code.
5378 if (isApprox(Arg, T)) {
5379 auto *TTPD = dyn_cast<TemplateTypeParmDecl>(Params->getParam(Index));
5380 if (!TTPD)
5381 continue;
5382 // T was used as an argument, and bound to the parameter TT.
5383 auto *TT = cast<TemplateTypeParmType>(TTPD->getTypeForDecl());
5384 // So now we know the constraint as a function of TT is true.
5385 believe(CD->getConstraintExpr(), TT);
5386 // (concepts themselves have no associated constraints to require)
5387 }
5388
5389 ++Index;
5390 }
5391 } else if (auto *BO = dyn_cast<BinaryOperator>(E)) {
5392 // For A && B, we can infer members from both branches.
5393 // For A || B, the union is still more useful than the intersection.
5394 if (BO->getOpcode() == BO_LAnd || BO->getOpcode() == BO_LOr) {
5395 believe(BO->getLHS(), T);
5396 believe(BO->getRHS(), T);
5397 }
5398 } else if (auto *RE = dyn_cast<RequiresExpr>(E)) {
5399 // A requires(){...} lets us infer members from each requirement.
5400 for (const concepts::Requirement *Req : RE->getRequirements()) {
5401 if (!Req->isDependent())
5402 continue; // Can't tell us anything about T.
5403 // Now Req cannot a substitution-error: those aren't dependent.
5404
5405 if (auto *TR = dyn_cast<concepts::TypeRequirement>(Req)) {
5406 // Do a full traversal so we get `foo` from `typename T::foo::bar`.
5407 QualType AssertedType = TR->getType()->getType();
5408 ValidVisitor(this, T).TraverseType(AssertedType);
5409 } else if (auto *ER = dyn_cast<concepts::ExprRequirement>(Req)) {
5410 ValidVisitor Visitor(this, T);
5411 // If we have a type constraint on the value of the expression,
5412 // AND the whole outer expression describes a member, then we'll
5413 // be able to use the constraint to provide the return type.
5414 if (ER->getReturnTypeRequirement().isTypeConstraint()) {
5415 Visitor.OuterType =
5416 ER->getReturnTypeRequirement().getTypeConstraint();
5417 Visitor.OuterExpr = ER->getExpr();
5418 }
5419 Visitor.TraverseStmt(ER->getExpr());
5420 } else if (auto *NR = dyn_cast<concepts::NestedRequirement>(Req)) {
5421 believe(NR->getConstraintExpr(), T);
5422 }
5423 }
5424 }
5425 }
5426
5427 // This visitor infers members of T based on traversing expressions/types
5428 // that involve T. It is invoked with code known to be valid for T.
5429 class ValidVisitor : public RecursiveASTVisitor<ValidVisitor> {
5430 ConceptInfo *Outer;
5431 const TemplateTypeParmType *T;
5432
5433 CallExpr *Caller = nullptr;
5434 Expr *Callee = nullptr;
5435
5436 public:
5437 // If set, OuterExpr is constrained by OuterType.
5438 Expr *OuterExpr = nullptr;
5439 const TypeConstraint *OuterType = nullptr;
5440
5441 ValidVisitor(ConceptInfo *Outer, const TemplateTypeParmType *T)
5442 : Outer(Outer), T(T) {
5443 assert(T);
5444 }
5445
5446 // In T.foo or T->foo, `foo` is a member function/variable.
5447 bool VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E) {
5448 const Type *Base = E->getBaseType().getTypePtr();
5449 bool IsArrow = E->isArrow();
5450 if (Base->isPointerType() && IsArrow) {
5451 IsArrow = false;
5452 Base = Base->getPointeeType().getTypePtr();
5453 }
5454 if (isApprox(Base, T))
5455 addValue(E, E->getMember(), IsArrow ? Member::Arrow : Member::Dot);
5456 return true;
5457 }
5458
5459 // In T::foo, `foo` is a static member function/variable.
5460 bool VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) {
5461 if (E->getQualifier() && isApprox(E->getQualifier()->getAsType(), T))
5462 addValue(E, E->getDeclName(), Member::Colons);
5463 return true;
5464 }
5465
5466 // In T::typename foo, `foo` is a type.
5467 bool VisitDependentNameType(DependentNameType *DNT) {
5468 const auto *Q = DNT->getQualifier();
5469 if (Q && isApprox(Q->getAsType(), T))
5470 addType(DNT->getIdentifier());
5471 return true;
5472 }
5473
5474 // In T::foo::bar, `foo` must be a type.
5475 // VisitNNS() doesn't exist, and TraverseNNS isn't always called :-(
5476 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNSL) {
5477 if (NNSL) {
5479 const auto *Q = NNS->getPrefix();
5480 if (Q && isApprox(Q->getAsType(), T))
5481 addType(NNS->getAsIdentifier());
5482 }
5483 // FIXME: also handle T::foo<X>::bar
5485 }
5486
5487 // FIXME also handle T::foo<X>
5488
5489 // Track the innermost caller/callee relationship so we can tell if a
5490 // nested expr is being called as a function.
5491 bool VisitCallExpr(CallExpr *CE) {
5492 Caller = CE;
5493 Callee = CE->getCallee();
5494 return true;
5495 }
5496
5497 private:
5498 void addResult(Member &&M) {
5499 auto R = Outer->Results.try_emplace(M.Name);
5500 Member &O = R.first->second;
5501 // Overwrite existing if the new member has more info.
5502 // The preference of . vs :: vs -> is fairly arbitrary.
5503 if (/*Inserted*/ R.second ||
5504 std::make_tuple(M.ArgTypes.has_value(), M.ResultType != nullptr,
5505 M.Operator) > std::make_tuple(O.ArgTypes.has_value(),
5506 O.ResultType != nullptr,
5507 O.Operator))
5508 O = std::move(M);
5509 }
5510
5511 void addType(const IdentifierInfo *Name) {
5512 if (!Name)
5513 return;
5514 Member M;
5515 M.Name = Name;
5516 M.Operator = Member::Colons;
5517 addResult(std::move(M));
5518 }
5519
5520 void addValue(Expr *E, DeclarationName Name,
5521 Member::AccessOperator Operator) {
5522 if (!Name.isIdentifier())
5523 return;
5524 Member Result;
5525 Result.Name = Name.getAsIdentifierInfo();
5526 Result.Operator = Operator;
5527 // If this is the callee of an immediately-enclosing CallExpr, then
5528 // treat it as a method, otherwise it's a variable.
5529 if (Caller != nullptr && Callee == E) {
5530 Result.ArgTypes.emplace();
5531 for (const auto *Arg : Caller->arguments())
5532 Result.ArgTypes->push_back(Arg->getType());
5533 if (Caller == OuterExpr) {
5534 Result.ResultType = OuterType;
5535 }
5536 } else {
5537 if (E == OuterExpr)
5538 Result.ResultType = OuterType;
5539 }
5540 addResult(std::move(Result));
5541 }
5542 };
5543
5544 static bool isApprox(const TemplateArgument &Arg, const Type *T) {
5545 return Arg.getKind() == TemplateArgument::Type &&
5546 isApprox(Arg.getAsType().getTypePtr(), T);
5547 }
5548
5549 static bool isApprox(const Type *T1, const Type *T2) {
5550 return T1 && T2 &&
5553 }
5554
5555 // Returns the DeclContext immediately enclosed by the template parameter
5556 // scope. For primary templates, this is the templated (e.g.) CXXRecordDecl.
5557 // For specializations, this is e.g. ClassTemplatePartialSpecializationDecl.
5558 static DeclContext *getTemplatedEntity(const TemplateTypeParmDecl *D,
5559 Scope *S) {
5560 if (D == nullptr)
5561 return nullptr;
5562 Scope *Inner = nullptr;
5563 while (S) {
5564 if (S->isTemplateParamScope() && S->isDeclScope(D))
5565 return Inner ? Inner->getEntity() : nullptr;
5566 Inner = S;
5567 S = S->getParent();
5568 }
5569 return nullptr;
5570 }
5571
5572 // Gets all the type constraint expressions that might apply to the type
5573 // variables associated with DC (as returned by getTemplatedEntity()).
5575 constraintsForTemplatedEntity(DeclContext *DC) {
5577 if (DC == nullptr)
5578 return Result;
5579 // Primary templates can have constraints.
5580 if (const auto *TD = cast<Decl>(DC)->getDescribedTemplate())
5581 TD->getAssociatedConstraints(Result);
5582 // Partial specializations may have constraints.
5583 if (const auto *CTPSD =
5584 dyn_cast<ClassTemplatePartialSpecializationDecl>(DC))
5585 CTPSD->getAssociatedConstraints(Result);
5586 if (const auto *VTPSD = dyn_cast<VarTemplatePartialSpecializationDecl>(DC))
5587 VTPSD->getAssociatedConstraints(Result);
5588 return Result;
5589 }
5590
5591 // Attempt to find the unique type satisfying a constraint.
5592 // This lets us show e.g. `int` instead of `std::same_as<int>`.
5593 static QualType deduceType(const TypeConstraint &T) {
5594 // Assume a same_as<T> return type constraint is std::same_as or equivalent.
5595 // In this case the return type is T.
5596 DeclarationName DN = T.getNamedConcept()->getDeclName();
5597 if (DN.isIdentifier() && DN.getAsIdentifierInfo()->isStr("same_as"))
5598 if (const auto *Args = T.getTemplateArgsAsWritten())
5599 if (Args->getNumTemplateArgs() == 1) {
5600 const auto &Arg = Args->arguments().front().getArgument();
5601 if (Arg.getKind() == TemplateArgument::Type)
5602 return Arg.getAsType();
5603 }
5604 return {};
5605 }
5606
5607 llvm::DenseMap<const IdentifierInfo *, Member> Results;
5608};
5609
5610// Returns a type for E that yields acceptable member completions.
5611// In particular, when E->getType() is DependentTy, try to guess a likely type.
5612// We accept some lossiness (like dropping parameters).
5613// We only try to handle common expressions on the LHS of MemberExpr.
5614QualType getApproximateType(const Expr *E) {
5615 if (E->getType().isNull())
5616 return QualType();
5617 E = E->IgnoreParenImpCasts();
5619 // We only resolve DependentTy, or undeduced autos (including auto* etc).
5620 if (!Unresolved->isSpecificBuiltinType(BuiltinType::Dependent)) {
5621 AutoType *Auto = Unresolved->getContainedAutoType();
5622 if (!Auto || !Auto->isUndeducedAutoType())
5623 return Unresolved;
5624 }
5625 // A call: approximate-resolve callee to a function type, get its return type
5626 if (const CallExpr *CE = llvm::dyn_cast<CallExpr>(E)) {
5627 QualType Callee = getApproximateType(CE->getCallee());
5628 if (Callee.isNull() ||
5629 Callee->isSpecificPlaceholderType(BuiltinType::BoundMember))
5631 if (Callee.isNull())
5632 return Unresolved;
5633
5634 if (const auto *FnTypePtr = Callee->getAs<PointerType>()) {
5635 Callee = FnTypePtr->getPointeeType();
5636 } else if (const auto *BPT = Callee->getAs<BlockPointerType>()) {
5637 Callee = BPT->getPointeeType();
5638 }
5639 if (const FunctionType *FnType = Callee->getAs<FunctionType>())
5640 return FnType->getReturnType().getNonReferenceType();
5641
5642 // Unresolved call: try to guess the return type.
5643 if (const auto *OE = llvm::dyn_cast<OverloadExpr>(CE->getCallee())) {
5644 // If all candidates have the same approximate return type, use it.
5645 // Discard references and const to allow more to be "the same".
5646 // (In particular, if there's one candidate + ADL, resolve it).
5647 const Type *Common = nullptr;
5648 for (const auto *D : OE->decls()) {
5649 QualType ReturnType;
5650 if (const auto *FD = llvm::dyn_cast<FunctionDecl>(D))
5651 ReturnType = FD->getReturnType();
5652 else if (const auto *FTD = llvm::dyn_cast<FunctionTemplateDecl>(D))
5653 ReturnType = FTD->getTemplatedDecl()->getReturnType();
5654 if (ReturnType.isNull())
5655 continue;
5656 const Type *Candidate =
5658 if (Common && Common != Candidate)
5659 return Unresolved; // Multiple candidates.
5660 Common = Candidate;
5661 }
5662 if (Common != nullptr)
5663 return QualType(Common, 0);
5664 }
5665 }
5666 // A dependent member: approximate-resolve the base, then lookup.
5667 if (const auto *CDSME = llvm::dyn_cast<CXXDependentScopeMemberExpr>(E)) {
5668 QualType Base = CDSME->isImplicitAccess()
5669 ? CDSME->getBaseType()
5670 : getApproximateType(CDSME->getBase());
5671 if (CDSME->isArrow() && !Base.isNull())
5672 Base = Base->getPointeeType(); // could handle unique_ptr etc here?
5673 auto *RD =
5674 Base.isNull()
5675 ? nullptr
5676 : llvm::dyn_cast_or_null<CXXRecordDecl>(getAsRecordDecl(Base));
5677 if (RD && RD->isCompleteDefinition()) {
5678 // Look up member heuristically, including in bases.
5679 for (const auto *Member : RD->lookupDependentName(
5680 CDSME->getMember(), [](const NamedDecl *Member) {
5681 return llvm::isa<ValueDecl>(Member);
5682 })) {
5683 return llvm::cast<ValueDecl>(Member)->getType().getNonReferenceType();
5684 }
5685 }
5686 }
5687 // A reference to an `auto` variable: approximate-resolve its initializer.
5688 if (const auto *DRE = llvm::dyn_cast<DeclRefExpr>(E)) {
5689 if (const auto *VD = llvm::dyn_cast<VarDecl>(DRE->getDecl())) {
5690 if (VD->hasInit())
5691 return getApproximateType(VD->getInit());
5692 }
5693 }
5694 if (const auto *UO = llvm::dyn_cast<UnaryOperator>(E)) {
5695 if (UO->getOpcode() == UnaryOperatorKind::UO_Deref)
5696 return UO->getSubExpr()->getType()->getPointeeType();
5697 }
5698 return Unresolved;
5699}
5700
5701// If \p Base is ParenListExpr, assume a chain of comma operators and pick the
5702// last expr. We expect other ParenListExprs to be resolved to e.g. constructor
5703// calls before here. (So the ParenListExpr should be nonempty, but check just
5704// in case)
5705Expr *unwrapParenList(Expr *Base) {
5706 if (auto *PLE = llvm::dyn_cast_or_null<ParenListExpr>(Base)) {
5707 if (PLE->getNumExprs() == 0)
5708 return nullptr;
5709 Base = PLE->getExpr(PLE->getNumExprs() - 1);
5710 }
5711 return Base;
5712}
5713
5714} // namespace
5715
5717 Scope *S, Expr *Base, Expr *OtherOpBase, SourceLocation OpLoc, bool IsArrow,
5718 bool IsBaseExprStatement, QualType PreferredType) {
5719 Base = unwrapParenList(Base);
5720 OtherOpBase = unwrapParenList(OtherOpBase);
5721 if (!Base || !CodeCompleter)
5722 return;
5723
5724 ExprResult ConvertedBase =
5725 SemaRef.PerformMemberExprBaseConversion(Base, IsArrow);
5726 if (ConvertedBase.isInvalid())
5727 return;
5728 QualType ConvertedBaseType = getApproximateType(ConvertedBase.get());
5729
5730 enum CodeCompletionContext::Kind contextKind;
5731
5732 if (IsArrow) {
5733 if (const auto *Ptr = ConvertedBaseType->getAs<PointerType>())
5734 ConvertedBaseType = Ptr->getPointeeType();
5735 }
5736
5737 if (IsArrow) {
5739 } else {
5740 if (ConvertedBaseType->isObjCObjectPointerType() ||
5741 ConvertedBaseType->isObjCObjectOrInterfaceType()) {
5743 } else {
5745 }
5746 }
5747
5748 CodeCompletionContext CCContext(contextKind, ConvertedBaseType);
5749 CCContext.setPreferredType(PreferredType);
5750 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(),
5751 CodeCompleter->getCodeCompletionTUInfo(), CCContext,
5752 &ResultBuilder::IsMember);
5753
5754 auto DoCompletion = [&](Expr *Base, bool IsArrow,
5755 std::optional<FixItHint> AccessOpFixIt) -> bool {
5756 if (!Base)
5757 return false;
5758
5759 ExprResult ConvertedBase =
5760 SemaRef.PerformMemberExprBaseConversion(Base, IsArrow);
5761 if (ConvertedBase.isInvalid())
5762 return false;
5763 Base = ConvertedBase.get();
5764
5765 QualType BaseType = getApproximateType(Base);
5766 if (BaseType.isNull())
5767 return false;
5768 ExprValueKind BaseKind = Base->getValueKind();
5769
5770 if (IsArrow) {
5771 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
5772 BaseType = Ptr->getPointeeType();
5773 BaseKind = VK_LValue;
5774 } else if (BaseType->isObjCObjectPointerType() ||
5775 BaseType->isTemplateTypeParmType()) {
5776 // Both cases (dot/arrow) handled below.
5777 } else {
5778 return false;
5779 }
5780 }
5781
5782 if (RecordDecl *RD = getAsRecordDecl(BaseType)) {
5783 AddRecordMembersCompletionResults(SemaRef, Results, S, BaseType, BaseKind,
5784 RD, std::move(AccessOpFixIt));
5785 } else if (const auto *TTPT =
5786 dyn_cast<TemplateTypeParmType>(BaseType.getTypePtr())) {
5787 auto Operator =
5788 IsArrow ? ConceptInfo::Member::Arrow : ConceptInfo::Member::Dot;
5789 for (const auto &R : ConceptInfo(*TTPT, S).members()) {
5790 if (R.Operator != Operator)
5791 continue;
5793 R.render(SemaRef, CodeCompleter->getAllocator(),
5794 CodeCompleter->getCodeCompletionTUInfo()));
5795 if (AccessOpFixIt)
5796 Result.FixIts.push_back(*AccessOpFixIt);
5797 Results.AddResult(std::move(Result));
5798 }
5799 } else if (!IsArrow && BaseType->isObjCObjectPointerType()) {
5800 // Objective-C property reference. Bail if we're performing fix-it code
5801 // completion since Objective-C properties are normally backed by ivars,
5802 // most Objective-C fix-its here would have little value.
5803 if (AccessOpFixIt) {
5804 return false;
5805 }
5806 AddedPropertiesSet AddedProperties;
5807
5808 if (const ObjCObjectPointerType *ObjCPtr =
5809 BaseType->getAsObjCInterfacePointerType()) {
5810 // Add property results based on our interface.
5811 assert(ObjCPtr && "Non-NULL pointer guaranteed above!");
5812 AddObjCProperties(CCContext, ObjCPtr->getInterfaceDecl(), true,
5813 /*AllowNullaryMethods=*/true, SemaRef.CurContext,
5814 AddedProperties, Results, IsBaseExprStatement);
5815 }
5816
5817 // Add properties from the protocols in a qualified interface.
5818 for (auto *I : BaseType->castAs<ObjCObjectPointerType>()->quals())
5819 AddObjCProperties(CCContext, I, true, /*AllowNullaryMethods=*/true,
5820 SemaRef.CurContext, AddedProperties, Results,
5821 IsBaseExprStatement, /*IsClassProperty*/ false,
5822 /*InOriginalClass*/ false);
5823 } else if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
5824 (!IsArrow && BaseType->isObjCObjectType())) {
5825 // Objective-C instance variable access. Bail if we're performing fix-it
5826 // code completion since Objective-C properties are normally backed by
5827 // ivars, most Objective-C fix-its here would have little value.
5828 if (AccessOpFixIt) {
5829 return false;
5830 }
5831 ObjCInterfaceDecl *Class = nullptr;
5832 if (const ObjCObjectPointerType *ObjCPtr =
5833 BaseType->getAs<ObjCObjectPointerType>())
5834 Class = ObjCPtr->getInterfaceDecl();
5835 else
5836 Class = BaseType->castAs<ObjCObjectType>()->getInterface();
5837
5838 // Add all ivars from this class and its superclasses.
5839 if (Class) {
5840 CodeCompletionDeclConsumer Consumer(Results, Class, BaseType);
5841 Results.setFilter(&ResultBuilder::IsObjCIvar);
5843 CodeCompleter->includeGlobals(),
5844 /*IncludeDependentBases=*/false,
5845 CodeCompleter->loadExternal());
5846 }
5847 }
5848
5849 // FIXME: How do we cope with isa?
5850 return true;
5851 };
5852
5853 Results.EnterNewScope();
5854
5855 bool CompletionSucceded = DoCompletion(Base, IsArrow, std::nullopt);
5856 if (CodeCompleter->includeFixIts()) {
5857 const CharSourceRange OpRange =
5858 CharSourceRange::getTokenRange(OpLoc, OpLoc);
5859 CompletionSucceded |= DoCompletion(
5860 OtherOpBase, !IsArrow,
5861 FixItHint::CreateReplacement(OpRange, IsArrow ? "." : "->"));
5862 }
5863
5864 Results.ExitScope();
5865
5866 if (!CompletionSucceded)
5867 return;
5868
5869 // Hand off the results found for code completion.
5870 HandleCodeCompleteResults(&SemaRef, CodeCompleter,
5871 Results.getCompletionContext(), Results.data(),
5872 Results.size());
5873}
5874
5876 Scope *S, const IdentifierInfo &ClassName, SourceLocation ClassNameLoc,
5877 bool IsBaseExprStatement) {
5878 const IdentifierInfo *ClassNamePtr = &ClassName;
5879 ObjCInterfaceDecl *IFace =
5880 SemaRef.ObjC().getObjCInterfaceDecl(ClassNamePtr, ClassNameLoc);
5881 if (!IFace)
5882 return;
5883 CodeCompletionContext CCContext(
5885 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(),
5886 CodeCompleter->getCodeCompletionTUInfo(), CCContext,
5887 &ResultBuilder::IsMember);
5888 Results.EnterNewScope();
5889 AddedPropertiesSet AddedProperties;
5890 AddObjCProperties(CCContext, IFace, true,
5891 /*AllowNullaryMethods=*/true, SemaRef.CurContext,
5892 AddedProperties, Results, IsBaseExprStatement,
5893 /*IsClassProperty=*/true);
5894 Results.ExitScope();
5895 HandleCodeCompleteResults(&SemaRef, CodeCompleter,
5896 Results.getCompletionContext(), Results.data(),
5897 Results.size());
5898}
5899
5900void SemaCodeCompletion::CodeCompleteTag(Scope *S, unsigned TagSpec) {
5901 if (!CodeCompleter)
5902 return;
5903
5904 ResultBuilder::LookupFilter Filter = nullptr;
5905 enum CodeCompletionContext::Kind ContextKind =
5907 switch ((DeclSpec::TST)TagSpec) {
5908 case DeclSpec::TST_enum:
5909 Filter = &ResultBuilder::IsEnum;
5911 break;
5912
5914 Filter = &ResultBuilder::IsUnion;
5916 break;
5917
5921 Filter = &ResultBuilder::IsClassOrStruct;
5923 break;
5924
5925 default:
5926 llvm_unreachable("Unknown type specifier kind in CodeCompleteTag");
5927 }
5928
5929 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(),
5930 CodeCompleter->getCodeCompletionTUInfo(), ContextKind);
5931 CodeCompletionDeclConsumer Consumer(Results, SemaRef.CurContext);
5932
5933 // First pass: look for tags.
5934 Results.setFilter(Filter);
5935 SemaRef.LookupVisibleDecls(S, Sema::LookupTagName, Consumer,
5936 CodeCompleter->includeGlobals(),
5937 CodeCompleter->loadExternal());
5938
5939 if (CodeCompleter->includeGlobals()) {
5940 // Second pass: look for nested name specifiers.
5941 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
5943 CodeCompleter->includeGlobals(),
5944 CodeCompleter->loadExternal());
5945 }
5946
5947 HandleCodeCompleteResults(&SemaRef, CodeCompleter,
5948 Results.getCompletionContext(), Results.data(),
5949 Results.size());
5950}
5951
5952static void AddTypeQualifierResults(DeclSpec &DS, ResultBuilder &Results,
5953 const LangOptions &LangOpts) {
5955 Results.AddResult("const");
5957 Results.AddResult("volatile");
5958 if (LangOpts.C99 && !(DS.getTypeQualifiers() & DeclSpec::TQ_restrict))
5959 Results.AddResult("restrict");
5960 if (LangOpts.C11 && !(DS.getTypeQualifiers() & DeclSpec::TQ_atomic))
5961 Results.AddResult("_Atomic");
5962 if (LangOpts.MSVCCompat && !(DS.getTypeQualifiers() & DeclSpec::TQ_unaligned))
5963 Results.AddResult("__unaligned");
5964}
5965
5967 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(),
5968 CodeCompleter->getCodeCompletionTUInfo(),
5970 Results.EnterNewScope();
5971 AddTypeQualifierResults(DS, Results, getLangOpts());
5972 Results.ExitScope();
5973 HandleCodeCompleteResults(&SemaRef, CodeCompleter,
5974 Results.getCompletionContext(), Results.data(),
5975 Results.size());
5976}
5977
5979 DeclSpec &DS, Declarator &D, const VirtSpecifiers *VS) {
5980 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(),
5981 CodeCompleter->getCodeCompletionTUInfo(),
5983 Results.EnterNewScope();
5984 AddTypeQualifierResults(DS, Results, getLangOpts());
5985 if (getLangOpts().CPlusPlus11) {
5986 Results.AddResult("noexcept");
5988 !D.isStaticMember()) {
5989 if (!VS || !VS->isFinalSpecified())
5990 Results.AddResult("final");
5991 if (!VS || !VS->isOverrideSpecified())
5992 Results.AddResult("override");
5993 }
5994 }
5995 Results.ExitScope();
5996 HandleCodeCompleteResults(&SemaRef, CodeCompleter,
5997 Results.getCompletionContext(), Results.data(),
5998 Results.size());
5999}
6000
6002 CodeCompleteExpression(S, QualType(getASTContext().getSizeType()));
6003}
6004
6006 if (SemaRef.getCurFunction()->SwitchStack.empty() || !CodeCompleter)
6007 return;
6008
6010 SemaRef.getCurFunction()->SwitchStack.back().getPointer();
6011 // Condition expression might be invalid, do not continue in this case.
6012 if (!Switch->getCond())
6013 return;
6014 QualType type = Switch->getCond()->IgnoreImplicit()->getType();
6015 if (!type->isEnumeralType()) {
6017 Data.IntegralConstantExpression = true;
6018 CodeCompleteExpression(S, Data);
6019 return;
6020 }
6021
6022 // Code-complete the cases of a switch statement over an enumeration type
6023 // by providing the list of
6024 EnumDecl *Enum = type->castAs<EnumType>()->getDecl();
6025 if (EnumDecl *Def = Enum->getDefinition())
6026 Enum = Def;
6027
6028 // Determine which enumerators we have already seen in the switch statement.
6029 // FIXME: Ideally, we would also be able to look *past* the code-completion
6030 // token, in case we are code-completing in the middle of the switch and not
6031 // at the end. However, we aren't able to do so at the moment.
6032 CoveredEnumerators Enumerators;
6033 for (SwitchCase *SC = Switch->getSwitchCaseList(); SC;
6034 SC = SC->getNextSwitchCase()) {
6035 CaseStmt *Case = dyn_cast<CaseStmt>(SC);
6036 if (!Case)
6037 continue;
6038
6039 Expr *CaseVal = Case->getLHS()->IgnoreParenCasts();
6040 if (auto *DRE = dyn_cast<DeclRefExpr>(CaseVal))
6041 if (auto *Enumerator =
6042 dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
6043 // We look into the AST of the case statement to determine which
6044 // enumerator was named. Alternatively, we could compute the value of
6045 // the integral constant expression, then compare it against the
6046 // values of each enumerator. However, value-based approach would not
6047 // work as well with C++ templates where enumerators declared within a
6048 // template are type- and value-dependent.
6049 Enumerators.Seen.insert(Enumerator);
6050
6051 // If this is a qualified-id, keep track of the nested-name-specifier
6052 // so that we can reproduce it as part of code completion, e.g.,
6053 //
6054 // switch (TagD.getKind()) {
6055 // case TagDecl::TK_enum:
6056 // break;
6057 // case XXX
6058 //
6059 // At the XXX, our completions are TagDecl::TK_union,
6060 // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
6061 // TK_struct, and TK_class.
6062 Enumerators.SuggestedQualifier = DRE->getQualifier();
6063 }
6064 }
6065
6066 // Add any enumerators that have not yet been mentioned.
6067 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(),
6068 CodeCompleter->getCodeCompletionTUInfo(),
6070 AddEnumerators(Results, getASTContext(), Enum, SemaRef.CurContext,
6071 Enumerators);
6072
6073 if (CodeCompleter->includeMacros()) {
6074 AddMacroResults(SemaRef.PP, Results, CodeCompleter->loadExternal(), false);
6075 }
6076 HandleCodeCompleteResults(&SemaRef, CodeCompleter,
6077 Results.getCompletionContext(), Results.data(),
6078 Results.size());
6079}
6080
6082 if (Args.size() && !Args.data())
6083 return true;
6084
6085 for (unsigned I = 0; I != Args.size(); ++I)
6086 if (!Args[I])
6087 return true;
6088
6089 return false;
6090}
6091
6093
6095 Sema &SemaRef, SmallVectorImpl<ResultCandidate> &Results,
6096 OverloadCandidateSet &CandidateSet, SourceLocation Loc, size_t ArgSize) {
6097 // Sort the overload candidate set by placing the best overloads first.
6098 llvm::stable_sort(CandidateSet, [&](const OverloadCandidate &X,
6099 const OverloadCandidate &Y) {
6100 return isBetterOverloadCandidate(SemaRef, X, Y, Loc,
6101 CandidateSet.getKind());
6102 });
6103
6104 // Add the remaining viable overload candidates as code-completion results.
6105 for (OverloadCandidate &Candidate : CandidateSet) {
6106 if (Candidate.Function) {
6107 if (Candidate.Function->isDeleted())
6108 continue;
6109 if (shouldEnforceArgLimit(/*PartialOverloading=*/true,
6110 Candidate.Function) &&
6111 Candidate.Function->getNumParams() <= ArgSize &&
6112 // Having zero args is annoying, normally we don't surface a function
6113 // with 2 params, if you already have 2 params, because you are
6114 // inserting the 3rd now. But with zero, it helps the user to figure
6115 // out there are no overloads that take any arguments. Hence we are
6116 // keeping the overload.
6117 ArgSize > 0)
6118 continue;
6119 }
6120 if (Candidate.Viable)
6121 Results.push_back(ResultCandidate(Candidate.Function));
6122 }
6123}
6124
6125/// Get the type of the Nth parameter from a given set of overload
6126/// candidates.
6128 ArrayRef<ResultCandidate> Candidates, unsigned N) {
6129
6130 // Given the overloads 'Candidates' for a function call matching all arguments
6131 // up to N, return the type of the Nth parameter if it is the same for all
6132 // overload candidates.
6133 QualType ParamType;
6134 for (auto &Candidate : Candidates) {
6135 QualType CandidateParamType = Candidate.getParamType(N);
6136 if (CandidateParamType.isNull())
6137 continue;
6138 if (ParamType.isNull()) {
6139 ParamType = CandidateParamType;
6140 continue;
6141 }
6142 if (!SemaRef.Context.hasSameUnqualifiedType(
6143 ParamType.getNonReferenceType(),
6144 CandidateParamType.getNonReferenceType()))
6145 // Two conflicting types, give up.
6146 return QualType();
6147 }
6148
6149 return ParamType;
6150}
6151
6152static QualType
6154 unsigned CurrentArg, SourceLocation OpenParLoc,
6155 bool Braced) {
6156 if (Candidates.empty())
6157 return QualType();
6160 SemaRef, CurrentArg, Candidates.data(), Candidates.size(), OpenParLoc,
6161 Braced);
6162 return getParamType(SemaRef, Candidates, CurrentArg);
6163}
6164
6165// Given a callee expression `Fn`, if the call is through a function pointer,
6166// try to find the declaration of the corresponding function pointer type,
6167// so that we can recover argument names from it.
6170
6171 if (const auto *T = Fn->getType().getTypePtr()->getAs<TypedefType>()) {
6172 Target = T->getDecl()->getTypeSourceInfo()->getTypeLoc();
6173
6174 } else if (const auto *DR = dyn_cast<DeclRefExpr>(Fn)) {
6175 const auto *D = DR->getDecl();
6176 if (const auto *const VD = dyn_cast<VarDecl>(D)) {
6177 Target = VD->getTypeSourceInfo()->getTypeLoc();
6178 }
6179 } else if (const auto *ME = dyn_cast<MemberExpr>(Fn)) {
6180 const auto *MD = ME->getMemberDecl();
6181 if (const auto *FD = dyn_cast<FieldDecl>(MD)) {
6182 Target = FD->getTypeSourceInfo()->getTypeLoc();
6183 }
6184 }
6185
6186 if (!Target)
6187 return {};
6188
6189 // Unwrap types that may be wrapping the function type
6190 while (true) {
6191 if (auto P = Target.getAs<PointerTypeLoc>()) {
6192 Target = P.getPointeeLoc();
6193 continue;
6194 }
6195 if (auto A = Target.getAs<AttributedTypeLoc>()) {
6196 Target = A.getModifiedLoc();
6197 continue;
6198 }
6199 if (auto P = Target.getAs<ParenTypeLoc>()) {
6200 Target = P.getInnerLoc();
6201 continue;
6202 }
6203 break;
6204 }
6205
6206 if (auto F = Target.getAs<FunctionProtoTypeLoc>()) {
6207 return F;
6208 }
6209
6210 return {};
6211}
6212
6215 SourceLocation OpenParLoc) {
6216 Fn = unwrapParenList(Fn);
6217 if (!CodeCompleter || !Fn)
6218 return QualType();
6219
6220 // FIXME: Provide support for variadic template functions.
6221 // Ignore type-dependent call expressions entirely.
6222 if (Fn->isTypeDependent() || anyNullArguments(Args))
6223 return QualType();
6224 // In presence of dependent args we surface all possible signatures using the
6225 // non-dependent args in the prefix. Afterwards we do a post filtering to make
6226 // sure provided candidates satisfy parameter count restrictions.
6227 auto ArgsWithoutDependentTypes =
6228 Args.take_while([](Expr *Arg) { return !Arg->isTypeDependent(); });
6229
6231
6232 Expr *NakedFn = Fn->IgnoreParenCasts();
6233 // Build an overload candidate set based on the functions we find.
6236
6237 if (auto ULE = dyn_cast<UnresolvedLookupExpr>(NakedFn)) {
6238 SemaRef.AddOverloadedCallCandidates(ULE, ArgsWithoutDependentTypes,
6239 CandidateSet,
6240 /*PartialOverloading=*/true);
6241 } else if (auto UME = dyn_cast<UnresolvedMemberExpr>(NakedFn)) {
6242 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
6243 if (UME->hasExplicitTemplateArgs()) {
6244 UME->copyTemplateArgumentsInto(TemplateArgsBuffer);
6245 TemplateArgs = &TemplateArgsBuffer;
6246 }
6247
6248 // Add the base as first argument (use a nullptr if the base is implicit).
6249 SmallVector<Expr *, 12> ArgExprs(
6250 1, UME->isImplicitAccess() ? nullptr : UME->getBase());
6251 ArgExprs.append(ArgsWithoutDependentTypes.begin(),
6252 ArgsWithoutDependentTypes.end());
6253 UnresolvedSet<8> Decls;
6254 Decls.append(UME->decls_begin(), UME->decls_end());
6255 const bool FirstArgumentIsBase = !UME->isImplicitAccess() && UME->getBase();
6256 SemaRef.AddFunctionCandidates(Decls, ArgExprs, CandidateSet, TemplateArgs,
6257 /*SuppressUserConversions=*/false,
6258 /*PartialOverloading=*/true,
6259 FirstArgumentIsBase);
6260 } else {
6261 FunctionDecl *FD = nullptr;
6262 if (auto *MCE = dyn_cast<MemberExpr>(NakedFn))
6263 FD = dyn_cast<FunctionDecl>(MCE->getMemberDecl());
6264 else if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn))
6265 FD = dyn_cast<FunctionDecl>(DRE->getDecl());
6266 if (FD) { // We check whether it's a resolved function declaration.
6267 if (!getLangOpts().CPlusPlus ||
6268 !FD->getType()->getAs<FunctionProtoType>())
6269 Results.push_back(ResultCandidate(FD));
6270 else
6271 SemaRef.AddOverloadCandidate(FD,
6273 ArgsWithoutDependentTypes, CandidateSet,
6274 /*SuppressUserConversions=*/false,
6275 /*PartialOverloading=*/true);
6276
6277 } else if (auto DC = NakedFn->getType()->getAsCXXRecordDecl()) {
6278 // If expression's type is CXXRecordDecl, it may overload the function
6279 // call operator, so we check if it does and add them as candidates.
6280 // A complete type is needed to lookup for member function call operators.
6281 if (SemaRef.isCompleteType(Loc, NakedFn->getType())) {
6282 DeclarationName OpName =
6283 getASTContext().DeclarationNames.getCXXOperatorName(OO_Call);
6284 LookupResult R(SemaRef, OpName, Loc, Sema::LookupOrdinaryName);
6285 SemaRef.LookupQualifiedName(R, DC);
6287 SmallVector<Expr *, 12> ArgExprs(1, NakedFn);
6288 ArgExprs.append(ArgsWithoutDependentTypes.begin(),
6289 ArgsWithoutDependentTypes.end());
6290 SemaRef.AddFunctionCandidates(R.asUnresolvedSet(), ArgExprs,
6291 CandidateSet,
6292 /*ExplicitArgs=*/nullptr,
6293 /*SuppressUserConversions=*/false,
6294 /*PartialOverloading=*/true);
6295 }
6296 } else {
6297 // Lastly we check whether expression's type is function pointer or
6298 // function.
6299
6301 QualType T = NakedFn->getType();
6302 if (!T->getPointeeType().isNull())
6303 T = T->getPointeeType();
6304
6305 if (auto FP = T->getAs<FunctionProtoType>()) {
6306 if (!SemaRef.TooManyArguments(FP->getNumParams(),
6307 ArgsWithoutDependentTypes.size(),
6308 /*PartialOverloading=*/true) ||
6309 FP->isVariadic()) {
6310 if (P) {
6311 Results.push_back(ResultCandidate(P));
6312 } else {
6313 Results.push_back(ResultCandidate(FP));
6314 }
6315 }
6316 } else if (auto FT = T->getAs<FunctionType>())
6317 // No prototype and declaration, it may be a K & R style function.
6318 Results.push_back(ResultCandidate(FT));
6319 }
6320 }
6321 mergeCandidatesWithResults(SemaRef, Results, CandidateSet, Loc, Args.size());
6322 QualType ParamType = ProduceSignatureHelp(SemaRef, Results, Args.size(),
6323 OpenParLoc, /*Braced=*/false);
6324 return !CandidateSet.empty() ? ParamType : QualType();
6325}
6326
6327// Determine which param to continue aggregate initialization from after
6328// a designated initializer.
6329//
6330// Given struct S { int a,b,c,d,e; }:
6331// after `S{.b=1,` we want to suggest c to continue
6332// after `S{.b=1, 2,` we continue with d (this is legal C and ext in C++)
6333// after `S{.b=1, .a=2,` we continue with b (this is legal C and ext in C++)
6334//
6335// Possible outcomes:
6336// - we saw a designator for a field, and continue from the returned index.
6337// Only aggregate initialization is allowed.
6338// - we saw a designator, but it was complex or we couldn't find the field.
6339// Only aggregate initialization is possible, but we can't assist with it.
6340// Returns an out-of-range index.
6341// - we saw no designators, just positional arguments.
6342// Returns std::nullopt.
6343static std::optional<unsigned>
6345 ArrayRef<Expr *> Args) {
6346 static constexpr unsigned Invalid = std::numeric_limits<unsigned>::max();
6347 assert(Aggregate.getKind() == ResultCandidate::CK_Aggregate);
6348
6349 // Look for designated initializers.
6350 // They're in their syntactic form, not yet resolved to fields.
6351 const IdentifierInfo *DesignatedFieldName = nullptr;
6352 unsigned ArgsAfterDesignator = 0;
6353 for (const Expr *Arg : Args) {
6354 if (const auto *DIE = dyn_cast<DesignatedInitExpr>(Arg)) {
6355 if (DIE->size() == 1 && DIE->getDesignator(0)->isFieldDesignator()) {
6356 DesignatedFieldName = DIE->getDesignator(0)->getFieldName();
6357 ArgsAfterDesignator = 0;
6358 } else {
6359 return Invalid; // Complicated designator.
6360 }
6361 } else if (isa<DesignatedInitUpdateExpr>(Arg)) {
6362 return Invalid; // Unsupported.
6363 } else {
6364 ++ArgsAfterDesignator;
6365 }
6366 }
6367 if (!DesignatedFieldName)
6368 return std::nullopt;
6369
6370 // Find the index within the class's fields.
6371 // (Probing getParamDecl() directly would be quadratic in number of fields).
6372 unsigned DesignatedIndex = 0;
6373 const FieldDecl *DesignatedField = nullptr;
6374 for (const auto *Field : Aggregate.getAggregate()->fields()) {
6375 if (Field->getIdentifier() == DesignatedFieldName) {
6376 DesignatedField = Field;
6377 break;
6378 }
6379 ++DesignatedIndex;
6380 }
6381 if (!DesignatedField)
6382 return Invalid; // Designator referred to a missing field, give up.
6383
6384 // Find the index within the aggregate (which may have leading bases).
6385 unsigned AggregateSize = Aggregate.getNumParams();
6386 while (DesignatedIndex < AggregateSize &&
6387 Aggregate.getParamDecl(DesignatedIndex) != DesignatedField)
6388 ++DesignatedIndex;
6389
6390 // Continue from the index after the last named field.
6391 return DesignatedIndex + ArgsAfterDesignator + 1;
6392}
6393
6396 SourceLocation OpenParLoc, bool Braced) {
6397 if (!CodeCompleter)
6398 return QualType();
6400
6401 // A complete type is needed to lookup for constructors.
6402 RecordDecl *RD =
6403 SemaRef.isCompleteType(Loc, Type) ? Type->getAsRecordDecl() : nullptr;
6404 if (!RD)
6405 return Type;
6406 CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD);
6407
6408 // Consider aggregate initialization.
6409 // We don't check that types so far are correct.
6410 // We also don't handle C99/C++17 brace-elision, we assume init-list elements
6411 // are 1:1 with fields.
6412 // FIXME: it would be nice to support "unwrapping" aggregates that contain
6413 // a single subaggregate, like std::array<T, N> -> T __elements[N].
6414 if (Braced && !RD->isUnion() &&
6415 (!getLangOpts().CPlusPlus || (CRD && CRD->isAggregate()))) {
6416 ResultCandidate AggregateSig(RD);
6417 unsigned AggregateSize = AggregateSig.getNumParams();
6418
6419 if (auto NextIndex =
6420 getNextAggregateIndexAfterDesignatedInit(AggregateSig, Args)) {
6421 // A designator was used, only aggregate init is possible.
6422 if (*NextIndex >= AggregateSize)
6423 return Type;
6424 Results.push_back(AggregateSig);
6425 return ProduceSignatureHelp(SemaRef, Results, *NextIndex, OpenParLoc,
6426 Braced);
6427 }
6428
6429 // Describe aggregate initialization, but also constructors below.
6430 if (Args.size() < AggregateSize)
6431 Results.push_back(AggregateSig);
6432 }
6433
6434 // FIXME: Provide support for member initializers.
6435 // FIXME: Provide support for variadic template constructors.
6436
6437 if (CRD) {
6439 for (NamedDecl *C : SemaRef.LookupConstructors(CRD)) {
6440 if (auto *FD = dyn_cast<FunctionDecl>(C)) {
6441 // FIXME: we can't yet provide correct signature help for initializer
6442 // list constructors, so skip them entirely.
6443 if (Braced && getLangOpts().CPlusPlus &&
6444 SemaRef.isInitListConstructor(FD))
6445 continue;
6446 SemaRef.AddOverloadCandidate(
6447 FD, DeclAccessPair::make(FD, C->getAccess()), Args, CandidateSet,
6448 /*SuppressUserConversions=*/false,
6449 /*PartialOverloading=*/true,
6450 /*AllowExplicit*/ true);
6451 } else if (auto *FTD = dyn_cast<FunctionTemplateDecl>(C)) {
6452 if (Braced && getLangOpts().CPlusPlus &&
6453 SemaRef.isInitListConstructor(FTD->getTemplatedDecl()))
6454 continue;
6455
6457 FTD, DeclAccessPair::make(FTD, C->getAccess()),
6458 /*ExplicitTemplateArgs=*/nullptr, Args, CandidateSet,
6459 /*SuppressUserConversions=*/false,
6460 /*PartialOverloading=*/true);
6461 }
6462 }
6463 mergeCandidatesWithResults(SemaRef, Results, CandidateSet, Loc,
6464 Args.size());
6465 }
6466
6467 return ProduceSignatureHelp(SemaRef, Results, Args.size(), OpenParLoc,
6468 Braced);
6469}
6470
6472 Decl *ConstructorDecl, CXXScopeSpec SS, ParsedType TemplateTypeTy,
6473 ArrayRef<Expr *> ArgExprs, IdentifierInfo *II, SourceLocation OpenParLoc,
6474 bool Braced) {
6475 if (!CodeCompleter)
6476 return QualType();
6477
6478 CXXConstructorDecl *Constructor =
6479 dyn_cast<CXXConstructorDecl>(ConstructorDecl);
6480 if (!Constructor)
6481 return QualType();
6482 // FIXME: Add support for Base class constructors as well.
6483 if (ValueDecl *MemberDecl = SemaRef.tryLookupCtorInitMemberDecl(
6484 Constructor->getParent(), SS, TemplateTypeTy, II))
6485 return ProduceConstructorSignatureHelp(MemberDecl->getType(),
6486 MemberDecl->getLocation(), ArgExprs,
6487 OpenParLoc, Braced);
6488 return QualType();
6489}
6490
6492 unsigned Index,
6493 const TemplateParameterList &Params) {
6494 const NamedDecl *Param;
6495 if (Index < Params.size())
6496 Param = Params.getParam(Index);
6497 else if (Params.hasParameterPack())
6498 Param = Params.asArray().back();
6499 else
6500 return false; // too many args
6501
6502 switch (Arg.getKind()) {
6504 return llvm::isa<TemplateTypeParmDecl>(Param); // constraints not checked
6506 return llvm::isa<NonTypeTemplateParmDecl>(Param); // type not checked
6508 return llvm::isa<TemplateTemplateParmDecl>(Param); // signature not checked
6509 }
6510 llvm_unreachable("Unhandled switch case");
6511}
6512
6514 TemplateTy ParsedTemplate, ArrayRef<ParsedTemplateArgument> Args,
6515 SourceLocation LAngleLoc) {
6516 if (!CodeCompleter || !ParsedTemplate)
6517 return QualType();
6518
6520 auto Consider = [&](const TemplateDecl *TD) {
6521 // Only add if the existing args are compatible with the template.
6522 bool Matches = true;
6523 for (unsigned I = 0; I < Args.size(); ++I) {
6524 if (!argMatchesTemplateParams(Args[I], I, *TD->getTemplateParameters())) {
6525 Matches = false;
6526 break;
6527 }
6528 }
6529 if (Matches)
6530 Results.emplace_back(TD);
6531 };
6532
6533 TemplateName Template = ParsedTemplate.get();
6534 if (const auto *TD = Template.getAsTemplateDecl()) {
6535 Consider(TD);
6536 } else if (const auto *OTS = Template.getAsOverloadedTemplate()) {
6537 for (const NamedDecl *ND : *OTS)
6538 if (const auto *TD = llvm::dyn_cast<TemplateDecl>(ND))
6539 Consider(TD);
6540 }
6541 return ProduceSignatureHelp(SemaRef, Results, Args.size(), LAngleLoc,
6542 /*Braced=*/false);
6543}
6544
6545static QualType getDesignatedType(QualType BaseType, const Designation &Desig) {
6546 for (unsigned I = 0; I < Desig.getNumDesignators(); ++I) {
6547 if (BaseType.isNull())
6548 break;
6549 QualType NextType;
6550 const auto &D = Desig.getDesignator(I);
6551 if (D.isArrayDesignator() || D.isArrayRangeDesignator()) {
6552 if (BaseType->isArrayType())
6553 NextType = BaseType->getAsArrayTypeUnsafe()->getElementType();
6554 } else {
6555 assert(D.isFieldDesignator());
6556 auto *RD = getAsRecordDecl(BaseType);
6557 if (RD && RD->isCompleteDefinition()) {
6558 for (const auto *Member : RD->lookup(D.getFieldDecl()))
6559 if (const FieldDecl *FD = llvm::dyn_cast<FieldDecl>(Member)) {
6560 NextType = FD->getType();
6561 break;
6562 }
6563 }
6564 }
6565 BaseType = NextType;
6566 }
6567 return BaseType;
6568}
6569
6571 QualType BaseType, llvm::ArrayRef<Expr *> InitExprs, const Designation &D) {
6572 BaseType = getDesignatedType(BaseType, D);
6573 if (BaseType.isNull())
6574 return;
6575 const auto *RD = getAsRecordDecl(BaseType);
6576 if (!RD || RD->fields().empty())
6577 return;
6578
6580 BaseType);
6581 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(),
6582 CodeCompleter->getCodeCompletionTUInfo(), CCC);
6583
6584 Results.EnterNewScope();
6585 for (const Decl *D : RD->decls()) {
6586 const FieldDecl *FD;
6587 if (auto *IFD = dyn_cast<IndirectFieldDecl>(D))
6588 FD = IFD->getAnonField();
6589 else if (auto *DFD = dyn_cast<FieldDecl>(D))
6590 FD = DFD;
6591 else
6592 continue;
6593
6594 // FIXME: Make use of previous designators to mark any fields before those
6595 // inaccessible, and also compute the next initializer priority.
6596 ResultBuilder::Result Result(FD, Results.getBasePriority(FD));
6597 Results.AddResult(Result, SemaRef.CurContext, /*Hiding=*/nullptr);
6598 }
6599 Results.ExitScope();
6600 HandleCodeCompleteResults(&SemaRef, CodeCompleter,
6601 Results.getCompletionContext(), Results.data(),
6602 Results.size());
6603}
6604
6606 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
6607 if (!VD) {
6608 CodeCompleteOrdinaryName(S, PCC_Expression);
6609 return;
6610 }
6611
6613 Data.PreferredType = VD->getType();
6614 // Ignore VD to avoid completing the variable itself, e.g. in 'int foo = ^'.
6615 Data.IgnoreDecls.push_back(VD);
6616
6617 CodeCompleteExpression(S, Data);
6618}
6619
6621 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(),
6622 CodeCompleter->getCodeCompletionTUInfo(),
6623 mapCodeCompletionContext(SemaRef, PCC_Statement));
6624 Results.setFilter(&ResultBuilder::IsOrdinaryName);
6625 Results.EnterNewScope();
6626
6627 CodeCompletionDeclConsumer Consumer(Results, SemaRef.CurContext);
6628 SemaRef.LookupVisibleDecls(S, Sema::LookupOrdinaryName, Consumer,
6629 CodeCompleter->includeGlobals(),
6630 CodeCompleter->loadExternal());
6631
6632 AddOrdinaryNameResults(PCC_Statement, S, SemaRef, Results);
6633
6634 // "else" block
6635 CodeCompletionBuilder Builder(Results.getAllocator(),
6636 Results.getCodeCompletionTUInfo());
6637
6638 auto AddElseBodyPattern = [&] {
6639 if (IsBracedThen) {
6641 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
6643 Builder.AddPlaceholderChunk("statements");
6645 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
6646 } else {
6649 Builder.AddPlaceholderChunk("statement");
6650 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
6651 }
6652 };
6653 Builder.AddTypedTextChunk("else");
6654 if (Results.includeCodePatterns())
6655 AddElseBodyPattern();
6656 Results.AddResult(Builder.TakeString());
6657
6658 // "else if" block
6659 Builder.AddTypedTextChunk("else if");
6661 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6662 if (getLangOpts().CPlusPlus)
6663 Builder.AddPlaceholderChunk("condition");
6664 else
6665 Builder.AddPlaceholderChunk("expression");
6666 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6667 if (Results.includeCodePatterns()) {
6668 AddElseBodyPattern();
6669 }
6670 Results.AddResult(Builder.TakeString());
6671
6672 Results.ExitScope();
6673
6674 if (S->getFnParent())
6675 AddPrettyFunctionResults(getLangOpts(), Results);
6676
6677 if (CodeCompleter->includeMacros())
6678 AddMacroResults(SemaRef.PP, Results, CodeCompleter->loadExternal(), false);
6679
6680 HandleCodeCompleteResults(&SemaRef, CodeCompleter,
6681 Results.getCompletionContext(), Results.data(),
6682 Results.size());
6683}
6684
6686 bool EnteringContext,
6687 bool IsUsingDeclaration,
6688 QualType BaseType,
6689 QualType PreferredType) {
6690 if (SS.isEmpty() || !CodeCompleter)
6691 return;
6692
6694 CC.setIsUsingDeclaration(IsUsingDeclaration);
6695 CC.setCXXScopeSpecifier(SS);
6696
6697 // We want to keep the scope specifier even if it's invalid (e.g. the scope
6698 // "a::b::" is not corresponding to any context/namespace in the AST), since
6699 // it can be useful for global code completion which have information about
6700 // contexts/symbols that are not in the AST.
6701 if (SS.isInvalid()) {
6702 // As SS is invalid, we try to collect accessible contexts from the current
6703 // scope with a dummy lookup so that the completion consumer can try to
6704 // guess what the specified scope is.
6705 ResultBuilder DummyResults(SemaRef, CodeCompleter->getAllocator(),
6706 CodeCompleter->getCodeCompletionTUInfo(), CC);
6707 if (!PreferredType.isNull())
6708 DummyResults.setPreferredType(PreferredType);
6709 if (S->getEntity()) {
6710 CodeCompletionDeclConsumer Consumer(DummyResults, S->getEntity(),
6711 BaseType);
6712 SemaRef.LookupVisibleDecls(S, Sema::LookupOrdinaryName, Consumer,
6713 /*IncludeGlobalScope=*/false,
6714 /*LoadExternal=*/false);
6715 }
6716 HandleCodeCompleteResults(&SemaRef, CodeCompleter,
6717 DummyResults.getCompletionContext(), nullptr, 0);
6718 return;
6719 }
6720 // Always pretend to enter a context to ensure that a dependent type
6721 // resolves to a dependent record.
6722 DeclContext *Ctx = SemaRef.computeDeclContext(SS, /*EnteringContext=*/true);
6723
6724 // Try to instantiate any non-dependent declaration contexts before
6725 // we look in them. Bail out if we fail.
6726 NestedNameSpecifier *NNS = SS.getScopeRep();
6727 if (NNS != nullptr && SS.isValid() && !NNS->isDependent()) {
6728 if (Ctx == nullptr || SemaRef.RequireCompleteDeclContext(SS, Ctx))
6729 return;
6730 }
6731
6732 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(),
6733 CodeCompleter->getCodeCompletionTUInfo(), CC);
6734 if (!PreferredType.isNull())
6735 Results.setPreferredType(PreferredType);
6736 Results.EnterNewScope();
6737
6738 // The "template" keyword can follow "::" in the grammar, but only
6739 // put it into the grammar if the nested-name-specifier is dependent.
6740 // FIXME: results is always empty, this appears to be dead.
6741 if (!Results.empty() && NNS && NNS->isDependent())
6742 Results.AddResult("template");
6743
6744 // If the scope is a concept-constrained type parameter, infer nested
6745 // members based on the constraints.
6746 if (NNS) {
6747 if (const auto *TTPT =
6748 dyn_cast_or_null<TemplateTypeParmType>(NNS->getAsType())) {
6749 for (const auto &R : ConceptInfo(*TTPT, S).members()) {
6750 if (R.Operator != ConceptInfo::Member::Colons)
6751 continue;
6752 Results.AddResult(CodeCompletionResult(
6753 R.render(SemaRef, CodeCompleter->getAllocator(),
6754 CodeCompleter->getCodeCompletionTUInfo())));
6755 }
6756 }
6757 }
6758
6759 // Add calls to overridden virtual functions, if there are any.
6760 //
6761 // FIXME: This isn't wonderful, because we don't know whether we're actually
6762 // in a context that permits expressions. This is a general issue with
6763 // qualified-id completions.
6764 if (Ctx && !EnteringContext)
6765 MaybeAddOverrideCalls(SemaRef, Ctx, Results);
6766 Results.ExitScope();
6767
6768 if (Ctx &&
6769 (CodeCompleter->includeNamespaceLevelDecls() || !Ctx->isFileContext())) {
6770 CodeCompletionDeclConsumer Consumer(Results, Ctx, BaseType);
6771 SemaRef.LookupVisibleDecls(Ctx, Sema::LookupOrdinaryName, Consumer,
6772 /*IncludeGlobalScope=*/true,
6773 /*IncludeDependentBases=*/true,
6774 CodeCompleter->loadExternal());
6775 }
6776
6777 HandleCodeCompleteResults(&SemaRef, CodeCompleter,
6778 Results.getCompletionContext(), Results.data(),
6779 Results.size());
6780}
6781
6783 if (!CodeCompleter)
6784 return;
6785
6786 // This can be both a using alias or using declaration, in the former we
6787 // expect a new name and a symbol in the latter case.
6789 Context.setIsUsingDeclaration(true);
6790
6791 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(),
6792 CodeCompleter->getCodeCompletionTUInfo(), Context,
6793 &ResultBuilder::IsNestedNameSpecifier);
6794 Results.EnterNewScope();
6795
6796 // If we aren't in class scope, we could see the "namespace" keyword.
6797 if (!S->isClassScope())
6798 Results.AddResult(CodeCompletionResult("namespace"));
6799
6800 // After "using", we can see anything that would start a
6801 // nested-name-specifier.
6802 CodeCompletionDeclConsumer Consumer(Results, SemaRef.CurContext);
6803 SemaRef.LookupVisibleDecls(S, Sema::LookupOrdinaryName, Consumer,
6804 CodeCompleter->includeGlobals(),
6805 CodeCompleter->loadExternal());
6806 Results.ExitScope();
6807
6808 HandleCodeCompleteResults(&SemaRef, CodeCompleter,
6809 Results.getCompletionContext(), Results.data(),
6810 Results.size());
6811}
6812
6814 if (!CodeCompleter)
6815 return;
6816
6817 // After "using namespace", we expect to see a namespace name or namespace
6818 // alias.
6819 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(),
6820 CodeCompleter->getCodeCompletionTUInfo(),
6822 &ResultBuilder::IsNamespaceOrAlias);
6823 Results.EnterNewScope();
6824 CodeCompletionDeclConsumer Consumer(Results, SemaRef.CurContext);
6825 SemaRef.LookupVisibleDecls(S, Sema::LookupOrdinaryName, Consumer,
6826 CodeCompleter->includeGlobals(),
6827 CodeCompleter->loadExternal());
6828 Results.ExitScope();
6829 HandleCodeCompleteResults(&SemaRef, CodeCompleter,
6830 Results.getCompletionContext(), Results.data(),
6831 Results.size());
6832}
6833
6835 if (!CodeCompleter)
6836 return;
6837
6838 DeclContext *Ctx = S->getEntity();
6839 if (!S->getParent())
6840 Ctx = getASTContext().getTranslationUnitDecl();
6841
6842 bool SuppressedGlobalResults =
6843 Ctx && !CodeCompleter->includeGlobals() && isa<TranslationUnitDecl>(Ctx);
6844
6845 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(),
6846 CodeCompleter->getCodeCompletionTUInfo(),
6847 SuppressedGlobalResults
6850 &ResultBuilder::IsNamespace);
6851
6852 if (Ctx && Ctx->isFileContext() && !SuppressedGlobalResults) {
6853 // We only want to see those namespaces that have already been defined
6854 // within this scope, because its likely that the user is creating an
6855 // extended namespace declaration. Keep track of the most recent
6856 // definition of each namespace.
6857 std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest;
6859 NS(Ctx->decls_begin()),
6860 NSEnd(Ctx->decls_end());
6861 NS != NSEnd; ++NS)
6862 OrigToLatest[NS->getOriginalNamespace()] = *NS;
6863
6864 // Add the most recent definition (or extended definition) of each
6865 // namespace to the list of results.
6866 Results.EnterNewScope();
6867 for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator
6868 NS = OrigToLatest.begin(),
6869 NSEnd = OrigToLatest.end();
6870 NS != NSEnd; ++NS)
6871 Results.AddResult(
6872 CodeCompletionResult(NS->second, Results.getBasePriority(NS->second),
6873 nullptr),
6874 SemaRef.CurContext, nullptr, false);
6875 Results.ExitScope();
6876 }
6877
6878 HandleCodeCompleteResults(&SemaRef, CodeCompleter,
6879 Results.getCompletionContext(), Results.data(),
6880 Results.size());
6881}
6882
6884 if (!CodeCompleter)
6885 return;
6886
6887 // After "namespace", we expect to see a namespace or alias.
6888 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(),
6889 CodeCompleter->getCodeCompletionTUInfo(),
6891 &ResultBuilder::IsNamespaceOrAlias);
6892 CodeCompletionDeclConsumer Consumer(Results, SemaRef.CurContext);
6893 SemaRef.LookupVisibleDecls(S, Sema::LookupOrdinaryName, Consumer,
6894 CodeCompleter->includeGlobals(),
6895 CodeCompleter->loadExternal());
6896 HandleCodeCompleteResults(&SemaRef, CodeCompleter,
6897 Results.getCompletionContext(), Results.data(),
6898 Results.size());
6899}
6900
6902 if (!CodeCompleter)
6903 return;
6904
6906 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(),
6907 CodeCompleter->getCodeCompletionTUInfo(),
6909 &ResultBuilder::IsType);
6910 Results.EnterNewScope();
6911
6912 // Add the names of overloadable operators. Note that OO_Conditional is not
6913 // actually overloadable.
6914#define OVERLOADED_OPERATOR(Name, Spelling, Token, Unary, Binary, MemberOnly) \
6915 if (OO_##Name != OO_Conditional) \
6916 Results.AddResult(Result(Spelling));
6917#include "clang/Basic/OperatorKinds.def"
6918
6919 // Add any type names visible from the current scope
6920 Results.allowNestedNameSpecifiers();
6921 CodeCompletionDeclConsumer Consumer(Results, SemaRef.CurContext);
6922 SemaRef.LookupVisibleDecls(S, Sema::LookupOrdinaryName, Consumer,
6923 CodeCompleter->includeGlobals(),
6924 CodeCompleter->loadExternal());
6925
6926 // Add any type specifiers
6927 AddTypeSpecifierResults(getLangOpts(), Results);
6928 Results.ExitScope();
6929
6930 HandleCodeCompleteResults(&SemaRef, CodeCompleter,
6931 Results.getCompletionContext(), Results.data(),
6932 Results.size());
6933}
6934
6936 Decl *ConstructorD, ArrayRef<CXXCtorInitializer *> Initializers) {
6937 if (!ConstructorD)
6938 return;
6939
6940 SemaRef.AdjustDeclIfTemplate(ConstructorD);
6941
6942 auto *Constructor = dyn_cast<CXXConstructorDecl>(ConstructorD);
6943 if (!Constructor)
6944 return;
6945
6946 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(),
6947 CodeCompleter->getCodeCompletionTUInfo(),
6949 Results.EnterNewScope();
6950
6951 // Fill in any already-initialized fields or base classes.
6952 llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields;
6953 llvm::SmallPtrSet<CanQualType, 4> InitializedBases;
6954 for (unsigned I = 0, E = Initializers.size(); I != E; ++I) {
6955 if (Initializers[I]->isBaseInitializer())
6956 InitializedBases.insert(getASTContext().getCanonicalType(
6957 QualType(Initializers[I]->getBaseClass(), 0)));
6958 else
6959 InitializedFields.insert(
6960 cast<FieldDecl>(Initializers[I]->getAnyMember()));
6961 }
6962
6963 // Add completions for base classes.
6965 bool SawLastInitializer = Initializers.empty();
6966 CXXRecordDecl *ClassDecl = Constructor->getParent();
6967
6968 auto GenerateCCS = [&](const NamedDecl *ND, const char *Name) {
6969 CodeCompletionBuilder Builder(Results.getAllocator(),
6970 Results.getCodeCompletionTUInfo());
6971 Builder.AddTypedTextChunk(Name);
6972 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6973 if (const auto *Function = dyn_cast<FunctionDecl>(ND))
6974 AddFunctionParameterChunks(SemaRef.PP, Policy, Function, Builder);
6975 else if (const auto *FunTemplDecl = dyn_cast<FunctionTemplateDecl>(ND))
6976 AddFunctionParameterChunks(SemaRef.PP, Policy,
6977 FunTemplDecl->getTemplatedDecl(), Builder);
6978 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6979 return Builder.TakeString();
6980 };
6981 auto AddDefaultCtorInit = [&](const char *Name, const char *Type,
6982 const NamedDecl *ND) {
6983 CodeCompletionBuilder Builder(Results.getAllocator(),
6984 Results.getCodeCompletionTUInfo());
6985 Builder.AddTypedTextChunk(Name);
6986 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
6987 Builder.AddPlaceholderChunk(Type);
6988 Builder.AddChunk(CodeCompletionString::CK_RightParen);
6989 if (ND) {
6990 auto CCR = CodeCompletionResult(
6991 Builder.TakeString(), ND,
6992 SawLastInitializer ? CCP_NextInitializer : CCP_MemberDeclaration);
6993 if (isa<FieldDecl>(ND))
6994 CCR.CursorKind = CXCursor_MemberRef;
6995 return Results.AddResult(CCR);
6996 }
6997 return Results.AddResult(CodeCompletionResult(
6998 Builder.TakeString(),
6999 SawLastInitializer ? CCP_NextInitializer : CCP_MemberDeclaration));
7000 };
7001 auto AddCtorsWithName = [&](const CXXRecordDecl *RD, unsigned int Priority,
7002 const char *Name, const FieldDecl *FD) {
7003 if (!RD)
7004 return AddDefaultCtorInit(Name,
7005 FD ? Results.getAllocator().CopyString(
7006 FD->getType().getAsString(Policy))
7007 : Name,
7008 FD);
7009 auto Ctors = getConstructors(getASTContext(), RD);
7010 if (Ctors.begin() == Ctors.end())
7011 return AddDefaultCtorInit(Name, Name, RD);
7012 for (const NamedDecl *Ctor : Ctors) {
7013 auto CCR = CodeCompletionResult(GenerateCCS(Ctor, Name), RD, Priority);
7014 CCR.CursorKind = getCursorKindForDecl(Ctor);
7015 Results.AddResult(CCR);
7016 }
7017 };
7018 auto AddBase = [&](const CXXBaseSpecifier &Base) {
7019 const char *BaseName =
7020 Results.getAllocator().CopyString(Base.getType().getAsString(Policy));
7021 const auto *RD = Base.getType()->getAsCXXRecordDecl();
7022 AddCtorsWithName(
7023 RD, SawLastInitializer ? CCP_NextInitializer : CCP_MemberDeclaration,
7024 BaseName, nullptr);
7025 };
7026 auto AddField = [&](const FieldDecl *FD) {
7027 const char *FieldName =
7028 Results.getAllocator().CopyString(FD->getIdentifier()->getName());
7029 const CXXRecordDecl *RD = FD->getType()->getAsCXXRecordDecl();
7030 AddCtorsWithName(
7031 RD, SawLastInitializer ? CCP_NextInitializer : CCP_MemberDeclaration,
7032 FieldName, FD);
7033 };
7034
7035 for (const auto &Base : ClassDecl->bases()) {
7036 if (!InitializedBases
7037 .insert(getASTContext().getCanonicalType(Base.getType()))
7038 .second) {
7039 SawLastInitializer =
7040 !Initializers.empty() && Initializers.back()->isBaseInitializer() &&
7041 getASTContext().hasSameUnqualifiedType(
7042 Base.getType(), QualType(Initializers.back()->getBaseClass(), 0));
7043 continue;
7044 }
7045
7046 AddBase(Base);
7047 SawLastInitializer = false;
7048 }
7049
7050 // Add completions for virtual base classes.
7051 for (const auto &Base : ClassDecl->vbases()) {
7052 if (!InitializedBases
7053 .insert(getASTContext().getCanonicalType(Base.getType()))
7054 .second) {
7055 SawLastInitializer =
7056 !Initializers.empty() && Initializers.back()->isBaseInitializer() &&
7057 getASTContext().hasSameUnqualifiedType(
7058 Base.getType(), QualType(Initializers.back()->getBaseClass(), 0));
7059 continue;
7060 }
7061
7062 AddBase(Base);
7063 SawLastInitializer = false;
7064 }
7065
7066 // Add completions for members.
7067 for (auto *Field : ClassDecl->fields()) {
7068 if (!InitializedFields.insert(cast<FieldDecl>(Field->getCanonicalDecl()))
7069 .second) {
7070 SawLastInitializer = !Initializers.empty() &&
7071 Initializers.back()->isAnyMemberInitializer() &&
7072 Initializers.back()->getAnyMember() == Field;
7073 continue;
7074 }
7075
7076 if (!Field->getDeclName())
7077 continue;
7078
7079 AddField(Field);
7080 SawLastInitializer = false;
7081 }
7082 Results.ExitScope();
7083
7084 HandleCodeCompleteResults(&SemaRef, CodeCompleter,
7085 Results.getCompletionContext(), Results.data(),
7086 Results.size());
7087}
7088
7089/// Determine whether this scope denotes a namespace.
7090static bool isNamespaceScope(Scope *S) {
7091 DeclContext *DC = S->getEntity();
7092 if (!DC)
7093 return false;
7094
7095 return DC->isFileContext();
7096}
7097
7099 LambdaIntroducer &Intro,
7100 bool AfterAmpersand) {
7101 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(),
7102 CodeCompleter->getCodeCompletionTUInfo(),
7104 Results.EnterNewScope();
7105
7106 // Note what has already been captured.
7108 bool IncludedThis = false;
7109 for (const auto &C : Intro.Captures) {
7110 if (C.Kind == LCK_This) {
7111 IncludedThis = true;
7112 continue;
7113 }
7114
7115 Known.insert(C.Id);
7116 }
7117
7118 // Look for other capturable variables.
7119 for (; S && !isNamespaceScope(S); S = S->getParent()) {
7120 for (const auto *D : S->decls()) {
7121 const auto *Var = dyn_cast<VarDecl>(D);
7122 if (!Var || !Var->hasLocalStorage() || Var->hasAttr<BlocksAttr>())
7123 continue;
7124
7125 if (Known.insert(Var->getIdentifier()).second)
7126 Results.AddResult(CodeCompletionResult(Var, CCP_LocalDeclaration),
7127 SemaRef.CurContext, nullptr, false);
7128 }
7129 }
7130
7131 // Add 'this', if it would be valid.
7132 if (!IncludedThis && !AfterAmpersand && Intro.Default != LCD_ByCopy)
7133 addThisCompletion(SemaRef, Results);
7134
7135 Results.ExitScope();
7136
7137 HandleCodeCompleteResults(&SemaRef, CodeCompleter,
7138 Results.getCompletionContext(), Results.data(),
7139 Results.size());
7140}
7141
7143 if (!getLangOpts().CPlusPlus11)
7144 return;
7145 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(),
7146 CodeCompleter->getCodeCompletionTUInfo(),
7148 auto ShouldAddDefault = [&D, this]() {
7149 if (!D.isFunctionDeclarator())
7150 return false;
7151 auto &Id = D.getName();
7153 return true;
7154 // FIXME(liuhui): Ideally, we should check the constructor parameter list to
7155 // verify that it is the default, copy or move constructor?
7156 if (Id.getKind() == UnqualifiedIdKind::IK_ConstructorName &&
7158 return true;
7160 auto Op = Id.OperatorFunctionId.Operator;
7161 // FIXME(liuhui): Ideally, we should check the function parameter list to
7162 // verify that it is the copy or move assignment?
7163 if (Op == OverloadedOperatorKind::OO_Equal)
7164 return true;
7165 if (getLangOpts().CPlusPlus20 &&
7166 (Op == OverloadedOperatorKind::OO_EqualEqual ||
7167 Op == OverloadedOperatorKind::OO_ExclaimEqual ||
7168 Op == OverloadedOperatorKind::OO_Less ||
7169 Op == OverloadedOperatorKind::OO_LessEqual ||
7170 Op == OverloadedOperatorKind::OO_Greater ||
7171 Op == OverloadedOperatorKind::OO_GreaterEqual ||
7172 Op == OverloadedOperatorKind::OO_Spaceship))
7173 return true;
7174 }
7175 return false;
7176 };
7177
7178 Results.EnterNewScope();
7179 if (ShouldAddDefault())
7180 Results.AddResult("default");
7181 // FIXME(liuhui): Ideally, we should only provide `delete` completion for the
7182 // first function declaration.
7183 Results.AddResult("delete");
7184 Results.ExitScope();
7185 HandleCodeCompleteResults(&SemaRef, CodeCompleter,
7186 Results.getCompletionContext(), Results.data(),
7187 Results.size());
7188}
7189
7190/// Macro that optionally prepends an "@" to the string literal passed in via
7191/// Keyword, depending on whether NeedAt is true or false.
7192#define OBJC_AT_KEYWORD_NAME(NeedAt, Keyword) ((NeedAt) ? "@" Keyword : Keyword)
7193
7194static void AddObjCImplementationResults(const LangOptions &LangOpts,
7195 ResultBuilder &Results, bool NeedAt) {
7197 // Since we have an implementation, we can end it.
7198 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "end")));
7199
7200 CodeCompletionBuilder Builder(Results.getAllocator(),
7201 Results.getCodeCompletionTUInfo());
7202 if (LangOpts.ObjC) {
7203 // @dynamic
7204 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "dynamic"));
7206 Builder.AddPlaceholderChunk("property");
7207 Results.AddResult(Result(Builder.TakeString()));
7208
7209 // @synthesize
7210 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "synthesize"));
7212 Builder.AddPlaceholderChunk("property");
7213 Results.AddResult(Result(Builder.TakeString()));
7214 }
7215}
7216
7217static void AddObjCInterfaceResults(const LangOptions &LangOpts,
7218 ResultBuilder &Results, bool NeedAt) {
7220
7221 // Since we have an interface or protocol, we can end it.
7222 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "end")));
7223
7224 if (LangOpts.ObjC) {
7225 // @property
7226 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "property")));
7227
7228 // @required
7229 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "required")));
7230
7231 // @optional
7232 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "optional")));
7233 }
7234}
7235
7236static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt) {
7238 CodeCompletionBuilder Builder(Results.getAllocator(),
7239 Results.getCodeCompletionTUInfo());
7240
7241 // @class name ;
7242 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "class"));
7244 Builder.AddPlaceholderChunk("name");
7245 Results.AddResult(Result(Builder.TakeString()));
7246
7247 if (Results.includeCodePatterns()) {
7248 // @interface name
7249 // FIXME: Could introduce the whole pattern, including superclasses and
7250 // such.
7251 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "interface"));
7253 Builder.AddPlaceholderChunk("class");
7254 Results.AddResult(Result(Builder.TakeString()));
7255
7256 // @protocol name
7257 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "protocol"));
7259 Builder.AddPlaceholderChunk("protocol");
7260 Results.AddResult(Result(Builder.TakeString()));
7261
7262 // @implementation name
7263 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "implementation"));
7265 Builder.AddPlaceholderChunk("class");
7266 Results.AddResult(Result(Builder.TakeString()));
7267 }
7268
7269 // @compatibility_alias name
7270 Builder.AddTypedTextChunk(
7271 OBJC_AT_KEYWORD_NAME(NeedAt, "compatibility_alias"));
7273 Builder.AddPlaceholderChunk("alias");
7275 Builder.AddPlaceholderChunk("class");
7276 Results.AddResult(Result(Builder.TakeString()));
7277
7278 if (Results.getSema().getLangOpts().Modules) {
7279 // @import name
7280 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "import"));
7282 Builder.AddPlaceholderChunk("module");
7283 Results.AddResult(Result(Builder.TakeString()));
7284 }
7285}
7286
7288 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(),
7289 CodeCompleter->getCodeCompletionTUInfo(),
7291 Results.EnterNewScope();
7292 if (isa<ObjCImplDecl>(SemaRef.CurContext))
7293 AddObjCImplementationResults(getLangOpts(), Results, false);
7294 else if (SemaRef.CurContext->isObjCContainer())
7295 AddObjCInterfaceResults(getLangOpts(), Results, false);
7296 else
7297 AddObjCTopLevelResults(Results, false);
7298 Results.ExitScope();
7299 HandleCodeCompleteResults(&SemaRef, CodeCompleter,
7300 Results.getCompletionContext(), Results.data(),
7301 Results.size());
7302}
7303
7304static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt) {
7306 CodeCompletionBuilder Builder(Results.getAllocator(),
7307 Results.getCodeCompletionTUInfo());
7308
7309 // @encode ( type-name )
7310 const char *EncodeType = "char[]";
7311 if (Results.getSema().getLangOpts().CPlusPlus ||
7312 Results.getSema().getLangOpts().ConstStrings)
7313 EncodeType = "const char[]";
7314 Builder.AddResultTypeChunk(EncodeType);
7315 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "encode"));
7316 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7317 Builder.AddPlaceholderChunk("type-name");
7318 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7319 Results.AddResult(Result(Builder.TakeString()));
7320
7321 // @protocol ( protocol-name )
7322 Builder.AddResultTypeChunk("Protocol *");
7323 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "protocol"));
7324 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7325 Builder.AddPlaceholderChunk("protocol-name");
7326 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7327 Results.AddResult(Result(Builder.TakeString()));
7328
7329 // @selector ( selector )
7330 Builder.AddResultTypeChunk("SEL");
7331 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "selector"));
7332 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7333 Builder.AddPlaceholderChunk("selector");
7334 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7335 Results.AddResult(Result(Builder.TakeString()));
7336
7337 // @"string"
7338 Builder.AddResultTypeChunk("NSString *");
7339 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "\""));
7340 Builder.AddPlaceholderChunk("string");
7341 Builder.AddTextChunk("\"");
7342 Results.AddResult(Result(Builder.TakeString()));
7343
7344 // @[objects, ...]
7345 Builder.AddResultTypeChunk("NSArray *");
7346 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "["));
7347 Builder.AddPlaceholderChunk("objects, ...");
7348 Builder.AddChunk(CodeCompletionString::CK_RightBracket);
7349 Results.AddResult(Result(Builder.TakeString()));
7350
7351 // @{key : object, ...}
7352 Builder.AddResultTypeChunk("NSDictionary *");
7353 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "{"));
7354 Builder.AddPlaceholderChunk("key");
7355 Builder.AddChunk(CodeCompletionString::CK_Colon);
7357 Builder.AddPlaceholderChunk("object, ...");
7358 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
7359 Results.AddResult(Result(Builder.TakeString()));
7360
7361 // @(expression)
7362 Builder.AddResultTypeChunk("id");
7363 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "("));
7364 Builder.AddPlaceholderChunk("expression");
7365 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7366 Results.AddResult(Result(Builder.TakeString()));
7367}
7368
7369static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt) {
7371 CodeCompletionBuilder Builder(Results.getAllocator(),
7372 Results.getCodeCompletionTUInfo());
7373
7374 if (Results.includeCodePatterns()) {
7375 // @try { statements } @catch ( declaration ) { statements } @finally
7376 // { statements }
7377 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "try"));
7378 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
7379 Builder.AddPlaceholderChunk("statements");
7380 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
7381 Builder.AddTextChunk("@catch");
7382 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7383 Builder.AddPlaceholderChunk("parameter");
7384 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7385 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
7386 Builder.AddPlaceholderChunk("statements");
7387 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
7388 Builder.AddTextChunk("@finally");
7389 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
7390 Builder.AddPlaceholderChunk("statements");
7391 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
7392 Results.AddResult(Result(Builder.TakeString()));
7393 }
7394
7395 // @throw
7396 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "throw"));
7398 Builder.AddPlaceholderChunk("expression");
7399 Results.AddResult(Result(Builder.TakeString()));
7400
7401 if (Results.includeCodePatterns()) {
7402 // @synchronized ( expression ) { statements }
7403 Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "synchronized"));
7405 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7406 Builder.AddPlaceholderChunk("expression");
7407 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7408 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
7409 Builder.AddPlaceholderChunk("statements");
7410 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
7411 Results.AddResult(Result(Builder.TakeString()));
7412 }
7413}
7414
7415static void AddObjCVisibilityResults(const LangOptions &LangOpts,
7416 ResultBuilder &Results, bool NeedAt) {
7418 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "private")));
7419 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "protected")));
7420 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "public")));
7421 if (LangOpts.ObjC)
7422 Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "package")));
7423}
7424
7426 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(),
7427 CodeCompleter->getCodeCompletionTUInfo(),
7429 Results.EnterNewScope();
7430 AddObjCVisibilityResults(getLangOpts(), Results, false);
7431 Results.ExitScope();
7432 HandleCodeCompleteResults(&SemaRef, CodeCompleter,
7433 Results.getCompletionContext(), Results.data(),
7434 Results.size());
7435}
7436
7438 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(),
7439 CodeCompleter->getCodeCompletionTUInfo(),
7441 Results.EnterNewScope();
7442 AddObjCStatementResults(Results, false);
7443 AddObjCExpressionResults(Results, false);
7444 Results.ExitScope();
7445 HandleCodeCompleteResults(&SemaRef, CodeCompleter,
7446 Results.getCompletionContext(), Results.data(),
7447 Results.size());
7448}
7449
7451 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(),
7452 CodeCompleter->getCodeCompletionTUInfo(),
7454 Results.EnterNewScope();
7455 AddObjCExpressionResults(Results, false);
7456 Results.ExitScope();
7457 HandleCodeCompleteResults(&SemaRef, CodeCompleter,
7458 Results.getCompletionContext(), Results.data(),
7459 Results.size());
7460}
7461
7462/// Determine whether the addition of the given flag to an Objective-C
7463/// property's attributes will cause a conflict.
7464static bool ObjCPropertyFlagConflicts(unsigned Attributes, unsigned NewFlag) {
7465 // Check if we've already added this flag.
7466 if (Attributes & NewFlag)
7467 return true;
7468
7469 Attributes |= NewFlag;
7470
7471 // Check for collisions with "readonly".
7472 if ((Attributes & ObjCPropertyAttribute::kind_readonly) &&
7474 return true;
7475
7476 // Check for more than one of { assign, copy, retain, strong, weak }.
7477 unsigned AssignCopyRetMask =
7478 Attributes &
7483 if (AssignCopyRetMask &&
7484 AssignCopyRetMask != ObjCPropertyAttribute::kind_assign &&
7485 AssignCopyRetMask != ObjCPropertyAttribute::kind_unsafe_unretained &&
7486 AssignCopyRetMask != ObjCPropertyAttribute::kind_copy &&
7487 AssignCopyRetMask != ObjCPropertyAttribute::kind_retain &&
7488 AssignCopyRetMask != ObjCPropertyAttribute::kind_strong &&
7489 AssignCopyRetMask != ObjCPropertyAttribute::kind_weak)
7490 return true;
7491
7492 return false;
7493}
7494
7496 ObjCDeclSpec &ODS) {
7497 if (!CodeCompleter)
7498 return;
7499
7500 unsigned Attributes = ODS.getPropertyAttributes();
7501
7502 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(),
7503 CodeCompleter->getCodeCompletionTUInfo(),
7505 Results.EnterNewScope();
7506 if (!ObjCPropertyFlagConflicts(Attributes,
7508 Results.AddResult(CodeCompletionResult("readonly"));
7509 if (!ObjCPropertyFlagConflicts(Attributes,
7511 Results.AddResult(CodeCompletionResult("assign"));
7512 if (!ObjCPropertyFlagConflicts(Attributes,
7514 Results.AddResult(CodeCompletionResult("unsafe_unretained"));
7515 if (!ObjCPropertyFlagConflicts(Attributes,
7517 Results.AddResult(CodeCompletionResult("readwrite"));
7518 if (!ObjCPropertyFlagConflicts(Attributes,
7520 Results.AddResult(CodeCompletionResult("retain"));
7521 if (!ObjCPropertyFlagConflicts(Attributes,
7523 Results.AddResult(CodeCompletionResult("strong"));
7525 Results.AddResult(CodeCompletionResult("copy"));
7526 if (!ObjCPropertyFlagConflicts(Attributes,
7528 Results.AddResult(CodeCompletionResult("nonatomic"));
7529 if (!ObjCPropertyFlagConflicts(Attributes,
7531 Results.AddResult(CodeCompletionResult("atomic"));
7532
7533 // Only suggest "weak" if we're compiling for ARC-with-weak-references or GC.
7534 if (getLangOpts().ObjCWeak || getLangOpts().getGC() != LangOptions::NonGC)
7535 if (!ObjCPropertyFlagConflicts(Attributes,
7537 Results.AddResult(CodeCompletionResult("weak"));
7538
7539 if (!ObjCPropertyFlagConflicts(Attributes,
7541 CodeCompletionBuilder Setter(Results.getAllocator(),
7542 Results.getCodeCompletionTUInfo());
7543 Setter.AddTypedTextChunk("setter");
7544 Setter.AddTextChunk("=");
7545 Setter.AddPlaceholderChunk("method");
7546 Results.AddResult(CodeCompletionResult(Setter.TakeString()));
7547 }
7548 if (!ObjCPropertyFlagConflicts(Attributes,
7550 CodeCompletionBuilder Getter(Results.getAllocator(),
7551 Results.getCodeCompletionTUInfo());
7552 Getter.AddTypedTextChunk("getter");
7553 Getter.AddTextChunk("=");
7554 Getter.AddPlaceholderChunk("method");
7555 Results.AddResult(CodeCompletionResult(Getter.TakeString()));
7556 }
7557 if (!ObjCPropertyFlagConflicts(Attributes,
7559 Results.AddResult(CodeCompletionResult("nonnull"));
7560 Results.AddResult(CodeCompletionResult("nullable"));
7561 Results.AddResult(CodeCompletionResult("null_unspecified"));
7562 Results.AddResult(CodeCompletionResult("null_resettable"));
7563 }
7564 Results.ExitScope();
7565 HandleCodeCompleteResults(&SemaRef, CodeCompleter,
7566 Results.getCompletionContext(), Results.data(),
7567 Results.size());
7568}
7569
7570/// Describes the kind of Objective-C method that we want to find
7571/// via code completion.
7573 MK_Any, ///< Any kind of method, provided it means other specified criteria.
7574 MK_ZeroArgSelector, ///< Zero-argument (unary) selector.
7575 MK_OneArgSelector ///< One-argument selector.
7577
7580 bool AllowSameLength = true) {
7581 unsigned NumSelIdents = SelIdents.size();
7582 if (NumSelIdents > Sel.getNumArgs())
7583 return false;
7584
7585 switch (WantKind) {
7586 case MK_Any:
7587 break;
7588 case MK_ZeroArgSelector:
7589 return Sel.isUnarySelector();
7590 case MK_OneArgSelector:
7591 return Sel.getNumArgs() == 1;
7592 }
7593
7594 if (!AllowSameLength && NumSelIdents && NumSelIdents == Sel.getNumArgs())
7595 return false;
7596
7597 for (unsigned I = 0; I != NumSelIdents; ++I)
7598 if (SelIdents[I] != Sel.getIdentifierInfoForSlot(I))
7599 return false;
7600
7601 return true;
7602}
7603
7605 ObjCMethodKind WantKind,
7607 bool AllowSameLength = true) {
7608 return isAcceptableObjCSelector(Method->getSelector(), WantKind, SelIdents,
7609 AllowSameLength);
7610}
7611
7612/// A set of selectors, which is used to avoid introducing multiple
7613/// completions with the same selector into the result set.
7615
7616/// Add all of the Objective-C methods in the given Objective-C
7617/// container to the set of results.
7618///
7619/// The container will be a class, protocol, category, or implementation of
7620/// any of the above. This mether will recurse to include methods from
7621/// the superclasses of classes along with their categories, protocols, and
7622/// implementations.
7623///
7624/// \param Container the container in which we'll look to find methods.
7625///
7626/// \param WantInstanceMethods Whether to add instance methods (only); if
7627/// false, this routine will add factory methods (only).
7628///
7629/// \param CurContext the context in which we're performing the lookup that
7630/// finds methods.
7631///
7632/// \param AllowSameLength Whether we allow a method to be added to the list
7633/// when it has the same number of parameters as we have selector identifiers.
7634///
7635/// \param Results the structure into which we'll add results.
7636static void AddObjCMethods(ObjCContainerDecl *Container,
7637 bool WantInstanceMethods, ObjCMethodKind WantKind,
7639 DeclContext *CurContext,
7640 VisitedSelectorSet &Selectors, bool AllowSameLength,
7641 ResultBuilder &Results, bool InOriginalClass = true,
7642 bool IsRootClass = false) {
7644 Container = getContainerDef(Container);
7645 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container);
7646 IsRootClass = IsRootClass || (IFace && !IFace->getSuperClass());
7647 for (ObjCMethodDecl *M : Container->methods()) {
7648 // The instance methods on the root class can be messaged via the
7649 // metaclass.
7650 if (M->isInstanceMethod() == WantInstanceMethods ||
7651 (IsRootClass && !WantInstanceMethods)) {
7652 // Check whether the selector identifiers we've been given are a
7653 // subset of the identifiers for this particular method.
7654 if (!isAcceptableObjCMethod(M, WantKind, SelIdents, AllowSameLength))
7655 continue;
7656
7657 if (!Selectors.insert(M->getSelector()).second)
7658 continue;
7659
7660 Result R = Result(M, Results.getBasePriority(M), nullptr);
7661 R.StartParameter = SelIdents.size();
7662 R.AllParametersAreInformative = (WantKind != MK_Any);
7663 if (!InOriginalClass)
7664 setInBaseClass(R);
7665 Results.MaybeAddResult(R, CurContext);
7666 }
7667 }
7668
7669 // Visit the protocols of protocols.
7670 if (const auto *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
7671 if (Protocol->hasDefinition()) {
7672 const ObjCList<ObjCProtocolDecl> &Protocols =
7673 Protocol->getReferencedProtocols();
7674 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
7675 E = Protocols.end();
7676 I != E; ++I)
7677 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, CurContext,
7678 Selectors, AllowSameLength, Results, false, IsRootClass);
7679 }
7680 }
7681
7682 if (!IFace || !IFace->hasDefinition())
7683 return;
7684
7685 // Add methods in protocols.
7686 for (ObjCProtocolDecl *I : IFace->protocols())
7687 AddObjCMethods(I, WantInstanceMethods, WantKind, SelIdents, CurContext,
7688 Selectors, AllowSameLength, Results, false, IsRootClass);
7689
7690 // Add methods in categories.
7691 for (ObjCCategoryDecl *CatDecl : IFace->known_categories()) {
7692 AddObjCMethods(CatDecl, WantInstanceMethods, WantKind, SelIdents,
7693 CurContext, Selectors, AllowSameLength, Results,
7694 InOriginalClass, IsRootClass);
7695
7696 // Add a categories protocol methods.
7697 const ObjCList<ObjCProtocolDecl> &Protocols =
7698 CatDecl->getReferencedProtocols();
7699 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
7700 E = Protocols.end();
7701 I != E; ++I)
7702 AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, CurContext,
7703 Selectors, AllowSameLength, Results, false, IsRootClass);
7704
7705 // Add methods in category implementations.
7706 if (ObjCCategoryImplDecl *Impl = CatDecl->getImplementation())
7707 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents, CurContext,
7708 Selectors, AllowSameLength, Results, InOriginalClass,
7709 IsRootClass);
7710 }
7711
7712 // Add methods in superclass.
7713 // Avoid passing in IsRootClass since root classes won't have super classes.
7714 if (IFace->getSuperClass())
7715 AddObjCMethods(IFace->getSuperClass(), WantInstanceMethods, WantKind,
7716 SelIdents, CurContext, Selectors, AllowSameLength, Results,
7717 /*IsRootClass=*/false);
7718
7719 // Add methods in our implementation, if any.
7720 if (ObjCImplementationDecl *Impl = IFace->getImplementation())
7721 AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents, CurContext,
7722 Selectors, AllowSameLength, Results, InOriginalClass,
7723 IsRootClass);
7724}
7725
7727 // Try to find the interface where getters might live.
7729 dyn_cast_or_null<ObjCInterfaceDecl>(SemaRef.CurContext);
7730 if (!Class) {
7732 dyn_cast_or_null<ObjCCategoryDecl>(SemaRef.CurContext))
7733 Class = Category->getClassInterface();
7734
7735 if (!Class)
7736 return;
7737 }
7738
7739 // Find all of the potential getters.
7740 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(),
7741 CodeCompleter->getCodeCompletionTUInfo(),
7743 Results.EnterNewScope();
7744
7745 VisitedSelectorSet Selectors;
7746 AddObjCMethods(Class, true, MK_ZeroArgSelector, std::nullopt,
7747 SemaRef.CurContext, Selectors,
7748 /*AllowSameLength=*/true, Results);
7749 Results.ExitScope();
7750 HandleCodeCompleteResults(&SemaRef, CodeCompleter,
7751 Results.getCompletionContext(), Results.data(),
7752 Results.size());
7753}
7754
7756 // Try to find the interface where setters might live.
7758 dyn_cast_or_null<ObjCInterfaceDecl>(SemaRef.CurContext);
7759 if (!Class) {
7761 dyn_cast_or_null<ObjCCategoryDecl>(SemaRef.CurContext))
7762 Class = Category->getClassInterface();
7763
7764 if (!Class)
7765 return;
7766 }
7767
7768 // Find all of the potential getters.
7769 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(),
7770 CodeCompleter->getCodeCompletionTUInfo(),
7772 Results.EnterNewScope();
7773
7774 VisitedSelectorSet Selectors;
7775 AddObjCMethods(Class, true, MK_OneArgSelector, std::nullopt,
7776 SemaRef.CurContext, Selectors,
7777 /*AllowSameLength=*/true, Results);
7778
7779 Results.ExitScope();
7780 HandleCodeCompleteResults(&SemaRef, CodeCompleter,
7781 Results.getCompletionContext(), Results.data(),
7782 Results.size());
7783}
7784
7786 bool IsParameter) {
7787 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(),
7788 CodeCompleter->getCodeCompletionTUInfo(),
7790 Results.EnterNewScope();
7791
7792 // Add context-sensitive, Objective-C parameter-passing keywords.
7793 bool AddedInOut = false;
7794 if ((DS.getObjCDeclQualifier() &
7796 Results.AddResult("in");
7797 Results.AddResult("inout");
7798 AddedInOut = true;
7799 }
7800 if ((DS.getObjCDeclQualifier() &
7802 Results.AddResult("out");
7803 if (!AddedInOut)
7804 Results.AddResult("inout");
7805 }
7806 if ((DS.getObjCDeclQualifier() &
7808 ObjCDeclSpec::DQ_Oneway)) == 0) {
7809 Results.AddResult("bycopy");
7810 Results.AddResult("byref");
7811 Results.AddResult("oneway");
7812 }
7814 Results.AddResult("nonnull");
7815 Results.AddResult("nullable");
7816 Results.AddResult("null_unspecified");
7817 }
7818
7819 // If we're completing the return type of an Objective-C method and the
7820 // identifier IBAction refers to a macro, provide a completion item for
7821 // an action, e.g.,
7822 // IBAction)<#selector#>:(id)sender
7823 if (DS.getObjCDeclQualifier() == 0 && !IsParameter &&
7824 SemaRef.PP.isMacroDefined("IBAction")) {
7825 CodeCompletionBuilder Builder(Results.getAllocator(),
7826 Results.getCodeCompletionTUInfo(),
7828 Builder.AddTypedTextChunk("IBAction");
7829 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7830 Builder.AddPlaceholderChunk("selector");
7831 Builder.AddChunk(CodeCompletionString::CK_Colon);
7832 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
7833 Builder.AddTextChunk("id");
7834 Builder.AddChunk(CodeCompletionString::CK_RightParen);
7835 Builder.AddTextChunk("sender");
7836 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
7837 }
7838
7839 // If we're completing the return type, provide 'instancetype'.
7840 if (!IsParameter) {
7841 Results.AddResult(CodeCompletionResult("instancetype"));
7842 }
7843
7844 // Add various builtin type names and specifiers.
7845 AddOrdinaryNameResults(PCC_Type, S, SemaRef, Results);
7846 Results.ExitScope();
7847
7848 // Add the various type names
7849 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
7850 CodeCompletionDeclConsumer Consumer(Results, SemaRef.CurContext);
7851 SemaRef.LookupVisibleDecls(S, Sema::LookupOrdinaryName, Consumer,
7852 CodeCompleter->includeGlobals(),
7853 CodeCompleter->loadExternal());
7854
7855 if (CodeCompleter->includeMacros())
7856 AddMacroResults(SemaRef.PP, Results, CodeCompleter->loadExternal(), false);
7857
7858 HandleCodeCompleteResults(&SemaRef, CodeCompleter,
7859 Results.getCompletionContext(), Results.data(),
7860 Results.size());
7861}
7862
7863/// When we have an expression with type "id", we may assume
7864/// that it has some more-specific class type based on knowledge of
7865/// common uses of Objective-C. This routine returns that class type,
7866/// or NULL if no better result could be determined.
7868 auto *Msg = dyn_cast_or_null<ObjCMessageExpr>(E);
7869 if (!Msg)
7870 return nullptr;
7871
7872 Selector Sel = Msg->getSelector();
7873 if (Sel.isNull())
7874 return nullptr;
7875
7877 if (!Id)
7878 return nullptr;
7879
7880 ObjCMethodDecl *Method = Msg->getMethodDecl();
7881 if (!Method)
7882 return nullptr;
7883
7884 // Determine the class that we're sending the message to.
7885 ObjCInterfaceDecl *IFace = nullptr;
7886 switch (Msg->getReceiverKind()) {
7888 if (const ObjCObjectType *ObjType =
7889 Msg->getClassReceiver()->getAs<ObjCObjectType>())
7890 IFace = ObjType->getInterface();
7891 break;
7892
7894 QualType T = Msg->getInstanceReceiver()->getType();
7896 IFace = Ptr->getInterfaceDecl();
7897 break;
7898 }
7899
7902 break;
7903 }
7904
7905 if (!IFace)
7906 return nullptr;
7907
7908 ObjCInterfaceDecl *Super = IFace->getSuperClass();
7909 if (Method->isInstanceMethod())
7910 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
7911 .Case("retain", IFace)
7912 .Case("strong", IFace)
7913 .Case("autorelease", IFace)
7914 .Case("copy", IFace)
7915 .Case("copyWithZone", IFace)
7916 .Case("mutableCopy", IFace)
7917 .Case("mutableCopyWithZone", IFace)
7918 .Case("awakeFromCoder", IFace)
7919 .Case("replacementObjectFromCoder", IFace)
7920 .Case("class", IFace)
7921 .Case("classForCoder", IFace)
7922 .Case("superclass", Super)
7923 .Default(nullptr);
7924
7925 return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
7926 .Case("new", IFace)
7927 .Case("alloc", IFace)
7928 .Case("allocWithZone", IFace)
7929 .Case("class", IFace)
7930 .Case("superclass", Super)
7931 .Default(nullptr);
7932}
7933
7934// Add a special completion for a message send to "super", which fills in the
7935// most likely case of forwarding all of our arguments to the superclass
7936// function.
7937///
7938/// \param S The semantic analysis object.
7939///
7940/// \param NeedSuperKeyword Whether we need to prefix this completion with
7941/// the "super" keyword. Otherwise, we just need to provide the arguments.
7942///
7943/// \param SelIdents The identifiers in the selector that have already been
7944/// provided as arguments for a send to "super".
7945///
7946/// \param Results The set of results to augment.
7947///
7948/// \returns the Objective-C method declaration that would be invoked by
7949/// this "super" completion. If NULL, no completion was added.
7950static ObjCMethodDecl *
7951AddSuperSendCompletion(Sema &S, bool NeedSuperKeyword,
7953 ResultBuilder &Results) {
7954 ObjCMethodDecl *CurMethod = S.getCurMethodDecl();
7955 if (!CurMethod)
7956 return nullptr;
7957
7959 if (!Class)
7960 return nullptr;
7961
7962 // Try to find a superclass method with the same selector.
7963 ObjCMethodDecl *SuperMethod = nullptr;
7964 while ((Class = Class->getSuperClass()) && !SuperMethod) {
7965 // Check in the class
7966 SuperMethod = Class->getMethod(CurMethod->getSelector(),
7967 CurMethod->isInstanceMethod());
7968
7969 // Check in categories or class extensions.
7970 if (!SuperMethod) {
7971 for (const auto *Cat : Class->known_categories()) {
7972 if ((SuperMethod = Cat->getMethod(CurMethod->getSelector(),
7973 CurMethod->isInstanceMethod())))
7974 break;
7975 }
7976 }
7977 }
7978
7979 if (!SuperMethod)
7980 return nullptr;
7981
7982 // Check whether the superclass method has the same signature.
7983 if (CurMethod->param_size() != SuperMethod->param_size() ||
7984 CurMethod->isVariadic() != SuperMethod->isVariadic())
7985 return nullptr;
7986
7987 for (ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin(),
7988 CurPEnd = CurMethod->param_end(),
7989 SuperP = SuperMethod->param_begin();
7990 CurP != CurPEnd; ++CurP, ++SuperP) {
7991 // Make sure the parameter types are compatible.
7992 if (!S.Context.hasSameUnqualifiedType((*CurP)->getType(),
7993 (*SuperP)->getType()))
7994 return nullptr;
7995
7996 // Make sure we have a parameter name to forward!
7997 if (!(*CurP)->getIdentifier())
7998 return nullptr;
7999 }
8000
8001 // We have a superclass method. Now, form the send-to-super completion.
8002 CodeCompletionBuilder Builder(Results.getAllocator(),
8003 Results.getCodeCompletionTUInfo());
8004
8005 // Give this completion a return type.
8007 Results.getCompletionContext().getBaseType(), Builder);
8008
8009 // If we need the "super" keyword, add it (plus some spacing).
8010 if (NeedSuperKeyword) {
8011 Builder.AddTypedTextChunk("super");
8013 }
8014
8015 Selector Sel = CurMethod->getSelector();
8016 if (Sel.isUnarySelector()) {
8017 if (NeedSuperKeyword)
8018 Builder.AddTextChunk(
8019 Builder.getAllocator().CopyString(Sel.getNameForSlot(0)));
8020 else
8021 Builder.AddTypedTextChunk(
8022 Builder.getAllocator().CopyString(Sel.getNameForSlot(0)));
8023 } else {
8024 ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin();
8025 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I, ++CurP) {
8026 if (I > SelIdents.size())
8028
8029 if (I < SelIdents.size())
8030 Builder.AddInformativeChunk(
8031 Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":"));
8032 else if (NeedSuperKeyword || I > SelIdents.size()) {
8033 Builder.AddTextChunk(
8034 Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":"));
8035 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
8036 (*CurP)->getIdentifier()->getName()));
8037 } else {
8038 Builder.AddTypedTextChunk(
8039 Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":"));
8040 Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
8041 (*CurP)->getIdentifier()->getName()));
8042 }
8043 }
8044 }
8045
8046 Results.AddResult(CodeCompletionResult(Builder.TakeString(), SuperMethod,
8048 return SuperMethod;
8049}
8050
8053 ResultBuilder Results(
8054 SemaRef, CodeCompleter->getAllocator(),
8055 CodeCompleter->getCodeCompletionTUInfo(),
8057 getLangOpts().CPlusPlus11
8058 ? &ResultBuilder::IsObjCMessageReceiverOrLambdaCapture
8059 : &ResultBuilder::IsObjCMessageReceiver);
8060
8061 CodeCompletionDeclConsumer Consumer(Results, SemaRef.CurContext);
8062 Results.EnterNewScope();
8063 SemaRef.LookupVisibleDecls(S, Sema::LookupOrdinaryName, Consumer,
8064 CodeCompleter->includeGlobals(),
8065 CodeCompleter->loadExternal());
8066
8067 // If we are in an Objective-C method inside a class that has a superclass,
8068 // add "super" as an option.
8069 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl())
8070 if (ObjCInterfaceDecl *Iface = Method->getClassInterface())
8071 if (Iface->getSuperClass()) {
8072 Results.AddResult(Result("super"));
8073
8074 AddSuperSendCompletion(SemaRef, /*NeedSuperKeyword=*/true, std::nullopt,
8075 Results);
8076 }
8077
8078 if (getLangOpts().CPlusPlus11)
8079 addThisCompletion(SemaRef, Results);
8080
8081 Results.ExitScope();
8082
8083 if (CodeCompleter->includeMacros())
8084 AddMacroResults(SemaRef.PP, Results, CodeCompleter->loadExternal(), false);
8085 HandleCodeCompleteResults(&SemaRef, CodeCompleter,
8086 Results.getCompletionContext(), Results.data(),
8087 Results.size());
8088}
8089
8091 Scope *S, SourceLocation SuperLoc,
8092 ArrayRef<const IdentifierInfo *> SelIdents, bool AtArgumentExpression) {
8093 ObjCInterfaceDecl *CDecl = nullptr;
8094 if (ObjCMethodDecl *CurMethod = SemaRef.getCurMethodDecl()) {
8095 // Figure out which interface we're in.
8096 CDecl = CurMethod->getClassInterface();
8097 if (!CDecl)
8098 return;
8099
8100 // Find the superclass of this class.
8101 CDecl = CDecl->getSuperClass();
8102 if (!CDecl)
8103 return;
8104
8105 if (CurMethod->isInstanceMethod()) {
8106 // We are inside an instance method, which means that the message
8107 // send [super ...] is actually calling an instance method on the
8108 // current object.
8109 return CodeCompleteObjCInstanceMessage(S, nullptr, SelIdents,
8110 AtArgumentExpression, CDecl);
8111 }
8112
8113 // Fall through to send to the superclass in CDecl.
8114 } else {
8115 // "super" may be the name of a type or variable. Figure out which
8116 // it is.
8117 const IdentifierInfo *Super = SemaRef.getSuperIdentifier();
8118 NamedDecl *ND =
8119 SemaRef.LookupSingleName(S, Super, SuperLoc, Sema::LookupOrdinaryName);
8120 if ((CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(ND))) {
8121 // "super" names an interface. Use it.
8122 } else if (TypeDecl *TD = dyn_cast_or_null<TypeDecl>(ND)) {
8123 if (const ObjCObjectType *Iface =
8124 getASTContext().getTypeDeclType(TD)->getAs<ObjCObjectType>())
8125 CDecl = Iface->getInterface();
8126 } else if (ND && isa<UnresolvedUsingTypenameDecl>(ND)) {
8127 // "super" names an unresolved type; we can't be more specific.
8128 } else {
8129 // Assume that "super" names some kind of value and parse that way.
8130 CXXScopeSpec SS;
8131 SourceLocation TemplateKWLoc;
8132 UnqualifiedId id;
8133 id.setIdentifier(Super, SuperLoc);
8134 ExprResult SuperExpr =
8135 SemaRef.ActOnIdExpression(S, SS, TemplateKWLoc, id,
8136 /*HasTrailingLParen=*/false,
8137 /*IsAddressOfOperand=*/false);
8138 return CodeCompleteObjCInstanceMessage(S, (Expr *)SuperExpr.get(),
8139 SelIdents, AtArgumentExpression);
8140 }
8141
8142 // Fall through
8143 }
8144
8145 ParsedType Receiver;
8146 if (CDecl)
8147 Receiver = ParsedType::make(getASTContext().getObjCInterfaceType(CDecl));
8148 return CodeCompleteObjCClassMessage(S, Receiver, SelIdents,
8149 AtArgumentExpression,
8150 /*IsSuper=*/true);
8151}
8152
8153/// Given a set of code-completion results for the argument of a message
8154/// send, determine the preferred type (if any) for that argument expression.
8156 unsigned NumSelIdents) {
8158 ASTContext &Context = Results.getSema().Context;
8159
8160 QualType PreferredType;
8161 unsigned BestPriority = CCP_Unlikely * 2;
8162 Result *ResultsData = Results.data();
8163 for (unsigned I = 0, N = Results.size(); I != N; ++I) {
8164 Result &R = ResultsData[I];
8165 if (R.Kind == Result::RK_Declaration &&
8166 isa<ObjCMethodDecl>(R.Declaration)) {
8167 if (R.Priority <= BestPriority) {
8168 const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(R.Declaration);
8169 if (NumSelIdents <= Method->param_size()) {
8170 QualType MyPreferredType =
8171 Method->parameters()[NumSelIdents - 1]->getType();
8172 if (R.Priority < BestPriority || PreferredType.isNull()) {
8173 BestPriority = R.Priority;
8174 PreferredType = MyPreferredType;
8175 } else if (!Context.hasSameUnqualifiedType(PreferredType,
8176 MyPreferredType)) {
8177 PreferredType = QualType();
8178 }
8179 }
8180 }
8181 }
8182 }
8183
8184 return PreferredType;
8185}
8186
8187static void
8190 bool AtArgumentExpression, bool IsSuper,
8191 ResultBuilder &Results) {
8193 ObjCInterfaceDecl *CDecl = nullptr;
8194
8195 // If the given name refers to an interface type, retrieve the
8196 // corresponding declaration.
8197 if (Receiver) {
8198 QualType T = SemaRef.GetTypeFromParser(Receiver, nullptr);
8199 if (!T.isNull())
8201 CDecl = Interface->getInterface();
8202 }
8203
8204 // Add all of the factory methods in this Objective-C class, its protocols,
8205 // superclasses, categories, implementation, etc.
8206 Results.EnterNewScope();
8207
8208 // If this is a send-to-super, try to add the special "super" send
8209 // completion.
8210 if (IsSuper) {
8211 if (ObjCMethodDecl *SuperMethod =
8212 AddSuperSendCompletion(SemaRef, false, SelIdents, Results))
8213 Results.Ignore(SuperMethod);
8214 }
8215
8216 // If we're inside an Objective-C method definition, prefer its selector to
8217 // others.
8218 if (ObjCMethodDecl *CurMethod = SemaRef.getCurMethodDecl())
8219 Results.setPreferredSelector(CurMethod->getSelector());
8220
8221 VisitedSelectorSet Selectors;
8222 if (CDecl)
8223 AddObjCMethods(CDecl, false, MK_Any, SelIdents, SemaRef.CurContext,
8224 Selectors, AtArgumentExpression, Results);
8225 else {
8226 // We're messaging "id" as a type; provide all class/factory methods.
8227
8228 // If we have an external source, load the entire class method
8229 // pool from the AST file.
8230 if (SemaRef.getExternalSource()) {
8231 for (uint32_t I = 0,
8233 I != N; ++I) {
8235 if (Sel.isNull() || SemaRef.ObjC().MethodPool.count(Sel))
8236 continue;
8237
8238 SemaRef.ObjC().ReadMethodPool(Sel);
8239 }
8240 }
8241
8243 M = SemaRef.ObjC().MethodPool.begin(),
8244 MEnd = SemaRef.ObjC().MethodPool.end();
8245 M != MEnd; ++M) {
8246 for (ObjCMethodList *MethList = &M->second.second;
8247 MethList && MethList->getMethod(); MethList = MethList->getNext()) {
8248 if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents))
8249 continue;
8250
8251 Result R(MethList->getMethod(),
8252 Results.getBasePriority(MethList->getMethod()), nullptr);
8253 R.StartParameter = SelIdents.size();
8254 R.AllParametersAreInformative = false;
8255 Results.MaybeAddResult(R, SemaRef.CurContext);
8256 }
8257 }
8258 }
8259
8260 Results.ExitScope();
8261}
8262
8264 Scope *S, ParsedType Receiver, ArrayRef<const IdentifierInfo *> SelIdents,
8265 bool AtArgumentExpression, bool IsSuper) {
8266
8267 QualType T = SemaRef.GetTypeFromParser(Receiver);
8268
8269 ResultBuilder Results(
8270 SemaRef, CodeCompleter->getAllocator(),
8271 CodeCompleter->getCodeCompletionTUInfo(),
8273 SelIdents));
8274
8275 AddClassMessageCompletions(SemaRef, S, Receiver, SelIdents,
8276 AtArgumentExpression, IsSuper, Results);
8277
8278 // If we're actually at the argument expression (rather than prior to the
8279 // selector), we're actually performing code completion for an expression.
8280 // Determine whether we have a single, best method. If so, we can
8281 // code-complete the expression using the corresponding parameter type as
8282 // our preferred type, improving completion results.
8283 if (AtArgumentExpression) {
8284 QualType PreferredType =
8285 getPreferredArgumentTypeForMessageSend(Results, SelIdents.size());
8286 if (PreferredType.isNull())
8287 CodeCompleteOrdinaryName(S, PCC_Expression);
8288 else
8289 CodeCompleteExpression(S, PreferredType);
8290 return;
8291 }
8292
8293 HandleCodeCompleteResults(&SemaRef, CodeCompleter,
8294 Results.getCompletionContext(), Results.data(),
8295 Results.size());
8296}
8297
8299 Scope *S, Expr *Receiver, ArrayRef<const IdentifierInfo *> SelIdents,
8300 bool AtArgumentExpression, ObjCInterfaceDecl *Super) {
8302 ASTContext &Context = getASTContext();
8303
8304 Expr *RecExpr = static_cast<Expr *>(Receiver);
8305
8306 // If necessary, apply function/array conversion to the receiver.
8307 // C99 6.7.5.3p[7,8].
8308 if (RecExpr) {
8309 ExprResult Conv = SemaRef.DefaultFunctionArrayLvalueConversion(RecExpr);
8310 if (Conv.isInvalid()) // conversion failed. bail.
8311 return;
8312 RecExpr = Conv.get();
8313 }
8314 QualType ReceiverType = RecExpr
8315 ? RecExpr->getType()
8316 : Super ? Context.getObjCObjectPointerType(
8317 Context.getObjCInterfaceType(Super))
8318 : Context.getObjCIdType();
8319
8320 // If we're messaging an expression with type "id" or "Class", check
8321 // whether we know something special about the receiver that allows
8322 // us to assume a more-specific receiver type.
8323 if (ReceiverType->isObjCIdType() || ReceiverType->isObjCClassType()) {
8324 if (ObjCInterfaceDecl *IFace = GetAssumedMessageSendExprType(RecExpr)) {
8325 if (ReceiverType->isObjCClassType())
8326 return CodeCompleteObjCClassMessage(
8327 S, ParsedType::make(Context.getObjCInterfaceType(IFace)), SelIdents,
8328 AtArgumentExpression, Super);
8329
8330 ReceiverType =
8331 Context.getObjCObjectPointerType(Context.getObjCInterfaceType(IFace));
8332 }
8333 } else if (RecExpr && getLangOpts().CPlusPlus) {
8335 if (Conv.isUsable()) {
8336 RecExpr = Conv.get();
8337 ReceiverType = RecExpr->getType();
8338 }
8339 }
8340
8341 // Build the set of methods we can see.
8342 ResultBuilder Results(
8343 SemaRef, CodeCompleter->getAllocator(),
8344 CodeCompleter->getCodeCompletionTUInfo(),
8346 ReceiverType, SelIdents));
8347
8348 Results.EnterNewScope();
8349
8350 // If this is a send-to-super, try to add the special "super" send
8351 // completion.
8352 if (Super) {
8353 if (ObjCMethodDecl *SuperMethod =
8354 AddSuperSendCompletion(SemaRef, false, SelIdents, Results))
8355 Results.Ignore(SuperMethod);
8356 }
8357
8358 // If we're inside an Objective-C method definition, prefer its selector to
8359 // others.
8360 if (ObjCMethodDecl *CurMethod = SemaRef.getCurMethodDecl())
8361 Results.setPreferredSelector(CurMethod->getSelector());
8362
8363 // Keep track of the selectors we've already added.
8364 VisitedSelectorSet Selectors;
8365
8366 // Handle messages to Class. This really isn't a message to an instance
8367 // method, so we treat it the same way we would treat a message send to a
8368 // class method.
8369 if (ReceiverType->isObjCClassType() ||
8370 ReceiverType->isObjCQualifiedClassType()) {
8371 if (ObjCMethodDecl *CurMethod = SemaRef.getCurMethodDecl()) {
8372 if (ObjCInterfaceDecl *ClassDecl = CurMethod->getClassInterface())
8373 AddObjCMethods(ClassDecl, false, MK_Any, SelIdents, SemaRef.CurContext,
8374 Selectors, AtArgumentExpression, Results);
8375 }
8376 }
8377 // Handle messages to a qualified ID ("id<foo>").
8378 else if (const ObjCObjectPointerType *QualID =
8379 ReceiverType->getAsObjCQualifiedIdType()) {
8380 // Search protocols for instance methods.
8381 for (auto *I : QualID->quals())
8382 AddObjCMethods(I, true, MK_Any, SelIdents, SemaRef.CurContext, Selectors,
8383 AtArgumentExpression, Results);
8384 }
8385 // Handle messages to a pointer to interface type.
8386 else if (const ObjCObjectPointerType *IFacePtr =
8387 ReceiverType->getAsObjCInterfacePointerType()) {
8388 // Search the class, its superclasses, etc., for instance methods.
8389 AddObjCMethods(IFacePtr->getInterfaceDecl(), true, MK_Any, SelIdents,
8390 SemaRef.CurContext, Selectors, AtArgumentExpression,
8391 Results);
8392
8393 // Search protocols for instance methods.
8394 for (auto *I : IFacePtr->quals())
8395 AddObjCMethods(I, true, MK_Any, SelIdents, SemaRef.CurContext, Selectors,
8396 AtArgumentExpression, Results);
8397 }
8398 // Handle messages to "id".
8399 else if (ReceiverType->isObjCIdType()) {
8400 // We're messaging "id", so provide all instance methods we know
8401 // about as code-completion results.
8402
8403 // If we have an external source, load the entire class method
8404 // pool from the AST file.
8405 if (SemaRef.ExternalSource) {
8406 for (uint32_t I = 0,
8407 N = SemaRef.ExternalSource->GetNumExternalSelectors();
8408 I != N; ++I) {
8409 Selector Sel = SemaRef.ExternalSource->GetExternalSelector(I);
8410 if (Sel.isNull() || SemaRef.ObjC().MethodPool.count(Sel))
8411 continue;
8412
8413 SemaRef.ObjC().ReadMethodPool(Sel);
8414 }
8415 }
8416
8418 M = SemaRef.ObjC().MethodPool.begin(),
8419 MEnd = SemaRef.ObjC().MethodPool.end();
8420 M != MEnd; ++M) {
8421 for (ObjCMethodList *MethList = &M->second.first;
8422 MethList && MethList->getMethod(); MethList = MethList->getNext()) {
8423 if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents))
8424 continue;
8425
8426 if (!Selectors.insert(MethList->getMethod()->getSelector()).second)
8427 continue;
8428
8429 Result R(MethList->getMethod(),
8430 Results.getBasePriority(MethList->getMethod()), nullptr);
8431 R.StartParameter = SelIdents.size();
8432 R.AllParametersAreInformative = false;
8433 Results.MaybeAddResult(R, SemaRef.CurContext);
8434 }
8435 }
8436 }
8437 Results.ExitScope();
8438
8439 // If we're actually at the argument expression (rather than prior to the
8440 // selector), we're actually performing code completion for an expression.
8441 // Determine whether we have a single, best method. If so, we can
8442 // code-complete the expression using the corresponding parameter type as
8443 // our preferred type, improving completion results.
8444 if (AtArgumentExpression) {
8445 QualType PreferredType =
8446 getPreferredArgumentTypeForMessageSend(Results, SelIdents.size());
8447 if (PreferredType.isNull())
8448 CodeCompleteOrdinaryName(S, PCC_Expression);
8449 else
8450 CodeCompleteExpression(S, PreferredType);
8451 return;
8452 }
8453
8454 HandleCodeCompleteResults(&SemaRef, CodeCompleter,
8455 Results.getCompletionContext(), Results.data(),
8456 Results.size());
8457}
8458
8460 Scope *S, DeclGroupPtrTy IterationVar) {
8462 Data.ObjCCollection = true;
8463
8464 if (IterationVar.getAsOpaquePtr()) {
8465 DeclGroupRef DG = IterationVar.get();
8466 for (DeclGroupRef::iterator I = DG.begin(), End = DG.end(); I != End; ++I) {
8467 if (*I)
8468 Data.IgnoreDecls.push_back(*I);
8469 }
8470 }
8471
8472 CodeCompleteExpression(S, Data);
8473}
8474
8477 // If we have an external source, load the entire class method
8478 // pool from the AST file.
8479 if (SemaRef.ExternalSource) {
8480 for (uint32_t I = 0, N = SemaRef.ExternalSource->GetNumExternalSelectors();
8481 I != N; ++I) {
8482 Selector Sel = SemaRef.ExternalSource->GetExternalSelector(I);
8483 if (Sel.isNull() || SemaRef.ObjC().MethodPool.count(Sel))
8484 continue;
8485
8486 SemaRef.ObjC().ReadMethodPool(Sel);
8487 }
8488 }
8489
8490 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(),
8491 CodeCompleter->getCodeCompletionTUInfo(),
8493 Results.EnterNewScope();
8495 M = SemaRef.ObjC().MethodPool.begin(),
8496 MEnd = SemaRef.ObjC().MethodPool.end();
8497 M != MEnd; ++M) {
8498
8499 Selector Sel = M->first;
8500 if (!isAcceptableObjCSelector(Sel, MK_Any, SelIdents))
8501 continue;
8502
8503 CodeCompletionBuilder Builder(Results.getAllocator(),
8504 Results.getCodeCompletionTUInfo());
8505 if (Sel.isUnarySelector()) {
8506 Builder.AddTypedTextChunk(
8507 Builder.getAllocator().CopyString(Sel.getNameForSlot(0)));
8508 Results.AddResult(Builder.TakeString());
8509 continue;
8510 }
8511
8512 std::string Accumulator;
8513 for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I) {
8514 if (I == SelIdents.size()) {
8515 if (!Accumulator.empty()) {
8516 Builder.AddInformativeChunk(
8517 Builder.getAllocator().CopyString(Accumulator));
8518 Accumulator.clear();
8519 }
8520 }
8521
8522 Accumulator += Sel.getNameForSlot(I);
8523 Accumulator += ':';
8524 }
8525 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(Accumulator));
8526 Results.AddResult(Builder.TakeString());
8527 }
8528 Results.ExitScope();
8529
8530 HandleCodeCompleteResults(&SemaRef, CodeCompleter,
8531 Results.getCompletionContext(), Results.data(),
8532 Results.size());
8533}
8534
8535/// Add all of the protocol declarations that we find in the given
8536/// (translation unit) context.
8537static void AddProtocolResults(DeclContext *Ctx, DeclContext *CurContext,
8538 bool OnlyForwardDeclarations,
8539 ResultBuilder &Results) {
8541
8542 for (const auto *D : Ctx->decls()) {
8543 // Record any protocols we find.
8544 if (const auto *Proto = dyn_cast<ObjCProtocolDecl>(D))
8545 if (!OnlyForwardDeclarations || !Proto->hasDefinition())
8546 Results.AddResult(
8547 Result(Proto, Results.getBasePriority(Proto), nullptr), CurContext,
8548 nullptr, false);
8549 }
8550}
8551
8553 ArrayRef<IdentifierLocPair> Protocols) {
8554 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(),
8555 CodeCompleter->getCodeCompletionTUInfo(),
8557
8558 if (CodeCompleter->includeGlobals()) {
8559 Results.EnterNewScope();
8560
8561 // Tell the result set to ignore all of the protocols we have
8562 // already seen.
8563 // FIXME: This doesn't work when caching code-completion results.
8564 for (const IdentifierLocPair &Pair : Protocols)
8565 if (ObjCProtocolDecl *Protocol =
8566 SemaRef.ObjC().LookupProtocol(Pair.first, Pair.second))
8567 Results.Ignore(Protocol);
8568
8569 // Add all protocols.
8570 AddProtocolResults(getASTContext().getTranslationUnitDecl(),
8571 SemaRef.CurContext, false, Results);
8572
8573 Results.ExitScope();
8574 }
8575
8576 HandleCodeCompleteResults(&SemaRef, CodeCompleter,
8577 Results.getCompletionContext(), Results.data(),
8578 Results.size());
8579}
8580
8582 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(),
8583 CodeCompleter->getCodeCompletionTUInfo(),
8585
8586 if (CodeCompleter->includeGlobals()) {
8587 Results.EnterNewScope();
8588
8589 // Add all protocols.
8590 AddProtocolResults(getASTContext().getTranslationUnitDecl(),
8591 SemaRef.CurContext, true, Results);
8592
8593 Results.ExitScope();
8594 }
8595
8596 HandleCodeCompleteResults(&SemaRef, CodeCompleter,
8597 Results.getCompletionContext(), Results.data(),
8598 Results.size());
8599}
8600
8601/// Add all of the Objective-C interface declarations that we find in
8602/// the given (translation unit) context.
8603static void AddInterfaceResults(DeclContext *Ctx, DeclContext *CurContext,
8604 bool OnlyForwardDeclarations,
8605 bool OnlyUnimplemented,
8606 ResultBuilder &Results) {
8608
8609 for (const auto *D : Ctx->decls()) {
8610 // Record any interfaces we find.
8611 if (const auto *Class = dyn_cast<ObjCInterfaceDecl>(D))
8612 if ((!OnlyForwardDeclarations || !Class->hasDefinition()) &&
8613 (!OnlyUnimplemented || !Class->getImplementation()))
8614 Results.AddResult(
8615 Result(Class, Results.getBasePriority(Class), nullptr), CurContext,
8616 nullptr, false);
8617 }
8618}
8619
8621 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(),
8622 CodeCompleter->getCodeCompletionTUInfo(),
8624 Results.EnterNewScope();
8625
8626 if (CodeCompleter->includeGlobals()) {
8627 // Add all classes.
8628 AddInterfaceResults(getASTContext().getTranslationUnitDecl(),
8629 SemaRef.CurContext, false, false, Results);
8630 }
8631
8632 Results.ExitScope();
8633
8634 HandleCodeCompleteResults(&SemaRef, CodeCompleter,
8635 Results.getCompletionContext(), Results.data(),
8636 Results.size());
8637}
8638
8640 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(),
8641 CodeCompleter->getCodeCompletionTUInfo(),
8643 Results.EnterNewScope();
8644
8645 if (CodeCompleter->includeGlobals()) {
8646 // Add all classes.
8647 AddInterfaceResults(getASTContext().getTranslationUnitDecl(),
8648 SemaRef.CurContext, false, false, Results);
8649 }
8650
8651 Results.ExitScope();
8652
8653 HandleCodeCompleteResults(&SemaRef, CodeCompleter,
8654 Results.getCompletionContext(), Results.data(),
8655 Results.size());
8656}
8657
8659 Scope *S, IdentifierInfo *ClassName, SourceLocation ClassNameLoc) {
8660 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(),
8661 CodeCompleter->getCodeCompletionTUInfo(),
8663 Results.EnterNewScope();
8664
8665 // Make sure that we ignore the class we're currently defining.
8666 NamedDecl *CurClass = SemaRef.LookupSingleName(
8667 SemaRef.TUScope, ClassName, ClassNameLoc, Sema::LookupOrdinaryName);
8668 if (CurClass && isa<ObjCInterfaceDecl>(CurClass))
8669 Results.Ignore(CurClass);
8670
8671 if (CodeCompleter->includeGlobals()) {
8672 // Add all classes.
8673 AddInterfaceResults(getASTContext().getTranslationUnitDecl(),
8674 SemaRef.CurContext, false, false, Results);
8675 }
8676
8677 Results.ExitScope();
8678
8679 HandleCodeCompleteResults(&SemaRef, CodeCompleter,
8680 Results.getCompletionContext(), Results.data(),
8681 Results.size());
8682}
8683
8685 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(),
8686 CodeCompleter->getCodeCompletionTUInfo(),
8688 Results.EnterNewScope();
8689
8690 if (CodeCompleter->includeGlobals()) {
8691 // Add all unimplemented classes.
8692 AddInterfaceResults(getASTContext().getTranslationUnitDecl(),
8693 SemaRef.CurContext, false, true, Results);
8694 }
8695
8696 Results.ExitScope();
8697
8698 HandleCodeCompleteResults(&SemaRef, CodeCompleter,
8699 Results.getCompletionContext(), Results.data(),
8700 Results.size());
8701}
8702
8704 Scope *S, IdentifierInfo *ClassName, SourceLocation ClassNameLoc) {
8706
8707 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(),
8708 CodeCompleter->getCodeCompletionTUInfo(),
8710
8711 // Ignore any categories we find that have already been implemented by this
8712 // interface.
8714 NamedDecl *CurClass = SemaRef.LookupSingleName(
8715 SemaRef.TUScope, ClassName, ClassNameLoc, Sema::LookupOrdinaryName);
8717 dyn_cast_or_null<ObjCInterfaceDecl>(CurClass)) {
8718 for (const auto *Cat : Class->visible_categories())
8719 CategoryNames.insert(Cat->getIdentifier());
8720 }
8721
8722 // Add all of the categories we know about.
8723 Results.EnterNewScope();
8724 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
8725 for (const auto *D : TU->decls())
8726 if (const auto *Category = dyn_cast<ObjCCategoryDecl>(D))
8727 if (CategoryNames.insert(Category->getIdentifier()).second)
8728 Results.AddResult(
8729 Result(Category, Results.getBasePriority(Category), nullptr),
8730 SemaRef.CurContext, nullptr, false);
8731 Results.ExitScope();
8732
8733 HandleCodeCompleteResults(&SemaRef, CodeCompleter,
8734 Results.getCompletionContext(), Results.data(),
8735 Results.size());
8736}
8737
8739 Scope *S, IdentifierInfo *ClassName, SourceLocation ClassNameLoc) {
8741
8742 // Find the corresponding interface. If we couldn't find the interface, the
8743 // program itself is ill-formed. However, we'll try to be helpful still by
8744 // providing the list of all of the categories we know about.
8745 NamedDecl *CurClass = SemaRef.LookupSingleName(
8746 SemaRef.TUScope, ClassName, ClassNameLoc, Sema::LookupOrdinaryName);
8747 ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass);
8748 if (!Class)
8749 return CodeCompleteObjCInterfaceCategory(S, ClassName, ClassNameLoc);
8750
8751 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(),
8752 CodeCompleter->getCodeCompletionTUInfo(),
8754
8755 // Add all of the categories that have corresponding interface
8756 // declarations in this class and any of its superclasses, except for
8757 // already-implemented categories in the class itself.
8759 Results.EnterNewScope();
8760 bool IgnoreImplemented = true;
8761 while (Class) {
8762 for (const auto *Cat : Class->visible_categories()) {
8763 if ((!IgnoreImplemented || !Cat->getImplementation()) &&
8764 CategoryNames.insert(Cat->getIdentifier()).second)
8765 Results.AddResult(Result(Cat, Results.getBasePriority(Cat), nullptr),
8766 SemaRef.CurContext, nullptr, false);
8767 }
8768
8769 Class = Class->getSuperClass();
8770 IgnoreImplemented = false;
8771 }
8772 Results.ExitScope();
8773
8774 HandleCodeCompleteResults(&SemaRef, CodeCompleter,
8775 Results.getCompletionContext(), Results.data(),
8776 Results.size());
8777}
8778
8781 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(),
8782 CodeCompleter->getCodeCompletionTUInfo(), CCContext);
8783
8784 // Figure out where this @synthesize lives.
8785 ObjCContainerDecl *Container =
8786 dyn_cast_or_null<ObjCContainerDecl>(SemaRef.CurContext);
8787 if (!Container || (!isa<ObjCImplementationDecl>(Container) &&
8788 !isa<ObjCCategoryImplDecl>(Container)))
8789 return;
8790
8791 // Ignore any properties that have already been implemented.
8792 Container = getContainerDef(Container);
8793 for (const auto *D : Container->decls())
8794 if (const auto *PropertyImpl = dyn_cast<ObjCPropertyImplDecl>(D))
8795 Results.Ignore(PropertyImpl->getPropertyDecl());
8796
8797 // Add any properties that we find.
8798 AddedPropertiesSet AddedProperties;
8799 Results.EnterNewScope();
8800 if (ObjCImplementationDecl *ClassImpl =
8801 dyn_cast<ObjCImplementationDecl>(Container))
8802 AddObjCProperties(CCContext, ClassImpl->getClassInterface(), false,
8803 /*AllowNullaryMethods=*/false, SemaRef.CurContext,
8804 AddedProperties, Results);
8805 else
8806 AddObjCProperties(CCContext,
8807 cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl(),
8808 false, /*AllowNullaryMethods=*/false, SemaRef.CurContext,
8809 AddedProperties, Results);
8810 Results.ExitScope();
8811
8812 HandleCodeCompleteResults(&SemaRef, CodeCompleter,
8813 Results.getCompletionContext(), Results.data(),
8814 Results.size());
8815}
8816
8818 Scope *S, IdentifierInfo *PropertyName) {
8820 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(),
8821 CodeCompleter->getCodeCompletionTUInfo(),
8823
8824 // Figure out where this @synthesize lives.
8825 ObjCContainerDecl *Container =
8826 dyn_cast_or_null<ObjCContainerDecl>(SemaRef.CurContext);
8827 if (!Container || (!isa<ObjCImplementationDecl>(Container) &&
8828 !isa<ObjCCategoryImplDecl>(Container)))
8829 return;
8830
8831 // Figure out which interface we're looking into.
8832 ObjCInterfaceDecl *Class = nullptr;
8833 if (ObjCImplementationDecl *ClassImpl =
8834 dyn_cast<ObjCImplementationDecl>(Container))
8835 Class = ClassImpl->getClassInterface();
8836 else
8837 Class = cast<ObjCCategoryImplDecl>(Container)
8838 ->getCategoryDecl()
8839 ->getClassInterface();
8840
8841 // Determine the type of the property we're synthesizing.
8842 QualType PropertyType = getASTContext().getObjCIdType();
8843 if (Class) {
8844 if (ObjCPropertyDecl *Property = Class->FindPropertyDeclaration(
8846 PropertyType =
8847 Property->getType().getNonReferenceType().getUnqualifiedType();
8848
8849 // Give preference to ivars
8850 Results.setPreferredType(PropertyType);
8851 }
8852 }
8853
8854 // Add all of the instance variables in this class and its superclasses.
8855 Results.EnterNewScope();
8856 bool SawSimilarlyNamedIvar = false;
8857 std::string NameWithPrefix;
8858 NameWithPrefix += '_';
8859 NameWithPrefix += PropertyName->getName();
8860 std::string NameWithSuffix = PropertyName->getName().str();
8861 NameWithSuffix += '_';
8862 for (; Class; Class = Class->getSuperClass()) {
8863 for (ObjCIvarDecl *Ivar = Class->all_declared_ivar_begin(); Ivar;
8864 Ivar = Ivar->getNextIvar()) {
8865 Results.AddResult(Result(Ivar, Results.getBasePriority(Ivar), nullptr),
8866 SemaRef.CurContext, nullptr, false);
8867
8868 // Determine whether we've seen an ivar with a name similar to the
8869 // property.
8870 if ((PropertyName == Ivar->getIdentifier() ||
8871 NameWithPrefix == Ivar->getName() ||
8872 NameWithSuffix == Ivar->getName())) {
8873 SawSimilarlyNamedIvar = true;
8874
8875 // Reduce the priority of this result by one, to give it a slight
8876 // advantage over other results whose names don't match so closely.
8877 if (Results.size() &&
8878 Results.data()[Results.size() - 1].Kind ==
8880 Results.data()[Results.size() - 1].Declaration == Ivar)
8881 Results.data()[Results.size() - 1].Priority--;
8882 }
8883 }
8884 }
8885
8886 if (!SawSimilarlyNamedIvar) {
8887 // Create ivar result _propName, that the user can use to synthesize
8888 // an ivar of the appropriate type.
8889 unsigned Priority = CCP_MemberDeclaration + 1;
8891 CodeCompletionAllocator &Allocator = Results.getAllocator();
8892 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo(),
8894
8896 Builder.AddResultTypeChunk(GetCompletionTypeString(
8897 PropertyType, getASTContext(), Policy, Allocator));
8898 Builder.AddTypedTextChunk(Allocator.CopyString(NameWithPrefix));
8899 Results.AddResult(
8900 Result(Builder.TakeString(), Priority, CXCursor_ObjCIvarDecl));
8901 }
8902
8903 Results.ExitScope();
8904
8905 HandleCodeCompleteResults(&SemaRef, CodeCompleter,
8906 Results.getCompletionContext(), Results.data(),
8907 Results.size());
8908}
8909
8910// Mapping from selectors to the methods that implement that selector, along
8911// with the "in original class" flag.
8912typedef llvm::DenseMap<Selector,
8913 llvm::PointerIntPair<ObjCMethodDecl *, 1, bool>>
8915
8916/// Find all of the methods that reside in the given container
8917/// (and its superclasses, protocols, etc.) that meet the given
8918/// criteria. Insert those methods into the map of known methods,
8919/// indexed by selector so they can be easily found.
8921 ObjCContainerDecl *Container,
8922 std::optional<bool> WantInstanceMethods,
8923 QualType ReturnType,
8924 KnownMethodsMap &KnownMethods,
8925 bool InOriginalClass = true) {
8926 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)) {
8927 // Make sure we have a definition; that's what we'll walk.
8928 if (!IFace->hasDefinition())
8929 return;
8930
8931 IFace = IFace->getDefinition();
8932 Container = IFace;
8933
8934 const ObjCList<ObjCProtocolDecl> &Protocols =
8935 IFace->getReferencedProtocols();
8936 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
8937 E = Protocols.end();
8938 I != E; ++I)
8939 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
8940 KnownMethods, InOriginalClass);
8941
8942 // Add methods from any class extensions and categories.
8943 for (auto *Cat : IFace->visible_categories()) {
8944 FindImplementableMethods(Context, Cat, WantInstanceMethods, ReturnType,
8945 KnownMethods, false);
8946 }
8947
8948 // Visit the superclass.
8949 if (IFace->getSuperClass())
8950 FindImplementableMethods(Context, IFace->getSuperClass(),
8951 WantInstanceMethods, ReturnType, KnownMethods,
8952 false);
8953 }
8954
8955 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
8956 // Recurse into protocols.
8957 const ObjCList<ObjCProtocolDecl> &Protocols =
8958 Category->getReferencedProtocols();
8959 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
8960 E = Protocols.end();
8961 I != E; ++I)
8962 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
8963 KnownMethods, InOriginalClass);
8964
8965 // If this category is the original class, jump to the interface.
8966 if (InOriginalClass && Category->getClassInterface())
8967 FindImplementableMethods(Context, Category->getClassInterface(),
8968 WantInstanceMethods, ReturnType, KnownMethods,
8969 false);
8970 }
8971
8972 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
8973 // Make sure we have a definition; that's what we'll walk.
8974 if (!Protocol->hasDefinition())
8975 return;
8976 Protocol = Protocol->getDefinition();
8977 Container = Protocol;
8978
8979 // Recurse into protocols.
8980 const ObjCList<ObjCProtocolDecl> &Protocols =
8981 Protocol->getReferencedProtocols();
8982 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
8983 E = Protocols.end();
8984 I != E; ++I)
8985 FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
8986 KnownMethods, false);
8987 }
8988
8989 // Add methods in this container. This operation occurs last because
8990 // we want the methods from this container to override any methods
8991 // we've previously seen with the same selector.
8992 for (auto *M : Container->methods()) {
8993 if (!WantInstanceMethods || M->isInstanceMethod() == *WantInstanceMethods) {
8994 if (!ReturnType.isNull() &&
8995 !Context.hasSameUnqualifiedType(ReturnType, M->getReturnType()))
8996 continue;
8997
8998 KnownMethods[M->getSelector()] =
8999 KnownMethodsMap::mapped_type(M, InOriginalClass);
9000 }
9001 }
9002}
9003
9004/// Add the parenthesized return or parameter type chunk to a code
9005/// completion string.
9006static void AddObjCPassingTypeChunk(QualType Type, unsigned ObjCDeclQuals,
9007 ASTContext &Context,
9008 const PrintingPolicy &Policy,
9009 CodeCompletionBuilder &Builder) {
9010 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9011 std::string Quals = formatObjCParamQualifiers(ObjCDeclQuals, Type);
9012 if (!Quals.empty())
9013 Builder.AddTextChunk(Builder.getAllocator().CopyString(Quals));
9014 Builder.AddTextChunk(
9015 GetCompletionTypeString(Type, Context, Policy, Builder.getAllocator()));
9016 Builder.AddChunk(CodeCompletionString::CK_RightParen);
9017}
9018
9019/// Determine whether the given class is or inherits from a class by
9020/// the given name.
9021static bool InheritsFromClassNamed(ObjCInterfaceDecl *Class, StringRef Name) {
9022 if (!Class)
9023 return false;
9024
9025 if (Class->getIdentifier() && Class->getIdentifier()->getName() == Name)
9026 return true;
9027
9028 return InheritsFromClassNamed(Class->getSuperClass(), Name);
9029}
9030
9031/// Add code completions for Objective-C Key-Value Coding (KVC) and
9032/// Key-Value Observing (KVO).
9034 bool IsInstanceMethod,
9035 QualType ReturnType, ASTContext &Context,
9036 VisitedSelectorSet &KnownSelectors,
9037 ResultBuilder &Results) {
9038 IdentifierInfo *PropName = Property->getIdentifier();
9039 if (!PropName || PropName->getLength() == 0)
9040 return;
9041
9042 PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema());
9043
9044 // Builder that will create each code completion.
9046 CodeCompletionAllocator &Allocator = Results.getAllocator();
9047 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
9048
9049 // The selector table.
9050 SelectorTable &Selectors = Context.Selectors;
9051
9052 // The property name, copied into the code completion allocation region
9053 // on demand.
9054 struct KeyHolder {
9055 CodeCompletionAllocator &Allocator;
9056 StringRef Key;
9057 const char *CopiedKey;
9058
9059 KeyHolder(CodeCompletionAllocator &Allocator, StringRef Key)
9060 : Allocator(Allocator), Key(Key), CopiedKey(nullptr) {}
9061
9062 operator const char *() {
9063 if (CopiedKey)
9064 return CopiedKey;
9065
9066 return CopiedKey = Allocator.CopyString(Key);
9067 }
9068 } Key(Allocator, PropName->getName());
9069
9070 // The uppercased name of the property name.
9071 std::string UpperKey = std::string(PropName->getName());
9072 if (!UpperKey.empty())
9073 UpperKey[0] = toUppercase(UpperKey[0]);
9074
9075 bool ReturnTypeMatchesProperty =
9076 ReturnType.isNull() ||
9077 Context.hasSameUnqualifiedType(ReturnType.getNonReferenceType(),
9078 Property->getType());
9079 bool ReturnTypeMatchesVoid = ReturnType.isNull() || ReturnType->isVoidType();
9080
9081 // Add the normal accessor -(type)key.
9082 if (IsInstanceMethod &&
9083 KnownSelectors.insert(Selectors.getNullarySelector(PropName)).second &&
9084 ReturnTypeMatchesProperty && !Property->getGetterMethodDecl()) {
9085 if (ReturnType.isNull())
9086 AddObjCPassingTypeChunk(Property->getType(), /*Quals=*/0, Context, Policy,
9087 Builder);
9088
9089 Builder.AddTypedTextChunk(Key);
9090 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
9092 }
9093
9094 // If we have an integral or boolean property (or the user has provided
9095 // an integral or boolean return type), add the accessor -(type)isKey.
9096 if (IsInstanceMethod &&
9097 ((!ReturnType.isNull() &&
9098 (ReturnType->isIntegerType() || ReturnType->isBooleanType())) ||
9099 (ReturnType.isNull() && (Property->getType()->isIntegerType() ||
9100 Property->getType()->isBooleanType())))) {
9101 std::string SelectorName = (Twine("is") + UpperKey).str();
9102 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
9103 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
9104 .second) {
9105 if (ReturnType.isNull()) {
9106 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9107 Builder.AddTextChunk("BOOL");
9108 Builder.AddChunk(CodeCompletionString::CK_RightParen);
9109 }
9110
9111 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorId->getName()));
9112 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
9114 }
9115 }
9116
9117 // Add the normal mutator.
9118 if (IsInstanceMethod && ReturnTypeMatchesVoid &&
9119 !Property->getSetterMethodDecl()) {
9120 std::string SelectorName = (Twine("set") + UpperKey).str();
9121 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
9122 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
9123 if (ReturnType.isNull()) {
9124 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9125 Builder.AddTextChunk("void");
9126 Builder.AddChunk(CodeCompletionString::CK_RightParen);
9127 }
9128
9129 Builder.AddTypedTextChunk(
9130 Allocator.CopyString(SelectorId->getName() + ":"));
9131 AddObjCPassingTypeChunk(Property->getType(), /*Quals=*/0, Context, Policy,
9132 Builder);
9133 Builder.AddTextChunk(Key);
9134 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
9136 }
9137 }
9138
9139 // Indexed and unordered accessors
9140 unsigned IndexedGetterPriority = CCP_CodePattern;
9141 unsigned IndexedSetterPriority = CCP_CodePattern;
9142 unsigned UnorderedGetterPriority = CCP_CodePattern;
9143 unsigned UnorderedSetterPriority = CCP_CodePattern;
9144 if (const auto *ObjCPointer =
9145 Property->getType()->getAs<ObjCObjectPointerType>()) {
9146 if (ObjCInterfaceDecl *IFace = ObjCPointer->getInterfaceDecl()) {
9147 // If this interface type is not provably derived from a known
9148 // collection, penalize the corresponding completions.
9149 if (!InheritsFromClassNamed(IFace, "NSMutableArray")) {
9150 IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
9151 if (!InheritsFromClassNamed(IFace, "NSArray"))
9152 IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
9153 }
9154
9155 if (!InheritsFromClassNamed(IFace, "NSMutableSet")) {
9156 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
9157 if (!InheritsFromClassNamed(IFace, "NSSet"))
9158 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
9159 }
9160 }
9161 } else {
9162 IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
9163 IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
9164 UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
9165 UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
9166 }
9167
9168 // Add -(NSUInteger)countOf<key>
9169 if (IsInstanceMethod &&
9170 (ReturnType.isNull() || ReturnType->isIntegerType())) {
9171 std::string SelectorName = (Twine("countOf") + UpperKey).str();
9172 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
9173 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
9174 .second) {
9175 if (ReturnType.isNull()) {
9176 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9177 Builder.AddTextChunk("NSUInteger");
9178 Builder.AddChunk(CodeCompletionString::CK_RightParen);
9179 }
9180
9181 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorId->getName()));
9182 Results.AddResult(
9183 Result(Builder.TakeString(),
9184 std::min(IndexedGetterPriority, UnorderedGetterPriority),
9186 }
9187 }
9188
9189 // Indexed getters
9190 // Add -(id)objectInKeyAtIndex:(NSUInteger)index
9191 if (IsInstanceMethod &&
9192 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
9193 std::string SelectorName = (Twine("objectIn") + UpperKey + "AtIndex").str();
9194 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
9195 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
9196 if (ReturnType.isNull()) {
9197 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9198 Builder.AddTextChunk("id");
9199 Builder.AddChunk(CodeCompletionString::CK_RightParen);
9200 }
9201
9202 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
9203 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9204 Builder.AddTextChunk("NSUInteger");
9205 Builder.AddChunk(CodeCompletionString::CK_RightParen);
9206 Builder.AddTextChunk("index");
9207 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
9209 }
9210 }
9211
9212 // Add -(NSArray *)keyAtIndexes:(NSIndexSet *)indexes
9213 if (IsInstanceMethod &&
9214 (ReturnType.isNull() ||
9215 (ReturnType->isObjCObjectPointerType() &&
9216 ReturnType->castAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
9217 ReturnType->castAs<ObjCObjectPointerType>()
9219 ->getName() == "NSArray"))) {
9220 std::string SelectorName = (Twine(Property->getName()) + "AtIndexes").str();
9221 IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
9222 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
9223 if (ReturnType.isNull()) {
9224 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9225 Builder.AddTextChunk("NSArray *");
9226 Builder.AddChunk(CodeCompletionString::CK_RightParen);
9227 }
9228
9229 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
9230 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9231 Builder.AddTextChunk("NSIndexSet *");
9232 Builder.AddChunk(CodeCompletionString::CK_RightParen);
9233 Builder.AddTextChunk("indexes");
9234 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
9236 }
9237 }
9238
9239 // Add -(void)getKey:(type **)buffer range:(NSRange)inRange
9240 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
9241 std::string SelectorName = (Twine("get") + UpperKey).str();
9242 const IdentifierInfo *SelectorIds[2] = {&Context.Idents.get(SelectorName),
9243 &Context.Idents.get("range")};
9244
9245 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
9246 if (ReturnType.isNull()) {
9247 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9248 Builder.AddTextChunk("void");
9249 Builder.AddChunk(CodeCompletionString::CK_RightParen);
9250 }
9251
9252 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
9253 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9254 Builder.AddPlaceholderChunk("object-type");
9255 Builder.AddTextChunk(" **");
9256 Builder.AddChunk(CodeCompletionString::CK_RightParen);
9257 Builder.AddTextChunk("buffer");
9259 Builder.AddTypedTextChunk("range:");
9260 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9261 Builder.AddTextChunk("NSRange");
9262 Builder.AddChunk(CodeCompletionString::CK_RightParen);
9263 Builder.AddTextChunk("inRange");
9264 Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
9266 }
9267 }
9268
9269 // Mutable indexed accessors
9270
9271 // - (void)insertObject:(type *)object inKeyAtIndex:(NSUInteger)index
9272 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
9273 std::string SelectorName = (Twine("in") + UpperKey + "AtIndex").str();
9274 const IdentifierInfo *SelectorIds[2] = {&Context.Idents.get("insertObject"),
9275 &Context.Idents.get(SelectorName)};
9276
9277 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
9278 if (ReturnType.isNull()) {
9279 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9280 Builder.AddTextChunk("void");
9281 Builder.AddChunk(CodeCompletionString::CK_RightParen);
9282 }
9283
9284 Builder.AddTypedTextChunk("insertObject:");
9285 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9286 Builder.AddPlaceholderChunk("object-type");
9287 Builder.AddTextChunk(" *");
9288 Builder.AddChunk(CodeCompletionString::CK_RightParen);
9289 Builder.AddTextChunk("object");
9291 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
9292 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9293 Builder.AddPlaceholderChunk("NSUInteger");
9294 Builder.AddChunk(CodeCompletionString::CK_RightParen);
9295 Builder.AddTextChunk("index");
9296 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
9298 }
9299 }
9300
9301 // - (void)insertKey:(NSArray *)array atIndexes:(NSIndexSet *)indexes
9302 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
9303 std::string SelectorName = (Twine("insert") + UpperKey).str();
9304 const IdentifierInfo *SelectorIds[2] = {&Context.Idents.get(SelectorName),
9305 &Context.Idents.get("atIndexes")};
9306
9307 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
9308 if (ReturnType.isNull()) {
9309 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9310 Builder.AddTextChunk("void");
9311 Builder.AddChunk(CodeCompletionString::CK_RightParen);
9312 }
9313
9314 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
9315 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9316 Builder.AddTextChunk("NSArray *");
9317 Builder.AddChunk(CodeCompletionString::CK_RightParen);
9318 Builder.AddTextChunk("array");
9320 Builder.AddTypedTextChunk("atIndexes:");
9321 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9322 Builder.AddPlaceholderChunk("NSIndexSet *");
9323 Builder.AddChunk(CodeCompletionString::CK_RightParen);
9324 Builder.AddTextChunk("indexes");
9325 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
9327 }
9328 }
9329
9330 // -(void)removeObjectFromKeyAtIndex:(NSUInteger)index
9331 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
9332 std::string SelectorName =
9333 (Twine("removeObjectFrom") + UpperKey + "AtIndex").str();
9334 const IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
9335 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
9336 if (ReturnType.isNull()) {
9337 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9338 Builder.AddTextChunk("void");
9339 Builder.AddChunk(CodeCompletionString::CK_RightParen);
9340 }
9341
9342 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
9343 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9344 Builder.AddTextChunk("NSUInteger");
9345 Builder.AddChunk(CodeCompletionString::CK_RightParen);
9346 Builder.AddTextChunk("index");
9347 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
9349 }
9350 }
9351
9352 // -(void)removeKeyAtIndexes:(NSIndexSet *)indexes
9353 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
9354 std::string SelectorName = (Twine("remove") + UpperKey + "AtIndexes").str();
9355 const IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
9356 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
9357 if (ReturnType.isNull()) {
9358 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9359 Builder.AddTextChunk("void");
9360 Builder.AddChunk(CodeCompletionString::CK_RightParen);
9361 }
9362
9363 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
9364 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9365 Builder.AddTextChunk("NSIndexSet *");
9366 Builder.AddChunk(CodeCompletionString::CK_RightParen);
9367 Builder.AddTextChunk("indexes");
9368 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
9370 }
9371 }
9372
9373 // - (void)replaceObjectInKeyAtIndex:(NSUInteger)index withObject:(id)object
9374 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
9375 std::string SelectorName =
9376 (Twine("replaceObjectIn") + UpperKey + "AtIndex").str();
9377 const IdentifierInfo *SelectorIds[2] = {&Context.Idents.get(SelectorName),
9378 &Context.Idents.get("withObject")};
9379
9380 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
9381 if (ReturnType.isNull()) {
9382 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9383 Builder.AddTextChunk("void");
9384 Builder.AddChunk(CodeCompletionString::CK_RightParen);
9385 }
9386
9387 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
9388 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9389 Builder.AddPlaceholderChunk("NSUInteger");
9390 Builder.AddChunk(CodeCompletionString::CK_RightParen);
9391 Builder.AddTextChunk("index");
9393 Builder.AddTypedTextChunk("withObject:");
9394 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9395 Builder.AddTextChunk("id");
9396 Builder.AddChunk(CodeCompletionString::CK_RightParen);
9397 Builder.AddTextChunk("object");
9398 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
9400 }
9401 }
9402
9403 // - (void)replaceKeyAtIndexes:(NSIndexSet *)indexes withKey:(NSArray *)array
9404 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
9405 std::string SelectorName1 =
9406 (Twine("replace") + UpperKey + "AtIndexes").str();
9407 std::string SelectorName2 = (Twine("with") + UpperKey).str();
9408 const IdentifierInfo *SelectorIds[2] = {&Context.Idents.get(SelectorName1),
9409 &Context.Idents.get(SelectorName2)};
9410
9411 if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
9412 if (ReturnType.isNull()) {
9413 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9414 Builder.AddTextChunk("void");
9415 Builder.AddChunk(CodeCompletionString::CK_RightParen);
9416 }
9417
9418 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName1 + ":"));
9419 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9420 Builder.AddPlaceholderChunk("NSIndexSet *");
9421 Builder.AddChunk(CodeCompletionString::CK_RightParen);
9422 Builder.AddTextChunk("indexes");
9424 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName2 + ":"));
9425 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9426 Builder.AddTextChunk("NSArray *");
9427 Builder.AddChunk(CodeCompletionString::CK_RightParen);
9428 Builder.AddTextChunk("array");
9429 Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
9431 }
9432 }
9433
9434 // Unordered getters
9435 // - (NSEnumerator *)enumeratorOfKey
9436 if (IsInstanceMethod &&
9437 (ReturnType.isNull() ||
9438 (ReturnType->isObjCObjectPointerType() &&
9439 ReturnType->castAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
9440 ReturnType->castAs<ObjCObjectPointerType>()
9442 ->getName() == "NSEnumerator"))) {
9443 std::string SelectorName = (Twine("enumeratorOf") + UpperKey).str();
9444 const IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
9445 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
9446 .second) {
9447 if (ReturnType.isNull()) {
9448 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9449 Builder.AddTextChunk("NSEnumerator *");
9450 Builder.AddChunk(CodeCompletionString::CK_RightParen);
9451 }
9452
9453 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
9454 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
9456 }
9457 }
9458
9459 // - (type *)memberOfKey:(type *)object
9460 if (IsInstanceMethod &&
9461 (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
9462 std::string SelectorName = (Twine("memberOf") + UpperKey).str();
9463 const IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
9464 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
9465 if (ReturnType.isNull()) {
9466 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9467 Builder.AddPlaceholderChunk("object-type");
9468 Builder.AddTextChunk(" *");
9469 Builder.AddChunk(CodeCompletionString::CK_RightParen);
9470 }
9471
9472 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
9473 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9474 if (ReturnType.isNull()) {
9475 Builder.AddPlaceholderChunk("object-type");
9476 Builder.AddTextChunk(" *");
9477 } else {
9478 Builder.AddTextChunk(GetCompletionTypeString(
9479 ReturnType, Context, Policy, Builder.getAllocator()));
9480 }
9481 Builder.AddChunk(CodeCompletionString::CK_RightParen);
9482 Builder.AddTextChunk("object");
9483 Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
9485 }
9486 }
9487
9488 // Mutable unordered accessors
9489 // - (void)addKeyObject:(type *)object
9490 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
9491 std::string SelectorName =
9492 (Twine("add") + UpperKey + Twine("Object")).str();
9493 const IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
9494 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
9495 if (ReturnType.isNull()) {
9496 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9497 Builder.AddTextChunk("void");
9498 Builder.AddChunk(CodeCompletionString::CK_RightParen);
9499 }
9500
9501 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
9502 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9503 Builder.AddPlaceholderChunk("object-type");
9504 Builder.AddTextChunk(" *");
9505 Builder.AddChunk(CodeCompletionString::CK_RightParen);
9506 Builder.AddTextChunk("object");
9507 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
9509 }
9510 }
9511
9512 // - (void)addKey:(NSSet *)objects
9513 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
9514 std::string SelectorName = (Twine("add") + UpperKey).str();
9515 const IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
9516 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
9517 if (ReturnType.isNull()) {
9518 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9519 Builder.AddTextChunk("void");
9520 Builder.AddChunk(CodeCompletionString::CK_RightParen);
9521 }
9522
9523 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
9524 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9525 Builder.AddTextChunk("NSSet *");
9526 Builder.AddChunk(CodeCompletionString::CK_RightParen);
9527 Builder.AddTextChunk("objects");
9528 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
9530 }
9531 }
9532
9533 // - (void)removeKeyObject:(type *)object
9534 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
9535 std::string SelectorName =
9536 (Twine("remove") + UpperKey + Twine("Object")).str();
9537 const IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
9538 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
9539 if (ReturnType.isNull()) {
9540 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9541 Builder.AddTextChunk("void");
9542 Builder.AddChunk(CodeCompletionString::CK_RightParen);
9543 }
9544
9545 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
9546 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9547 Builder.AddPlaceholderChunk("object-type");
9548 Builder.AddTextChunk(" *");
9549 Builder.AddChunk(CodeCompletionString::CK_RightParen);
9550 Builder.AddTextChunk("object");
9551 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
9553 }
9554 }
9555
9556 // - (void)removeKey:(NSSet *)objects
9557 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
9558 std::string SelectorName = (Twine("remove") + UpperKey).str();
9559 const IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
9560 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
9561 if (ReturnType.isNull()) {
9562 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9563 Builder.AddTextChunk("void");
9564 Builder.AddChunk(CodeCompletionString::CK_RightParen);
9565 }
9566
9567 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
9568 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9569 Builder.AddTextChunk("NSSet *");
9570 Builder.AddChunk(CodeCompletionString::CK_RightParen);
9571 Builder.AddTextChunk("objects");
9572 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
9574 }
9575 }
9576
9577 // - (void)intersectKey:(NSSet *)objects
9578 if (IsInstanceMethod && ReturnTypeMatchesVoid) {
9579 std::string SelectorName = (Twine("intersect") + UpperKey).str();
9580 const IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
9581 if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
9582 if (ReturnType.isNull()) {
9583 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9584 Builder.AddTextChunk("void");
9585 Builder.AddChunk(CodeCompletionString::CK_RightParen);
9586 }
9587
9588 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
9589 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9590 Builder.AddTextChunk("NSSet *");
9591 Builder.AddChunk(CodeCompletionString::CK_RightParen);
9592 Builder.AddTextChunk("objects");
9593 Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
9595 }
9596 }
9597
9598 // Key-Value Observing
9599 // + (NSSet *)keyPathsForValuesAffectingKey
9600 if (!IsInstanceMethod &&
9601 (ReturnType.isNull() ||
9602 (ReturnType->isObjCObjectPointerType() &&
9603 ReturnType->castAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
9604 ReturnType->castAs<ObjCObjectPointerType>()
9606 ->getName() == "NSSet"))) {
9607 std::string SelectorName =
9608 (Twine("keyPathsForValuesAffecting") + UpperKey).str();
9609 const IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
9610 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
9611 .second) {
9612 if (ReturnType.isNull()) {
9613 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9614 Builder.AddTextChunk("NSSet<NSString *> *");
9615 Builder.AddChunk(CodeCompletionString::CK_RightParen);
9616 }
9617
9618 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
9619 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
9621 }
9622 }
9623
9624 // + (BOOL)automaticallyNotifiesObserversForKey
9625 if (!IsInstanceMethod &&
9626 (ReturnType.isNull() || ReturnType->isIntegerType() ||
9627 ReturnType->isBooleanType())) {
9628 std::string SelectorName =
9629 (Twine("automaticallyNotifiesObserversOf") + UpperKey).str();
9630 const IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
9631 if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
9632 .second) {
9633 if (ReturnType.isNull()) {
9634 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9635 Builder.AddTextChunk("BOOL");
9636 Builder.AddChunk(CodeCompletionString::CK_RightParen);
9637 }
9638
9639 Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
9640 Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
9642 }
9643 }
9644}
9645
9647 Scope *S, std::optional<bool> IsInstanceMethod, ParsedType ReturnTy) {
9648 ASTContext &Context = getASTContext();
9649 // Determine the return type of the method we're declaring, if
9650 // provided.
9651 QualType ReturnType = SemaRef.GetTypeFromParser(ReturnTy);
9652 Decl *IDecl = nullptr;
9653 if (SemaRef.CurContext->isObjCContainer()) {
9654 ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(SemaRef.CurContext);
9655 IDecl = OCD;
9656 }
9657 // Determine where we should start searching for methods.
9658 ObjCContainerDecl *SearchDecl = nullptr;
9659 bool IsInImplementation = false;
9660 if (Decl *D = IDecl) {
9661 if (ObjCImplementationDecl *Impl = dyn_cast<ObjCImplementationDecl>(D)) {
9662 SearchDecl = Impl->getClassInterface();
9663 IsInImplementation = true;
9664 } else if (ObjCCategoryImplDecl *CatImpl =
9665 dyn_cast<ObjCCategoryImplDecl>(D)) {
9666 SearchDecl = CatImpl->getCategoryDecl();
9667 IsInImplementation = true;
9668 } else
9669 SearchDecl = dyn_cast<ObjCContainerDecl>(D);
9670 }
9671
9672 if (!SearchDecl && S) {
9673 if (DeclContext *DC = S->getEntity())
9674 SearchDecl = dyn_cast<ObjCContainerDecl>(DC);
9675 }
9676
9677 if (!SearchDecl) {
9678 HandleCodeCompleteResults(&SemaRef, CodeCompleter,
9680 return;
9681 }
9682
9683 // Find all of the methods that we could declare/implement here.
9684 KnownMethodsMap KnownMethods;
9685 FindImplementableMethods(Context, SearchDecl, IsInstanceMethod, ReturnType,
9686 KnownMethods);
9687
9688 // Add declarations or definitions for each of the known methods.
9690 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(),
9691 CodeCompleter->getCodeCompletionTUInfo(),
9693 Results.EnterNewScope();
9695 for (KnownMethodsMap::iterator M = KnownMethods.begin(),
9696 MEnd = KnownMethods.end();
9697 M != MEnd; ++M) {
9698 ObjCMethodDecl *Method = M->second.getPointer();
9699 CodeCompletionBuilder Builder(Results.getAllocator(),
9700 Results.getCodeCompletionTUInfo());
9701
9702 // Add the '-'/'+' prefix if it wasn't provided yet.
9703 if (!IsInstanceMethod) {
9704 Builder.AddTextChunk(Method->isInstanceMethod() ? "-" : "+");
9706 }
9707
9708 // If the result type was not already provided, add it to the
9709 // pattern as (type).
9710 if (ReturnType.isNull()) {
9711 QualType ResTy = Method->getSendResultType().stripObjCKindOfType(Context);
9713 AddObjCPassingTypeChunk(ResTy, Method->getObjCDeclQualifier(), Context,
9714 Policy, Builder);
9715 }
9716
9717 Selector Sel = Method->getSelector();
9718
9719 if (Sel.isUnarySelector()) {
9720 // Unary selectors have no arguments.
9721 Builder.AddTypedTextChunk(
9722 Builder.getAllocator().CopyString(Sel.getNameForSlot(0)));
9723 } else {
9724 // Add all parameters to the pattern.
9725 unsigned I = 0;
9727 PEnd = Method->param_end();
9728 P != PEnd; (void)++P, ++I) {
9729 // Add the part of the selector name.
9730 if (I == 0)
9731 Builder.AddTypedTextChunk(
9732 Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":"));
9733 else if (I < Sel.getNumArgs()) {
9735 Builder.AddTypedTextChunk(
9736 Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":"));
9737 } else
9738 break;
9739
9740 // Add the parameter type.
9741 QualType ParamType;
9742 if ((*P)->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
9743 ParamType = (*P)->getType();
9744 else
9745 ParamType = (*P)->getOriginalType();
9746 ParamType = ParamType.substObjCTypeArgs(
9749 AddObjCPassingTypeChunk(ParamType, (*P)->getObjCDeclQualifier(),
9750 Context, Policy, Builder);
9751
9752 if (IdentifierInfo *Id = (*P)->getIdentifier())
9753 Builder.AddTextChunk(
9754 Builder.getAllocator().CopyString(Id->getName()));
9755 }
9756 }
9757
9758 if (Method->isVariadic()) {
9759 if (Method->param_size() > 0)
9760 Builder.AddChunk(CodeCompletionString::CK_Comma);
9761 Builder.AddTextChunk("...");
9762 }
9763
9764 if (IsInImplementation && Results.includeCodePatterns()) {
9765 // We will be defining the method here, so add a compound statement.
9767 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
9769 if (!Method->getReturnType()->isVoidType()) {
9770 // If the result type is not void, add a return clause.
9771 Builder.AddTextChunk("return");
9773 Builder.AddPlaceholderChunk("expression");
9774 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
9775 } else
9776 Builder.AddPlaceholderChunk("statements");
9777
9779 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
9780 }
9781
9782 unsigned Priority = CCP_CodePattern;
9783 auto R = Result(Builder.TakeString(), Method, Priority);
9784 if (!M->second.getInt())
9785 setInBaseClass(R);
9786 Results.AddResult(std::move(R));
9787 }
9788
9789 // Add Key-Value-Coding and Key-Value-Observing accessor methods for all of
9790 // the properties in this class and its categories.
9791 if (Context.getLangOpts().ObjC) {
9793 Containers.push_back(SearchDecl);
9794
9795 VisitedSelectorSet KnownSelectors;
9796 for (KnownMethodsMap::iterator M = KnownMethods.begin(),
9797 MEnd = KnownMethods.end();
9798 M != MEnd; ++M)
9799 KnownSelectors.insert(M->first);
9800
9801 ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(SearchDecl);
9802 if (!IFace)
9803 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(SearchDecl))
9804 IFace = Category->getClassInterface();
9805
9806 if (IFace)
9807 llvm::append_range(Containers, IFace->visible_categories());
9808
9809 if (IsInstanceMethod) {
9810 for (unsigned I = 0, N = Containers.size(); I != N; ++I)
9811 for (auto *P : Containers[I]->instance_properties())
9812 AddObjCKeyValueCompletions(P, *IsInstanceMethod, ReturnType, Context,
9813 KnownSelectors, Results);
9814 }
9815 }
9816
9817 Results.ExitScope();
9818
9819 HandleCodeCompleteResults(&SemaRef, CodeCompleter,
9820 Results.getCompletionContext(), Results.data(),
9821 Results.size());
9822}
9823
9825 Scope *S, bool IsInstanceMethod, bool AtParameterName, ParsedType ReturnTy,
9827 // If we have an external source, load the entire class method
9828 // pool from the AST file.
9829 if (SemaRef.ExternalSource) {
9830 for (uint32_t I = 0, N = SemaRef.ExternalSource->GetNumExternalSelectors();
9831 I != N; ++I) {
9832 Selector Sel = SemaRef.ExternalSource->GetExternalSelector(I);
9833 if (Sel.isNull() || SemaRef.ObjC().MethodPool.count(Sel))
9834 continue;
9835
9836 SemaRef.ObjC().ReadMethodPool(Sel);
9837 }
9838 }
9839
9840 // Build the set of methods we can see.
9842 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(),
9843 CodeCompleter->getCodeCompletionTUInfo(),
9845
9846 if (ReturnTy)
9847 Results.setPreferredType(
9848 SemaRef.GetTypeFromParser(ReturnTy).getNonReferenceType());
9849
9850 Results.EnterNewScope();
9852 M = SemaRef.ObjC().MethodPool.begin(),
9853 MEnd = SemaRef.ObjC().MethodPool.end();
9854 M != MEnd; ++M) {
9855 for (ObjCMethodList *MethList = IsInstanceMethod ? &M->second.first
9856 : &M->second.second;
9857 MethList && MethList->getMethod(); MethList = MethList->getNext()) {
9858 if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents))
9859 continue;
9860
9861 if (AtParameterName) {
9862 // Suggest parameter names we've seen before.
9863 unsigned NumSelIdents = SelIdents.size();
9864 if (NumSelIdents &&
9865 NumSelIdents <= MethList->getMethod()->param_size()) {
9866 ParmVarDecl *Param =
9867 MethList->getMethod()->parameters()[NumSelIdents - 1];
9868 if (Param->getIdentifier()) {
9869 CodeCompletionBuilder Builder(Results.getAllocator(),
9870 Results.getCodeCompletionTUInfo());
9871 Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
9872 Param->getIdentifier()->getName()));
9873 Results.AddResult(Builder.TakeString());
9874 }
9875 }
9876
9877 continue;
9878 }
9879
9880 Result R(MethList->getMethod(),
9881 Results.getBasePriority(MethList->getMethod()), nullptr);
9882 R.StartParameter = SelIdents.size();
9883 R.AllParametersAreInformative = false;
9884 R.DeclaringEntity = true;
9885 Results.MaybeAddResult(R, SemaRef.CurContext);
9886 }
9887 }
9888
9889 Results.ExitScope();
9890
9891 if (!AtParameterName && !SelIdents.empty() &&
9892 SelIdents.front()->getName().starts_with("init")) {
9893 for (const auto &M : SemaRef.PP.macros()) {
9894 if (M.first->getName() != "NS_DESIGNATED_INITIALIZER")
9895 continue;
9896 Results.EnterNewScope();
9897 CodeCompletionBuilder Builder(Results.getAllocator(),
9898 Results.getCodeCompletionTUInfo());
9899 Builder.AddTypedTextChunk(
9900 Builder.getAllocator().CopyString(M.first->getName()));
9901 Results.AddResult(CodeCompletionResult(Builder.TakeString(), CCP_Macro,
9903 Results.ExitScope();
9904 }
9905 }
9906
9907 HandleCodeCompleteResults(&SemaRef, CodeCompleter,
9908 Results.getCompletionContext(), Results.data(),
9909 Results.size());
9910}
9911
9913 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(),
9914 CodeCompleter->getCodeCompletionTUInfo(),
9916 Results.EnterNewScope();
9917
9918 // #if <condition>
9919 CodeCompletionBuilder Builder(Results.getAllocator(),
9920 Results.getCodeCompletionTUInfo());
9921 Builder.AddTypedTextChunk("if");
9923 Builder.AddPlaceholderChunk("condition");
9924 Results.AddResult(Builder.TakeString());
9925
9926 // #ifdef <macro>
9927 Builder.AddTypedTextChunk("ifdef");
9929 Builder.AddPlaceholderChunk("macro");
9930 Results.AddResult(Builder.TakeString());
9931
9932 // #ifndef <macro>
9933 Builder.AddTypedTextChunk("ifndef");
9935 Builder.AddPlaceholderChunk("macro");
9936 Results.AddResult(Builder.TakeString());
9937
9938 if (InConditional) {
9939 // #elif <condition>
9940 Builder.AddTypedTextChunk("elif");
9942 Builder.AddPlaceholderChunk("condition");
9943 Results.AddResult(Builder.TakeString());
9944
9945 // #elifdef <macro>
9946 Builder.AddTypedTextChunk("elifdef");
9948 Builder.AddPlaceholderChunk("macro");
9949 Results.AddResult(Builder.TakeString());
9950
9951 // #elifndef <macro>
9952 Builder.AddTypedTextChunk("elifndef");
9954 Builder.AddPlaceholderChunk("macro");
9955 Results.AddResult(Builder.TakeString());
9956
9957 // #else
9958 Builder.AddTypedTextChunk("else");
9959 Results.AddResult(Builder.TakeString());
9960
9961 // #endif
9962 Builder.AddTypedTextChunk("endif");
9963 Results.AddResult(Builder.TakeString());
9964 }
9965
9966 // #include "header"
9967 Builder.AddTypedTextChunk("include");
9969 Builder.AddTextChunk("\"");
9970 Builder.AddPlaceholderChunk("header");
9971 Builder.AddTextChunk("\"");
9972 Results.AddResult(Builder.TakeString());
9973
9974 // #include <header>
9975 Builder.AddTypedTextChunk("include");
9977 Builder.AddTextChunk("<");
9978 Builder.AddPlaceholderChunk("header");
9979 Builder.AddTextChunk(">");
9980 Results.AddResult(Builder.TakeString());
9981
9982 // #define <macro>
9983 Builder.AddTypedTextChunk("define");
9985 Builder.AddPlaceholderChunk("macro");
9986 Results.AddResult(Builder.TakeString());
9987
9988 // #define <macro>(<args>)
9989 Builder.AddTypedTextChunk("define");
9991 Builder.AddPlaceholderChunk("macro");
9992 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
9993 Builder.AddPlaceholderChunk("args");
9994 Builder.AddChunk(CodeCompletionString::CK_RightParen);
9995 Results.AddResult(Builder.TakeString());
9996
9997 // #undef <macro>
9998 Builder.AddTypedTextChunk("undef");
10000 Builder.AddPlaceholderChunk("macro");
10001 Results.AddResult(Builder.TakeString());
10002
10003 // #line <number>
10004 Builder.AddTypedTextChunk("line");
10006 Builder.AddPlaceholderChunk("number");
10007 Results.AddResult(Builder.TakeString());
10008
10009 // #line <number> "filename"
10010 Builder.AddTypedTextChunk("line");
10012 Builder.AddPlaceholderChunk("number");
10014 Builder.AddTextChunk("\"");
10015 Builder.AddPlaceholderChunk("filename");
10016 Builder.AddTextChunk("\"");
10017 Results.AddResult(Builder.TakeString());
10018
10019 // #error <message>
10020 Builder.AddTypedTextChunk("error");
10022 Builder.AddPlaceholderChunk("message");
10023 Results.AddResult(Builder.TakeString());
10024
10025 // #pragma <arguments>
10026 Builder.AddTypedTextChunk("pragma");
10028 Builder.AddPlaceholderChunk("arguments");
10029 Results.AddResult(Builder.TakeString());
10030
10031 if (getLangOpts().ObjC) {
10032 // #import "header"
10033 Builder.AddTypedTextChunk("import");
10035 Builder.AddTextChunk("\"");
10036 Builder.AddPlaceholderChunk("header");
10037 Builder.AddTextChunk("\"");
10038 Results.AddResult(Builder.TakeString());
10039
10040 // #import <header>
10041 Builder.AddTypedTextChunk("import");
10043 Builder.AddTextChunk("<");
10044 Builder.AddPlaceholderChunk("header");
10045 Builder.AddTextChunk(">");
10046 Results.AddResult(Builder.TakeString());
10047 }
10048
10049 // #include_next "header"
10050 Builder.AddTypedTextChunk("include_next");
10052 Builder.AddTextChunk("\"");
10053 Builder.AddPlaceholderChunk("header");
10054 Builder.AddTextChunk("\"");
10055 Results.AddResult(Builder.TakeString());
10056
10057 // #include_next <header>
10058 Builder.AddTypedTextChunk("include_next");
10060 Builder.AddTextChunk("<");
10061 Builder.AddPlaceholderChunk("header");
10062 Builder.AddTextChunk(">");
10063 Results.AddResult(Builder.TakeString());
10064
10065 // #warning <message>
10066 Builder.AddTypedTextChunk("warning");
10068 Builder.AddPlaceholderChunk("message");
10069 Results.AddResult(Builder.TakeString());
10070
10071 // Note: #ident and #sccs are such crazy anachronisms that we don't provide
10072 // completions for them. And __include_macros is a Clang-internal extension
10073 // that we don't want to encourage anyone to use.
10074
10075 // FIXME: we don't support #assert or #unassert, so don't suggest them.
10076 Results.ExitScope();
10077
10078 HandleCodeCompleteResults(&SemaRef, CodeCompleter,
10079 Results.getCompletionContext(), Results.data(),
10080 Results.size());
10081}
10082
10084 Scope *S) {
10085 CodeCompleteOrdinaryName(S, S->getFnParent()
10088}
10089
10091 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(),
10092 CodeCompleter->getCodeCompletionTUInfo(),
10095 if (!IsDefinition && CodeCompleter->includeMacros()) {
10096 // Add just the names of macros, not their arguments.
10097 CodeCompletionBuilder Builder(Results.getAllocator(),
10098 Results.getCodeCompletionTUInfo());
10099 Results.EnterNewScope();
10100 for (Preprocessor::macro_iterator M = SemaRef.PP.macro_begin(),
10101 MEnd = SemaRef.PP.macro_end();
10102 M != MEnd; ++M) {
10103 Builder.AddTypedTextChunk(
10104 Builder.getAllocator().CopyString(M->first->getName()));
10105 Results.AddResult(CodeCompletionResult(
10106 Builder.TakeString(), CCP_CodePattern, CXCursor_MacroDefinition));
10107 }
10108 Results.ExitScope();
10109 } else if (IsDefinition) {
10110 // FIXME: Can we detect when the user just wrote an include guard above?
10111 }
10112
10113 HandleCodeCompleteResults(&SemaRef, CodeCompleter,
10114 Results.getCompletionContext(), Results.data(),
10115 Results.size());
10116}
10117
10119 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(),
10120 CodeCompleter->getCodeCompletionTUInfo(),
10122
10123 if (CodeCompleter->includeMacros())
10124 AddMacroResults(SemaRef.PP, Results, CodeCompleter->loadExternal(), true);
10125
10126 // defined (<macro>)
10127 Results.EnterNewScope();
10128 CodeCompletionBuilder Builder(Results.getAllocator(),
10129 Results.getCodeCompletionTUInfo());
10130 Builder.AddTypedTextChunk("defined");
10132 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
10133 Builder.AddPlaceholderChunk("macro");
10134 Builder.AddChunk(CodeCompletionString::CK_RightParen);
10135 Results.AddResult(Builder.TakeString());
10136 Results.ExitScope();
10137
10138 HandleCodeCompleteResults(&SemaRef, CodeCompleter,
10139 Results.getCompletionContext(), Results.data(),
10140 Results.size());
10141}
10142
10144 Scope *S, IdentifierInfo *Macro, MacroInfo *MacroInfo, unsigned Argument) {
10145 // FIXME: In the future, we could provide "overload" results, much like we
10146 // do for function calls.
10147
10148 // Now just ignore this. There will be another code-completion callback
10149 // for the expanded tokens.
10150}
10151
10152// This handles completion inside an #include filename, e.g. #include <foo/ba
10153// We look for the directory "foo" under each directory on the include path,
10154// list its files, and reassemble the appropriate #include.
10156 bool Angled) {
10157 // RelDir should use /, but unescaped \ is possible on windows!
10158 // Our completions will normalize to / for simplicity, this case is rare.
10159 std::string RelDir = llvm::sys::path::convert_to_slash(Dir);
10160 // We need the native slashes for the actual file system interactions.
10161 SmallString<128> NativeRelDir = StringRef(RelDir);
10162 llvm::sys::path::native(NativeRelDir);
10163 llvm::vfs::FileSystem &FS =
10165
10166 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(),
10167 CodeCompleter->getCodeCompletionTUInfo(),
10169 llvm::DenseSet<StringRef> SeenResults; // To deduplicate results.
10170
10171 // Helper: adds one file or directory completion result.
10172 auto AddCompletion = [&](StringRef Filename, bool IsDirectory) {
10173 SmallString<64> TypedChunk = Filename;
10174 // Directory completion is up to the slash, e.g. <sys/
10175 TypedChunk.push_back(IsDirectory ? '/' : Angled ? '>' : '"');
10176 auto R = SeenResults.insert(TypedChunk);
10177 if (R.second) { // New completion
10178 const char *InternedTyped = Results.getAllocator().CopyString(TypedChunk);
10179 *R.first = InternedTyped; // Avoid dangling StringRef.
10180 CodeCompletionBuilder Builder(CodeCompleter->getAllocator(),
10181 CodeCompleter->getCodeCompletionTUInfo());
10182 Builder.AddTypedTextChunk(InternedTyped);
10183 // The result is a "Pattern", which is pretty opaque.
10184 // We may want to include the real filename to allow smart ranking.
10185 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
10186 }
10187 };
10188
10189 // Helper: scans IncludeDir for nice files, and adds results for each.
10190 auto AddFilesFromIncludeDir = [&](StringRef IncludeDir,
10191 bool IsSystem,
10192 DirectoryLookup::LookupType_t LookupType) {
10193 llvm::SmallString<128> Dir = IncludeDir;
10194 if (!NativeRelDir.empty()) {
10195 if (LookupType == DirectoryLookup::LT_Framework) {
10196 // For a framework dir, #include <Foo/Bar/> actually maps to
10197 // a path of Foo.framework/Headers/Bar/.
10198 auto Begin = llvm::sys::path::begin(NativeRelDir);
10199 auto End = llvm::sys::path::end(NativeRelDir);
10200
10201 llvm::sys::path::append(Dir, *Begin + ".framework", "Headers");
10202 llvm::sys::path::append(Dir, ++Begin, End);
10203 } else {
10204 llvm::sys::path::append(Dir, NativeRelDir);
10205 }
10206 }
10207
10208 const StringRef &Dirname = llvm::sys::path::filename(Dir);
10209 const bool isQt = Dirname.starts_with("Qt") || Dirname == "ActiveQt";
10210 const bool ExtensionlessHeaders =
10211 IsSystem || isQt || Dir.ends_with(".framework/Headers");
10212 std::error_code EC;
10213 unsigned Count = 0;
10214 for (auto It = FS.dir_begin(Dir, EC);
10215 !EC && It != llvm::vfs::directory_iterator(); It.increment(EC)) {
10216 if (++Count == 2500) // If we happen to hit a huge directory,
10217 break; // bail out early so we're not too slow.
10218 StringRef Filename = llvm::sys::path::filename(It->path());
10219
10220 // To know whether a symlink should be treated as file or a directory, we
10221 // have to stat it. This should be cheap enough as there shouldn't be many
10222 // symlinks.
10223 llvm::sys::fs::file_type Type = It->type();
10224 if (Type == llvm::sys::fs::file_type::symlink_file) {
10225 if (auto FileStatus = FS.status(It->path()))
10226 Type = FileStatus->getType();
10227 }
10228 switch (Type) {
10229 case llvm::sys::fs::file_type::directory_file:
10230 // All entries in a framework directory must have a ".framework" suffix,
10231 // but the suffix does not appear in the source code's include/import.
10232 if (LookupType == DirectoryLookup::LT_Framework &&
10233 NativeRelDir.empty() && !Filename.consume_back(".framework"))
10234 break;
10235
10236 AddCompletion(Filename, /*IsDirectory=*/true);
10237 break;
10238 case llvm::sys::fs::file_type::regular_file: {
10239 // Only files that really look like headers. (Except in special dirs).
10240 const bool IsHeader = Filename.ends_with_insensitive(".h") ||
10241 Filename.ends_with_insensitive(".hh") ||
10242 Filename.ends_with_insensitive(".hpp") ||
10243 Filename.ends_with_insensitive(".hxx") ||
10244 Filename.ends_with_insensitive(".inc") ||
10245 (ExtensionlessHeaders && !Filename.contains('.'));
10246 if (!IsHeader)
10247 break;
10248 AddCompletion(Filename, /*IsDirectory=*/false);
10249 break;
10250 }
10251 default:
10252 break;
10253 }
10254 }
10255 };
10256
10257 // Helper: adds results relative to IncludeDir, if possible.
10258 auto AddFilesFromDirLookup = [&](const DirectoryLookup &IncludeDir,
10259 bool IsSystem) {
10260 switch (IncludeDir.getLookupType()) {
10262 // header maps are not (currently) enumerable.
10263 break;
10265 AddFilesFromIncludeDir(IncludeDir.getDirRef()->getName(), IsSystem,
10267 break;
10269 AddFilesFromIncludeDir(IncludeDir.getFrameworkDirRef()->getName(),
10271 break;
10272 }
10273 };
10274
10275 // Finally with all our helpers, we can scan the include path.
10276 // Do this in standard order so deduplication keeps the right file.
10277 // (In case we decide to add more details to the results later).
10278 const auto &S = SemaRef.PP.getHeaderSearchInfo();
10279 using llvm::make_range;
10280 if (!Angled) {
10281 // The current directory is on the include path for "quoted" includes.
10282 if (auto CurFile = SemaRef.PP.getCurrentFileLexer()->getFileEntry())
10283 AddFilesFromIncludeDir(CurFile->getDir().getName(), false,
10285 for (const auto &D : make_range(S.quoted_dir_begin(), S.quoted_dir_end()))
10286 AddFilesFromDirLookup(D, false);
10287 }
10288 for (const auto &D : make_range(S.angled_dir_begin(), S.angled_dir_end()))
10289 AddFilesFromDirLookup(D, false);
10290 for (const auto &D : make_range(S.system_dir_begin(), S.system_dir_end()))
10291 AddFilesFromDirLookup(D, true);
10292
10293 HandleCodeCompleteResults(&SemaRef, CodeCompleter,
10294 Results.getCompletionContext(), Results.data(),
10295 Results.size());
10296}
10297
10299 HandleCodeCompleteResults(&SemaRef, CodeCompleter,
10301 0);
10302}
10303
10305 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(),
10306 CodeCompleter->getCodeCompletionTUInfo(),
10308 Results.EnterNewScope();
10309 static const char *Platforms[] = {"macOS", "iOS", "watchOS", "tvOS"};
10310 for (const char *Platform : llvm::ArrayRef(Platforms)) {
10311 Results.AddResult(CodeCompletionResult(Platform));
10312 Results.AddResult(CodeCompletionResult(Results.getAllocator().CopyString(
10313 Twine(Platform) + "ApplicationExtension")));
10314 }
10315 Results.ExitScope();
10316 HandleCodeCompleteResults(&SemaRef, CodeCompleter,
10317 Results.getCompletionContext(), Results.data(),
10318 Results.size());
10319}
10320
10322 CodeCompletionAllocator &Allocator, CodeCompletionTUInfo &CCTUInfo,
10324 ResultBuilder Builder(SemaRef, Allocator, CCTUInfo,
10326 if (!CodeCompleter || CodeCompleter->includeGlobals()) {
10327 CodeCompletionDeclConsumer Consumer(
10328 Builder, getASTContext().getTranslationUnitDecl());
10329 SemaRef.LookupVisibleDecls(getASTContext().getTranslationUnitDecl(),
10330 Sema::LookupAnyName, Consumer,
10331 !CodeCompleter || CodeCompleter->loadExternal());
10332 }
10333
10334 if (!CodeCompleter || CodeCompleter->includeMacros())
10335 AddMacroResults(SemaRef.PP, Builder,
10336 !CodeCompleter || CodeCompleter->loadExternal(), true);
10337
10338 Results.clear();
10339 Results.insert(Results.end(), Builder.data(),
10340 Builder.data() + Builder.size());
10341}
10342
10344 CodeCompleteConsumer *CompletionConsumer)
10345 : SemaBase(S), CodeCompleter(CompletionConsumer) {}
This file provides AST data structures related to concepts.
NodeId Parent
Definition: ASTDiff.cpp:191
int Id
Definition: ASTDiff.cpp:190
StringRef P
#define SM(sm)
Definition: Cuda.cpp:83
llvm::DenseMap< const Stmt *, CFGBlock * > SMap
Definition: CFGStmtMap.cpp:22
static Decl::Kind getKind(const Decl *D)
Definition: DeclBase.cpp:1125
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the C++ template declaration subclasses.
Defines the clang::Expr interface and subclasses for C++ expressions.
Defines Expressions and AST nodes for C++2a concepts.
StringRef Text
Definition: Format.cpp:2976
int Priority
Definition: Format.cpp:2979
int Category
Definition: Format.cpp:2978
StringRef Filename
Definition: Format.cpp:2975
#define X(type, name)
Definition: Value.h:143
llvm::MachO::Target Target
Definition: MachO.h:50
llvm::MachO::Record Record
Definition: MachO.h:31
Defines the clang::MacroInfo and clang::MacroDirective classes.
Defines an enumeration for C++ overloaded operators.
Defines the clang::Preprocessor interface.
static std::string getName(const CallEvent &Call)
static AccessResult IsAccessible(Sema &S, const EffectiveContext &EC, AccessTarget &Entity)
Determines whether the accessed entity is accessible.
CastType
Definition: SemaCast.cpp:48
static QualType getPreferredArgumentTypeForMessageSend(ResultBuilder &Results, unsigned NumSelIdents)
Given a set of code-completion results for the argument of a message send, determine the preferred ty...
static void printOverrideString(const CodeCompletionString &CCS, std::string &BeforeName, std::string &NameAndSignature)
static bool isConstructor(const Decl *ND)
static void findTypeLocationForBlockDecl(const TypeSourceInfo *TSInfo, FunctionTypeLoc &Block, FunctionProtoTypeLoc &BlockProto, bool SuppressBlock=false)
Tries to find the most appropriate type location for an Objective-C block placeholder.
static void AddQualifierToCompletionString(CodeCompletionBuilder &Result, NestedNameSpecifier *Qualifier, bool QualifierIsInformative, ASTContext &Context, const PrintingPolicy &Policy)
Add a qualifier to the given code-completion string, if the provided nested-name-specifier is non-NUL...
static bool isObjCReceiverType(ASTContext &C, QualType T)
static void AddMacroResults(Preprocessor &PP, ResultBuilder &Results, bool LoadExternal, bool IncludeUndefined, bool TargetTypeIsPointer=false)
static std::string formatTemplateParameterPlaceholder(const NamedDecl *Param, bool &Optional, const PrintingPolicy &Policy)
static std::string formatBlockPlaceholder(const PrintingPolicy &Policy, const NamedDecl *BlockDecl, FunctionTypeLoc &Block, FunctionProtoTypeLoc &BlockProto, bool SuppressBlockName=false, bool SuppressBlock=false, std::optional< ArrayRef< QualType > > ObjCSubsts=std::nullopt)
Returns a placeholder string that corresponds to an Objective-C block declaration.
static void AddTemplateParameterChunks(ASTContext &Context, const PrintingPolicy &Policy, const TemplateDecl *Template, CodeCompletionBuilder &Result, unsigned MaxParameters=0, unsigned Start=0, bool InDefaultArg=false)
Add template parameter chunks to the given code completion string.
static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt)
static FunctionProtoTypeLoc GetPrototypeLoc(Expr *Fn)
static void AddFunctionParameterChunks(Preprocessor &PP, const PrintingPolicy &Policy, const FunctionDecl *Function, CodeCompletionBuilder &Result, unsigned Start=0, bool InOptional=false)
Add function parameter chunks to the given code completion string.
llvm::SmallPtrSet< const IdentifierInfo *, 16 > AddedPropertiesSet
The set of properties that have already been added, referenced by property name.
static bool argMatchesTemplateParams(const ParsedTemplateArgument &Arg, unsigned Index, const TemplateParameterList &Params)
static void setInBaseClass(ResultBuilder::Result &R)
static void AddObjCMethods(ObjCContainerDecl *Container, bool WantInstanceMethods, ObjCMethodKind WantKind, ArrayRef< const IdentifierInfo * > SelIdents, DeclContext *CurContext, VisitedSelectorSet &Selectors, bool AllowSameLength, ResultBuilder &Results, bool InOriginalClass=true, bool IsRootClass=false)
Add all of the Objective-C methods in the given Objective-C container to the set of results.
static bool shouldIgnoreDueToReservedName(const NamedDecl *ND, Sema &SemaRef)
static RecordDecl * getAsRecordDecl(QualType BaseType)
static CodeCompletionString * createTemplateSignatureString(const TemplateDecl *TD, CodeCompletionBuilder &Builder, unsigned CurrentArg, const PrintingPolicy &Policy)
static QualType getParamType(Sema &SemaRef, ArrayRef< ResultCandidate > Candidates, unsigned N)
Get the type of the Nth parameter from a given set of overload candidates.
static void AddStorageSpecifiers(SemaCodeCompletion::ParserCompletionContext CCC, const LangOptions &LangOpts, ResultBuilder &Results)
static const NamedDecl * extractFunctorCallOperator(const NamedDecl *ND)
OverloadCompare
static void AddFunctionSpecifiers(SemaCodeCompletion::ParserCompletionContext CCC, const LangOptions &LangOpts, ResultBuilder &Results)
static QualType ProduceSignatureHelp(Sema &SemaRef, MutableArrayRef< ResultCandidate > Candidates, unsigned CurrentArg, SourceLocation OpenParLoc, bool Braced)
static OverloadCompare compareOverloads(const CXXMethodDecl &Candidate, const CXXMethodDecl &Incumbent, const Qualifiers &ObjectQuals, ExprValueKind ObjectKind)
static std::string FormatFunctionParameter(const PrintingPolicy &Policy, const DeclaratorDecl *Param, bool SuppressName=false, bool SuppressBlock=false, std::optional< ArrayRef< QualType > > ObjCSubsts=std::nullopt)
static void AddOverrideResults(ResultBuilder &Results, const CodeCompletionContext &CCContext, CodeCompletionBuilder &Builder)
static std::string formatObjCParamQualifiers(unsigned ObjCQuals, QualType &Type)
llvm::SmallPtrSet< Selector, 16 > VisitedSelectorSet
A set of selectors, which is used to avoid introducing multiple completions with the same selector in...
static void AddOverloadAggregateChunks(const RecordDecl *RD, const PrintingPolicy &Policy, CodeCompletionBuilder &Result, unsigned CurrentArg)
static void AddTypedefResult(ResultBuilder &Results)
static void AddPrettyFunctionResults(const LangOptions &LangOpts, ResultBuilder &Results)
static QualType getDesignatedType(QualType BaseType, const Designation &Desig)
static void AddObjCPassingTypeChunk(QualType Type, unsigned ObjCDeclQuals, ASTContext &Context, const PrintingPolicy &Policy, CodeCompletionBuilder &Builder)
Add the parenthesized return or parameter type chunk to a code completion string.
static void AddObjCKeyValueCompletions(ObjCPropertyDecl *Property, bool IsInstanceMethod, QualType ReturnType, ASTContext &Context, VisitedSelectorSet &KnownSelectors, ResultBuilder &Results)
Add code completions for Objective-C Key-Value Coding (KVC) and Key-Value Observing (KVO).
static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt)
static bool ObjCPropertyFlagConflicts(unsigned Attributes, unsigned NewFlag)
Determine whether the addition of the given flag to an Objective-C property's attributes will cause a...
static void AddEnumerators(ResultBuilder &Results, ASTContext &Context, EnumDecl *Enum, DeclContext *CurContext, const CoveredEnumerators &Enumerators)
llvm::DenseMap< Selector, llvm::PointerIntPair< ObjCMethodDecl *, 1, bool > > KnownMethodsMap
static const FunctionProtoType * TryDeconstructFunctionLike(QualType T)
Try to find a corresponding FunctionProtoType for function-like types (e.g.
static DeclContext::lookup_result getConstructors(ASTContext &Context, const CXXRecordDecl *Record)
static void AddResultTypeChunk(ASTContext &Context, const PrintingPolicy &Policy, const NamedDecl *ND, QualType BaseType, CodeCompletionBuilder &Result)
If the given declaration has an associated type, add it as a result type chunk.
static void AddObjCVisibilityResults(const LangOptions &LangOpts, ResultBuilder &Results, bool NeedAt)
static void addThisCompletion(Sema &S, ResultBuilder &Results)
Add a completion for "this", if we're in a member function.
static void AddObjCImplementationResults(const LangOptions &LangOpts, ResultBuilder &Results, bool NeedAt)
static ObjCMethodDecl * AddSuperSendCompletion(Sema &S, bool NeedSuperKeyword, ArrayRef< const IdentifierInfo * > SelIdents, ResultBuilder &Results)
static void AddRecordMembersCompletionResults(Sema &SemaRef, ResultBuilder &Results, Scope *S, QualType BaseType, ExprValueKind BaseKind, RecordDecl *RD, std::optional< FixItHint > AccessOpFixIt)
static void AddObjCBlockCall(ASTContext &Context, const PrintingPolicy &Policy, CodeCompletionBuilder &Builder, const NamedDecl *BD, const FunctionTypeLoc &BlockLoc, const FunctionProtoTypeLoc &BlockProtoLoc)
Adds a block invocation code completion result for the given block declaration BD.
static void AddLambdaCompletion(ResultBuilder &Results, llvm::ArrayRef< QualType > Parameters, const LangOptions &LangOpts)
Adds a pattern completion for a lambda expression with the specified parameter types and placeholders...
static void AddTypeSpecifierResults(const LangOptions &LangOpts, ResultBuilder &Results)
Add type specifiers for the current language as keyword results.
static std::optional< unsigned > getNextAggregateIndexAfterDesignatedInit(const ResultCandidate &Aggregate, ArrayRef< Expr * > Args)
static std::string GetDefaultValueString(const ParmVarDecl *Param, const SourceManager &SM, const LangOptions &LangOpts)
static CodeCompletionContext mapCodeCompletionContext(Sema &S, SemaCodeCompletion::ParserCompletionContext PCC)
static void AddInterfaceResults(DeclContext *Ctx, DeclContext *CurContext, bool OnlyForwardDeclarations, bool OnlyUnimplemented, ResultBuilder &Results)
Add all of the Objective-C interface declarations that we find in the given (translation unit) contex...
static NestedNameSpecifier * getRequiredQualification(ASTContext &Context, const DeclContext *CurContext, const DeclContext *TargetContext)
Compute the qualification required to get from the current context (CurContext) to the target context...
static void FindImplementableMethods(ASTContext &Context, ObjCContainerDecl *Container, std::optional< bool > WantInstanceMethods, QualType ReturnType, KnownMethodsMap &KnownMethods, bool InOriginalClass=true)
Find all of the methods that reside in the given container (and its superclasses, protocols,...
static bool anyNullArguments(ArrayRef< Expr * > Args)
static const char * noUnderscoreAttrScope(llvm::StringRef Scope)
static void AddFunctionTypeQualsToCompletionString(CodeCompletionBuilder &Result, const FunctionDecl *Function)
static void MaybeAddSentinel(Preprocessor &PP, const NamedDecl *FunctionOrMethod, CodeCompletionBuilder &Result)
static void AddOverloadParameterChunks(ASTContext &Context, const PrintingPolicy &Policy, const FunctionDecl *Function, const FunctionProtoType *Prototype, FunctionProtoTypeLoc PrototypeLoc, CodeCompletionBuilder &Result, unsigned CurrentArg, unsigned Start=0, bool InOptional=false)
Add function overload parameter chunks to the given code completion string.
static void AddObjCProperties(const CodeCompletionContext &CCContext, ObjCContainerDecl *Container, bool AllowCategories, bool AllowNullaryMethods, DeclContext *CurContext, AddedPropertiesSet &AddedProperties, ResultBuilder &Results, bool IsBaseExprStatement=false, bool IsClassProperty=false, bool InOriginalClass=true)
static void HandleCodeCompleteResults(Sema *S, CodeCompleteConsumer *CodeCompleter, const CodeCompletionContext &Context, CodeCompletionResult *Results, unsigned NumResults)
static void AddTypeQualifierResults(DeclSpec &DS, ResultBuilder &Results, const LangOptions &LangOpts)
static void MaybeAddOverrideCalls(Sema &S, DeclContext *InContext, ResultBuilder &Results)
If we're in a C++ virtual member function, add completion results that invoke the functions we overri...
static ObjCContainerDecl * getContainerDef(ObjCContainerDecl *Container)
Retrieve the container definition, if any?
static const char * underscoreAttrScope(llvm::StringRef Scope)
static bool isAcceptableObjCMethod(ObjCMethodDecl *Method, ObjCMethodKind WantKind, ArrayRef< const IdentifierInfo * > SelIdents, bool AllowSameLength=true)
static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt)
static bool WantTypesInContext(SemaCodeCompletion::ParserCompletionContext CCC, const LangOptions &LangOpts)
CodeCompleteConsumer::OverloadCandidate ResultCandidate
static std::string templateResultType(const TemplateDecl *TD, const PrintingPolicy &Policy)
static void AddTypedNameChunk(ASTContext &Context, const PrintingPolicy &Policy, const NamedDecl *ND, CodeCompletionBuilder &Result)
Add the name of the given declaration.
static void AddClassMessageCompletions(Sema &SemaRef, Scope *S, ParsedType Receiver, ArrayRef< const IdentifierInfo * > SelIdents, bool AtArgumentExpression, bool IsSuper, ResultBuilder &Results)
static const char * GetCompletionTypeString(QualType T, ASTContext &Context, const PrintingPolicy &Policy, CodeCompletionAllocator &Allocator)
Retrieve the string representation of the given type as a string that has the appropriate lifetime fo...
static bool InheritsFromClassNamed(ObjCInterfaceDecl *Class, StringRef Name)
Determine whether the given class is or inherits from a class by the given name.
#define OBJC_AT_KEYWORD_NAME(NeedAt, Keyword)
Macro that optionally prepends an "@" to the string literal passed in via Keyword,...
static bool isAcceptableObjCSelector(Selector Sel, ObjCMethodKind WantKind, ArrayRef< const IdentifierInfo * > SelIdents, bool AllowSameLength=true)
static QualType getPreferredTypeOfBinaryRHS(Sema &S, Expr *LHS, tok::TokenKind Op)
static void AddOrdinaryNameResults(SemaCodeCompletion::ParserCompletionContext CCC, Scope *S, Sema &SemaRef, ResultBuilder &Results)
Add language constructs that show up for "ordinary" names.
static QualType getPreferredTypeOfUnaryArg(Sema &S, QualType ContextType, tok::TokenKind Op)
Get preferred type for an argument of an unary expression.
static void AddUsingAliasResult(CodeCompletionBuilder &Builder, ResultBuilder &Results)
static ObjCInterfaceDecl * GetAssumedMessageSendExprType(Expr *E)
When we have an expression with type "id", we may assume that it has some more-specific class type ba...
ObjCMethodKind
Describes the kind of Objective-C method that we want to find via code completion.
@ MK_OneArgSelector
One-argument selector.
@ MK_ZeroArgSelector
Zero-argument (unary) selector.
@ MK_Any
Any kind of method, provided it means other specified criteria.
static void mergeCandidatesWithResults(Sema &SemaRef, SmallVectorImpl< ResultCandidate > &Results, OverloadCandidateSet &CandidateSet, SourceLocation Loc, size_t ArgSize)
static void AddProtocolResults(DeclContext *Ctx, DeclContext *CurContext, bool OnlyForwardDeclarations, ResultBuilder &Results)
Add all of the protocol declarations that we find in the given (translation unit) context.
static void AddStaticAssertResult(CodeCompletionBuilder &Builder, ResultBuilder &Results, const LangOptions &LangOpts)
static void AddObjCInterfaceResults(const LangOptions &LangOpts, ResultBuilder &Results, bool NeedAt)
static bool isNamespaceScope(Scope *S)
Determine whether this scope denotes a namespace.
static PrintingPolicy getCompletionPrintingPolicy(const ASTContext &Context, const Preprocessor &PP)
This file declares facilities that support code completion.
SourceLocation Loc
Definition: SemaObjC.cpp:755
This file declares semantic analysis for Objective-C.
static TemplateDecl * getDescribedTemplate(Decl *Templated)
Defines various enumerations that describe declaration and type specifiers.
enum clang::format::@1262::AnnotatingParser::Context::@343 ContextType
C Language Family Type Representation.
SourceLocation Begin
friend bool operator!=(const iterator &X, const iterator &Y)
iterator(const NamedDecl *SingleDecl, unsigned Index)
iterator(const DeclIndexPair *Iterator)
friend bool operator==(const iterator &X, const iterator &Y)
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:182
SourceManager & getSourceManager()
Definition: ASTContext.h:705
QualType getObjCInterfaceType(const ObjCInterfaceDecl *Decl, ObjCInterfaceDecl *PrevDecl=nullptr) const
getObjCInterfaceType - Return the unique reference to the type for the specified ObjC interface decl.
DeclarationNameTable DeclarationNames
Definition: ASTContext.h:648
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2575
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2591
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
CanQualType DependentTy
Definition: ASTContext.h:1119
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
Definition: ASTContext.h:1591
IdentifierTable & Idents
Definition: ASTContext.h:644
const LangOptions & getLangOpts() const
Definition: ASTContext.h:775
SelectorTable & Selectors
Definition: ASTContext.h:645
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
QualType getPointerDiffType() const
Return the unique type for "ptrdiff_t" (C99 7.17) defined in <stddef.h>.
CanQualType BoolTy
Definition: ASTContext.h:1092
CanQualType IntTy
Definition: ASTContext.h:1100
QualType getObjCObjectPointerType(QualType OIT) const
Return a ObjCObjectPointerType type for the given ObjCObjectType.
const RawComment * getRawCommentForAnyRedecl(const Decl *D, const Decl **OriginalDecl=nullptr) const
Return the documentation comment attached to a given declaration.
Definition: ASTContext.cpp:402
QualType getObjCIdType() const
Represents the Objective-CC id type.
Definition: ASTContext.h:2064
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2618
PtrTy get() const
Definition: Ownership.h:170
bool isInvalid() const
Definition: Ownership.h:166
bool isUsable() const
Definition: Ownership.h:168
QualType getElementType() const
Definition: Type.h:3530
Syntax
The style used to specify an attribute.
Type source information for an attributed type.
Definition: TypeLoc.h:875
static std::optional< NullabilityKind > stripOuterNullability(QualType &T)
Strip off the top-level nullability annotation on the given type, if it's there.
Definition: Type.cpp:4793
Represents a C++11 auto or C++14 decltype(auto) type, possibly constrained by a type-constraint.
Definition: Type.h:5981
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition: Decl.h:4494
Wrapper for source info for block pointers.
Definition: TypeLoc.h:1314
Pointer to a block type.
Definition: Type.h:3349
This class is used for builtin types like 'int'.
Definition: Type.h:2981
Represents a base class of a C++ class.
Definition: DeclCXX.h:146
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2535
Represents a C++ member access expression where the actual member referenced could not be resolved be...
Definition: ExprCXX.h:3676
bool isArrow() const
Determine whether this member expression used the '->' operator; otherwise, it used the '.
Definition: ExprCXX.h:3779
DeclarationName getMember() const
Retrieve the name of the member that this expression refers to.
Definition: ExprCXX.h:3818
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2060
bool isVirtual() const
Definition: DeclCXX.h:2115
overridden_method_range overridden_methods() const
Definition: DeclCXX.cpp:2534
RefQualifierKind getRefQualifier() const
Retrieve the ref-qualifier associated with this method.
Definition: DeclCXX.h:2236
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition: DeclCXX.h:2186
bool isInstance() const
Definition: DeclCXX.h:2087
Qualifiers getMethodQualifiers() const
Definition: DeclCXX.h:2221
bool isStatic() const
Definition: DeclCXX.cpp:2186
CXXMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:2156
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
bool isAggregate() const
Determine whether this class is an aggregate (C++ [dcl.init.aggr]), which is a class with no user-dec...
Definition: DeclCXX.h:1147
base_class_range bases()
Definition: DeclCXX.h:619
CXXRecordDecl * getDefinition() const
Definition: DeclCXX.h:564
base_class_range vbases()
Definition: DeclCXX.h:636
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:523
bool isDerivedFrom(const CXXRecordDecl *Base) const
Determine whether this class is derived from the class Base.
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:74
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition: DeclSpec.h:215
NestedNameSpecifier * getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition: DeclSpec.h:95
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition: DeclSpec.h:213
bool isEmpty() const
No scope specifier.
Definition: DeclSpec.h:208
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2820
Expr * getCallee()
Definition: Expr.h:2970
arg_range arguments()
Definition: Expr.h:3059
bool isNull() const
Definition: CanonicalType.h:97
CaseStmt - Represent a case statement.
Definition: Stmt.h:1801
Expr * getLHS()
Definition: Stmt.h:1888
Represents a character-granular source range.
static CharSourceRange getTokenRange(SourceRange R)
Declaration of a class template.
CodeCompletionString * CreateSignatureString(unsigned CurrentArg, Sema &S, CodeCompletionAllocator &Allocator, CodeCompletionTUInfo &CCTUInfo, bool IncludeBriefComments, bool Braced) const
Create a new code-completion string that describes the function signature of this overload candidate.
const FunctionType * getFunctionType() const
Retrieve the function type of the entity, regardless of how the function is stored.
CandidateKind getKind() const
Determine the kind of overload candidate.
const RecordDecl * getAggregate() const
Retrieve the aggregate type being initialized.
FunctionDecl * getFunction() const
Retrieve the function overload candidate or the templated function declaration for a function templat...
const FunctionProtoTypeLoc getFunctionProtoTypeLoc() const
Retrieve the function ProtoTypeLoc candidate.
@ CK_Aggregate
The candidate is aggregate initialization of a record type.
@ CK_Template
The candidate is a template, template arguments are being completed.
unsigned getNumParams() const
Get the number of parameters in this signature.
Abstract interface for a consumer of code-completion information.
bool includeGlobals() const
Whether to include global (top-level) declaration results.
virtual void ProcessCodeCompleteResults(Sema &S, CodeCompletionContext Context, CodeCompletionResult *Results, unsigned NumResults)
Process the finalized code-completion results.
bool includeCodePatterns() const
Whether the code-completion consumer wants to see code patterns.
bool loadExternal() const
Hint whether to load data from the external AST in order to provide full results.
virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg, OverloadCandidate *Candidates, unsigned NumCandidates, SourceLocation OpenParLoc, bool Braced)
An allocator used specifically for the purpose of code completion.
const char * CopyString(const Twine &String)
Copy the given string into this allocator.
A builder class used to construct new code-completion strings.
CodeCompletionString * TakeString()
Take the resulting completion string.
void AddPlaceholderChunk(const char *Placeholder)
Add a new placeholder chunk.
void AddTextChunk(const char *Text)
Add a new text chunk.
void AddCurrentParameterChunk(const char *CurrentParameter)
Add a new current-parameter chunk.
void AddTypedTextChunk(const char *Text)
Add a new typed-text chunk.
void AddChunk(CodeCompletionString::ChunkKind CK, const char *Text="")
Add a new chunk.
CodeCompletionAllocator & getAllocator() const
Retrieve the allocator into which the code completion strings should be allocated.
The context in which code completion occurred, so that the code-completion consumer can process the r...
Kind getKind() const
Retrieve the kind of code-completion context.
void setCXXScopeSpecifier(CXXScopeSpec SS)
Sets the scope specifier that comes before the completion token.
@ CCC_TypeQualifiers
Code completion within a type-qualifier list.
@ CCC_ObjCMessageReceiver
Code completion occurred where an Objective-C message receiver is expected.
@ CCC_PreprocessorExpression
Code completion occurred within a preprocessor expression.
@ CCC_ObjCCategoryName
Code completion where an Objective-C category name is expected.
@ CCC_ObjCIvarList
Code completion occurred within the instance variable list of an Objective-C interface,...
@ CCC_Statement
Code completion occurred where a statement (or declaration) is expected in a function,...
@ CCC_Type
Code completion occurred where a type name is expected.
@ CCC_ArrowMemberAccess
Code completion occurred on the right-hand side of a member access expression using the arrow operato...
@ CCC_ClassStructUnion
Code completion occurred within a class, struct, or union.
@ CCC_ObjCInterface
Code completion occurred within an Objective-C interface, protocol, or category interface.
@ CCC_ObjCPropertyAccess
Code completion occurred on the right-hand side of an Objective-C property access expression.
@ CCC_Expression
Code completion occurred where an expression is expected.
@ CCC_SelectorName
Code completion for a selector, as in an @selector expression.
@ CCC_TopLevelOrExpression
Code completion at a top level, i.e.
@ CCC_EnumTag
Code completion occurred after the "enum" keyword, to indicate an enumeration name.
@ CCC_UnionTag
Code completion occurred after the "union" keyword, to indicate a union name.
@ CCC_ParenthesizedExpression
Code completion in a parenthesized expression, which means that we may also have types here in C and ...
@ CCC_TopLevel
Code completion occurred within a "top-level" completion context, e.g., at namespace or global scope.
@ CCC_ClassOrStructTag
Code completion occurred after the "struct" or "class" keyword, to indicate a struct or class name.
@ CCC_ObjCClassMessage
Code completion where an Objective-C class message is expected.
@ CCC_ObjCImplementation
Code completion occurred within an Objective-C implementation or category implementation.
@ CCC_IncludedFile
Code completion inside the filename part of a #include directive.
@ CCC_ObjCInstanceMessage
Code completion where an Objective-C instance message is expected.
@ CCC_SymbolOrNewName
Code completion occurred where both a new name and an existing symbol is permissible.
@ CCC_Recovery
An unknown context, in which we are recovering from a parsing error and don't know which completions ...
@ CCC_ObjCProtocolName
Code completion occurred where a protocol name is expected.
@ CCC_NewName
Code completion occurred where a new name is expected.
@ CCC_MacroNameUse
Code completion occurred where a macro name is expected (without any arguments, in the case of a func...
@ CCC_Symbol
Code completion occurred where an existing name(such as type, function or variable) is expected.
@ CCC_Attribute
Code completion of an attribute name.
@ CCC_Other
An unspecified code-completion context.
@ CCC_DotMemberAccess
Code completion occurred on the right-hand side of a member access expression using the dot operator.
@ CCC_MacroName
Code completion occurred where an macro is being defined.
@ CCC_Namespace
Code completion occurred where a namespace or namespace alias is expected.
@ CCC_PreprocessorDirective
Code completion occurred where a preprocessor directive is expected.
@ CCC_NaturalLanguage
Code completion occurred in a context where natural language is expected, e.g., a comment or string l...
@ CCC_ObjCInterfaceName
Code completion where the name of an Objective-C class is expected.
QualType getBaseType() const
Retrieve the type of the base object in a member-access expression.
bool wantConstructorResults() const
Determines whether we want C++ constructors as results within this context.
void addVisitedContext(DeclContext *Ctx)
Adds a visited context.
Captures a result of code completion.
bool DeclaringEntity
Whether we're completing a declaration of the given entity, rather than a use of that entity.
ResultKind Kind
The kind of result stored here.
const char * Keyword
When Kind == RK_Keyword, the string representing the keyword or symbol's spelling.
CXAvailabilityKind Availability
The availability of this result.
NestedNameSpecifier * Qualifier
If the result should have a nested-name-specifier, this is it.
CodeCompletionString * CreateCodeCompletionString(Sema &S, const CodeCompletionContext &CCContext, CodeCompletionAllocator &Allocator, CodeCompletionTUInfo &CCTUInfo, bool IncludeBriefComments)
Create a new code-completion string that describes how to insert this result into a program.
bool QualifierIsInformative
Whether this result was found via lookup into a base class.
const NamedDecl * Declaration
When Kind == RK_Declaration or RK_Pattern, the declaration we are referring to.
CodeCompletionString * createCodeCompletionStringForDecl(Preprocessor &PP, ASTContext &Ctx, CodeCompletionBuilder &Result, bool IncludeBriefComments, const CodeCompletionContext &CCContext, PrintingPolicy &Policy)
CodeCompletionString * CreateCodeCompletionStringForMacro(Preprocessor &PP, CodeCompletionAllocator &Allocator, CodeCompletionTUInfo &CCTUInfo)
Creates a new code-completion string for the macro result.
unsigned StartParameter
Specifies which parameter (of a function, Objective-C method, macro, etc.) we should start with when ...
bool InBaseClass
Whether this is a class member from base class.
unsigned Priority
The priority of this particular code-completion result.
bool StartsNestedNameSpecifier
Whether this declaration is the beginning of a nested-name-specifier and, therefore,...
CodeCompletionString * Pattern
When Kind == RK_Pattern, the code-completion string that describes the completion text to insert.
bool FunctionCanBeCall
When completing a function, whether it can be a call.
bool AllParametersAreInformative
Whether all parameters (of a function, Objective-C method, etc.) should be considered "informative".
CodeCompletionString * createCodeCompletionStringForOverride(Preprocessor &PP, ASTContext &Ctx, CodeCompletionBuilder &Result, bool IncludeBriefComments, const CodeCompletionContext &CCContext, PrintingPolicy &Policy)
const IdentifierInfo * Macro
When Kind == RK_Macro, the identifier that refers to a macro.
@ RK_Pattern
Refers to a precomputed pattern.
@ RK_Declaration
Refers to a declaration.
@ RK_Keyword
Refers to a keyword or symbol.
A "string" used to describe how code completion can be performed for an entity.
@ CK_Optional
A code completion string that is entirely optional.
@ CK_CurrentParameter
A piece of text that describes the parameter that corresponds to the code-completion location within ...
@ CK_Comma
A comma separator (',').
@ CK_Placeholder
A string that acts as a placeholder for, e.g., a function call argument.
@ CK_LeftParen
A left parenthesis ('(').
@ CK_HorizontalSpace
Horizontal whitespace (' ').
@ CK_RightAngle
A right angle bracket ('>').
@ CK_LeftBracket
A left bracket ('[').
@ CK_RightParen
A right parenthesis (')').
@ CK_RightBrace
A right brace ('}').
@ CK_VerticalSpace
Vertical whitespace ('\n' or '\r\n', depending on the platform).
@ CK_TypedText
The piece of text that the user is expected to type to match the code-completion string,...
@ CK_RightBracket
A right bracket (']').
@ CK_LeftBrace
A left brace ('{').
@ CK_LeftAngle
A left angle bracket ('<').
Declaration of a C++20 concept.
Expr * getConstraintExpr() const
const TypeClass * getTypePtr() const
Definition: TypeLoc.h:421
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
The results of name lookup within a DeclContext.
Definition: DeclBase.h:1369
specific_decl_iterator - Iterates over a subrange of declarations stored in a DeclContext,...
Definition: DeclBase.h:2342
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1436
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2066
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition: DeclBase.h:2191
bool isFileContext() const
Definition: DeclBase.h:2137
bool isObjCContainer() const
Definition: DeclBase.h:2105
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1282
bool isRecord() const
Definition: DeclBase.h:2146
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:1938
decl_iterator decls_end() const
Definition: DeclBase.h:2324
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition: DeclBase.h:2322
bool isFunctionOrMethod() const
Definition: DeclBase.h:2118
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context encloses the declaration context DC.
Definition: DeclBase.cpp:1352
decl_iterator decls_begin() const
Definition: DeclBase.cpp:1572
iterator begin()
Definition: DeclGroup.h:99
iterator end()
Definition: DeclGroup.h:105
Captures information about "declaration specifiers".
Definition: DeclSpec.h:247
static const TST TST_typename
Definition: DeclSpec.h:306
TST getTypeSpecType() const
Definition: DeclSpec.h:534
static const TST TST_interface
Definition: DeclSpec.h:304
unsigned getTypeQualifiers() const
getTypeQualifiers - Return a set of TQs.
Definition: DeclSpec.h:613
static const TST TST_union
Definition: DeclSpec.h:302
TSC getTypeSpecComplex() const
Definition: DeclSpec.h:530
ParsedType getRepAsType() const
Definition: DeclSpec.h:544
static const TST TST_enum
Definition: DeclSpec.h:301
static const TST TST_class
Definition: DeclSpec.h:305
unsigned getParsedSpecifiers() const
Return a bitmask of which flavors of specifiers this DeclSpec includes.
Definition: DeclSpec.cpp:468
bool isTypeAltiVecVector() const
Definition: DeclSpec.h:535
TypeSpecifierSign getTypeSpecSign() const
Definition: DeclSpec.h:531
static const TST TST_struct
Definition: DeclSpec.h:303
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition: DeclBase.h:1216
T * getAttr() const
Definition: DeclBase.h:579
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:501
@ FOK_Undeclared
A friend of a previously-undeclared entity.
Definition: DeclBase.h:1209
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition: DeclBase.cpp:227
ObjCDeclQualifier
ObjCDeclQualifier - 'Qualifiers' written next to the return and parameter types in method declaration...
Definition: DeclBase.h:198
@ OBJC_TQ_Byref
Definition: DeclBase.h:204
@ OBJC_TQ_Oneway
Definition: DeclBase.h:205
@ OBJC_TQ_Bycopy
Definition: DeclBase.h:203
@ OBJC_TQ_None
Definition: DeclBase.h:199
@ OBJC_TQ_CSNullability
The nullability qualifier is set when the nullability of the result or parameter was expressed via a ...
Definition: DeclBase.h:210
@ OBJC_TQ_Inout
Definition: DeclBase.h:201
unsigned getIdentifierNamespace() const
Definition: DeclBase.h:879
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition: DeclBase.h:565
SourceLocation getLocation() const
Definition: DeclBase.h:445
@ IDNS_Ordinary
Ordinary names.
Definition: DeclBase.h:144
@ IDNS_Member
Members, declared with object declarations within tag definitions.
Definition: DeclBase.h:136
@ IDNS_ObjCProtocol
Objective C @protocol.
Definition: DeclBase.h:147
@ IDNS_Namespace
Namespaces, declared with 'namespace foo {}'.
Definition: DeclBase.h:140
@ IDNS_LocalExtern
This declaration is a function-local extern declaration of a variable or function.
Definition: DeclBase.h:175
@ IDNS_Tag
Tags, declared with 'struct foo;' and referenced with 'struct foo'.
Definition: DeclBase.h:125
DeclContext * getDeclContext()
Definition: DeclBase.h:454
AccessSpecifier getAccess() const
Definition: DeclBase.h:513
TranslationUnitDecl * getTranslationUnitDecl()
Definition: DeclBase.cpp:486
void print(raw_ostream &Out, unsigned Indentation=0, bool PrintInstantiation=false) const
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition: DeclBase.h:908
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:968
Kind getKind() const
Definition: DeclBase.h:448
DeclarationName getCXXConstructorName(CanQualType Ty)
Returns the name of a C++ constructor for the given Type.
The name of a declaration.
uintptr_t getAsOpaqueInteger() const
Get the representation of this declaration name as an opaque integer.
IdentifierInfo * getAsIdentifierInfo() const
Retrieve the IdentifierInfo * stored in this declaration name, or null if this declaration name isn't...
void print(raw_ostream &OS, const PrintingPolicy &Policy) const
NameKind getNameKind() const
Determine what kind of name this is.
bool isIdentifier() const
Predicate functions for querying what type of name this is.
Represents a ValueDecl that came out of a declarator.
Definition: Decl.h:770
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:799
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1900
bool isFunctionDeclarator(unsigned &idx) const
isFunctionDeclarator - This method returns true if the declarator is a function declarator (looking t...
Definition: DeclSpec.h:2456
DeclaratorContext getContext() const
Definition: DeclSpec.h:2072
bool isCtorOrDtor()
Returns true if this declares a constructor or a destructor.
Definition: DeclSpec.cpp:436
UnqualifiedId & getName()
Retrieve the name specified by this declarator.
Definition: DeclSpec.h:2066
bool isStaticMember()
Returns true if this declares a static member.
Definition: DeclSpec.cpp:416
DeclaratorChunk::FunctionTypeInfo & getFunctionTypeInfo()
getFunctionTypeInfo - Retrieves the function type info object (looking through parentheses).
Definition: DeclSpec.h:2487
Represents a qualified type name for which the type name is dependent.
Definition: Type.h:6452
NestedNameSpecifier * getQualifier() const
Retrieve the qualification on this type.
Definition: Type.h:6470
const IdentifierInfo * getIdentifier() const
Retrieve the type named by the typename specifier as an identifier.
Definition: Type.h:6477
A qualified reference to a name whose declaration cannot yet be resolved.
Definition: ExprCXX.h:3316
NestedNameSpecifier * getQualifier() const
Retrieve the nested-name-specifier that qualifies this declaration.
Definition: ExprCXX.h:3368
DeclarationName getDeclName() const
Retrieve the name that this expression refers to.
Definition: ExprCXX.h:3355
Designation - Represent a full designation, which is a sequence of designators.
Definition: Designator.h:208
const Designator & getDesignator(unsigned Idx) const
Definition: Designator.h:219
unsigned getNumDesignators() const
Definition: Designator.h:218
DirectoryLookup - This class represents one entry in the search list that specifies the search order ...
Represents an enum.
Definition: Decl.h:3867
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:5575
This represents one expression.
Definition: Expr.h:110
static QualType findBoundMemberType(const Expr *expr)
Given an expression of bound-member type, find the type of the member.
Definition: Expr.cpp:3015
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition: Expr.cpp:3064
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition: Expr.h:192
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition: Expr.cpp:3059
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:277
QualType getType() const
Definition: Expr.h:142
virtual Selector GetExternalSelector(uint32_t ID)
Resolve a selector ID into a selector.
virtual uint32_t GetNumExternalSelectors()
Returns the number of selectors known to the external AST source.
Represents a member of a struct/union/class.
Definition: Decl.h:3057
llvm::vfs::FileSystem & getVirtualFileSystem() const
Definition: FileManager.h:251
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition: Diagnostic.h:134
Represents a function declaration or definition.
Definition: Decl.h:1971
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to call this function.
Definition: Decl.cpp:3713
param_iterator param_end()
Definition: Decl.h:2696
QualType getReturnType() const
Definition: Decl.h:2754
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2683
param_iterator param_begin()
Definition: Decl.h:2695
bool isVariadic() const
Whether this function is variadic.
Definition: Decl.cpp:3089
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:3692
size_t param_size() const
Definition: Decl.h:2699
Represents a prototype with parameter type info, e.g.
Definition: Type.h:4656
bool isVariadic() const
Whether this function prototype is variadic.
Definition: Type.h:5012
Declaration of a template function.
Definition: DeclTemplate.h:957
Wrapper for source info for functions.
Definition: TypeLoc.h:1428
unsigned getNumParams() const
Definition: TypeLoc.h:1500
ParmVarDecl * getParam(unsigned i) const
Definition: TypeLoc.h:1506
TypeLoc getReturnLoc() const
Definition: TypeLoc.h:1509
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:4256
QualType getReturnType() const
Definition: Type.h:4573
void collectAllModules(SmallVectorImpl< Module * > &Modules)
Collect the set of all known, top-level modules.
One of these records is kept for each identifier that is lexed.
unsigned getLength() const
Efficiently return the length of this identifier info.
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
StringRef deuglifiedName() const
If the identifier is an "uglified" reserved name, return a cleaned form.
StringRef getName() const
Return the actual identifier string.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
const TypeClass * getTypePtr() const
Definition: TypeLoc.h:514
The injected class name of a C++ class template or class template partial specialization.
Definition: Type.h:6221
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:461
static StringRef getSourceText(CharSourceRange Range, const SourceManager &SM, const LangOptions &LangOpts, bool *Invalid=nullptr)
Returns a string for the source that the range encompasses.
Definition: Lexer.cpp:1024
Represents the results of name lookup.
Definition: Lookup.h:46
const UnresolvedSetImpl & asUnresolvedSet() const
Definition: Lookup.h:354
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition: Lookup.h:634
Encapsulates the data about a macro definition (e.g.
Definition: MacroInfo.h:39
bool isC99Varargs() const
Definition: MacroInfo.h:207
bool isFunctionLike() const
Definition: MacroInfo.h:201
param_iterator param_begin() const
Definition: MacroInfo.h:182
IdentifierInfo *const * param_iterator
Parameters - The list of parameters for a function-like macro.
Definition: MacroInfo.h:180
bool isVariadic() const
Definition: MacroInfo.h:209
param_iterator param_end() const
Definition: MacroInfo.h:183
bool isUsedForHeaderGuard() const
Determine whether this macro was used for a header guard.
Definition: MacroInfo.h:294
virtual ModuleLoadResult loadModule(SourceLocation ImportLoc, ModuleIdPath Path, Module::NameVisibilityKind Visibility, bool IsInclusionDirective)=0
Attempt to load the given module.
Describes a module or submodule.
Definition: Module.h:105
@ AllVisible
All of the names in this module are visible.
Definition: Module.h:391
llvm::iterator_range< submodule_iterator > submodules()
Definition: Module.h:783
This represents a decl that may have a name.
Definition: Decl.h:249
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition: Decl.h:462
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:270
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:276
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:315
std::string getNameAsString() const
Get a human-readable name for the declaration, even if it is one of the special kinds of names (C++ c...
Definition: Decl.h:292
ReservedIdentifierStatus isReserved(const LangOptions &LangOpts) const
Determine if the declaration obeys the reserved identifier rules of the given language.
Definition: Decl.cpp:1119
Represent a C++ namespace.
Definition: Decl.h:547
A C++ nested-name-specifier augmented with source location information.
NestedNameSpecifier * getNestedNameSpecifier() const
Retrieve the nested-name-specifier to which this instance refers.
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
bool isDependent() const
Whether this nested name specifier refers to a dependent type or not.
static NestedNameSpecifier * Create(const ASTContext &Context, NestedNameSpecifier *Prefix, const IdentifierInfo *II)
Builds a specifier combining a prefix and an identifier.
IdentifierInfo * getAsIdentifier() const
Retrieve the identifier stored in this nested name specifier.
NestedNameSpecifier * getPrefix() const
Return the prefix of this nested name specifier.
void print(raw_ostream &OS, const PrintingPolicy &Policy, bool ResolveTemplateArguments=false) const
Print this nested name specifier to the given output stream.
const Type * getAsType() const
Retrieve the type stored in this nested name specifier.
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
ObjCCategoryDecl - Represents a category declaration.
Definition: DeclObjC.h:2326
ObjCCategoryImplDecl - An object of this class encapsulates a category @implementation declaration.
Definition: DeclObjC.h:2542
ObjCContainerDecl - Represents a container for method declarations.
Definition: DeclObjC.h:947
Captures information about "declaration specifiers" specific to Objective-C.
Definition: DeclSpec.h:897
ObjCPropertyAttribute::Kind getPropertyAttributes() const
Definition: DeclSpec.h:931
ObjCDeclQualifier getObjCDeclQualifier() const
Definition: DeclSpec.h:921
ObjCImplementationDecl - Represents a class definition - this is where method definitions are specifi...
Definition: DeclObjC.h:2594
Represents an ObjC class declaration.
Definition: DeclObjC.h:1153
bool hasDefinition() const
Determine whether this class has been defined.
Definition: DeclObjC.h:1527
protocol_range protocols() const
Definition: DeclObjC.h:1358
known_categories_range known_categories() const
Definition: DeclObjC.h:1686
ObjCImplementationDecl * getImplementation() const
Definition: DeclObjC.cpp:1629
visible_categories_range visible_categories() const
Definition: DeclObjC.h:1652
ObjCInterfaceDecl * getSuperClass() const
Definition: DeclObjC.cpp:352
ObjCIvarDecl - Represents an ObjC instance variable.
Definition: DeclObjC.h:1950
ObjCList - This is a simple template class used to hold various lists of decls etc,...
Definition: DeclObjC.h:82
iterator end() const
Definition: DeclObjC.h:91
iterator begin() const
Definition: DeclObjC.h:90
T *const * iterator
Definition: DeclObjC.h:88
@ SuperInstance
The receiver is the instance of the superclass object.
Definition: ExprObjC.h:959
@ Instance
The receiver is an object instance.
Definition: ExprObjC.h:953
@ SuperClass
The receiver is a superclass.
Definition: ExprObjC.h:956
@ Class
The receiver is a class.
Definition: ExprObjC.h:950
ObjCMethodDecl - Represents an instance or class method declaration.
Definition: DeclObjC.h:140
ObjCDeclQualifier getObjCDeclQualifier() const
Definition: DeclObjC.h:246
ArrayRef< ParmVarDecl * > parameters() const
Definition: DeclObjC.h:373
unsigned param_size() const
Definition: DeclObjC.h:347
param_const_iterator param_end() const
Definition: DeclObjC.h:358
QualType getSendResultType() const
Determine the type of an expression that sends a message to this function.
Definition: DeclObjC.cpp:1238
param_const_iterator param_begin() const
Definition: DeclObjC.h:354
bool isVariadic() const
Definition: DeclObjC.h:431
const ParmVarDecl *const * param_const_iterator
Definition: DeclObjC.h:349
Selector getSelector() const
Definition: DeclObjC.h:327
bool isInstanceMethod() const
Definition: DeclObjC.h:426
QualType getReturnType() const
Definition: DeclObjC.h:329
ParmVarDecl *const * param_iterator
Definition: DeclObjC.h:350
ObjCInterfaceDecl * getClassInterface()
Definition: DeclObjC.cpp:1211
Represents a pointer to an Objective C object.
Definition: Type.h:7008
ObjCInterfaceDecl * getInterfaceDecl() const
If this pointer points to an Objective @interface type, gets the declaration for that interface.
Definition: Type.h:7060
qual_range quals() const
Definition: Type.h:7127
Represents a class type in Objective C.
Definition: Type.h:6754
Represents one property declaration in an Objective-C interface.
Definition: DeclObjC.h:730
static ObjCPropertyDecl * findPropertyDecl(const DeclContext *DC, const IdentifierInfo *propertyID, ObjCPropertyQueryKind queryKind)
Lookup a property by name in the specified DeclContext.
Definition: DeclObjC.cpp:179
Selector getGetterName() const
Definition: DeclObjC.h:884
Represents an Objective-C protocol declaration.
Definition: DeclObjC.h:2082
void * getAsOpaquePtr() const
Definition: Ownership.h:90
PtrTy get() const
Definition: Ownership.h:80
static OpaquePtr make(QualType P)
Definition: Ownership.h:60
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition: Overload.h:980
@ CSK_Normal
Normal lookup.
Definition: Overload.h:984
CandidateSetKind getKind() const
Definition: Overload.h:1129
Represents a parameter to a function.
Definition: Decl.h:1761
SourceRange getDefaultArgRange() const
Retrieve the source range that covers the entire default argument.
Definition: Decl.cpp:2985
bool hasDefaultArg() const
Determines whether this parameter has a default argument, either parsed or not.
Definition: Decl.cpp:3016
Represents the parsed form of a C++ template argument.
KindType getKind() const
Determine what kind of template argument we have.
@ Type
A template type parameter, stored as a type.
@ Template
A template template argument, stored as a template name.
@ NonType
A non-type template parameter, stored as an expression.
Wrapper for source info for pointers.
Definition: TypeLoc.h:1301
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:3139
void enterFunctionArgument(SourceLocation Tok, llvm::function_ref< QualType()> ComputeType)
Computing a type for the function argument may require running overloading, so we postpone its comput...
void enterCondition(Sema &S, SourceLocation Tok)
void enterTypeCast(SourceLocation Tok, QualType CastType)
Handles all type casts, including C-style cast, C++ casts, etc.
void enterMemAccess(Sema &S, SourceLocation Tok, Expr *Base)
void enterSubscript(Sema &S, SourceLocation Tok, Expr *LHS)
void enterUnary(Sema &S, SourceLocation Tok, tok::TokenKind OpKind, SourceLocation OpLoc)
void enterReturn(Sema &S, SourceLocation Tok)
void enterDesignatedInitializer(SourceLocation Tok, QualType BaseType, const Designation &D)
Handles e.g. BaseType{ .D = Tok...
void enterBinary(Sema &S, SourceLocation Tok, Expr *LHS, tok::TokenKind Op)
void enterParenExpr(SourceLocation Tok, SourceLocation LParLoc)
void enterVariableInit(SourceLocation Tok, Decl *D)
QualType get(SourceLocation Tok) const
Get the expected type associated with this location, if any.
Definition: Sema.h:329
OptionalFileEntryRef getFileEntry() const
getFileEntry - Return the FileEntry corresponding to this FileID.
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Definition: Preprocessor.h:128
const MacroInfo * getMacroInfo(const IdentifierInfo *II) const
macro_iterator macro_begin(bool IncludeExternalMacros=true) const
ModuleLoader & getModuleLoader() const
Retrieve the module loader associated with this preprocessor.
macro_iterator macro_end(bool IncludeExternalMacros=true) const
SourceManager & getSourceManager() const
MacroDefinition getMacroDefinition(const IdentifierInfo *II)
bool isMacroDefined(StringRef Id)
MacroMap::const_iterator macro_iterator
llvm::iterator_range< macro_iterator > macros(bool IncludeExternalMacros=true) const
PreprocessorLexer * getCurrentFileLexer() const
Return the current file lexer being lexed from.
HeaderSearch & getHeaderSearchInfo() const
const LangOptions & getLangOpts() const
bool isCodeCompletionReached() const
Returns true if code-completion is enabled and we have hit the code-completion point.
A (possibly-)qualified type.
Definition: Type.h:940
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:1007
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:7359
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:7399
QualType stripObjCKindOfType(const ASTContext &ctx) const
Strip Objective-C "__kindof" types from the given type.
Definition: Type.cpp:1612
void print(raw_ostream &OS, const PrintingPolicy &Policy, const Twine &PlaceHolder=Twine(), unsigned Indentation=0) const
void getAsStringInternal(std::string &Str, const PrintingPolicy &Policy) const
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition: Type.h:7560
QualType getCanonicalType() const
Definition: Type.h:7411
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:7453
QualType substObjCTypeArgs(ASTContext &ctx, ArrayRef< QualType > typeArgs, ObjCSubstitutionContext context) const
Substitute type arguments for the Objective-C type parameters used in the subject type.
Definition: Type.cpp:1596
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition: Type.h:1327
Wrapper of type source information for a type with non-trivial direct qualifiers.
Definition: TypeLoc.h:289
The collection of all-type qualifiers we support.
Definition: Type.h:318
bool hasConst() const
Definition: Type.h:443
bool compatiblyIncludes(Qualifiers other) const
Determines if these qualifiers compatibly include another set.
Definition: Type.h:731
Represents a struct/union/class.
Definition: Decl.h:4168
bool isLambda() const
Determine whether this record is a class describing a lambda function object.
Definition: Decl.cpp:5040
field_range fields() const
Definition: Decl.h:4374
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:5549
A class that does preorder or postorder depth-first traversal on the entire Clang AST and visits each...
bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS)
Recursively visit a C++ nested-name-specifier with location information.
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:3380
QualType getPointeeType() const
Definition: Type.h:3398
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:41
@ FunctionPrototypeScope
This is a scope that corresponds to the parameters within a function prototype.
Definition: Scope.h:85
@ AtCatchScope
This is a scope that corresponds to the Objective-C @catch statement.
Definition: Scope.h:95
@ TemplateParamScope
This is a scope that corresponds to the template parameters of a C++ template.
Definition: Scope.h:81
@ ClassScope
The scope of a struct/union/class definition.
Definition: Scope.h:69
@ DeclScope
This is a scope that can contain a declaration.
Definition: Scope.h:63
This table allows us to fully hide how we implement multi-keyword caching.
Selector getNullarySelector(const IdentifierInfo *ID)
Selector getSelector(unsigned NumArgs, const IdentifierInfo **IIV)
Can create any sort of selector.
Selector getUnarySelector(const IdentifierInfo *ID)
Smart pointer class that efficiently represents Objective-C method names.
StringRef getNameForSlot(unsigned argIndex) const
Retrieve the name at a given position in the selector.
const IdentifierInfo * getIdentifierInfoForSlot(unsigned argIndex) const
Retrieve the identifier at a given position in the selector.
bool isUnarySelector() const
bool isNull() const
Determine whether this is the empty selector.
unsigned getNumArgs() const
void CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver, ArrayRef< const IdentifierInfo * > SelIdents, bool AtArgumentExpression, ObjCInterfaceDecl *Super=nullptr)
void CodeCompleteObjCPropertySynthesizeIvar(Scope *S, IdentifierInfo *PropertyName)
void CodeCompleteAttribute(AttributeCommonInfo::Syntax Syntax, AttributeCompletion Completion=AttributeCompletion::Attribute, const IdentifierInfo *Scope=nullptr)
QualType ProduceTemplateArgumentSignatureHelp(TemplateTy, ArrayRef< ParsedTemplateArgument >, SourceLocation LAngleLoc)
QualType ProduceCtorInitMemberSignatureHelp(Decl *ConstructorDecl, CXXScopeSpec SS, ParsedType TemplateTypeTy, ArrayRef< Expr * > ArgExprs, IdentifierInfo *II, SourceLocation OpenParLoc, bool Braced)
void CodeCompleteObjCClassForwardDecl(Scope *S)
void CodeCompleteNamespaceAliasDecl(Scope *S)
void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator, CodeCompletionTUInfo &CCTUInfo, SmallVectorImpl< CodeCompletionResult > &Results)
void CodeCompleteObjCAtStatement(Scope *S)
void CodeCompleteObjCMessageReceiver(Scope *S)
void CodeCompleteOperatorName(Scope *S)
void CodeCompleteUsingDirective(Scope *S)
void CodeCompleteObjCProtocolDecl(Scope *S)
void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS)
ParserCompletionContext
Describes the context in which code completion occurs.
@ PCC_LocalDeclarationSpecifiers
Code completion occurs within a sequence of declaration specifiers within a function,...
@ PCC_MemberTemplate
Code completion occurs following one or more template headers within a class.
@ PCC_Condition
Code completion occurs within the condition of an if, while, switch, or for statement.
@ PCC_ParenthesizedExpression
Code completion occurs in a parenthesized expression, which might also be a type cast.
@ PCC_TopLevelOrExpression
Code completion occurs at top-level in a REPL session.
@ PCC_Class
Code completion occurs within a class, struct, or union.
@ PCC_ForInit
Code completion occurs at the beginning of the initialization statement (or expression) in a for loop...
@ PCC_Type
Code completion occurs where only a type is permitted.
@ PCC_ObjCImplementation
Code completion occurs within an Objective-C implementation or category implementation.
@ PCC_ObjCInterface
Code completion occurs within an Objective-C interface, protocol, or category.
@ PCC_Namespace
Code completion occurs at top-level or namespace context.
@ PCC_Expression
Code completion occurs within an expression.
@ PCC_RecoveryInFunction
Code completion occurs within the body of a function on a recovery path, where we do not have a speci...
@ PCC_ObjCInstanceVariableList
Code completion occurs within the list of instance variables in an Objective-C interface,...
@ PCC_Template
Code completion occurs following one or more template headers.
@ PCC_Statement
Code completion occurs within a statement, which may also be an expression or a declaration.
void CodeCompleteObjCAtDirective(Scope *S)
void CodeCompleteObjCPropertySetter(Scope *S)
void CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro, bool AfterAmpersand)
void CodeCompleteObjCImplementationCategory(Scope *S, IdentifierInfo *ClassName, SourceLocation ClassNameLoc)
void CodeCompleteObjCInterfaceDecl(Scope *S)
void CodeCompleteFunctionQualifiers(DeclSpec &DS, Declarator &D, const VirtSpecifiers *VS=nullptr)
void CodeCompletePreprocessorMacroName(bool IsDefinition)
void CodeCompleteInPreprocessorConditionalExclusion(Scope *S)
void CodeCompleteObjCAtExpression(Scope *S)
void CodeCompleteTypeQualifiers(DeclSpec &DS)
void CodeCompleteObjCPropertyDefinition(Scope *S)
void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc, ArrayRef< const IdentifierInfo * > SelIdents, bool AtArgumentExpression)
CodeCompleteConsumer * CodeCompleter
Code-completion consumer.
void CodeCompleteAfterFunctionEquals(Declarator &D)
QualType ProduceConstructorSignatureHelp(QualType Type, SourceLocation Loc, ArrayRef< Expr * > Args, SourceLocation OpenParLoc, bool Braced)
void CodeCompleteExpression(Scope *S, const CodeCompleteExpressionData &Data)
Perform code-completion in an expression context when we know what type we're looking for.
QualType ProduceCallSignatureHelp(Expr *Fn, ArrayRef< Expr * > Args, SourceLocation OpenParLoc)
Determines the preferred type of the current function argument, by examining the signatures of all po...
void CodeCompleteObjCMethodDeclSelector(Scope *S, bool IsInstanceMethod, bool AtParameterName, ParsedType ReturnType, ArrayRef< const IdentifierInfo * > SelIdents)
void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS, bool EnteringContext, bool IsUsingDeclaration, QualType BaseType, QualType PreferredType)
void CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled)
void CodeCompletePreprocessorMacroArgument(Scope *S, IdentifierInfo *Macro, MacroInfo *MacroInfo, unsigned Argument)
void CodeCompleteModuleImport(SourceLocation ImportLoc, ModuleIdPath Path)
void CodeCompleteObjCInterfaceCategory(Scope *S, IdentifierInfo *ClassName, SourceLocation ClassNameLoc)
void CodeCompleteObjCSelector(Scope *S, ArrayRef< const IdentifierInfo * > SelIdents)
void CodeCompleteConstructorInitializer(Decl *Constructor, ArrayRef< CXXCtorInitializer * > Initializers)
void CodeCompleteObjCImplementationDecl(Scope *S)
void CodeCompleteAfterIf(Scope *S, bool IsBracedThen)
void CodeCompleteObjCMethodDecl(Scope *S, std::optional< bool > IsInstanceMethod, ParsedType ReturnType)
void CodeCompleteOrdinaryName(Scope *S, ParserCompletionContext CompletionContext)
void CodeCompleteObjCProtocolReferences(ArrayRef< IdentifierLocPair > Protocols)
void CodeCompleteObjCClassPropertyRefExpr(Scope *S, const IdentifierInfo &ClassName, SourceLocation ClassNameLoc, bool IsBaseExprStatement)
void CodeCompleteInitializer(Scope *S, Decl *D)
void CodeCompleteNamespaceDecl(Scope *S)
void CodeCompleteDesignator(const QualType BaseType, llvm::ArrayRef< Expr * > InitExprs, const Designation &D)
Trigger code completion for a record of BaseType.
void CodeCompletePreprocessorDirective(bool InConditional)
SemaCodeCompletion(Sema &S, CodeCompleteConsumer *CompletionConsumer)
void CodeCompleteBracketDeclarator(Scope *S)
void CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName, SourceLocation ClassNameLoc)
void CodeCompleteObjCAtVisibility(Scope *S)
void CodeCompleteTag(Scope *S, unsigned TagSpec)
void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver, ArrayRef< const IdentifierInfo * > SelIdents, bool AtArgumentExpression, bool IsSuper=false)
void CodeCompleteObjCForCollection(Scope *S, DeclGroupPtrTy IterationVar)
void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base, Expr *OtherOpBase, SourceLocation OpLoc, bool IsArrow, bool IsBaseExprStatement, QualType PreferredType)
void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS, bool IsParameter)
void CodeCompleteObjCPropertyGetter(Scope *S)
void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS, bool AllowNonIdentifiers, bool AllowNestedNameSpecifiers)
void CodeCompletePostfixExpression(Scope *S, ExprResult LHS, QualType PreferredType)
llvm::DenseMap< Selector, Lists >::iterator iterator
Definition: SemaObjC.h:191
int count(Selector Sel) const
Definition: SemaObjC.h:198
ObjCInterfaceDecl * getObjCInterfaceDecl(const IdentifierInfo *&Id, SourceLocation IdLoc, bool TypoCorrection=false)
Look for an Objective-C class in the translation unit.
ObjCProtocolDecl * LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc, RedeclarationKind Redecl=RedeclarationKind::NotForRedeclaration)
Find the protocol with the given name, if any.
Definition: SemaObjC.cpp:1297
GlobalMethodPool MethodPool
Method Pool - allows efficient lookup when typechecking messages to "id".
Definition: SemaObjC.h:211
void ReadMethodPool(Selector Sel)
Read the contents of the method pool for a given selector from external storage.
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:451
QualType getCurrentThisType()
Try to retrieve the type of the 'this' pointer.
ExprResult PerformContextuallyConvertToObjCPointer(Expr *From)
PerformContextuallyConvertToObjCPointer - Perform a contextual conversion of the expression From to a...
bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs=true)
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition: Sema.h:7289
@ LookupNestedNameSpecifierName
Look up of a name that precedes the '::' scope resolution operator in C++.
Definition: Sema.h:7308
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition: Sema.h:7297
@ LookupTagName
Tag name lookup, which finds the names of enums, classes, structs, and unions.
Definition: Sema.h:7292
@ LookupAnyName
Look up any declaration with any name.
Definition: Sema.h:7334
TemplateDecl * AdjustDeclIfTemplate(Decl *&Decl)
AdjustDeclIfTemplate - If the given decl happens to be a template, reset the parameter D to reference...
bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC)
Require that the context specified by SS be complete.
ExprResult ActOnIdExpression(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand, CorrectionCandidateCallback *CCC=nullptr, bool IsInlineAsmIdentifier=false, Token *KeywordReplacement=nullptr)
Definition: SemaExpr.cpp:2694
Preprocessor & getPreprocessor() const
Definition: Sema.h:516
NamedDecl * LookupSingleName(Scope *S, DeclarationName Name, SourceLocation Loc, LookupNameKind NameKind, RedeclarationKind Redecl=RedeclarationKind::NotForRedeclaration)
Look up a name, looking for a single declaration.
IdentifierInfo * getSuperIdentifier() const
Definition: Sema.cpp:2686
ASTContext & Context
Definition: Sema.h:848
static bool TooManyArguments(size_t NumParams, size_t NumArgs, bool PartialOverloading=false)
To be used for checking whether the arguments being passed to function exceeds the number of paramete...
Definition: Sema.h:6192
ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow)
Perform conversions on the LHS of a member access expression.
SemaObjC & ObjC()
Definition: Sema.h:1003
ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose=true)
Definition: SemaExpr.cpp:764
ASTContext & getASTContext() const
Definition: Sema.h:517
bool isInitListConstructor(const FunctionDecl *Ctor)
Determine whether Ctor is an initializer-list constructor, as defined in [dcl.init....
ValueDecl * tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl, CXXScopeSpec &SS, ParsedType TemplateTypeTy, IdentifierInfo *MemberOrBase)
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition: Sema.h:765
ObjCMethodDecl * getCurMethodDecl()
getCurMethodDecl - If inside of a method body, this returns a pointer to the method decl for the meth...
Definition: Sema.cpp:1504
void AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, bool AllowExplicit=true, ADLCallKind IsADLCandidate=ADLCallKind::NotADL, OverloadCandidateParamOrder PO={}, bool AggregateCandidateDeduction=false)
Add a C++ function template specialization as a candidate in the candidate set, using template argume...
const LangOptions & getLangOpts() const
Definition: Sema.h:510
void LookupVisibleDecls(Scope *S, LookupNameKind Kind, VisibleDeclConsumer &Consumer, bool IncludeGlobalScope=true, bool LoadExternal=true)
SemaCodeCompletion & CodeCompletion()
Definition: Sema.h:988
Preprocessor & PP
Definition: Sema.h:847
sema::FunctionScopeInfo * getCurFunction() const
Definition: Sema.h:882
void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool PartialOverloading=false)
Add the overload candidates named by callee and/or found by argument dependent lookup to the given ov...
sema::BlockScopeInfo * getCurBlock()
Retrieve the current block, if any.
Definition: Sema.cpp:2322
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:986
SourceManager & getSourceManager() const
Definition: Sema.h:515
DeclContext * computeDeclContext(QualType T)
Compute the DeclContext that is associated with the given type.
void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, bool AllowExplicit=true, bool AllowExplicitConversion=false, ADLCallKind IsADLCandidate=ADLCallKind::NotADL, ConversionSequenceList EarlyConversions=std::nullopt, OverloadCandidateParamOrder PO={}, bool AggregateCandidateDeduction=false)
AddOverloadCandidate - Adds the given function to the set of candidate functions, using the given fun...
ExternalSemaSource * getExternalSource() const
Definition: Sema.h:520
bool isCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind=CompleteTypeKind::Default)
Definition: Sema.h:11584
IntrusiveRefCntPtr< ExternalSemaSource > ExternalSource
Source of additional semantic information.
Definition: Sema.h:1024
void AddFunctionCandidates(const UnresolvedSetImpl &Functions, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, TemplateArgumentListInfo *ExplicitTemplateArgs=nullptr, bool SuppressUserConversions=false, bool PartialOverloading=false, bool FirstArgumentIsBase=false)
Add all of the function declarations in the given function set to the overload candidate set.
bool isAcceptableNestedNameSpecifier(const NamedDecl *SD, bool *CanCorrect=nullptr)
Determines whether the given declaration is an valid acceptable result for name lookup of a nested-na...
Scope * TUScope
Translation Unit Scope - useful to Objective-C actions that need to lookup file scope declarations in...
Definition: Sema.h:820
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
SourceManager & SourceMgr
Definition: Sema.h:851
static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo=nullptr)
Definition: SemaType.cpp:2805
DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class)
Look up the constructors for the given class.
void MarkDeducedTemplateParameters(const FunctionTemplateDecl *FunctionTemplate, llvm::SmallBitVector &Deduced)
Definition: Sema.h:9635
Encodes a location in the source.
This class handles loading and caching of source files into memory.
SourceLocation getSpellingLoc(SourceLocation Loc) const
Given a SourceLocation object, return the spelling location referenced by the ID.
FileManager & getFileManager() const
bool isInSystemHeader(SourceLocation Loc) const
Returns if a SourceLocation is in a system header.
A trivial tuple used to represent a source range.
SwitchStmt - This represents a 'switch' stmt.
Definition: Stmt.h:2388
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3584
bool isUnion() const
Definition: Decl.h:3790
A convenient class for passing around template argument information.
Definition: TemplateBase.h:632
Represents a template argument.
Definition: TemplateBase.h:61
QualType getAsType() const
Retrieve the type for a type template argument.
Definition: TemplateBase.h:319
@ Type
The template argument is a type.
Definition: TemplateBase.h:70
ArgKind getKind() const
Return the kind of stored template argument.
Definition: TemplateBase.h:295
The base class of all kinds of template declarations (e.g., class, function, etc.).
Definition: DeclTemplate.h:394
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Definition: DeclTemplate.h:413
Represents a C++ template name within the type system.
Definition: TemplateName.h:202
TemplateDecl * getAsTemplateDecl() const
Retrieve the underlying template declaration that this template name refers to, if known.
OverloadedTemplateStorage * getAsOverloadedTemplate() const
Retrieve the underlying, overloaded function template declarations that this template name refers to,...
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:73
NamedDecl * getParam(unsigned Idx)
Definition: DeclTemplate.h:144
bool hasParameterPack() const
Determine whether this template parameter list contains a parameter pack.
Definition: DeclTemplate.h:172
ArrayRef< NamedDecl * > asArray()
Definition: DeclTemplate.h:139
Represents a type template specialization; the template must be a class template, a type alias templa...
Definition: Type.h:6089
TemplateTemplateParmDecl - Declares a template template parameter, e.g., "T" in.
bool hasDefaultArgument() const
Determine whether this template parameter has a default argument.
Declaration of a template type parameter.
TemplateTypeParmDecl * getDecl() const
Definition: Type.h:5782
The top declaration context.
Definition: Decl.h:84
Models the abbreviated syntax to constrain a template type parameter: template <convertible_to<string...
Definition: ASTConcept.h:231
void print(llvm::raw_ostream &OS, const PrintingPolicy &Policy) const
Definition: ASTConcept.h:282
Represents a declaration of a type.
Definition: Decl.h:3390
Base wrapper for a particular "section" of type source info.
Definition: TypeLoc.h:59
UnqualTypeLoc getUnqualifiedLoc() const
Skips past any qualifiers, if this is qualified.
Definition: TypeLoc.h:338
QualType getType() const
Get the type for which this source info wrapper provides information.
Definition: TypeLoc.h:133
T getAs() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition: TypeLoc.h:89
TypeLoc IgnoreParens() const
Definition: TypeLoc.h:1225
T getAsAdjusted() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition: TypeLoc.h:2684
A container of type source information.
Definition: Type.h:7330
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition: TypeLoc.h:256
The base class of the type hierarchy.
Definition: Type.h:1813
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1871
bool isBlockPointerType() const
Definition: Type.h:7620
bool isVoidType() const
Definition: Type.h:7905
bool isBooleanType() const
Definition: Type.h:8033
const ObjCObjectPointerType * getAsObjCQualifiedIdType() const
Definition: Type.cpp:1820
bool isArrayType() const
Definition: Type.h:7678
bool isPointerType() const
Definition: Type.h:7612
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:7945
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8193
const ObjCObjectPointerType * getAsObjCInterfacePointerType() const
Definition: Type.cpp:1848
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:695
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:8020
bool isObjCObjectOrInterfaceType() const
Definition: Type.h:7752
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2653
bool isTemplateTypeParmType() const
Definition: Type.h:7870
bool isMemberPointerType() const
Definition: Type.h:7660
bool isObjCIdType() const
Definition: Type.h:7777
bool isObjCObjectType() const
Definition: Type.h:7748
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition: Type.h:8179
bool isObjCObjectPointerType() const
Definition: Type.h:7744
bool isObjCQualifiedClassType() const
Definition: Type.h:7771
bool isObjCClassType() const
Definition: Type.h:7783
std::optional< ArrayRef< QualType > > getObjCSubstitutions(const DeclContext *dc) const
Retrieve the set of substitutions required when accessing a member of the Objective-C receiver type t...
Definition: Type.cpp:1626
TypeClass getTypeClass() const
Definition: Type.h:2300
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8126
bool isRecordType() const
Definition: Type.h:7706
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition: Type.cpp:1875
Wrapper for source info for typedefs.
Definition: TypeLoc.h:693
Represents a C++ unqualified-id that has been parsed.
Definition: DeclSpec.h:1025
void setIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc)
Specify that this unqualified-id was parsed as an identifier.
Definition: DeclSpec.h:1113
void append(iterator I, iterator E)
A set of unresolved declarations.
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition: DeclCXX.h:3320
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:706
QualType getType() const
Definition: Decl.h:717
QualType getType() const
Definition: Value.cpp:234
Represents a C++11 virt-specifier-seq.
Definition: DeclSpec.h:2780
bool isOverrideSpecified() const
Definition: DeclSpec.h:2799
bool isFinalSpecified() const
Definition: DeclSpec.h:2802
Consumes visible declarations found when searching for all visible names within a given scope or cont...
Definition: Lookup.h:836
A static requirement that can be used in a requires-expression to check properties of types and expre...
Definition: ExprConcepts.h:168
Retains information about a block that is currently being parsed.
Definition: ScopeInfo.h:784
QualType ReturnType
ReturnType - The target type of return statements in this context, or null if unknown.
Definition: ScopeInfo.h:729
SmallVector< SwitchInfo, 8 > SwitchStack
SwitchStack - This is the current set of active switch statements in the block.
Definition: ScopeInfo.h:209
CXCursorKind
Describes the kind of entity that a cursor refers to.
Definition: Index.h:1186
@ CXCursor_ObjCInterfaceDecl
An Objective-C @interface.
Definition: Index.h:1220
@ CXCursor_Namespace
A C++ namespace.
Definition: Index.h:1242
@ CXCursor_TypedefDecl
A typedef.
Definition: Index.h:1238
@ CXCursor_CXXAccessSpecifier
An access specifier.
Definition: Index.h:1276
@ CXCursor_EnumConstantDecl
An enumerator constant.
Definition: Index.h:1212
@ CXCursor_ConversionFunction
A C++ conversion function.
Definition: Index.h:1250
@ CXCursor_ConceptDecl
a concept declaration.
Definition: Index.h:2240
@ CXCursor_ClassTemplate
A C++ class template.
Definition: Index.h:1260
@ CXCursor_UnionDecl
A C or C++ union.
Definition: Index.h:1201
@ CXCursor_ObjCSynthesizeDecl
An Objective-C @synthesize definition.
Definition: Index.h:1272
@ CXCursor_ParmDecl
A function or method parameter.
Definition: Index.h:1218
@ CXCursor_FieldDecl
A field (in C) or non-static data member (in C++) in a struct, union, or C++ class.
Definition: Index.h:1210
@ CXCursor_CXXMethod
A C++ class method.
Definition: Index.h:1240
@ CXCursor_EnumDecl
An enumeration.
Definition: Index.h:1205
@ CXCursor_ObjCClassMethodDecl
An Objective-C class method.
Definition: Index.h:1232
@ CXCursor_TranslationUnit
Cursor that represents the translation unit itself.
Definition: Index.h:2161
@ CXCursor_ClassTemplatePartialSpecialization
A C++ class template partial specialization.
Definition: Index.h:1262
@ CXCursor_ObjCProtocolDecl
An Objective-C @protocol declaration.
Definition: Index.h:1224
@ CXCursor_FunctionTemplate
A C++ function template.
Definition: Index.h:1258
@ CXCursor_ObjCImplementationDecl
An Objective-C @implementation.
Definition: Index.h:1234
@ CXCursor_NonTypeTemplateParameter
A C++ non-type template parameter.
Definition: Index.h:1254
@ CXCursor_FunctionDecl
A function.
Definition: Index.h:1214
@ CXCursor_ObjCPropertyDecl
An Objective-C @property declaration.
Definition: Index.h:1226
@ CXCursor_Destructor
A C++ destructor.
Definition: Index.h:1248
@ CXCursor_ObjCIvarDecl
An Objective-C instance variable.
Definition: Index.h:1228
@ CXCursor_TypeAliasTemplateDecl
Definition: Index.h:2228
@ CXCursor_ObjCCategoryImplDecl
An Objective-C @implementation for a category.
Definition: Index.h:1236
@ CXCursor_ObjCDynamicDecl
An Objective-C @dynamic definition.
Definition: Index.h:1274
@ CXCursor_MacroDefinition
Definition: Index.h:2216
@ CXCursor_VarDecl
A variable.
Definition: Index.h:1216
@ CXCursor_TemplateTypeParameter
A C++ template type parameter.
Definition: Index.h:1252
@ CXCursor_TemplateTemplateParameter
A C++ template template parameter.
Definition: Index.h:1256
@ CXCursor_UnexposedDecl
A declaration whose specific kind is not exposed via this interface.
Definition: Index.h:1197
@ CXCursor_ObjCInstanceMethodDecl
An Objective-C instance method.
Definition: Index.h:1230
@ CXCursor_StructDecl
A C or C++ struct.
Definition: Index.h:1199
@ CXCursor_UsingDeclaration
A C++ using declaration.
Definition: Index.h:1268
@ CXCursor_LinkageSpec
A linkage specification, e.g.
Definition: Index.h:1244
@ CXCursor_ClassDecl
A C++ class.
Definition: Index.h:1203
@ CXCursor_ObjCCategoryDecl
An Objective-C @interface for a category.
Definition: Index.h:1222
@ CXCursor_StaticAssert
A static_assert or _Static_assert node.
Definition: Index.h:2232
@ CXCursor_ModuleImportDecl
A module import declaration.
Definition: Index.h:2227
@ CXCursor_MemberRef
A reference to a member of a struct, union, or class that occurs in some non-expression context,...
Definition: Index.h:1316
@ CXCursor_NamespaceAlias
A C++ namespace alias declaration.
Definition: Index.h:1264
@ CXCursor_Constructor
A C++ constructor.
Definition: Index.h:1246
@ CXCursor_FriendDecl
a friend declaration.
Definition: Index.h:2236
@ CXCursor_TypeAliasDecl
A C++ alias declaration.
Definition: Index.h:1270
@ CXCursor_UsingDirective
A C++ using directive.
Definition: Index.h:1266
@ CXAvailability_Available
The entity is available.
Definition: Index.h:134
@ CXAvailability_Deprecated
The entity is available, but has been deprecated (and its use is not recommended).
Definition: Index.h:139
@ CXAvailability_NotAvailable
The entity is not available; any use of it will be an error.
Definition: Index.h:143
@ kind_nullability
Indicates that the nullability of the type was spelled with a property attribute rather than a type q...
QualType getFullyQualifiedType(QualType QT, const ASTContext &Ctx, bool WithGlobalNsPrefix=false)
Generates a QualType that can be used to name the same type if used at the end of the current transla...
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
bool Add(InterpState &S, CodePtr OpPC)
Definition: Interp.h:312
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition: TokenKinds.h:25
llvm::cl::opt< std::string > Filter
The JSON file list parser is used to communicate input to InstallAPI.
TypeSpecifierType
Specifies the kind of type.
Definition: Specifiers.h:55
@ OO_None
Not an overloaded operator.
Definition: OperatorKinds.h:22
@ NUM_OVERLOADED_OPERATORS
Definition: OperatorKinds.h:26
@ CPlusPlus
Definition: LangStandard.h:55
@ CPlusPlus11
Definition: LangStandard.h:56
@ Specialization
We are substituting template parameters for template arguments in order to form a template specializa...
@ CCF_ExactTypeMatch
Divide by this factor when a code-completion result's type exactly matches the type we expect.
@ CCF_SimilarTypeMatch
Divide by this factor when a code-completion result's type is similar to the type we expect (e....
QualType getDeclUsageType(ASTContext &C, const NamedDecl *ND)
Determine the type that this declaration will have if it is used as a type or in an expression.
bool isReservedInAllContexts(ReservedIdentifierStatus Status)
Determine whether an identifier is reserved in all contexts.
@ Nullable
Values of this type can be null.
@ Unspecified
Whether values of this type can be null is (explicitly) unspecified.
@ NonNull
Values of this type can never be null.
CXCursorKind getCursorKindForDecl(const Decl *D)
Determine the libclang cursor kind associated with the given declaration.
RefQualifierKind
The kind of C++11 ref-qualifier associated with a function type.
Definition: Type.h:1760
@ RQ_None
No ref-qualifier was provided.
Definition: Type.h:1762
@ RQ_LValue
An lvalue ref-qualifier was provided (&).
Definition: Type.h:1765
@ RQ_RValue
An rvalue ref-qualifier was provided (&&).
Definition: Type.h:1768
const RawComment * getParameterComment(const ASTContext &Ctx, const CodeCompleteConsumer::OverloadCandidate &Result, unsigned ArgIndex)
Get the documentation comment used to produce CodeCompletionString::BriefComment for OverloadCandidat...
@ LCK_This
Capturing the *this object by reference.
Definition: Lambda.h:34
@ IK_ConstructorName
A constructor name.
@ IK_DestructorName
A destructor name.
@ IK_OperatorFunctionId
An overloaded operator name, e.g., operator+.
@ Property
The type of a property.
@ Parameter
The parameter type of a method or function.
@ Result
The result type of a method or function.
SimplifiedTypeClass
A simplified classification of types used when determining "similar" types for code completion.
const RawComment * getPatternCompletionComment(const ASTContext &Ctx, const NamedDecl *Decl)
Get the documentation comment used to produce CodeCompletionString::BriefComment for RK_Pattern.
@ Interface
The "__interface" keyword.
@ Struct
The "struct" keyword.
@ Class
The "class" keyword.
@ Union
The "union" keyword.
@ Enum
The "enum" keyword.
LLVM_READONLY char toUppercase(char c)
Converts the given ASCII character to its uppercase equivalent.
Definition: CharInfo.h:233
const RawComment * getCompletionComment(const ASTContext &Ctx, const NamedDecl *Decl)
Get the documentation comment used to produce CodeCompletionString::BriefComment for RK_Declaration.
SimplifiedTypeClass getSimplifiedTypeClass(CanQualType T)
Determine the simplified type class of the given canonical type.
@ LCD_ByCopy
Definition: Lambda.h:24
@ CCD_SelectorMatch
The selector of the given message exactly matches the selector of the current method,...
@ CCD_ObjectQualifierMatch
The result is a C++ non-static member function whose qualifiers exactly match the object type on whic...
@ CCD_bool_in_ObjC
Adjustment to the "bool" type in Objective-C, where the typedef "BOOL" is preferred.
@ CCD_InBaseClass
The result is in a base class.
@ CCD_ProbablyNotObjCCollection
Adjustment for KVC code pattern priorities when it doesn't look like the.
@ CCD_BlockPropertySetter
An Objective-C block property completed as a setter with a block placeholder.
@ CCD_MethodAsProperty
An Objective-C method being used as a property.
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition: Specifiers.h:129
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition: Specifiers.h:141
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:136
bool isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2, SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind)
isBetterOverloadCandidate - Determines whether the first overload candidate is a better candidate tha...
@ CCP_Type
Priority for a type.
@ CCP_ObjC_cmd
Priority for the Objective-C "_cmd" implicit parameter.
@ CCP_Macro
Priority for a preprocessor macro.
@ CCP_LocalDeclaration
Priority for a declaration that is in the local scope.
@ CCP_Unlikely
Priority for a result that isn't likely to be what the user wants, but is included for completeness.
@ CCP_NestedNameSpecifier
Priority for a nested-name-specifier.
@ CCP_SuperCompletion
Priority for a send-to-super completion.
@ CCP_NextInitializer
Priority for the next initialization in a constructor initializer list.
@ CCP_Declaration
Priority for a non-type declaration.
@ CCP_Constant
Priority for a constant value (e.g., enumerator).
@ CCP_MemberDeclaration
Priority for a member declaration found from the current method or member function.
@ CCP_EnumInCase
Priority for an enumeration constant inside a switch whose condition is of the enumeration type.
@ CCP_CodePattern
Priority for a code pattern.
const FunctionProtoType * T
unsigned getMacroUsagePriority(StringRef MacroName, const LangOptions &LangOpts, bool PreferredTypeIsPointer=false)
Determine the priority to be given to a macro code completion result with the given name.
bool shouldEnforceArgLimit(bool PartialOverloading, FunctionDecl *Function)
llvm::StringRef getAsString(SyncScope S)
Definition: SyncScope.h:60
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition: Specifiers.h:188
std::pair< IdentifierInfo *, SourceLocation > IdentifierLocPair
A simple pair of identifier info and location.
@ Interface
The "__interface" keyword introduces the elaborated-type-specifier.
@ Class
The "class" keyword introduces the elaborated-type-specifier.
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
ReservedIdentifierStatus
Definition: Format.h:5428
__UINTPTR_TYPE__ uintptr_t
An unsigned integer type with the property that any valid pointer to void can be converted to this ty...
#define false
Definition: stdbool.h:26
#define bool
Definition: stdbool.h:24
CodeCompleteExpressionData(QualType PreferredType=QualType(), bool IsParenthesized=false)
unsigned NumParams
NumParams - This is the number of formal parameters specified by the declarator.
Definition: DeclSpec.h:1400
Represents a complete lambda introducer.
Definition: DeclSpec.h:2832
SmallVector< LambdaCapture, 4 > Captures
Definition: DeclSpec.h:2857
LambdaCaptureDefault Default
Definition: DeclSpec.h:2856
a linked list of methods with the same selector name but different signatures.
ObjCMethodDecl * getMethod() const
OverloadCandidate - A single candidate in an overload set (C++ 13.3).
Definition: Overload.h:848
static ArrayRef< const ParsedAttrInfo * > getAllBuiltin()
Definition: ParsedAttr.cpp:144
Describes how types, statements, expressions, and declarations should be printed.
Definition: PrettyPrinter.h:57
unsigned SuppressUnwrittenScope
Suppress printing parts of scope specifiers that are never written, e.g., for anonymous namespaces.
unsigned AnonymousTagLocations
When printing an anonymous tag name, also print the location of that entity (e.g.,...
unsigned CleanUglifiedParameters
Whether to strip underscores when printing reserved parameter names.
unsigned SuppressStrongLifetime
When true, suppress printing of the __strong lifetime qualifier in ARC.
unsigned SuppressScope
Suppresses printing of scope specifiers.
unsigned SuppressTemplateArgsInCXXConstructors
When true, suppresses printing template arguments in names of C++ constructors.