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