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