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