clang 20.0.0git
SemaCodeComplete.cpp
Go to the documentation of this file.
1//===---------------- SemaCodeComplete.cpp - Code Completion ----*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the code-completion semantic actions.
10//
11//===----------------------------------------------------------------------===//
13#include "clang/AST/Decl.h"
14#include "clang/AST/DeclBase.h"
15#include "clang/AST/DeclCXX.h"
16#include "clang/AST/DeclObjC.h"
18#include "clang/AST/Expr.h"
19#include "clang/AST/ExprCXX.h"
21#include "clang/AST/ExprObjC.h"
26#include "clang/AST/Type.h"
32#include "clang/Lex/MacroInfo.h"
35#include "clang/Sema/DeclSpec.h"
37#include "clang/Sema/Lookup.h"
38#include "clang/Sema/Overload.h"
41#include "clang/Sema/Scope.h"
43#include "clang/Sema/Sema.h"
46#include "clang/Sema/SemaObjC.h"
47#include "llvm/ADT/ArrayRef.h"
48#include "llvm/ADT/DenseSet.h"
49#include "llvm/ADT/SmallBitVector.h"
50#include "llvm/ADT/SmallPtrSet.h"
51#include "llvm/ADT/SmallString.h"
52#include "llvm/ADT/StringExtras.h"
53#include "llvm/ADT/StringSwitch.h"
54#include "llvm/ADT/Twine.h"
55#include "llvm/ADT/iterator_range.h"
56#include "llvm/Support/Casting.h"
57#include "llvm/Support/Path.h"
58#include "llvm/Support/raw_ostream.h"
59
60#include <list>
61#include <map>
62#include <optional>
63#include <string>
64#include <vector>
65
66using namespace clang;
67using namespace sema;
68
69namespace {
70/// A container of code-completion results.
71class ResultBuilder {
72public:
73 /// The type of a name-lookup filter, which can be provided to the
74 /// name-lookup routines to specify which declarations should be included in
75 /// the result set (when it returns true) and which declarations should be
76 /// filtered out (returns false).
77 typedef bool (ResultBuilder::*LookupFilter)(const NamedDecl *) const;
78
79 typedef CodeCompletionResult Result;
80
81private:
82 /// The actual results we have found.
83 std::vector<Result> Results;
84
85 /// A record of all of the declarations we have found and placed
86 /// into the result set, used to ensure that no declaration ever gets into
87 /// the result set twice.
89
90 typedef std::pair<const NamedDecl *, unsigned> DeclIndexPair;
91
92 /// An entry in the shadow map, which is optimized to store
93 /// a single (declaration, index) mapping (the common case) but
94 /// can also store a list of (declaration, index) mappings.
95 class ShadowMapEntry {
96 typedef SmallVector<DeclIndexPair, 4> DeclIndexPairVector;
97
98 /// Contains either the solitary NamedDecl * or a vector
99 /// of (declaration, index) pairs.
100 llvm::PointerUnion<const NamedDecl *, DeclIndexPairVector *> DeclOrVector;
101
102 /// When the entry contains a single declaration, this is
103 /// the index associated with that entry.
104 unsigned SingleDeclIndex = 0;
105
106 public:
107 ShadowMapEntry() = default;
108 ShadowMapEntry(const ShadowMapEntry &) = delete;
109 ShadowMapEntry(ShadowMapEntry &&Move) { *this = std::move(Move); }
110 ShadowMapEntry &operator=(const ShadowMapEntry &) = delete;
111 ShadowMapEntry &operator=(ShadowMapEntry &&Move) {
112 SingleDeclIndex = Move.SingleDeclIndex;
113 DeclOrVector = Move.DeclOrVector;
114 Move.DeclOrVector = nullptr;
115 return *this;
116 }
117
118 void Add(const NamedDecl *ND, unsigned Index) {
119 if (DeclOrVector.isNull()) {
120 // 0 - > 1 elements: just set the single element information.
121 DeclOrVector = ND;
122 SingleDeclIndex = Index;
123 return;
124 }
125
126 if (const NamedDecl *PrevND =
127 DeclOrVector.dyn_cast<const NamedDecl *>()) {
128 // 1 -> 2 elements: create the vector of results and push in the
129 // existing declaration.
130 DeclIndexPairVector *Vec = new DeclIndexPairVector;
131 Vec->push_back(DeclIndexPair(PrevND, SingleDeclIndex));
132 DeclOrVector = Vec;
133 }
134
135 // Add the new element to the end of the vector.
136 DeclOrVector.get<DeclIndexPairVector *>()->push_back(
137 DeclIndexPair(ND, Index));
138 }
139
140 ~ShadowMapEntry() {
141 if (DeclIndexPairVector *Vec =
142 DeclOrVector.dyn_cast<DeclIndexPairVector *>()) {
143 delete Vec;
144 DeclOrVector = ((NamedDecl *)nullptr);
145 }
146 }
147
148 // Iteration.
149 class iterator;
150 iterator begin() const;
151 iterator end() const;
152 };
153
154 /// A mapping from declaration names to the declarations that have
155 /// this name within a particular scope and their index within the list of
156 /// results.
157 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
158
159 /// The semantic analysis object for which results are being
160 /// produced.
161 Sema &SemaRef;
162
163 /// The allocator used to allocate new code-completion strings.
164 CodeCompletionAllocator &Allocator;
165
166 CodeCompletionTUInfo &CCTUInfo;
167
168 /// If non-NULL, a filter function used to remove any code-completion
169 /// results that are not desirable.
170 LookupFilter Filter;
171
172 /// Whether we should allow declarations as
173 /// nested-name-specifiers that would otherwise be filtered out.
174 bool AllowNestedNameSpecifiers;
175
176 /// If set, the type that we would prefer our resulting value
177 /// declarations to have.
178 ///
179 /// Closely matching the preferred type gives a boost to a result's
180 /// priority.
181 CanQualType PreferredType;
182
183 /// A list of shadow maps, which is used to model name hiding at
184 /// different levels of, e.g., the inheritance hierarchy.
185 std::list<ShadowMap> ShadowMaps;
186
187 /// Overloaded C++ member functions found by SemaLookup.
188 /// Used to determine when one overload is dominated by another.
189 llvm::DenseMap<std::pair<DeclContext *, /*Name*/uintptr_t>, ShadowMapEntry>
190 OverloadMap;
191
192 /// If we're potentially referring to a C++ member function, the set
193 /// of qualifiers applied to the object type.
194 Qualifiers ObjectTypeQualifiers;
195 /// The kind of the object expression, for rvalue/lvalue overloads.
196 ExprValueKind ObjectKind;
197
198 /// Whether the \p ObjectTypeQualifiers field is active.
199 bool HasObjectTypeQualifiers;
200
201 /// The selector that we prefer.
202 Selector PreferredSelector;
203
204 /// The completion context in which we are gathering results.
205 CodeCompletionContext CompletionContext;
206
207 /// If we are in an instance method definition, the \@implementation
208 /// object.
209 ObjCImplementationDecl *ObjCImplementation;
210
211 void AdjustResultPriorityForDecl(Result &R);
212
213 void MaybeAddConstructorResults(Result R);
214
215public:
216 explicit ResultBuilder(Sema &SemaRef, CodeCompletionAllocator &Allocator,
217 CodeCompletionTUInfo &CCTUInfo,
218 const CodeCompletionContext &CompletionContext,
219 LookupFilter Filter = nullptr)
220 : SemaRef(SemaRef), Allocator(Allocator), CCTUInfo(CCTUInfo),
221 Filter(Filter), AllowNestedNameSpecifiers(false),
222 HasObjectTypeQualifiers(false), CompletionContext(CompletionContext),
223 ObjCImplementation(nullptr) {
224 // If this is an Objective-C instance method definition, dig out the
225 // corresponding implementation.
226 switch (CompletionContext.getKind()) {
233 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl())
234 if (Method->isInstanceMethod())
235 if (ObjCInterfaceDecl *Interface = Method->getClassInterface())
236 ObjCImplementation = Interface->getImplementation();
237 break;
238
239 default:
240 break;
241 }
242 }
243
244 /// Determine the priority for a reference to the given declaration.
245 unsigned getBasePriority(const NamedDecl *D);
246
247 /// Whether we should include code patterns in the completion
248 /// results.
249 bool includeCodePatterns() const {
250 return SemaRef.CodeCompletion().CodeCompleter &&
252 }
253
254 /// Set the filter used for code-completion results.
255 void setFilter(LookupFilter Filter) { this->Filter = Filter; }
256
257 Result *data() { return Results.empty() ? nullptr : &Results.front(); }
258 unsigned size() const { return Results.size(); }
259 bool empty() const { return Results.empty(); }
260
261 /// Specify the preferred type.
262 void setPreferredType(QualType T) {
263 PreferredType = SemaRef.Context.getCanonicalType(T);
264 }
265
266 /// Set the cv-qualifiers on the object type, for us in filtering
267 /// calls to member functions.
268 ///
269 /// When there are qualifiers in this set, they will be used to filter
270 /// out member functions that aren't available (because there will be a
271 /// cv-qualifier mismatch) or prefer functions with an exact qualifier
272 /// match.
273 void setObjectTypeQualifiers(Qualifiers Quals, ExprValueKind Kind) {
274 ObjectTypeQualifiers = Quals;
275 ObjectKind = Kind;
276 HasObjectTypeQualifiers = true;
277 }
278
279 /// Set the preferred selector.
280 ///
281 /// When an Objective-C method declaration result is added, and that
282 /// method's selector matches this preferred selector, we give that method
283 /// a slight priority boost.
284 void setPreferredSelector(Selector Sel) { PreferredSelector = Sel; }
285
286 /// Retrieve the code-completion context for which results are
287 /// being collected.
288 const CodeCompletionContext &getCompletionContext() const {
289 return CompletionContext;
290 }
291
292 /// Specify whether nested-name-specifiers are allowed.
293 void allowNestedNameSpecifiers(bool Allow = true) {
294 AllowNestedNameSpecifiers = Allow;
295 }
296
297 /// Return the semantic analysis object for which we are collecting
298 /// code completion results.
299 Sema &getSema() const { return SemaRef; }
300
301 /// Retrieve the allocator used to allocate code completion strings.
302 CodeCompletionAllocator &getAllocator() const { return Allocator; }
303
304 CodeCompletionTUInfo &getCodeCompletionTUInfo() const { return CCTUInfo; }
305
306 /// Determine whether the given declaration is at all interesting
307 /// as a code-completion result.
308 ///
309 /// \param ND the declaration that we are inspecting.
310 ///
311 /// \param AsNestedNameSpecifier will be set true if this declaration is
312 /// only interesting when it is a nested-name-specifier.
313 bool isInterestingDecl(const NamedDecl *ND,
314 bool &AsNestedNameSpecifier) const;
315
316 /// Decide whether or not a use of function Decl can be a call.
317 ///
318 /// \param ND the function declaration.
319 ///
320 /// \param BaseExprType the object type in a member access expression,
321 /// if any.
322 bool canFunctionBeCalled(const NamedDecl *ND, QualType BaseExprType) const;
323
324 /// Decide whether or not a use of member function Decl can be a call.
325 ///
326 /// \param Method the function declaration.
327 ///
328 /// \param BaseExprType the object type in a member access expression,
329 /// if any.
330 bool canCxxMethodBeCalled(const CXXMethodDecl *Method,
331 QualType BaseExprType) const;
332
333 /// Check whether the result is hidden by the Hiding declaration.
334 ///
335 /// \returns true if the result is hidden and cannot be found, false if
336 /// the hidden result could still be found. When false, \p R may be
337 /// modified to describe how the result can be found (e.g., via extra
338 /// qualification).
339 bool CheckHiddenResult(Result &R, DeclContext *CurContext,
340 const NamedDecl *Hiding);
341
342 /// Add a new result to this result set (if it isn't already in one
343 /// of the shadow maps), or replace an existing result (for, e.g., a
344 /// redeclaration).
345 ///
346 /// \param R the result to add (if it is unique).
347 ///
348 /// \param CurContext the context in which this result will be named.
349 void MaybeAddResult(Result R, DeclContext *CurContext = nullptr);
350
351 /// Add a new result to this result set, where we already know
352 /// the hiding declaration (if any).
353 ///
354 /// \param R the result to add (if it is unique).
355 ///
356 /// \param CurContext the context in which this result will be named.
357 ///
358 /// \param Hiding the declaration that hides the result.
359 ///
360 /// \param InBaseClass whether the result was found in a base
361 /// class of the searched context.
362 ///
363 /// \param BaseExprType the type of expression that precedes the "." or "->"
364 /// in a member access expression.
365 void AddResult(Result R, DeclContext *CurContext, NamedDecl *Hiding,
366 bool InBaseClass, QualType BaseExprType);
367
368 /// Add a new non-declaration result to this result set.
369 void AddResult(Result R);
370
371 /// Enter into a new scope.
372 void EnterNewScope();
373
374 /// Exit from the current scope.
375 void ExitScope();
376
377 /// Ignore this declaration, if it is seen again.
378 void Ignore(const Decl *D) { AllDeclsFound.insert(D->getCanonicalDecl()); }
379
380 /// Add a visited context.
381 void addVisitedContext(DeclContext *Ctx) {
382 CompletionContext.addVisitedContext(Ctx);
383 }
384
385 /// \name Name lookup predicates
386 ///
387 /// These predicates can be passed to the name lookup functions to filter the
388 /// results of name lookup. All of the predicates have the same type, so that
389 ///
390 //@{
391 bool IsOrdinaryName(const NamedDecl *ND) const;
392 bool IsOrdinaryNonTypeName(const NamedDecl *ND) const;
393 bool IsIntegralConstantValue(const NamedDecl *ND) const;
394 bool IsOrdinaryNonValueName(const NamedDecl *ND) const;
395 bool IsNestedNameSpecifier(const NamedDecl *ND) const;
396 bool IsEnum(const NamedDecl *ND) const;
397 bool IsClassOrStruct(const NamedDecl *ND) const;
398 bool IsUnion(const NamedDecl *ND) const;
399 bool IsNamespace(const NamedDecl *ND) const;
400 bool IsNamespaceOrAlias(const NamedDecl *ND) const;
401 bool IsType(const NamedDecl *ND) const;
402 bool IsMember(const NamedDecl *ND) const;
403 bool IsObjCIvar(const NamedDecl *ND) const;
404 bool IsObjCMessageReceiver(const NamedDecl *ND) const;
405 bool IsObjCMessageReceiverOrLambdaCapture(const NamedDecl *ND) const;
406 bool IsObjCCollection(const NamedDecl *ND) const;
407 bool IsImpossibleToSatisfy(const NamedDecl *ND) const;
408 //@}
409};
410} // namespace
411
413 if (!Enabled)
414 return;
415 if (isa<BlockDecl>(S.CurContext)) {
416 if (sema::BlockScopeInfo *BSI = S.getCurBlock()) {
417 ComputeType = nullptr;
418 Type = BSI->ReturnType;
419 ExpectedLoc = Tok;
420 }
421 } else if (const auto *Function = dyn_cast<FunctionDecl>(S.CurContext)) {
422 ComputeType = nullptr;
423 Type = Function->getReturnType();
424 ExpectedLoc = Tok;
425 } else if (const auto *Method = dyn_cast<ObjCMethodDecl>(S.CurContext)) {
426 ComputeType = nullptr;
427 Type = Method->getReturnType();
428 ExpectedLoc = Tok;
429 }
430}
431
433 if (!Enabled)
434 return;
435 auto *VD = llvm::dyn_cast_or_null<ValueDecl>(D);
436 ComputeType = nullptr;
437 Type = VD ? VD->getType() : QualType();
438 ExpectedLoc = Tok;
439}
440
441static QualType getDesignatedType(QualType BaseType, const Designation &Desig);
442
444 QualType BaseType,
445 const Designation &D) {
446 if (!Enabled)
447 return;
448 ComputeType = nullptr;
449 Type = getDesignatedType(BaseType, D);
450 ExpectedLoc = Tok;
451}
452
454 SourceLocation Tok, llvm::function_ref<QualType()> ComputeType) {
455 if (!Enabled)
456 return;
457 this->ComputeType = ComputeType;
458 Type = QualType();
459 ExpectedLoc = Tok;
460}
461
463 SourceLocation LParLoc) {
464 if (!Enabled)
465 return;
466 // expected type for parenthesized expression does not change.
467 if (ExpectedLoc == LParLoc)
468 ExpectedLoc = Tok;
469}
470
472 tok::TokenKind Op) {
473 if (!LHS)
474 return QualType();
475
476 QualType LHSType = LHS->getType();
477 if (LHSType->isPointerType()) {
478 if (Op == tok::plus || Op == tok::plusequal || Op == tok::minusequal)
480 // Pointer difference is more common than subtracting an int from a pointer.
481 if (Op == tok::minus)
482 return LHSType;
483 }
484
485 switch (Op) {
486 // No way to infer the type of RHS from LHS.
487 case tok::comma:
488 return QualType();
489 // Prefer the type of the left operand for all of these.
490 // Arithmetic operations.
491 case tok::plus:
492 case tok::plusequal:
493 case tok::minus:
494 case tok::minusequal:
495 case tok::percent:
496 case tok::percentequal:
497 case tok::slash:
498 case tok::slashequal:
499 case tok::star:
500 case tok::starequal:
501 // Assignment.
502 case tok::equal:
503 // Comparison operators.
504 case tok::equalequal:
505 case tok::exclaimequal:
506 case tok::less:
507 case tok::lessequal:
508 case tok::greater:
509 case tok::greaterequal:
510 case tok::spaceship:
511 return LHS->getType();
512 // Binary shifts are often overloaded, so don't try to guess those.
513 case tok::greatergreater:
514 case tok::greatergreaterequal:
515 case tok::lessless:
516 case tok::lesslessequal:
517 if (LHSType->isIntegralOrEnumerationType())
518 return S.getASTContext().IntTy;
519 return QualType();
520 // Logical operators, assume we want bool.
521 case tok::ampamp:
522 case tok::pipepipe:
523 case tok::caretcaret:
524 return S.getASTContext().BoolTy;
525 // Operators often used for bit manipulation are typically used with the type
526 // of the left argument.
527 case tok::pipe:
528 case tok::pipeequal:
529 case tok::caret:
530 case tok::caretequal:
531 case tok::amp:
532 case tok::ampequal:
533 if (LHSType->isIntegralOrEnumerationType())
534 return LHSType;
535 return QualType();
536 // RHS should be a pointer to a member of the 'LHS' type, but we can't give
537 // any particular type here.
538 case tok::periodstar:
539 case tok::arrowstar:
540 return QualType();
541 default:
542 // FIXME(ibiryukov): handle the missing op, re-add the assertion.
543 // assert(false && "unhandled binary op");
544 return QualType();
545 }
546}
547
548/// Get preferred type for an argument of an unary expression. \p ContextType is
549/// preferred type of the whole unary expression.
551 tok::TokenKind Op) {
552 switch (Op) {
553 case tok::exclaim:
554 return S.getASTContext().BoolTy;
555 case tok::amp:
556 if (!ContextType.isNull() && ContextType->isPointerType())
557 return ContextType->getPointeeType();
558 return QualType();
559 case tok::star:
560 if (ContextType.isNull())
561 return QualType();
562 return S.getASTContext().getPointerType(ContextType.getNonReferenceType());
563 case tok::plus:
564 case tok::minus:
565 case tok::tilde:
566 case tok::minusminus:
567 case tok::plusplus:
568 if (ContextType.isNull())
569 return S.getASTContext().IntTy;
570 // leave as is, these operators typically return the same type.
571 return ContextType;
572 case tok::kw___real:
573 case tok::kw___imag:
574 return QualType();
575 default:
576 assert(false && "unhandled unary op");
577 return QualType();
578 }
579}
580
582 tok::TokenKind Op) {
583 if (!Enabled)
584 return;
585 ComputeType = nullptr;
586 Type = getPreferredTypeOfBinaryRHS(S, LHS, Op);
587 ExpectedLoc = Tok;
588}
589
591 Expr *Base) {
592 if (!Enabled || !Base)
593 return;
594 // Do we have expected type for Base?
595 if (ExpectedLoc != Base->getBeginLoc())
596 return;
597 // Keep the expected type, only update the location.
598 ExpectedLoc = Tok;
599}
600
602 tok::TokenKind OpKind,
603 SourceLocation OpLoc) {
604 if (!Enabled)
605 return;
606 ComputeType = nullptr;
607 Type = getPreferredTypeOfUnaryArg(S, this->get(OpLoc), OpKind);
608 ExpectedLoc = Tok;
609}
610
612 Expr *LHS) {
613 if (!Enabled)
614 return;
615 ComputeType = nullptr;
617 ExpectedLoc = Tok;
618}
619
622 if (!Enabled)
623 return;
624 ComputeType = nullptr;
625 Type = !CastType.isNull() ? CastType.getCanonicalType() : QualType();
626 ExpectedLoc = Tok;
627}
628
630 if (!Enabled)
631 return;
632 ComputeType = nullptr;
634 ExpectedLoc = Tok;
635}
636
638 llvm::PointerUnion<const NamedDecl *, const DeclIndexPair *> DeclOrIterator;
639 unsigned SingleDeclIndex;
640
641public:
642 typedef DeclIndexPair value_type;
644 typedef std::ptrdiff_t difference_type;
645 typedef std::input_iterator_tag iterator_category;
646
647 class pointer {
648 DeclIndexPair Value;
649
650 public:
651 pointer(const DeclIndexPair &Value) : Value(Value) {}
652
653 const DeclIndexPair *operator->() const { return &Value; }
654 };
655
656 iterator() : DeclOrIterator((NamedDecl *)nullptr), SingleDeclIndex(0) {}
657
658 iterator(const NamedDecl *SingleDecl, unsigned Index)
659 : DeclOrIterator(SingleDecl), SingleDeclIndex(Index) {}
660
661 iterator(const DeclIndexPair *Iterator)
662 : DeclOrIterator(Iterator), SingleDeclIndex(0) {}
663
665 if (DeclOrIterator.is<const NamedDecl *>()) {
666 DeclOrIterator = (NamedDecl *)nullptr;
667 SingleDeclIndex = 0;
668 return *this;
669 }
670
671 const DeclIndexPair *I = DeclOrIterator.get<const DeclIndexPair *>();
672 ++I;
673 DeclOrIterator = I;
674 return *this;
675 }
676
677 /*iterator operator++(int) {
678 iterator tmp(*this);
679 ++(*this);
680 return tmp;
681 }*/
682
684 if (const NamedDecl *ND = DeclOrIterator.dyn_cast<const NamedDecl *>())
685 return reference(ND, SingleDeclIndex);
686
687 return *DeclOrIterator.get<const DeclIndexPair *>();
688 }
689
690 pointer operator->() const { return pointer(**this); }
691
692 friend bool operator==(const iterator &X, const iterator &Y) {
693 return X.DeclOrIterator.getOpaqueValue() ==
694 Y.DeclOrIterator.getOpaqueValue() &&
695 X.SingleDeclIndex == Y.SingleDeclIndex;
696 }
697
698 friend bool operator!=(const iterator &X, const iterator &Y) {
699 return !(X == Y);
700 }
701};
702
704ResultBuilder::ShadowMapEntry::begin() const {
705 if (DeclOrVector.isNull())
706 return iterator();
707
708 if (const NamedDecl *ND = DeclOrVector.dyn_cast<const NamedDecl *>())
709 return iterator(ND, SingleDeclIndex);
710
711 return iterator(DeclOrVector.get<DeclIndexPairVector *>()->begin());
712}
713
715ResultBuilder::ShadowMapEntry::end() const {
716 if (DeclOrVector.is<const NamedDecl *>() || DeclOrVector.isNull())
717 return iterator();
718
719 return iterator(DeclOrVector.get<DeclIndexPairVector *>()->end());
720}
721
722/// Compute the qualification required to get from the current context
723/// (\p CurContext) to the target context (\p TargetContext).
724///
725/// \param Context the AST context in which the qualification will be used.
726///
727/// \param CurContext the context where an entity is being named, which is
728/// typically based on the current scope.
729///
730/// \param TargetContext the context in which the named entity actually
731/// resides.
732///
733/// \returns a nested name specifier that refers into the target context, or
734/// NULL if no qualification is needed.
735static NestedNameSpecifier *
737 const DeclContext *TargetContext) {
739
740 for (const DeclContext *CommonAncestor = TargetContext;
741 CommonAncestor && !CommonAncestor->Encloses(CurContext);
742 CommonAncestor = CommonAncestor->getLookupParent()) {
743 if (CommonAncestor->isTransparentContext() ||
744 CommonAncestor->isFunctionOrMethod())
745 continue;
746
747 TargetParents.push_back(CommonAncestor);
748 }
749
750 NestedNameSpecifier *Result = nullptr;
751 while (!TargetParents.empty()) {
752 const DeclContext *Parent = TargetParents.pop_back_val();
753
754 if (const auto *Namespace = dyn_cast<NamespaceDecl>(Parent)) {
755 if (!Namespace->getIdentifier())
756 continue;
757
758 Result = NestedNameSpecifier::Create(Context, Result, Namespace);
759 } else if (const auto *TD = dyn_cast<TagDecl>(Parent))
761 Context, Result, false, Context.getTypeDeclType(TD).getTypePtr());
762 }
763 return Result;
764}
765
766// Some declarations have reserved names that we don't want to ever show.
767// Filter out names reserved for the implementation if they come from a
768// system header.
769static bool shouldIgnoreDueToReservedName(const NamedDecl *ND, Sema &SemaRef) {
770 // Debuggers want access to all identifiers, including reserved ones.
771 if (SemaRef.getLangOpts().DebuggerSupport)
772 return false;
773
774 ReservedIdentifierStatus Status = ND->isReserved(SemaRef.getLangOpts());
775 // Ignore reserved names for compiler provided decls.
776 if (isReservedInAllContexts(Status) && ND->getLocation().isInvalid())
777 return true;
778
779 // For system headers ignore only double-underscore names.
780 // This allows for system headers providing private symbols with a single
781 // underscore.
784 SemaRef.SourceMgr.getSpellingLoc(ND->getLocation())))
785 return true;
786
787 return false;
788}
789
790bool ResultBuilder::isInterestingDecl(const NamedDecl *ND,
791 bool &AsNestedNameSpecifier) const {
792 AsNestedNameSpecifier = false;
793
794 auto *Named = ND;
795 ND = ND->getUnderlyingDecl();
796
797 // Skip unnamed entities.
798 if (!ND->getDeclName())
799 return false;
800
801 // Friend declarations and declarations introduced due to friends are never
802 // added as results.
804 return false;
805
806 // Class template (partial) specializations are never added as results.
807 if (isa<ClassTemplateSpecializationDecl>(ND) ||
808 isa<ClassTemplatePartialSpecializationDecl>(ND))
809 return false;
810
811 // Using declarations themselves are never added as results.
812 if (isa<UsingDecl>(ND))
813 return false;
814
815 if (shouldIgnoreDueToReservedName(ND, SemaRef))
816 return false;
817
818 if (Filter == &ResultBuilder::IsNestedNameSpecifier ||
819 (isa<NamespaceDecl>(ND) && Filter != &ResultBuilder::IsNamespace &&
820 Filter != &ResultBuilder::IsNamespaceOrAlias && Filter != nullptr))
821 AsNestedNameSpecifier = true;
822
823 // Filter out any unwanted results.
824 if (Filter && !(this->*Filter)(Named)) {
825 // Check whether it is interesting as a nested-name-specifier.
826 if (AllowNestedNameSpecifiers && SemaRef.getLangOpts().CPlusPlus &&
827 IsNestedNameSpecifier(ND) &&
828 (Filter != &ResultBuilder::IsMember ||
829 (isa<CXXRecordDecl>(ND) &&
830 cast<CXXRecordDecl>(ND)->isInjectedClassName()))) {
831 AsNestedNameSpecifier = true;
832 return true;
833 }
834
835 return false;
836 }
837 // ... then it must be interesting!
838 return true;
839}
840
841bool ResultBuilder::CheckHiddenResult(Result &R, DeclContext *CurContext,
842 const NamedDecl *Hiding) {
843 // In C, there is no way to refer to a hidden name.
844 // FIXME: This isn't true; we can find a tag name hidden by an ordinary
845 // name if we introduce the tag type.
846 if (!SemaRef.getLangOpts().CPlusPlus)
847 return true;
848
849 const DeclContext *HiddenCtx =
850 R.Declaration->getDeclContext()->getRedeclContext();
851
852 // There is no way to qualify a name declared in a function or method.
853 if (HiddenCtx->isFunctionOrMethod())
854 return true;
855
856 if (HiddenCtx == Hiding->getDeclContext()->getRedeclContext())
857 return true;
858
859 // We can refer to the result with the appropriate qualification. Do it.
860 R.Hidden = true;
861 R.QualifierIsInformative = false;
862
863 if (!R.Qualifier)
864 R.Qualifier = getRequiredQualification(SemaRef.Context, CurContext,
865 R.Declaration->getDeclContext());
866 return false;
867}
868
869/// A simplified classification of types used to determine whether two
870/// types are "similar enough" when adjusting priorities.
872 switch (T->getTypeClass()) {
873 case Type::Builtin:
874 switch (cast<BuiltinType>(T)->getKind()) {
875 case BuiltinType::Void:
876 return STC_Void;
877
878 case BuiltinType::NullPtr:
879 return STC_Pointer;
880
881 case BuiltinType::Overload:
882 case BuiltinType::Dependent:
883 return STC_Other;
884
885 case BuiltinType::ObjCId:
886 case BuiltinType::ObjCClass:
887 case BuiltinType::ObjCSel:
888 return STC_ObjectiveC;
889
890 default:
891 return STC_Arithmetic;
892 }
893
894 case Type::Complex:
895 return STC_Arithmetic;
896
897 case Type::Pointer:
898 return STC_Pointer;
899
900 case Type::BlockPointer:
901 return STC_Block;
902
903 case Type::LValueReference:
904 case Type::RValueReference:
906
907 case Type::ConstantArray:
908 case Type::IncompleteArray:
909 case Type::VariableArray:
910 case Type::DependentSizedArray:
911 return STC_Array;
912
913 case Type::DependentSizedExtVector:
914 case Type::Vector:
915 case Type::ExtVector:
916 return STC_Arithmetic;
917
918 case Type::FunctionProto:
919 case Type::FunctionNoProto:
920 return STC_Function;
921
922 case Type::Record:
923 return STC_Record;
924
925 case Type::Enum:
926 return STC_Arithmetic;
927
928 case Type::ObjCObject:
929 case Type::ObjCInterface:
930 case Type::ObjCObjectPointer:
931 return STC_ObjectiveC;
932
933 default:
934 return STC_Other;
935 }
936}
937
938/// Get the type that a given expression will have if this declaration
939/// is used as an expression in its "typical" code-completion form.
941 ND = ND->getUnderlyingDecl();
942
943 if (const auto *Type = dyn_cast<TypeDecl>(ND))
944 return C.getTypeDeclType(Type);
945 if (const auto *Iface = dyn_cast<ObjCInterfaceDecl>(ND))
946 return C.getObjCInterfaceType(Iface);
947
948 QualType T;
949 if (const FunctionDecl *Function = ND->getAsFunction())
950 T = Function->getCallResultType();
951 else if (const auto *Method = dyn_cast<ObjCMethodDecl>(ND))
952 T = Method->getSendResultType();
953 else if (const auto *Enumerator = dyn_cast<EnumConstantDecl>(ND))
954 T = C.getTypeDeclType(cast<EnumDecl>(Enumerator->getDeclContext()));
955 else if (const auto *Property = dyn_cast<ObjCPropertyDecl>(ND))
956 T = Property->getType();
957 else if (const auto *Value = dyn_cast<ValueDecl>(ND))
958 T = Value->getType();
959
960 if (T.isNull())
961 return QualType();
962
963 // Dig through references, function pointers, and block pointers to
964 // get down to the likely type of an expression when the entity is
965 // used.
966 do {
967 if (const auto *Ref = T->getAs<ReferenceType>()) {
968 T = Ref->getPointeeType();
969 continue;
970 }
971
972 if (const auto *Pointer = T->getAs<PointerType>()) {
973 if (Pointer->getPointeeType()->isFunctionType()) {
974 T = Pointer->getPointeeType();
975 continue;
976 }
977
978 break;
979 }
980
981 if (const auto *Block = T->getAs<BlockPointerType>()) {
982 T = Block->getPointeeType();
983 continue;
984 }
985
986 if (const auto *Function = T->getAs<FunctionType>()) {
987 T = Function->getReturnType();
988 continue;
989 }
990
991 break;
992 } while (true);
993
994 return T;
995}
996
997unsigned ResultBuilder::getBasePriority(const NamedDecl *ND) {
998 if (!ND)
999 return CCP_Unlikely;
1000
1001 // Context-based decisions.
1002 const DeclContext *LexicalDC = ND->getLexicalDeclContext();
1003 if (LexicalDC->isFunctionOrMethod()) {
1004 // _cmd is relatively rare
1005 if (const auto *ImplicitParam = dyn_cast<ImplicitParamDecl>(ND))
1006 if (ImplicitParam->getIdentifier() &&
1007 ImplicitParam->getIdentifier()->isStr("_cmd"))
1008 return CCP_ObjC_cmd;
1009
1010 return CCP_LocalDeclaration;
1011 }
1012
1013 const DeclContext *DC = ND->getDeclContext()->getRedeclContext();
1014 if (DC->isRecord() || isa<ObjCContainerDecl>(DC)) {
1015 // Explicit destructor calls are very rare.
1016 if (isa<CXXDestructorDecl>(ND))
1017 return CCP_Unlikely;
1018 // Explicit operator and conversion function calls are also very rare.
1019 auto DeclNameKind = ND->getDeclName().getNameKind();
1020 if (DeclNameKind == DeclarationName::CXXOperatorName ||
1023 return CCP_Unlikely;
1024 return CCP_MemberDeclaration;
1025 }
1026
1027 // Content-based decisions.
1028 if (isa<EnumConstantDecl>(ND))
1029 return CCP_Constant;
1030
1031 // Use CCP_Type for type declarations unless we're in a statement, Objective-C
1032 // message receiver, or parenthesized expression context. There, it's as
1033 // likely that the user will want to write a type as other declarations.
1034 if ((isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) &&
1035 !(CompletionContext.getKind() == CodeCompletionContext::CCC_Statement ||
1036 CompletionContext.getKind() ==
1038 CompletionContext.getKind() ==
1040 return CCP_Type;
1041
1042 return CCP_Declaration;
1043}
1044
1045void ResultBuilder::AdjustResultPriorityForDecl(Result &R) {
1046 // If this is an Objective-C method declaration whose selector matches our
1047 // preferred selector, give it a priority boost.
1048 if (!PreferredSelector.isNull())
1049 if (const auto *Method = dyn_cast<ObjCMethodDecl>(R.Declaration))
1050 if (PreferredSelector == Method->getSelector())
1051 R.Priority += CCD_SelectorMatch;
1052
1053 // If we have a preferred type, adjust the priority for results with exactly-
1054 // matching or nearly-matching types.
1055 if (!PreferredType.isNull()) {
1056 QualType T = getDeclUsageType(SemaRef.Context, R.Declaration);
1057 if (!T.isNull()) {
1058 CanQualType TC = SemaRef.Context.getCanonicalType(T);
1059 // Check for exactly-matching types (modulo qualifiers).
1060 if (SemaRef.Context.hasSameUnqualifiedType(PreferredType, TC))
1061 R.Priority /= CCF_ExactTypeMatch;
1062 // Check for nearly-matching types, based on classification of each.
1063 else if ((getSimplifiedTypeClass(PreferredType) ==
1065 !(PreferredType->isEnumeralType() && TC->isEnumeralType()))
1066 R.Priority /= CCF_SimilarTypeMatch;
1067 }
1068 }
1069}
1070
1072 const CXXRecordDecl *Record) {
1073 QualType RecordTy = Context.getTypeDeclType(Record);
1074 DeclarationName ConstructorName =
1076 Context.getCanonicalType(RecordTy));
1077 return Record->lookup(ConstructorName);
1078}
1079
1080void ResultBuilder::MaybeAddConstructorResults(Result R) {
1081 if (!SemaRef.getLangOpts().CPlusPlus || !R.Declaration ||
1082 !CompletionContext.wantConstructorResults())
1083 return;
1084
1085 const NamedDecl *D = R.Declaration;
1086 const CXXRecordDecl *Record = nullptr;
1087 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D))
1088 Record = ClassTemplate->getTemplatedDecl();
1089 else if ((Record = dyn_cast<CXXRecordDecl>(D))) {
1090 // Skip specializations and partial specializations.
1091 if (isa<ClassTemplateSpecializationDecl>(Record))
1092 return;
1093 } else {
1094 // There are no constructors here.
1095 return;
1096 }
1097
1099 if (!Record)
1100 return;
1101
1102 for (NamedDecl *Ctor : getConstructors(SemaRef.Context, Record)) {
1103 R.Declaration = Ctor;
1104 R.CursorKind = getCursorKindForDecl(R.Declaration);
1105 Results.push_back(R);
1106 }
1107}
1108
1109static bool isConstructor(const Decl *ND) {
1110 if (const auto *Tmpl = dyn_cast<FunctionTemplateDecl>(ND))
1111 ND = Tmpl->getTemplatedDecl();
1112 return isa<CXXConstructorDecl>(ND);
1113}
1114
1115void ResultBuilder::MaybeAddResult(Result R, DeclContext *CurContext) {
1116 assert(!ShadowMaps.empty() && "Must enter into a results scope");
1117
1118 if (R.Kind != Result::RK_Declaration) {
1119 // For non-declaration results, just add the result.
1120 Results.push_back(R);
1121 return;
1122 }
1123
1124 // Look through using declarations.
1125 if (const UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
1126 CodeCompletionResult Result(Using->getTargetDecl(),
1127 getBasePriority(Using->getTargetDecl()),
1128 R.Qualifier, false,
1129 (R.Availability == CXAvailability_Available ||
1130 R.Availability == CXAvailability_Deprecated),
1131 std::move(R.FixIts));
1132 Result.ShadowDecl = Using;
1133 MaybeAddResult(Result, CurContext);
1134 return;
1135 }
1136
1137 const Decl *CanonDecl = R.Declaration->getCanonicalDecl();
1138 unsigned IDNS = CanonDecl->getIdentifierNamespace();
1139
1140 bool AsNestedNameSpecifier = false;
1141 if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
1142 return;
1143
1144 // C++ constructors are never found by name lookup.
1145 if (isConstructor(R.Declaration))
1146 return;
1147
1148 ShadowMap &SMap = ShadowMaps.back();
1149 ShadowMapEntry::iterator I, IEnd;
1150 ShadowMap::iterator NamePos = SMap.find(R.Declaration->getDeclName());
1151 if (NamePos != SMap.end()) {
1152 I = NamePos->second.begin();
1153 IEnd = NamePos->second.end();
1154 }
1155
1156 for (; I != IEnd; ++I) {
1157 const NamedDecl *ND = I->first;
1158 unsigned Index = I->second;
1159 if (ND->getCanonicalDecl() == CanonDecl) {
1160 // This is a redeclaration. Always pick the newer declaration.
1161 Results[Index].Declaration = R.Declaration;
1162
1163 // We're done.
1164 return;
1165 }
1166 }
1167
1168 // This is a new declaration in this scope. However, check whether this
1169 // declaration name is hidden by a similarly-named declaration in an outer
1170 // scope.
1171 std::list<ShadowMap>::iterator SM, SMEnd = ShadowMaps.end();
1172 --SMEnd;
1173 for (SM = ShadowMaps.begin(); SM != SMEnd; ++SM) {
1174 ShadowMapEntry::iterator I, IEnd;
1175 ShadowMap::iterator NamePos = SM->find(R.Declaration->getDeclName());
1176 if (NamePos != SM->end()) {
1177 I = NamePos->second.begin();
1178 IEnd = NamePos->second.end();
1179 }
1180 for (; I != IEnd; ++I) {
1181 // A tag declaration does not hide a non-tag declaration.
1182 if (I->first->hasTagIdentifierNamespace() &&
1185 continue;
1186
1187 // Protocols are in distinct namespaces from everything else.
1188 if (((I->first->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol) ||
1189 (IDNS & Decl::IDNS_ObjCProtocol)) &&
1190 I->first->getIdentifierNamespace() != IDNS)
1191 continue;
1192
1193 // The newly-added result is hidden by an entry in the shadow map.
1194 if (CheckHiddenResult(R, CurContext, I->first))
1195 return;
1196
1197 break;
1198 }
1199 }
1200
1201 // Make sure that any given declaration only shows up in the result set once.
1202 if (!AllDeclsFound.insert(CanonDecl).second)
1203 return;
1204
1205 // If the filter is for nested-name-specifiers, then this result starts a
1206 // nested-name-specifier.
1207 if (AsNestedNameSpecifier) {
1208 R.StartsNestedNameSpecifier = true;
1209 R.Priority = CCP_NestedNameSpecifier;
1210 } else
1211 AdjustResultPriorityForDecl(R);
1212
1213 // If this result is supposed to have an informative qualifier, add one.
1214 if (R.QualifierIsInformative && !R.Qualifier &&
1215 !R.StartsNestedNameSpecifier) {
1216 const DeclContext *Ctx = R.Declaration->getDeclContext();
1217 if (const NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
1218 R.Qualifier =
1219 NestedNameSpecifier::Create(SemaRef.Context, nullptr, Namespace);
1220 else if (const TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
1221 R.Qualifier = NestedNameSpecifier::Create(
1222 SemaRef.Context, nullptr, false,
1223 SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
1224 else
1225 R.QualifierIsInformative = false;
1226 }
1227
1228 // Insert this result into the set of results and into the current shadow
1229 // map.
1230 SMap[R.Declaration->getDeclName()].Add(R.Declaration, Results.size());
1231 Results.push_back(R);
1232
1233 if (!AsNestedNameSpecifier)
1234 MaybeAddConstructorResults(R);
1235}
1236
1239 R.InBaseClass = true;
1240}
1241
1243// Will Candidate ever be called on the object, when overloaded with Incumbent?
1244// Returns Dominates if Candidate is always called, Dominated if Incumbent is
1245// always called, BothViable if either may be called depending on arguments.
1246// Precondition: must actually be overloads!
1248 const CXXMethodDecl &Incumbent,
1249 const Qualifiers &ObjectQuals,
1250 ExprValueKind ObjectKind) {
1251 // Base/derived shadowing is handled elsewhere.
1252 if (Candidate.getDeclContext() != Incumbent.getDeclContext())
1253 return OverloadCompare::BothViable;
1254 if (Candidate.isVariadic() != Incumbent.isVariadic() ||
1255 Candidate.getNumParams() != Incumbent.getNumParams() ||
1256 Candidate.getMinRequiredArguments() !=
1257 Incumbent.getMinRequiredArguments())
1258 return OverloadCompare::BothViable;
1259 for (unsigned I = 0, E = Candidate.getNumParams(); I != E; ++I)
1260 if (Candidate.parameters()[I]->getType().getCanonicalType() !=
1261 Incumbent.parameters()[I]->getType().getCanonicalType())
1262 return OverloadCompare::BothViable;
1263 if (!Candidate.specific_attrs<EnableIfAttr>().empty() ||
1264 !Incumbent.specific_attrs<EnableIfAttr>().empty())
1265 return OverloadCompare::BothViable;
1266 // At this point, we know calls can't pick one or the other based on
1267 // arguments, so one of the two must win. (Or both fail, handled elsewhere).
1268 RefQualifierKind CandidateRef = Candidate.getRefQualifier();
1269 RefQualifierKind IncumbentRef = Incumbent.getRefQualifier();
1270 if (CandidateRef != IncumbentRef) {
1271 // If the object kind is LValue/RValue, there's one acceptable ref-qualifier
1272 // and it can't be mixed with ref-unqualified overloads (in valid code).
1273
1274 // For xvalue objects, we prefer the rvalue overload even if we have to
1275 // add qualifiers (which is rare, because const&& is rare).
1276 if (ObjectKind == clang::VK_XValue)
1277 return CandidateRef == RQ_RValue ? OverloadCompare::Dominates
1278 : OverloadCompare::Dominated;
1279 }
1280 // Now the ref qualifiers are the same (or we're in some invalid state).
1281 // So make some decision based on the qualifiers.
1282 Qualifiers CandidateQual = Candidate.getMethodQualifiers();
1283 Qualifiers IncumbentQual = Incumbent.getMethodQualifiers();
1284 bool CandidateSuperset = CandidateQual.compatiblyIncludes(IncumbentQual);
1285 bool IncumbentSuperset = IncumbentQual.compatiblyIncludes(CandidateQual);
1286 if (CandidateSuperset == IncumbentSuperset)
1287 return OverloadCompare::BothViable;
1288 return IncumbentSuperset ? OverloadCompare::Dominates
1289 : OverloadCompare::Dominated;
1290}
1291
1292bool ResultBuilder::canCxxMethodBeCalled(const CXXMethodDecl *Method,
1293 QualType BaseExprType) const {
1294 // Find the class scope that we're currently in.
1295 // We could e.g. be inside a lambda, so walk up the DeclContext until we
1296 // find a CXXMethodDecl.
1297 DeclContext *CurContext = SemaRef.CurContext;
1298 const auto *CurrentClassScope = [&]() -> const CXXRecordDecl * {
1299 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getParent()) {
1300 const auto *CtxMethod = llvm::dyn_cast<CXXMethodDecl>(Ctx);
1301 if (CtxMethod && !CtxMethod->getParent()->isLambda()) {
1302 return CtxMethod->getParent();
1303 }
1304 }
1305 return nullptr;
1306 }();
1307
1308 // If we're not inside the scope of the method's class, it can't be a call.
1309 bool FunctionCanBeCall =
1310 CurrentClassScope &&
1311 (CurrentClassScope == Method->getParent() ||
1312 CurrentClassScope->isDerivedFrom(Method->getParent()));
1313
1314 // We skip the following calculation for exceptions if it's already true.
1315 if (FunctionCanBeCall)
1316 return true;
1317
1318 // Exception: foo->FooBase::bar() or foo->Foo::bar() *is* a call.
1319 if (const CXXRecordDecl *MaybeDerived =
1320 BaseExprType.isNull() ? nullptr
1321 : BaseExprType->getAsCXXRecordDecl()) {
1322 auto *MaybeBase = Method->getParent();
1323 FunctionCanBeCall =
1324 MaybeDerived == MaybeBase || MaybeDerived->isDerivedFrom(MaybeBase);
1325 }
1326
1327 return FunctionCanBeCall;
1328}
1329
1330bool ResultBuilder::canFunctionBeCalled(const NamedDecl *ND,
1331 QualType BaseExprType) const {
1332 // We apply heuristics only to CCC_Symbol:
1333 // * CCC_{Arrow,Dot}MemberAccess reflect member access expressions:
1334 // f.method() and f->method(). These are always calls.
1335 // * A qualified name to a member function may *not* be a call. We have to
1336 // subdivide the cases: For example, f.Base::method(), which is regarded as
1337 // CCC_Symbol, should be a call.
1338 // * Non-member functions and static member functions are always considered
1339 // calls.
1340 if (CompletionContext.getKind() == clang::CodeCompletionContext::CCC_Symbol) {
1341 if (const auto *FuncTmpl = dyn_cast<FunctionTemplateDecl>(ND)) {
1342 ND = FuncTmpl->getTemplatedDecl();
1343 }
1344 const auto *Method = dyn_cast<CXXMethodDecl>(ND);
1345 if (Method && !Method->isStatic()) {
1346 return canCxxMethodBeCalled(Method, BaseExprType);
1347 }
1348 }
1349 return true;
1350}
1351
1352void ResultBuilder::AddResult(Result R, DeclContext *CurContext,
1353 NamedDecl *Hiding, bool InBaseClass = false,
1354 QualType BaseExprType = QualType()) {
1355 if (R.Kind != Result::RK_Declaration) {
1356 // For non-declaration results, just add the result.
1357 Results.push_back(R);
1358 return;
1359 }
1360
1361 // Look through using declarations.
1362 if (const auto *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
1363 CodeCompletionResult Result(Using->getTargetDecl(),
1364 getBasePriority(Using->getTargetDecl()),
1365 R.Qualifier, false,
1366 (R.Availability == CXAvailability_Available ||
1367 R.Availability == CXAvailability_Deprecated),
1368 std::move(R.FixIts));
1369 Result.ShadowDecl = Using;
1370 AddResult(Result, CurContext, Hiding, /*InBaseClass=*/false,
1371 /*BaseExprType=*/BaseExprType);
1372 return;
1373 }
1374
1375 bool AsNestedNameSpecifier = false;
1376 if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
1377 return;
1378
1379 // C++ constructors are never found by name lookup.
1380 if (isConstructor(R.Declaration))
1381 return;
1382
1383 if (Hiding && CheckHiddenResult(R, CurContext, Hiding))
1384 return;
1385
1386 // Make sure that any given declaration only shows up in the result set once.
1387 if (!AllDeclsFound.insert(R.Declaration->getCanonicalDecl()).second)
1388 return;
1389
1390 // If the filter is for nested-name-specifiers, then this result starts a
1391 // nested-name-specifier.
1392 if (AsNestedNameSpecifier) {
1393 R.StartsNestedNameSpecifier = true;
1394 R.Priority = CCP_NestedNameSpecifier;
1395 } else if (Filter == &ResultBuilder::IsMember && !R.Qualifier &&
1396 InBaseClass &&
1397 isa<CXXRecordDecl>(
1398 R.Declaration->getDeclContext()->getRedeclContext()))
1399 R.QualifierIsInformative = true;
1400
1401 // If this result is supposed to have an informative qualifier, add one.
1402 if (R.QualifierIsInformative && !R.Qualifier &&
1403 !R.StartsNestedNameSpecifier) {
1404 const DeclContext *Ctx = R.Declaration->getDeclContext();
1405 if (const auto *Namespace = dyn_cast<NamespaceDecl>(Ctx))
1406 R.Qualifier =
1407 NestedNameSpecifier::Create(SemaRef.Context, nullptr, Namespace);
1408 else if (const auto *Tag = dyn_cast<TagDecl>(Ctx))
1409 R.Qualifier = NestedNameSpecifier::Create(
1410 SemaRef.Context, nullptr, false,
1411 SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
1412 else
1413 R.QualifierIsInformative = false;
1414 }
1415
1416 // Adjust the priority if this result comes from a base class.
1417 if (InBaseClass)
1418 setInBaseClass(R);
1419
1420 AdjustResultPriorityForDecl(R);
1421
1422 if (HasObjectTypeQualifiers)
1423 if (const auto *Method = dyn_cast<CXXMethodDecl>(R.Declaration))
1424 if (Method->isInstance()) {
1425 Qualifiers MethodQuals = Method->getMethodQualifiers();
1426 if (ObjectTypeQualifiers == MethodQuals)
1427 R.Priority += CCD_ObjectQualifierMatch;
1428 else if (ObjectTypeQualifiers - MethodQuals) {
1429 // The method cannot be invoked, because doing so would drop
1430 // qualifiers.
1431 return;
1432 }
1433 // Detect cases where a ref-qualified method cannot be invoked.
1434 switch (Method->getRefQualifier()) {
1435 case RQ_LValue:
1436 if (ObjectKind != VK_LValue && !MethodQuals.hasConst())
1437 return;
1438 break;
1439 case RQ_RValue:
1440 if (ObjectKind == VK_LValue)
1441 return;
1442 break;
1443 case RQ_None:
1444 break;
1445 }
1446
1447 /// Check whether this dominates another overloaded method, which should
1448 /// be suppressed (or vice versa).
1449 /// Motivating case is const_iterator begin() const vs iterator begin().
1450 auto &OverloadSet = OverloadMap[std::make_pair(
1451 CurContext, Method->getDeclName().getAsOpaqueInteger())];
1452 for (const DeclIndexPair Entry : OverloadSet) {
1453 Result &Incumbent = Results[Entry.second];
1454 switch (compareOverloads(*Method,
1455 *cast<CXXMethodDecl>(Incumbent.Declaration),
1456 ObjectTypeQualifiers, ObjectKind)) {
1457 case OverloadCompare::Dominates:
1458 // Replace the dominated overload with this one.
1459 // FIXME: if the overload dominates multiple incumbents then we
1460 // should remove all. But two overloads is by far the common case.
1461 Incumbent = std::move(R);
1462 return;
1463 case OverloadCompare::Dominated:
1464 // This overload can't be called, drop it.
1465 return;
1466 case OverloadCompare::BothViable:
1467 break;
1468 }
1469 }
1470 OverloadSet.Add(Method, Results.size());
1471 }
1472
1473 R.FunctionCanBeCall = canFunctionBeCalled(R.getDeclaration(), BaseExprType);
1474
1475 // Insert this result into the set of results.
1476 Results.push_back(R);
1477
1478 if (!AsNestedNameSpecifier)
1479 MaybeAddConstructorResults(R);
1480}
1481
1482void ResultBuilder::AddResult(Result R) {
1483 assert(R.Kind != Result::RK_Declaration &&
1484 "Declaration results need more context");
1485 Results.push_back(R);
1486}
1487
1488/// Enter into a new scope.
1489void ResultBuilder::EnterNewScope() { ShadowMaps.emplace_back(); }
1490
1491/// Exit from the current scope.
1492void ResultBuilder::ExitScope() {
1493 ShadowMaps.pop_back();
1494}
1495
1496/// Determines whether this given declaration will be found by
1497/// ordinary name lookup.
1498bool ResultBuilder::IsOrdinaryName(const NamedDecl *ND) const {
1499 ND = ND->getUnderlyingDecl();
1500
1501 // If name lookup finds a local extern declaration, then we are in a
1502 // context where it behaves like an ordinary name.
1504 if (SemaRef.getLangOpts().CPlusPlus)
1506 else if (SemaRef.getLangOpts().ObjC) {
1507 if (isa<ObjCIvarDecl>(ND))
1508 return true;
1509 }
1510
1511 return ND->getIdentifierNamespace() & IDNS;
1512}
1513
1514/// Determines whether this given declaration will be found by
1515/// ordinary name lookup but is not a type name.
1516bool ResultBuilder::IsOrdinaryNonTypeName(const NamedDecl *ND) const {
1517 ND = ND->getUnderlyingDecl();
1518 if (isa<TypeDecl>(ND))
1519 return false;
1520 // Objective-C interfaces names are not filtered by this method because they
1521 // can be used in a class property expression. We can still filter out
1522 // @class declarations though.
1523 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND)) {
1524 if (!ID->getDefinition())
1525 return false;
1526 }
1527
1529 if (SemaRef.getLangOpts().CPlusPlus)
1531 else if (SemaRef.getLangOpts().ObjC) {
1532 if (isa<ObjCIvarDecl>(ND))
1533 return true;
1534 }
1535
1536 return ND->getIdentifierNamespace() & IDNS;
1537}
1538
1539bool ResultBuilder::IsIntegralConstantValue(const NamedDecl *ND) const {
1540 if (!IsOrdinaryNonTypeName(ND))
1541 return false;
1542
1543 if (const auto *VD = dyn_cast<ValueDecl>(ND->getUnderlyingDecl()))
1544 if (VD->getType()->isIntegralOrEnumerationType())
1545 return true;
1546
1547 return false;
1548}
1549
1550/// Determines whether this given declaration will be found by
1551/// ordinary name lookup.
1552bool ResultBuilder::IsOrdinaryNonValueName(const NamedDecl *ND) const {
1553 ND = ND->getUnderlyingDecl();
1554
1556 if (SemaRef.getLangOpts().CPlusPlus)
1558
1559 return (ND->getIdentifierNamespace() & IDNS) && !isa<ValueDecl>(ND) &&
1560 !isa<FunctionTemplateDecl>(ND) && !isa<ObjCPropertyDecl>(ND);
1561}
1562
1563/// Determines whether the given declaration is suitable as the
1564/// start of a C++ nested-name-specifier, e.g., a class or namespace.
1565bool ResultBuilder::IsNestedNameSpecifier(const NamedDecl *ND) const {
1566 // Allow us to find class templates, too.
1567 if (const auto *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
1568 ND = ClassTemplate->getTemplatedDecl();
1569
1570 return SemaRef.isAcceptableNestedNameSpecifier(ND);
1571}
1572
1573/// Determines whether the given declaration is an enumeration.
1574bool ResultBuilder::IsEnum(const NamedDecl *ND) const {
1575 return isa<EnumDecl>(ND);
1576}
1577
1578/// Determines whether the given declaration is a class or struct.
1579bool ResultBuilder::IsClassOrStruct(const NamedDecl *ND) const {
1580 // Allow us to find class templates, too.
1581 if (const auto *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
1582 ND = ClassTemplate->getTemplatedDecl();
1583
1584 // For purposes of this check, interfaces match too.
1585 if (const auto *RD = dyn_cast<RecordDecl>(ND))
1586 return RD->getTagKind() == TagTypeKind::Class ||
1587 RD->getTagKind() == TagTypeKind::Struct ||
1588 RD->getTagKind() == TagTypeKind::Interface;
1589
1590 return false;
1591}
1592
1593/// Determines whether the given declaration is a union.
1594bool ResultBuilder::IsUnion(const NamedDecl *ND) const {
1595 // Allow us to find class templates, too.
1596 if (const auto *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
1597 ND = ClassTemplate->getTemplatedDecl();
1598
1599 if (const auto *RD = dyn_cast<RecordDecl>(ND))
1600 return RD->getTagKind() == TagTypeKind::Union;
1601
1602 return false;
1603}
1604
1605/// Determines whether the given declaration is a namespace.
1606bool ResultBuilder::IsNamespace(const NamedDecl *ND) const {
1607 return isa<NamespaceDecl>(ND);
1608}
1609
1610/// Determines whether the given declaration is a namespace or
1611/// namespace alias.
1612bool ResultBuilder::IsNamespaceOrAlias(const NamedDecl *ND) const {
1613 return isa<NamespaceDecl>(ND->getUnderlyingDecl());
1614}
1615
1616/// Determines whether the given declaration is a type.
1617bool ResultBuilder::IsType(const NamedDecl *ND) const {
1618 ND = ND->getUnderlyingDecl();
1619 return isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
1620}
1621
1622/// Determines which members of a class should be visible via
1623/// "." or "->". Only value declarations, nested name specifiers, and
1624/// using declarations thereof should show up.
1625bool ResultBuilder::IsMember(const NamedDecl *ND) const {
1626 ND = ND->getUnderlyingDecl();
1627 return isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND) ||
1628 isa<ObjCPropertyDecl>(ND);
1629}
1630
1632 T = C.getCanonicalType(T);
1633 switch (T->getTypeClass()) {
1634 case Type::ObjCObject:
1635 case Type::ObjCInterface:
1636 case Type::ObjCObjectPointer:
1637 return true;
1638
1639 case Type::Builtin:
1640 switch (cast<BuiltinType>(T)->getKind()) {
1641 case BuiltinType::ObjCId:
1642 case BuiltinType::ObjCClass:
1643 case BuiltinType::ObjCSel:
1644 return true;
1645
1646 default:
1647 break;
1648 }
1649 return false;
1650
1651 default:
1652 break;
1653 }
1654
1655 if (!C.getLangOpts().CPlusPlus)
1656 return false;
1657
1658 // FIXME: We could perform more analysis here to determine whether a
1659 // particular class type has any conversions to Objective-C types. For now,
1660 // just accept all class types.
1661 return T->isDependentType() || T->isRecordType();
1662}
1663
1664bool ResultBuilder::IsObjCMessageReceiver(const NamedDecl *ND) const {
1665 QualType T = getDeclUsageType(SemaRef.Context, ND);
1666 if (T.isNull())
1667 return false;
1668
1669 T = SemaRef.Context.getBaseElementType(T);
1670 return isObjCReceiverType(SemaRef.Context, T);
1671}
1672
1673bool ResultBuilder::IsObjCMessageReceiverOrLambdaCapture(
1674 const NamedDecl *ND) const {
1675 if (IsObjCMessageReceiver(ND))
1676 return true;
1677
1678 const auto *Var = dyn_cast<VarDecl>(ND);
1679 if (!Var)
1680 return false;
1681
1682 return Var->hasLocalStorage() && !Var->hasAttr<BlocksAttr>();
1683}
1684
1685bool ResultBuilder::IsObjCCollection(const NamedDecl *ND) const {
1686 if ((SemaRef.getLangOpts().CPlusPlus && !IsOrdinaryName(ND)) ||
1687 (!SemaRef.getLangOpts().CPlusPlus && !IsOrdinaryNonTypeName(ND)))
1688 return false;
1689
1690 QualType T = getDeclUsageType(SemaRef.Context, ND);
1691 if (T.isNull())
1692 return false;
1693
1694 T = SemaRef.Context.getBaseElementType(T);
1695 return T->isObjCObjectType() || T->isObjCObjectPointerType() ||
1696 T->isObjCIdType() ||
1697 (SemaRef.getLangOpts().CPlusPlus && T->isRecordType());
1698}
1699
1700bool ResultBuilder::IsImpossibleToSatisfy(const NamedDecl *ND) const {
1701 return false;
1702}
1703
1704/// Determines whether the given declaration is an Objective-C
1705/// instance variable.
1706bool ResultBuilder::IsObjCIvar(const NamedDecl *ND) const {
1707 return isa<ObjCIvarDecl>(ND);
1708}
1709
1710namespace {
1711
1712/// Visible declaration consumer that adds a code-completion result
1713/// for each visible declaration.
1714class CodeCompletionDeclConsumer : public VisibleDeclConsumer {
1715 ResultBuilder &Results;
1716 DeclContext *InitialLookupCtx;
1717 // NamingClass and BaseType are used for access-checking. See
1718 // Sema::IsSimplyAccessible for details.
1719 CXXRecordDecl *NamingClass;
1720 QualType BaseType;
1721 std::vector<FixItHint> FixIts;
1722
1723public:
1724 CodeCompletionDeclConsumer(
1725 ResultBuilder &Results, DeclContext *InitialLookupCtx,
1726 QualType BaseType = QualType(),
1727 std::vector<FixItHint> FixIts = std::vector<FixItHint>())
1728 : Results(Results), InitialLookupCtx(InitialLookupCtx),
1729 FixIts(std::move(FixIts)) {
1730 NamingClass = llvm::dyn_cast<CXXRecordDecl>(InitialLookupCtx);
1731 // If BaseType was not provided explicitly, emulate implicit 'this->'.
1732 if (BaseType.isNull()) {
1733 auto ThisType = Results.getSema().getCurrentThisType();
1734 if (!ThisType.isNull()) {
1735 assert(ThisType->isPointerType());
1736 BaseType = ThisType->getPointeeType();
1737 if (!NamingClass)
1738 NamingClass = BaseType->getAsCXXRecordDecl();
1739 }
1740 }
1741 this->BaseType = BaseType;
1742 }
1743
1744 void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
1745 bool InBaseClass) override {
1746 ResultBuilder::Result Result(ND, Results.getBasePriority(ND), nullptr,
1747 false, IsAccessible(ND, Ctx), FixIts);
1748 Results.AddResult(Result, InitialLookupCtx, Hiding, InBaseClass, BaseType);
1749 }
1750
1751 void EnteredContext(DeclContext *Ctx) override {
1752 Results.addVisitedContext(Ctx);
1753 }
1754
1755private:
1756 bool IsAccessible(NamedDecl *ND, DeclContext *Ctx) {
1757 // Naming class to use for access check. In most cases it was provided
1758 // explicitly (e.g. member access (lhs.foo) or qualified lookup (X::)),
1759 // for unqualified lookup we fallback to the \p Ctx in which we found the
1760 // member.
1761 auto *NamingClass = this->NamingClass;
1762 QualType BaseType = this->BaseType;
1763 if (auto *Cls = llvm::dyn_cast_or_null<CXXRecordDecl>(Ctx)) {
1764 if (!NamingClass)
1765 NamingClass = Cls;
1766 // When we emulate implicit 'this->' in an unqualified lookup, we might
1767 // end up with an invalid naming class. In that case, we avoid emulating
1768 // 'this->' qualifier to satisfy preconditions of the access checking.
1769 if (NamingClass->getCanonicalDecl() != Cls->getCanonicalDecl() &&
1770 !NamingClass->isDerivedFrom(Cls)) {
1771 NamingClass = Cls;
1772 BaseType = QualType();
1773 }
1774 } else {
1775 // The decl was found outside the C++ class, so only ObjC access checks
1776 // apply. Those do not rely on NamingClass and BaseType, so we clear them
1777 // out.
1778 NamingClass = nullptr;
1779 BaseType = QualType();
1780 }
1781 return Results.getSema().IsSimplyAccessible(ND, NamingClass, BaseType);
1782 }
1783};
1784} // namespace
1785
1786/// Add type specifiers for the current language as keyword results.
1787static void AddTypeSpecifierResults(const LangOptions &LangOpts,
1788 ResultBuilder &Results) {
1790 Results.AddResult(Result("short", CCP_Type));
1791 Results.AddResult(Result("long", CCP_Type));
1792 Results.AddResult(Result("signed", CCP_Type));
1793 Results.AddResult(Result("unsigned", CCP_Type));
1794 Results.AddResult(Result("void", CCP_Type));
1795 Results.AddResult(Result("char", CCP_Type));
1796 Results.AddResult(Result("int", CCP_Type));
1797 Results.AddResult(Result("float", CCP_Type));
1798 Results.AddResult(Result("double", CCP_Type));
1799 Results.AddResult(Result("enum", CCP_Type));
1800 Results.AddResult(Result("struct", CCP_Type));
1801 Results.AddResult(Result("union", CCP_Type));
1802 Results.AddResult(Result("const", CCP_Type));
1803 Results.AddResult(Result("volatile", CCP_Type));
1804
1805 if (LangOpts.C99) {
1806 // C99-specific
1807 Results.AddResult(Result("_Complex", CCP_Type));
1808 if (!LangOpts.C2y)
1809 Results.AddResult(Result("_Imaginary", CCP_Type));
1810 Results.AddResult(Result("_Bool", CCP_Type));
1811 Results.AddResult(Result("restrict", CCP_Type));
1812 }
1813
1814 CodeCompletionBuilder Builder(Results.getAllocator(),
1815 Results.getCodeCompletionTUInfo());
1816 if (LangOpts.CPlusPlus) {
1817 // C++-specific
1818 Results.AddResult(
1819 Result("bool", CCP_Type + (LangOpts.ObjC ? CCD_bool_in_ObjC : 0)));
1820 Results.AddResult(Result("class", CCP_Type));
1821 Results.AddResult(Result("wchar_t", CCP_Type));
1822
1823 // typename name
1824 Builder.AddTypedTextChunk("typename");
1826 Builder.AddPlaceholderChunk("name");
1827 Results.AddResult(Result(Builder.TakeString()));
1828
1829 if (LangOpts.CPlusPlus11) {
1830 Results.AddResult(Result("auto", CCP_Type));
1831 Results.AddResult(Result("char16_t", CCP_Type));
1832 Results.AddResult(Result("char32_t", CCP_Type));
1833
1834 Builder.AddTypedTextChunk("decltype");
1835 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1836 Builder.AddPlaceholderChunk("expression");
1837 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1838 Results.AddResult(Result(Builder.TakeString()));
1839 }
1840 } else
1841 Results.AddResult(Result("__auto_type", CCP_Type));
1842
1843 // GNU keywords
1844 if (LangOpts.GNUKeywords) {
1845 // FIXME: Enable when we actually support decimal floating point.
1846 // Results.AddResult(Result("_Decimal32"));
1847 // Results.AddResult(Result("_Decimal64"));
1848 // Results.AddResult(Result("_Decimal128"));
1849
1850 Builder.AddTypedTextChunk("typeof");
1852 Builder.AddPlaceholderChunk("expression");
1853 Results.AddResult(Result(Builder.TakeString()));
1854
1855 Builder.AddTypedTextChunk("typeof");
1856 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1857 Builder.AddPlaceholderChunk("type");
1858 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1859 Results.AddResult(Result(Builder.TakeString()));
1860 }
1861
1862 // Nullability
1863 Results.AddResult(Result("_Nonnull", CCP_Type));
1864 Results.AddResult(Result("_Null_unspecified", CCP_Type));
1865 Results.AddResult(Result("_Nullable", CCP_Type));
1866}
1867
1868static void
1870 const LangOptions &LangOpts, ResultBuilder &Results) {
1872 // Note: we don't suggest either "auto" or "register", because both
1873 // are pointless as storage specifiers. Elsewhere, we suggest "auto"
1874 // in C++0x as a type specifier.
1875 Results.AddResult(Result("extern"));
1876 Results.AddResult(Result("static"));
1877
1878 if (LangOpts.CPlusPlus11) {
1879 CodeCompletionAllocator &Allocator = Results.getAllocator();
1880 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
1881
1882 // alignas
1883 Builder.AddTypedTextChunk("alignas");
1884 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1885 Builder.AddPlaceholderChunk("expression");
1886 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1887 Results.AddResult(Result(Builder.TakeString()));
1888
1889 Results.AddResult(Result("constexpr"));
1890 Results.AddResult(Result("thread_local"));
1891 }
1892}
1893
1894static void
1896 const LangOptions &LangOpts, ResultBuilder &Results) {
1898 switch (CCC) {
1901 if (LangOpts.CPlusPlus) {
1902 Results.AddResult(Result("explicit"));
1903 Results.AddResult(Result("friend"));
1904 Results.AddResult(Result("mutable"));
1905 Results.AddResult(Result("virtual"));
1906 }
1907 [[fallthrough]];
1908
1913 if (LangOpts.CPlusPlus || LangOpts.C99)
1914 Results.AddResult(Result("inline"));
1915 break;
1916
1927 break;
1928 }
1929}
1930
1931static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt);
1932static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt);
1933static void AddObjCVisibilityResults(const LangOptions &LangOpts,
1934 ResultBuilder &Results, bool NeedAt);
1935static void AddObjCImplementationResults(const LangOptions &LangOpts,
1936 ResultBuilder &Results, bool NeedAt);
1937static void AddObjCInterfaceResults(const LangOptions &LangOpts,
1938 ResultBuilder &Results, bool NeedAt);
1939static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt);
1940
1941static void AddTypedefResult(ResultBuilder &Results) {
1942 CodeCompletionBuilder Builder(Results.getAllocator(),
1943 Results.getCodeCompletionTUInfo());
1944 Builder.AddTypedTextChunk("typedef");
1946 Builder.AddPlaceholderChunk("type");
1948 Builder.AddPlaceholderChunk("name");
1949 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
1950 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
1951}
1952
1953// using name = type
1955 ResultBuilder &Results) {
1956 Builder.AddTypedTextChunk("using");
1958 Builder.AddPlaceholderChunk("name");
1959 Builder.AddChunk(CodeCompletionString::CK_Equal);
1960 Builder.AddPlaceholderChunk("type");
1961 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
1962 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
1963}
1964
1966 const LangOptions &LangOpts) {
1967 switch (CCC) {
1979 return true;
1980
1983 return LangOpts.CPlusPlus;
1984
1987 return false;
1988
1990 return LangOpts.CPlusPlus || LangOpts.ObjC || LangOpts.C99;
1991 }
1992
1993 llvm_unreachable("Invalid ParserCompletionContext!");
1994}
1995
1997 const Preprocessor &PP) {
1998 PrintingPolicy Policy = Sema::getPrintingPolicy(Context, PP);
1999 Policy.AnonymousTagLocations = false;
2000 Policy.SuppressStrongLifetime = true;
2001 Policy.SuppressUnwrittenScope = true;
2002 Policy.SuppressScope = true;
2003 Policy.CleanUglifiedParameters = true;
2004 return Policy;
2005}
2006
2007/// Retrieve a printing policy suitable for code completion.
2010}
2011
2012/// Retrieve the string representation of the given type as a string
2013/// that has the appropriate lifetime for code completion.
2014///
2015/// This routine provides a fast path where we provide constant strings for
2016/// common type names.
2017static const char *GetCompletionTypeString(QualType T, ASTContext &Context,
2018 const PrintingPolicy &Policy,
2019 CodeCompletionAllocator &Allocator) {
2020 if (!T.getLocalQualifiers()) {
2021 // Built-in type names are constant strings.
2022 if (const BuiltinType *BT = dyn_cast<BuiltinType>(T))
2023 return BT->getNameAsCString(Policy);
2024
2025 // Anonymous tag types are constant strings.
2026 if (const TagType *TagT = dyn_cast<TagType>(T))
2027 if (TagDecl *Tag = TagT->getDecl())
2028 if (!Tag->hasNameForLinkage()) {
2029 switch (Tag->getTagKind()) {
2031 return "struct <anonymous>";
2033 return "__interface <anonymous>";
2034 case TagTypeKind::Class:
2035 return "class <anonymous>";
2036 case TagTypeKind::Union:
2037 return "union <anonymous>";
2038 case TagTypeKind::Enum:
2039 return "enum <anonymous>";
2040 }
2041 }
2042 }
2043
2044 // Slow path: format the type as a string.
2045 std::string Result;
2046 T.getAsStringInternal(Result, Policy);
2047 return Allocator.CopyString(Result);
2048}
2049
2050/// Add a completion for "this", if we're in a member function.
2051static void addThisCompletion(Sema &S, ResultBuilder &Results) {
2052 QualType ThisTy = S.getCurrentThisType();
2053 if (ThisTy.isNull())
2054 return;
2055
2056 CodeCompletionAllocator &Allocator = Results.getAllocator();
2057 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
2059 Builder.AddResultTypeChunk(
2060 GetCompletionTypeString(ThisTy, S.Context, Policy, Allocator));
2061 Builder.AddTypedTextChunk("this");
2062 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
2063}
2064
2066 ResultBuilder &Results,
2067 const LangOptions &LangOpts) {
2068 if (!LangOpts.CPlusPlus11)
2069 return;
2070
2071 Builder.AddTypedTextChunk("static_assert");
2072 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2073 Builder.AddPlaceholderChunk("expression");
2074 Builder.AddChunk(CodeCompletionString::CK_Comma);
2075 Builder.AddPlaceholderChunk("message");
2076 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2077 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2078 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
2079}
2080
2081static void AddOverrideResults(ResultBuilder &Results,
2082 const CodeCompletionContext &CCContext,
2083 CodeCompletionBuilder &Builder) {
2084 Sema &S = Results.getSema();
2085 const auto *CR = llvm::dyn_cast<CXXRecordDecl>(S.CurContext);
2086 // If not inside a class/struct/union return empty.
2087 if (!CR)
2088 return;
2089 // First store overrides within current class.
2090 // These are stored by name to make querying fast in the later step.
2091 llvm::StringMap<std::vector<FunctionDecl *>> Overrides;
2092 for (auto *Method : CR->methods()) {
2093 if (!Method->isVirtual() || !Method->getIdentifier())
2094 continue;
2095 Overrides[Method->getName()].push_back(Method);
2096 }
2097
2098 for (const auto &Base : CR->bases()) {
2099 const auto *BR = Base.getType().getTypePtr()->getAsCXXRecordDecl();
2100 if (!BR)
2101 continue;
2102 for (auto *Method : BR->methods()) {
2103 if (!Method->isVirtual() || !Method->getIdentifier())
2104 continue;
2105 const auto it = Overrides.find(Method->getName());
2106 bool IsOverriden = false;
2107 if (it != Overrides.end()) {
2108 for (auto *MD : it->second) {
2109 // If the method in current body is not an overload of this virtual
2110 // function, then it overrides this one.
2111 if (!S.IsOverload(MD, Method, false)) {
2112 IsOverriden = true;
2113 break;
2114 }
2115 }
2116 }
2117 if (!IsOverriden) {
2118 // Generates a new CodeCompletionResult by taking this function and
2119 // converting it into an override declaration with only one chunk in the
2120 // final CodeCompletionString as a TypedTextChunk.
2121 CodeCompletionResult CCR(Method, 0);
2122 PrintingPolicy Policy =
2125 S.getPreprocessor(), S.getASTContext(), Builder,
2126 /*IncludeBriefComments=*/false, CCContext, Policy);
2127 Results.AddResult(CodeCompletionResult(CCS, Method, CCP_CodePattern));
2128 }
2129 }
2130 }
2131}
2132
2133/// Add language constructs that show up for "ordinary" names.
2134static void
2136 Scope *S, Sema &SemaRef, ResultBuilder &Results) {
2137 CodeCompletionAllocator &Allocator = Results.getAllocator();
2138 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
2139
2141 switch (CCC) {
2143 if (SemaRef.getLangOpts().CPlusPlus) {
2144 if (Results.includeCodePatterns()) {
2145 // namespace <identifier> { declarations }
2146 Builder.AddTypedTextChunk("namespace");
2148 Builder.AddPlaceholderChunk("identifier");
2150 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
2152 Builder.AddPlaceholderChunk("declarations");
2154 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
2155 Results.AddResult(Result(Builder.TakeString()));
2156 }
2157
2158 // namespace identifier = identifier ;
2159 Builder.AddTypedTextChunk("namespace");
2161 Builder.AddPlaceholderChunk("name");
2162 Builder.AddChunk(CodeCompletionString::CK_Equal);
2163 Builder.AddPlaceholderChunk("namespace");
2164 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2165 Results.AddResult(Result(Builder.TakeString()));
2166
2167 // Using directives
2168 Builder.AddTypedTextChunk("using namespace");
2170 Builder.AddPlaceholderChunk("identifier");
2171 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2172 Results.AddResult(Result(Builder.TakeString()));
2173
2174 // asm(string-literal)
2175 Builder.AddTypedTextChunk("asm");
2176 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2177 Builder.AddPlaceholderChunk("string-literal");
2178 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2179 Results.AddResult(Result(Builder.TakeString()));
2180
2181 if (Results.includeCodePatterns()) {
2182 // Explicit template instantiation
2183 Builder.AddTypedTextChunk("template");
2185 Builder.AddPlaceholderChunk("declaration");
2186 Results.AddResult(Result(Builder.TakeString()));
2187 } else {
2188 Results.AddResult(Result("template", CodeCompletionResult::RK_Keyword));
2189 }
2190 }
2191
2192 if (SemaRef.getLangOpts().ObjC)
2193 AddObjCTopLevelResults(Results, true);
2194
2195 AddTypedefResult(Results);
2196 [[fallthrough]];
2197
2199 if (SemaRef.getLangOpts().CPlusPlus) {
2200 // Using declaration
2201 Builder.AddTypedTextChunk("using");
2203 Builder.AddPlaceholderChunk("qualifier");
2204 Builder.AddTextChunk("::");
2205 Builder.AddPlaceholderChunk("name");
2206 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2207 Results.AddResult(Result(Builder.TakeString()));
2208
2209 if (SemaRef.getLangOpts().CPlusPlus11)
2210 AddUsingAliasResult(Builder, Results);
2211
2212 // using typename qualifier::name (only in a dependent context)
2213 if (SemaRef.CurContext->isDependentContext()) {
2214 Builder.AddTypedTextChunk("using typename");
2216 Builder.AddPlaceholderChunk("qualifier");
2217 Builder.AddTextChunk("::");
2218 Builder.AddPlaceholderChunk("name");
2219 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2220 Results.AddResult(Result(Builder.TakeString()));
2221 }
2222
2223 AddStaticAssertResult(Builder, Results, SemaRef.getLangOpts());
2224
2225 if (CCC == SemaCodeCompletion::PCC_Class) {
2226 AddTypedefResult(Results);
2227
2228 bool IsNotInheritanceScope = !S->isClassInheritanceScope();
2229 // public:
2230 Builder.AddTypedTextChunk("public");
2231 if (IsNotInheritanceScope && Results.includeCodePatterns())
2232 Builder.AddChunk(CodeCompletionString::CK_Colon);
2233 Results.AddResult(Result(Builder.TakeString()));
2234
2235 // protected:
2236 Builder.AddTypedTextChunk("protected");
2237 if (IsNotInheritanceScope && Results.includeCodePatterns())
2238 Builder.AddChunk(CodeCompletionString::CK_Colon);
2239 Results.AddResult(Result(Builder.TakeString()));
2240
2241 // private:
2242 Builder.AddTypedTextChunk("private");
2243 if (IsNotInheritanceScope && Results.includeCodePatterns())
2244 Builder.AddChunk(CodeCompletionString::CK_Colon);
2245 Results.AddResult(Result(Builder.TakeString()));
2246
2247 // FIXME: This adds override results only if we are at the first word of
2248 // the declaration/definition. Also call this from other sides to have
2249 // more use-cases.
2251 Builder);
2252 }
2253 }
2254 [[fallthrough]];
2255
2258 if (SemaRef.getLangOpts().CPlusPlus && Results.includeCodePatterns()) {
2259 // template < parameters >
2260 Builder.AddTypedTextChunk("template");
2261 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
2262 Builder.AddPlaceholderChunk("parameters");
2263 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
2264 Results.AddResult(Result(Builder.TakeString()));
2265 } else {
2266 Results.AddResult(Result("template", CodeCompletionResult::RK_Keyword));
2267 }
2268
2269 AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
2270 AddFunctionSpecifiers(CCC, SemaRef.getLangOpts(), Results);
2271 break;
2272
2274 AddObjCInterfaceResults(SemaRef.getLangOpts(), Results, true);
2275 AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
2276 AddFunctionSpecifiers(CCC, SemaRef.getLangOpts(), Results);
2277 break;
2278
2280 AddObjCImplementationResults(SemaRef.getLangOpts(), Results, true);
2281 AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
2282 AddFunctionSpecifiers(CCC, SemaRef.getLangOpts(), Results);
2283 break;
2284
2286 AddObjCVisibilityResults(SemaRef.getLangOpts(), Results, true);
2287 break;
2288
2292 if (SemaRef.getLangOpts().CPlusPlus11)
2293 AddUsingAliasResult(Builder, Results);
2294
2295 AddTypedefResult(Results);
2296
2297 if (SemaRef.getLangOpts().CPlusPlus && Results.includeCodePatterns() &&
2298 SemaRef.getLangOpts().CXXExceptions) {
2299 Builder.AddTypedTextChunk("try");
2301 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
2303 Builder.AddPlaceholderChunk("statements");
2305 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
2307 Builder.AddTextChunk("catch");
2309 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2310 Builder.AddPlaceholderChunk("declaration");
2311 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2313 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
2315 Builder.AddPlaceholderChunk("statements");
2317 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
2318 Results.AddResult(Result(Builder.TakeString()));
2319 }
2320 if (SemaRef.getLangOpts().ObjC)
2321 AddObjCStatementResults(Results, true);
2322
2323 if (Results.includeCodePatterns()) {
2324 // if (condition) { statements }
2325 Builder.AddTypedTextChunk("if");
2327 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2328 if (SemaRef.getLangOpts().CPlusPlus)
2329 Builder.AddPlaceholderChunk("condition");
2330 else
2331 Builder.AddPlaceholderChunk("expression");
2332 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2334 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
2336 Builder.AddPlaceholderChunk("statements");
2338 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
2339 Results.AddResult(Result(Builder.TakeString()));
2340
2341 // switch (condition) { }
2342 Builder.AddTypedTextChunk("switch");
2344 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2345 if (SemaRef.getLangOpts().CPlusPlus)
2346 Builder.AddPlaceholderChunk("condition");
2347 else
2348 Builder.AddPlaceholderChunk("expression");
2349 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2351 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
2353 Builder.AddPlaceholderChunk("cases");
2355 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
2356 Results.AddResult(Result(Builder.TakeString()));
2357 }
2358
2359 // Switch-specific statements.
2360 if (SemaRef.getCurFunction() &&
2361 !SemaRef.getCurFunction()->SwitchStack.empty()) {
2362 // case expression:
2363 Builder.AddTypedTextChunk("case");
2365 Builder.AddPlaceholderChunk("expression");
2366 Builder.AddChunk(CodeCompletionString::CK_Colon);
2367 Results.AddResult(Result(Builder.TakeString()));
2368
2369 // default:
2370 Builder.AddTypedTextChunk("default");
2371 Builder.AddChunk(CodeCompletionString::CK_Colon);
2372 Results.AddResult(Result(Builder.TakeString()));
2373 }
2374
2375 if (Results.includeCodePatterns()) {
2376 /// while (condition) { statements }
2377 Builder.AddTypedTextChunk("while");
2379 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2380 if (SemaRef.getLangOpts().CPlusPlus)
2381 Builder.AddPlaceholderChunk("condition");
2382 else
2383 Builder.AddPlaceholderChunk("expression");
2384 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2386 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
2388 Builder.AddPlaceholderChunk("statements");
2390 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
2391 Results.AddResult(Result(Builder.TakeString()));
2392
2393 // do { statements } while ( expression );
2394 Builder.AddTypedTextChunk("do");
2396 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
2398 Builder.AddPlaceholderChunk("statements");
2400 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
2401 Builder.AddTextChunk("while");
2403 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2404 Builder.AddPlaceholderChunk("expression");
2405 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2406 Results.AddResult(Result(Builder.TakeString()));
2407
2408 // for ( for-init-statement ; condition ; expression ) { statements }
2409 Builder.AddTypedTextChunk("for");
2411 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2412 if (SemaRef.getLangOpts().CPlusPlus || SemaRef.getLangOpts().C99)
2413 Builder.AddPlaceholderChunk("init-statement");
2414 else
2415 Builder.AddPlaceholderChunk("init-expression");
2416 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2418 Builder.AddPlaceholderChunk("condition");
2419 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2421 Builder.AddPlaceholderChunk("inc-expression");
2422 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2424 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
2426 Builder.AddPlaceholderChunk("statements");
2428 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
2429 Results.AddResult(Result(Builder.TakeString()));
2430
2431 if (SemaRef.getLangOpts().CPlusPlus11 || SemaRef.getLangOpts().ObjC) {
2432 // for ( range_declaration (:|in) range_expression ) { statements }
2433 Builder.AddTypedTextChunk("for");
2435 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2436 Builder.AddPlaceholderChunk("range-declaration");
2438 if (SemaRef.getLangOpts().ObjC)
2439 Builder.AddTextChunk("in");
2440 else
2441 Builder.AddChunk(CodeCompletionString::CK_Colon);
2443 Builder.AddPlaceholderChunk("range-expression");
2444 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2446 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
2448 Builder.AddPlaceholderChunk("statements");
2450 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
2451 Results.AddResult(Result(Builder.TakeString()));
2452 }
2453 }
2454
2455 if (S->getContinueParent()) {
2456 // continue ;
2457 Builder.AddTypedTextChunk("continue");
2458 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2459 Results.AddResult(Result(Builder.TakeString()));
2460 }
2461
2462 if (S->getBreakParent()) {
2463 // break ;
2464 Builder.AddTypedTextChunk("break");
2465 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2466 Results.AddResult(Result(Builder.TakeString()));
2467 }
2468
2469 // "return expression ;" or "return ;", depending on the return type.
2470 QualType ReturnType;
2471 if (const auto *Function = dyn_cast<FunctionDecl>(SemaRef.CurContext))
2472 ReturnType = Function->getReturnType();
2473 else if (const auto *Method = dyn_cast<ObjCMethodDecl>(SemaRef.CurContext))
2474 ReturnType = Method->getReturnType();
2475 else if (SemaRef.getCurBlock() &&
2476 !SemaRef.getCurBlock()->ReturnType.isNull())
2477 ReturnType = SemaRef.getCurBlock()->ReturnType;;
2478 if (ReturnType.isNull() || ReturnType->isVoidType()) {
2479 Builder.AddTypedTextChunk("return");
2480 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2481 Results.AddResult(Result(Builder.TakeString()));
2482 } else {
2483 assert(!ReturnType.isNull());
2484 // "return expression ;"
2485 Builder.AddTypedTextChunk("return");
2487 Builder.AddPlaceholderChunk("expression");
2488 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2489 Results.AddResult(Result(Builder.TakeString()));
2490 // When boolean, also add 'return true;' and 'return false;'.
2491 if (ReturnType->isBooleanType()) {
2492 Builder.AddTypedTextChunk("return true");
2493 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2494 Results.AddResult(Result(Builder.TakeString()));
2495
2496 Builder.AddTypedTextChunk("return false");
2497 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2498 Results.AddResult(Result(Builder.TakeString()));
2499 }
2500 // For pointers, suggest 'return nullptr' in C++.
2501 if (SemaRef.getLangOpts().CPlusPlus11 &&
2502 (ReturnType->isPointerType() || ReturnType->isMemberPointerType())) {
2503 Builder.AddTypedTextChunk("return nullptr");
2504 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2505 Results.AddResult(Result(Builder.TakeString()));
2506 }
2507 }
2508
2509 // goto identifier ;
2510 Builder.AddTypedTextChunk("goto");
2512 Builder.AddPlaceholderChunk("label");
2513 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2514 Results.AddResult(Result(Builder.TakeString()));
2515
2516 // Using directives
2517 Builder.AddTypedTextChunk("using namespace");
2519 Builder.AddPlaceholderChunk("identifier");
2520 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2521 Results.AddResult(Result(Builder.TakeString()));
2522
2523 AddStaticAssertResult(Builder, Results, SemaRef.getLangOpts());
2524 }
2525 [[fallthrough]];
2526
2527 // Fall through (for statement expressions).
2530 AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
2531 // Fall through: conditions and statements can have expressions.
2532 [[fallthrough]];
2533
2535 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
2537 // (__bridge <type>)<expression>
2538 Builder.AddTypedTextChunk("__bridge");
2540 Builder.AddPlaceholderChunk("type");
2541 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2542 Builder.AddPlaceholderChunk("expression");
2543 Results.AddResult(Result(Builder.TakeString()));
2544
2545 // (__bridge_transfer <Objective-C type>)<expression>
2546 Builder.AddTypedTextChunk("__bridge_transfer");
2548 Builder.AddPlaceholderChunk("Objective-C type");
2549 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2550 Builder.AddPlaceholderChunk("expression");
2551 Results.AddResult(Result(Builder.TakeString()));
2552
2553 // (__bridge_retained <CF type>)<expression>
2554 Builder.AddTypedTextChunk("__bridge_retained");
2556 Builder.AddPlaceholderChunk("CF type");
2557 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2558 Builder.AddPlaceholderChunk("expression");
2559 Results.AddResult(Result(Builder.TakeString()));
2560 }
2561 // Fall through
2562 [[fallthrough]];
2563
2565 if (SemaRef.getLangOpts().CPlusPlus) {
2566 // 'this', if we're in a non-static member function.
2567 addThisCompletion(SemaRef, Results);
2568
2569 // true
2570 Builder.AddResultTypeChunk("bool");
2571 Builder.AddTypedTextChunk("true");
2572 Results.AddResult(Result(Builder.TakeString()));
2573
2574 // false
2575 Builder.AddResultTypeChunk("bool");
2576 Builder.AddTypedTextChunk("false");
2577 Results.AddResult(Result(Builder.TakeString()));
2578
2579 if (SemaRef.getLangOpts().RTTI) {
2580 // dynamic_cast < type-id > ( expression )
2581 Builder.AddTypedTextChunk("dynamic_cast");
2582 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
2583 Builder.AddPlaceholderChunk("type");
2584 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
2585 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2586 Builder.AddPlaceholderChunk("expression");
2587 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2588 Results.AddResult(Result(Builder.TakeString()));
2589 }
2590
2591 // static_cast < type-id > ( expression )
2592 Builder.AddTypedTextChunk("static_cast");
2593 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
2594 Builder.AddPlaceholderChunk("type");
2595 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
2596 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2597 Builder.AddPlaceholderChunk("expression");
2598 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2599 Results.AddResult(Result(Builder.TakeString()));
2600
2601 // reinterpret_cast < type-id > ( expression )
2602 Builder.AddTypedTextChunk("reinterpret_cast");
2603 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
2604 Builder.AddPlaceholderChunk("type");
2605 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
2606 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2607 Builder.AddPlaceholderChunk("expression");
2608 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2609 Results.AddResult(Result(Builder.TakeString()));
2610
2611 // const_cast < type-id > ( expression )
2612 Builder.AddTypedTextChunk("const_cast");
2613 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
2614 Builder.AddPlaceholderChunk("type");
2615 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
2616 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2617 Builder.AddPlaceholderChunk("expression");
2618 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2619 Results.AddResult(Result(Builder.TakeString()));
2620
2621 if (SemaRef.getLangOpts().RTTI) {
2622 // typeid ( expression-or-type )
2623 Builder.AddResultTypeChunk("std::type_info");
2624 Builder.AddTypedTextChunk("typeid");
2625 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2626 Builder.AddPlaceholderChunk("expression-or-type");
2627 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2628 Results.AddResult(Result(Builder.TakeString()));
2629 }
2630
2631 // new T ( ... )
2632 Builder.AddTypedTextChunk("new");
2634 Builder.AddPlaceholderChunk("type");
2635 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2636 Builder.AddPlaceholderChunk("expressions");
2637 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2638 Results.AddResult(Result(Builder.TakeString()));
2639
2640 // new T [ ] ( ... )
2641 Builder.AddTypedTextChunk("new");
2643 Builder.AddPlaceholderChunk("type");
2644 Builder.AddChunk(CodeCompletionString::CK_LeftBracket);
2645 Builder.AddPlaceholderChunk("size");
2646 Builder.AddChunk(CodeCompletionString::CK_RightBracket);
2647 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2648 Builder.AddPlaceholderChunk("expressions");
2649 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2650 Results.AddResult(Result(Builder.TakeString()));
2651
2652 // delete expression
2653 Builder.AddResultTypeChunk("void");
2654 Builder.AddTypedTextChunk("delete");
2656 Builder.AddPlaceholderChunk("expression");
2657 Results.AddResult(Result(Builder.TakeString()));
2658
2659 // delete [] expression
2660 Builder.AddResultTypeChunk("void");
2661 Builder.AddTypedTextChunk("delete");
2663 Builder.AddChunk(CodeCompletionString::CK_LeftBracket);
2664 Builder.AddChunk(CodeCompletionString::CK_RightBracket);
2666 Builder.AddPlaceholderChunk("expression");
2667 Results.AddResult(Result(Builder.TakeString()));
2668
2669 if (SemaRef.getLangOpts().CXXExceptions) {
2670 // throw expression
2671 Builder.AddResultTypeChunk("void");
2672 Builder.AddTypedTextChunk("throw");
2674 Builder.AddPlaceholderChunk("expression");
2675 Results.AddResult(Result(Builder.TakeString()));
2676 }
2677
2678 // FIXME: Rethrow?
2679
2680 if (SemaRef.getLangOpts().CPlusPlus11) {
2681 // nullptr
2682 Builder.AddResultTypeChunk("std::nullptr_t");
2683 Builder.AddTypedTextChunk("nullptr");
2684 Results.AddResult(Result(Builder.TakeString()));
2685
2686 // alignof
2687 Builder.AddResultTypeChunk("size_t");
2688 Builder.AddTypedTextChunk("alignof");
2689 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2690 Builder.AddPlaceholderChunk("type");
2691 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2692 Results.AddResult(Result(Builder.TakeString()));
2693
2694 // noexcept
2695 Builder.AddResultTypeChunk("bool");
2696 Builder.AddTypedTextChunk("noexcept");
2697 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2698 Builder.AddPlaceholderChunk("expression");
2699 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2700 Results.AddResult(Result(Builder.TakeString()));
2701
2702 // sizeof... expression
2703 Builder.AddResultTypeChunk("size_t");
2704 Builder.AddTypedTextChunk("sizeof...");
2705 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2706 Builder.AddPlaceholderChunk("parameter-pack");
2707 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2708 Results.AddResult(Result(Builder.TakeString()));
2709 }
2710 }
2711
2712 if (SemaRef.getLangOpts().ObjC) {
2713 // Add "super", if we're in an Objective-C class with a superclass.
2714 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
2715 // The interface can be NULL.
2716 if (ObjCInterfaceDecl *ID = Method->getClassInterface())
2717 if (ID->getSuperClass()) {
2718 std::string SuperType;
2719 SuperType = ID->getSuperClass()->getNameAsString();
2720 if (Method->isInstanceMethod())
2721 SuperType += " *";
2722
2723 Builder.AddResultTypeChunk(Allocator.CopyString(SuperType));
2724 Builder.AddTypedTextChunk("super");
2725 Results.AddResult(Result(Builder.TakeString()));
2726 }
2727 }
2728
2729 AddObjCExpressionResults(Results, true);
2730 }
2731
2732 if (SemaRef.getLangOpts().C11) {
2733 // _Alignof
2734 Builder.AddResultTypeChunk("size_t");
2735 if (SemaRef.PP.isMacroDefined("alignof"))
2736 Builder.AddTypedTextChunk("alignof");
2737 else
2738 Builder.AddTypedTextChunk("_Alignof");
2739 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2740 Builder.AddPlaceholderChunk("type");
2741 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2742 Results.AddResult(Result(Builder.TakeString()));
2743 }
2744
2745 if (SemaRef.getLangOpts().C23) {
2746 // nullptr
2747 Builder.AddResultTypeChunk("nullptr_t");
2748 Builder.AddTypedTextChunk("nullptr");
2749 Results.AddResult(Result(Builder.TakeString()));
2750 }
2751
2752 // sizeof expression
2753 Builder.AddResultTypeChunk("size_t");
2754 Builder.AddTypedTextChunk("sizeof");
2755 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2756 Builder.AddPlaceholderChunk("expression-or-type");
2757 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2758 Results.AddResult(Result(Builder.TakeString()));
2759 break;
2760 }
2761
2764 break;
2765 }
2766
2767 if (WantTypesInContext(CCC, SemaRef.getLangOpts()))
2768 AddTypeSpecifierResults(SemaRef.getLangOpts(), Results);
2769
2770 if (SemaRef.getLangOpts().CPlusPlus && CCC != SemaCodeCompletion::PCC_Type)
2771 Results.AddResult(Result("operator"));
2772}
2773
2774/// If the given declaration has an associated type, add it as a result
2775/// type chunk.
2776static void AddResultTypeChunk(ASTContext &Context,
2777 const PrintingPolicy &Policy,
2778 const NamedDecl *ND, QualType BaseType,
2780 if (!ND)
2781 return;
2782
2783 // Skip constructors and conversion functions, which have their return types
2784 // built into their names.
2785 if (isConstructor(ND) || isa<CXXConversionDecl>(ND))
2786 return;
2787
2788 // Determine the type of the declaration (if it has a type).
2789 QualType T;
2790 if (const FunctionDecl *Function = ND->getAsFunction())
2791 T = Function->getReturnType();
2792 else if (const auto *Method = dyn_cast<ObjCMethodDecl>(ND)) {
2793 if (!BaseType.isNull())
2794 T = Method->getSendResultType(BaseType);
2795 else
2796 T = Method->getReturnType();
2797 } else if (const auto *Enumerator = dyn_cast<EnumConstantDecl>(ND)) {
2798 T = Context.getTypeDeclType(cast<TypeDecl>(Enumerator->getDeclContext()));
2800 } else if (isa<UnresolvedUsingValueDecl>(ND)) {
2801 /* Do nothing: ignore unresolved using declarations*/
2802 } else if (const auto *Ivar = dyn_cast<ObjCIvarDecl>(ND)) {
2803 if (!BaseType.isNull())
2804 T = Ivar->getUsageType(BaseType);
2805 else
2806 T = Ivar->getType();
2807 } else if (const auto *Value = dyn_cast<ValueDecl>(ND)) {
2808 T = Value->getType();
2809 } else if (const auto *Property = dyn_cast<ObjCPropertyDecl>(ND)) {
2810 if (!BaseType.isNull())
2811 T = Property->getUsageType(BaseType);
2812 else
2813 T = Property->getType();
2814 }
2815
2816 if (T.isNull() || Context.hasSameType(T, Context.DependentTy))
2817 return;
2818
2819 Result.AddResultTypeChunk(
2820 GetCompletionTypeString(T, Context, Policy, Result.getAllocator()));
2821}
2822
2824 const NamedDecl *FunctionOrMethod,
2826 if (SentinelAttr *Sentinel = FunctionOrMethod->getAttr<SentinelAttr>())
2827 if (Sentinel->getSentinel() == 0) {
2828 if (PP.getLangOpts().ObjC && PP.isMacroDefined("nil"))
2829 Result.AddTextChunk(", nil");
2830 else if (PP.isMacroDefined("NULL"))
2831 Result.AddTextChunk(", NULL");
2832 else
2833 Result.AddTextChunk(", (void*)0");
2834 }
2835}
2836
2837static std::string formatObjCParamQualifiers(unsigned ObjCQuals,
2838 QualType &Type) {
2839 std::string Result;
2840 if (ObjCQuals & Decl::OBJC_TQ_In)
2841 Result += "in ";
2842 else if (ObjCQuals & Decl::OBJC_TQ_Inout)
2843 Result += "inout ";
2844 else if (ObjCQuals & Decl::OBJC_TQ_Out)
2845 Result += "out ";
2846 if (ObjCQuals & Decl::OBJC_TQ_Bycopy)
2847 Result += "bycopy ";
2848 else if (ObjCQuals & Decl::OBJC_TQ_Byref)
2849 Result += "byref ";
2850 if (ObjCQuals & Decl::OBJC_TQ_Oneway)
2851 Result += "oneway ";
2852 if (ObjCQuals & Decl::OBJC_TQ_CSNullability) {
2853 if (auto nullability = AttributedType::stripOuterNullability(Type)) {
2854 switch (*nullability) {
2856 Result += "nonnull ";
2857 break;
2858
2860 Result += "nullable ";
2861 break;
2862
2864 Result += "null_unspecified ";
2865 break;
2866
2868 llvm_unreachable("Not supported as a context-sensitive keyword!");
2869 break;
2870 }
2871 }
2872 }
2873 return Result;
2874}
2875
2876/// Tries to find the most appropriate type location for an Objective-C
2877/// block placeholder.
2878///
2879/// This function ignores things like typedefs and qualifiers in order to
2880/// present the most relevant and accurate block placeholders in code completion
2881/// results.
2884 FunctionProtoTypeLoc &BlockProto,
2885 bool SuppressBlock = false) {
2886 if (!TSInfo)
2887 return;
2888 TypeLoc TL = TSInfo->getTypeLoc().getUnqualifiedLoc();
2889 while (true) {
2890 // Look through typedefs.
2891 if (!SuppressBlock) {
2892 if (TypedefTypeLoc TypedefTL = TL.getAsAdjusted<TypedefTypeLoc>()) {
2893 if (TypeSourceInfo *InnerTSInfo =
2894 TypedefTL.getTypedefNameDecl()->getTypeSourceInfo()) {
2895 TL = InnerTSInfo->getTypeLoc().getUnqualifiedLoc();
2896 continue;
2897 }
2898 }
2899
2900 // Look through qualified types
2901 if (QualifiedTypeLoc QualifiedTL = TL.getAs<QualifiedTypeLoc>()) {
2902 TL = QualifiedTL.getUnqualifiedLoc();
2903 continue;
2904 }
2905
2906 if (AttributedTypeLoc AttrTL = TL.getAs<AttributedTypeLoc>()) {
2907 TL = AttrTL.getModifiedLoc();
2908 continue;
2909 }
2910 }
2911
2912 // Try to get the function prototype behind the block pointer type,
2913 // then we're done.
2914 if (BlockPointerTypeLoc BlockPtr = TL.getAs<BlockPointerTypeLoc>()) {
2915 TL = BlockPtr.getPointeeLoc().IgnoreParens();
2916 Block = TL.getAs<FunctionTypeLoc>();
2917 BlockProto = TL.getAs<FunctionProtoTypeLoc>();
2918 }
2919 break;
2920 }
2921}
2922
2923static std::string formatBlockPlaceholder(
2924 const PrintingPolicy &Policy, const NamedDecl *BlockDecl,
2926 bool SuppressBlockName = false, bool SuppressBlock = false,
2927 std::optional<ArrayRef<QualType>> ObjCSubsts = std::nullopt);
2928
2929static std::string FormatFunctionParameter(
2930 const PrintingPolicy &Policy, const DeclaratorDecl *Param,
2931 bool SuppressName = false, bool SuppressBlock = false,
2932 std::optional<ArrayRef<QualType>> ObjCSubsts = std::nullopt) {
2933 // Params are unavailable in FunctionTypeLoc if the FunctionType is invalid.
2934 // It would be better to pass in the param Type, which is usually available.
2935 // But this case is rare, so just pretend we fell back to int as elsewhere.
2936 if (!Param)
2937 return "int";
2939 if (const auto *PVD = dyn_cast<ParmVarDecl>(Param))
2940 ObjCQual = PVD->getObjCDeclQualifier();
2941 bool ObjCMethodParam = isa<ObjCMethodDecl>(Param->getDeclContext());
2942 if (Param->getType()->isDependentType() ||
2943 !Param->getType()->isBlockPointerType()) {
2944 // The argument for a dependent or non-block parameter is a placeholder
2945 // containing that parameter's type.
2946 std::string Result;
2947
2948 if (Param->getIdentifier() && !ObjCMethodParam && !SuppressName)
2949 Result = std::string(Param->getIdentifier()->deuglifiedName());
2950
2951 QualType Type = Param->getType();
2952 if (ObjCSubsts)
2953 Type = Type.substObjCTypeArgs(Param->getASTContext(), *ObjCSubsts,
2955 if (ObjCMethodParam) {
2956 Result = "(" + formatObjCParamQualifiers(ObjCQual, Type);
2957 Result += Type.getAsString(Policy) + ")";
2958 if (Param->getIdentifier() && !SuppressName)
2959 Result += Param->getIdentifier()->deuglifiedName();
2960 } else {
2961 Type.getAsStringInternal(Result, Policy);
2962 }
2963 return Result;
2964 }
2965
2966 // The argument for a block pointer parameter is a block literal with
2967 // the appropriate type.
2969 FunctionProtoTypeLoc BlockProto;
2971 SuppressBlock);
2972 // Try to retrieve the block type information from the property if this is a
2973 // parameter in a setter.
2974 if (!Block && ObjCMethodParam &&
2975 cast<ObjCMethodDecl>(Param->getDeclContext())->isPropertyAccessor()) {
2976 if (const auto *PD = cast<ObjCMethodDecl>(Param->getDeclContext())
2977 ->findPropertyDecl(/*CheckOverrides=*/false))
2978 findTypeLocationForBlockDecl(PD->getTypeSourceInfo(), Block, BlockProto,
2979 SuppressBlock);
2980 }
2981
2982 if (!Block) {
2983 // We were unable to find a FunctionProtoTypeLoc with parameter names
2984 // for the block; just use the parameter type as a placeholder.
2985 std::string Result;
2986 if (!ObjCMethodParam && Param->getIdentifier())
2987 Result = std::string(Param->getIdentifier()->deuglifiedName());
2988
2990
2991 if (ObjCMethodParam) {
2992 Result = Type.getAsString(Policy);
2993 std::string Quals = formatObjCParamQualifiers(ObjCQual, Type);
2994 if (!Quals.empty())
2995 Result = "(" + Quals + " " + Result + ")";
2996 if (Result.back() != ')')
2997 Result += " ";
2998 if (Param->getIdentifier())
2999 Result += Param->getIdentifier()->deuglifiedName();
3000 } else {
3001 Type.getAsStringInternal(Result, Policy);
3002 }
3003
3004 return Result;
3005 }
3006
3007 // We have the function prototype behind the block pointer type, as it was
3008 // written in the source.
3009 return formatBlockPlaceholder(Policy, Param, Block, BlockProto,
3010 /*SuppressBlockName=*/false, SuppressBlock,
3011 ObjCSubsts);
3012}
3013
3014/// Returns a placeholder string that corresponds to an Objective-C block
3015/// declaration.
3016///
3017/// \param BlockDecl A declaration with an Objective-C block type.
3018///
3019/// \param Block The most relevant type location for that block type.
3020///
3021/// \param SuppressBlockName Determines whether or not the name of the block
3022/// declaration is included in the resulting string.
3023static std::string
3026 bool SuppressBlockName, bool SuppressBlock,
3027 std::optional<ArrayRef<QualType>> ObjCSubsts) {
3028 std::string Result;
3029 QualType ResultType = Block.getTypePtr()->getReturnType();
3030 if (ObjCSubsts)
3031 ResultType =
3032 ResultType.substObjCTypeArgs(BlockDecl->getASTContext(), *ObjCSubsts,
3034 if (!ResultType->isVoidType() || SuppressBlock)
3035 ResultType.getAsStringInternal(Result, Policy);
3036
3037 // Format the parameter list.
3038 std::string Params;
3039 if (!BlockProto || Block.getNumParams() == 0) {
3040 if (BlockProto && BlockProto.getTypePtr()->isVariadic())
3041 Params = "(...)";
3042 else
3043 Params = "(void)";
3044 } else {
3045 Params += "(";
3046 for (unsigned I = 0, N = Block.getNumParams(); I != N; ++I) {
3047 if (I)
3048 Params += ", ";
3049 Params += FormatFunctionParameter(Policy, Block.getParam(I),
3050 /*SuppressName=*/false,
3051 /*SuppressBlock=*/true, ObjCSubsts);
3052
3053 if (I == N - 1 && BlockProto.getTypePtr()->isVariadic())
3054 Params += ", ...";
3055 }
3056 Params += ")";
3057 }
3058
3059 if (SuppressBlock) {
3060 // Format as a parameter.
3061 Result = Result + " (^";
3062 if (!SuppressBlockName && BlockDecl->getIdentifier())
3063 Result += BlockDecl->getIdentifier()->getName();
3064 Result += ")";
3065 Result += Params;
3066 } else {
3067 // Format as a block literal argument.
3068 Result = '^' + Result;
3069 Result += Params;
3070
3071 if (!SuppressBlockName && BlockDecl->getIdentifier())
3072 Result += BlockDecl->getIdentifier()->getName();
3073 }
3074
3075 return Result;
3076}
3077
3078static std::string GetDefaultValueString(const ParmVarDecl *Param,
3079 const SourceManager &SM,
3080 const LangOptions &LangOpts) {
3081 const SourceRange SrcRange = Param->getDefaultArgRange();
3082 CharSourceRange CharSrcRange = CharSourceRange::getTokenRange(SrcRange);
3083 bool Invalid = CharSrcRange.isInvalid();
3084 if (Invalid)
3085 return "";
3086 StringRef srcText =
3087 Lexer::getSourceText(CharSrcRange, SM, LangOpts, &Invalid);
3088 if (Invalid)
3089 return "";
3090
3091 if (srcText.empty() || srcText == "=") {
3092 // Lexer can't determine the value.
3093 // This happens if the code is incorrect (for example class is forward
3094 // declared).
3095 return "";
3096 }
3097 std::string DefValue(srcText.str());
3098 // FIXME: remove this check if the Lexer::getSourceText value is fixed and
3099 // this value always has (or always does not have) '=' in front of it
3100 if (DefValue.at(0) != '=') {
3101 // If we don't have '=' in front of value.
3102 // Lexer returns built-in types values without '=' and user-defined types
3103 // values with it.
3104 return " = " + DefValue;
3105 }
3106 return " " + DefValue;
3107}
3108
3109/// Add function parameter chunks to the given code completion string.
3111 const PrintingPolicy &Policy,
3112 const FunctionDecl *Function,
3114 unsigned Start = 0,
3115 bool InOptional = false) {
3116 bool FirstParameter = true;
3117
3118 for (unsigned P = Start, N = Function->getNumParams(); P != N; ++P) {
3119 const ParmVarDecl *Param = Function->getParamDecl(P);
3120
3121 if (Param->hasDefaultArg() && !InOptional) {
3122 // When we see an optional default argument, put that argument and
3123 // the remaining default arguments into a new, optional string.
3124 CodeCompletionBuilder Opt(Result.getAllocator(),
3125 Result.getCodeCompletionTUInfo());
3126 if (!FirstParameter)
3128 AddFunctionParameterChunks(PP, Policy, Function, Opt, P, true);
3129 Result.AddOptionalChunk(Opt.TakeString());
3130 break;
3131 }
3132
3133 if (FirstParameter)
3134 FirstParameter = false;
3135 else
3137
3138 InOptional = false;
3139
3140 // Format the placeholder string.
3141 std::string PlaceholderStr = FormatFunctionParameter(Policy, Param);
3142 if (Param->hasDefaultArg())
3143 PlaceholderStr +=
3145
3146 if (Function->isVariadic() && P == N - 1)
3147 PlaceholderStr += ", ...";
3148
3149 // Add the placeholder string.
3150 Result.AddPlaceholderChunk(
3151 Result.getAllocator().CopyString(PlaceholderStr));
3152 }
3153
3154 if (const auto *Proto = Function->getType()->getAs<FunctionProtoType>())
3155 if (Proto->isVariadic()) {
3156 if (Proto->getNumParams() == 0)
3157 Result.AddPlaceholderChunk("...");
3158
3160 }
3161}
3162
3163/// Add template parameter chunks to the given code completion string.
3165 ASTContext &Context, const PrintingPolicy &Policy,
3166 const TemplateDecl *Template, CodeCompletionBuilder &Result,
3167 unsigned MaxParameters = 0, unsigned Start = 0, bool InDefaultArg = false) {
3168 bool FirstParameter = true;
3169
3170 // Prefer to take the template parameter names from the first declaration of
3171 // the template.
3172 Template = cast<TemplateDecl>(Template->getCanonicalDecl());
3173
3174 TemplateParameterList *Params = Template->getTemplateParameters();
3175 TemplateParameterList::iterator PEnd = Params->end();
3176 if (MaxParameters)
3177 PEnd = Params->begin() + MaxParameters;
3178 for (TemplateParameterList::iterator P = Params->begin() + Start; P != PEnd;
3179 ++P) {
3180 bool HasDefaultArg = false;
3181 std::string PlaceholderStr;
3182 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
3183 if (TTP->wasDeclaredWithTypename())
3184 PlaceholderStr = "typename";
3185 else if (const auto *TC = TTP->getTypeConstraint()) {
3186 llvm::raw_string_ostream OS(PlaceholderStr);
3187 TC->print(OS, Policy);
3188 } else
3189 PlaceholderStr = "class";
3190
3191 if (TTP->getIdentifier()) {
3192 PlaceholderStr += ' ';
3193 PlaceholderStr += TTP->getIdentifier()->deuglifiedName();
3194 }
3195
3196 HasDefaultArg = TTP->hasDefaultArgument();
3197 } else if (NonTypeTemplateParmDecl *NTTP =
3198 dyn_cast<NonTypeTemplateParmDecl>(*P)) {
3199 if (NTTP->getIdentifier())
3200 PlaceholderStr = std::string(NTTP->getIdentifier()->deuglifiedName());
3201 NTTP->getType().getAsStringInternal(PlaceholderStr, Policy);
3202 HasDefaultArg = NTTP->hasDefaultArgument();
3203 } else {
3204 assert(isa<TemplateTemplateParmDecl>(*P));
3205 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
3206
3207 // Since putting the template argument list into the placeholder would
3208 // be very, very long, we just use an abbreviation.
3209 PlaceholderStr = "template<...> class";
3210 if (TTP->getIdentifier()) {
3211 PlaceholderStr += ' ';
3212 PlaceholderStr += TTP->getIdentifier()->deuglifiedName();
3213 }
3214
3215 HasDefaultArg = TTP->hasDefaultArgument();
3216 }
3217
3218 if (HasDefaultArg && !InDefaultArg) {
3219 // When we see an optional default argument, put that argument and
3220 // the remaining default arguments into a new, optional string.
3221 CodeCompletionBuilder Opt(Result.getAllocator(),
3222 Result.getCodeCompletionTUInfo());
3223 if (!FirstParameter)
3225 AddTemplateParameterChunks(Context, Policy, Template, Opt, MaxParameters,
3226 P - Params->begin(), true);
3227 Result.AddOptionalChunk(Opt.TakeString());
3228 break;
3229 }
3230
3231 InDefaultArg = false;
3232
3233 if (FirstParameter)
3234 FirstParameter = false;
3235 else
3237
3238 // Add the placeholder string.
3239 Result.AddPlaceholderChunk(
3240 Result.getAllocator().CopyString(PlaceholderStr));
3241 }
3242}
3243
3244/// Add a qualifier to the given code-completion string, if the
3245/// provided nested-name-specifier is non-NULL.
3247 NestedNameSpecifier *Qualifier,
3248 bool QualifierIsInformative,
3249 ASTContext &Context,
3250 const PrintingPolicy &Policy) {
3251 if (!Qualifier)
3252 return;
3253
3254 std::string PrintedNNS;
3255 {
3256 llvm::raw_string_ostream OS(PrintedNNS);
3257 Qualifier->print(OS, Policy);
3258 }
3259 if (QualifierIsInformative)
3260 Result.AddInformativeChunk(Result.getAllocator().CopyString(PrintedNNS));
3261 else
3262 Result.AddTextChunk(Result.getAllocator().CopyString(PrintedNNS));
3263}
3264
3265static void
3267 const FunctionDecl *Function) {
3268 const auto *Proto = Function->getType()->getAs<FunctionProtoType>();
3269 if (!Proto || !Proto->getMethodQuals())
3270 return;
3271
3272 // FIXME: Add ref-qualifier!
3273
3274 // Handle single qualifiers without copying
3275 if (Proto->getMethodQuals().hasOnlyConst()) {
3276 Result.AddInformativeChunk(" const");
3277 return;
3278 }
3279
3280 if (Proto->getMethodQuals().hasOnlyVolatile()) {
3281 Result.AddInformativeChunk(" volatile");
3282 return;
3283 }
3284
3285 if (Proto->getMethodQuals().hasOnlyRestrict()) {
3286 Result.AddInformativeChunk(" restrict");
3287 return;
3288 }
3289
3290 // Handle multiple qualifiers.
3291 std::string QualsStr;
3292 if (Proto->isConst())
3293 QualsStr += " const";
3294 if (Proto->isVolatile())
3295 QualsStr += " volatile";
3296 if (Proto->isRestrict())
3297 QualsStr += " restrict";
3298 Result.AddInformativeChunk(Result.getAllocator().CopyString(QualsStr));
3299}
3300
3301/// Add the name of the given declaration
3302static void AddTypedNameChunk(ASTContext &Context, const PrintingPolicy &Policy,
3303 const NamedDecl *ND,
3305 DeclarationName Name = ND->getDeclName();
3306 if (!Name)
3307 return;
3308
3309 switch (Name.getNameKind()) {
3311 const char *OperatorName = nullptr;
3312 switch (Name.getCXXOverloadedOperator()) {
3313 case OO_None:
3314 case OO_Conditional:
3316 OperatorName = "operator";
3317 break;
3318
3319#define OVERLOADED_OPERATOR(Name, Spelling, Token, Unary, Binary, MemberOnly) \
3320 case OO_##Name: \
3321 OperatorName = "operator" Spelling; \
3322 break;
3323#define OVERLOADED_OPERATOR_MULTI(Name, Spelling, Unary, Binary, MemberOnly)
3324#include "clang/Basic/OperatorKinds.def"
3325
3326 case OO_New:
3327 OperatorName = "operator new";
3328 break;
3329 case OO_Delete:
3330 OperatorName = "operator delete";
3331 break;
3332 case OO_Array_New:
3333 OperatorName = "operator new[]";
3334 break;
3335 case OO_Array_Delete:
3336 OperatorName = "operator delete[]";
3337 break;
3338 case OO_Call:
3339 OperatorName = "operator()";
3340 break;
3341 case OO_Subscript:
3342 OperatorName = "operator[]";
3343 break;
3344 }
3345 Result.AddTypedTextChunk(OperatorName);
3346 break;
3347 }
3348
3353 Result.AddTypedTextChunk(
3354 Result.getAllocator().CopyString(ND->getNameAsString()));
3355 break;
3356
3362 break;
3363
3365 CXXRecordDecl *Record = nullptr;
3366 QualType Ty = Name.getCXXNameType();
3367 if (const auto *RecordTy = Ty->getAs<RecordType>())
3368 Record = cast<CXXRecordDecl>(RecordTy->getDecl());
3369 else if (const auto *InjectedTy = Ty->getAs<InjectedClassNameType>())
3370 Record = InjectedTy->getDecl();
3371 else {
3372 Result.AddTypedTextChunk(
3373 Result.getAllocator().CopyString(ND->getNameAsString()));
3374 break;
3375 }
3376
3377 Result.AddTypedTextChunk(
3378 Result.getAllocator().CopyString(Record->getNameAsString()));
3379 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) {
3381 AddTemplateParameterChunks(Context, Policy, Template, Result);
3383 }
3384 break;
3385 }
3386 }
3387}
3388
3390 Sema &S, const CodeCompletionContext &CCContext,
3391 CodeCompletionAllocator &Allocator, CodeCompletionTUInfo &CCTUInfo,
3392 bool IncludeBriefComments) {
3393 return CreateCodeCompletionString(S.Context, S.PP, CCContext, Allocator,
3394 CCTUInfo, IncludeBriefComments);
3395}
3396
3398 Preprocessor &PP, CodeCompletionAllocator &Allocator,
3399 CodeCompletionTUInfo &CCTUInfo) {
3400 assert(Kind == RK_Macro);
3401 CodeCompletionBuilder Result(Allocator, CCTUInfo, Priority, Availability);
3402 const MacroInfo *MI = PP.getMacroInfo(Macro);
3403 Result.AddTypedTextChunk(Result.getAllocator().CopyString(Macro->getName()));
3404
3405 if (!MI || !MI->isFunctionLike())
3406 return Result.TakeString();
3407
3408 // Format a function-like macro with placeholders for the arguments.
3410 MacroInfo::param_iterator A = MI->param_begin(), AEnd = MI->param_end();
3411
3412 // C99 variadic macros add __VA_ARGS__ at the end. Skip it.
3413 if (MI->isC99Varargs()) {
3414 --AEnd;
3415
3416 if (A == AEnd) {
3417 Result.AddPlaceholderChunk("...");
3418 }
3419 }
3420
3421 for (MacroInfo::param_iterator A = MI->param_begin(); A != AEnd; ++A) {
3422 if (A != MI->param_begin())
3424
3425 if (MI->isVariadic() && (A + 1) == AEnd) {
3426 SmallString<32> Arg = (*A)->getName();
3427 if (MI->isC99Varargs())
3428 Arg += ", ...";
3429 else
3430 Arg += "...";
3431 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
3432 break;
3433 }
3434
3435 // Non-variadic macros are simple.
3436 Result.AddPlaceholderChunk(
3437 Result.getAllocator().CopyString((*A)->getName()));
3438 }
3440 return Result.TakeString();
3441}
3442
3443/// If possible, create a new code completion string for the given
3444/// result.
3445///
3446/// \returns Either a new, heap-allocated code completion string describing
3447/// how to use this result, or NULL to indicate that the string or name of the
3448/// result is all that is needed.
3450 ASTContext &Ctx, Preprocessor &PP, const CodeCompletionContext &CCContext,
3451 CodeCompletionAllocator &Allocator, CodeCompletionTUInfo &CCTUInfo,
3452 bool IncludeBriefComments) {
3453 if (Kind == RK_Macro)
3454 return CreateCodeCompletionStringForMacro(PP, Allocator, CCTUInfo);
3455
3456 CodeCompletionBuilder Result(Allocator, CCTUInfo, Priority, Availability);
3457
3459 if (Kind == RK_Pattern) {
3460 Pattern->Priority = Priority;
3461 Pattern->Availability = Availability;
3462
3463 if (Declaration) {
3464 Result.addParentContext(Declaration->getDeclContext());
3465 Pattern->ParentName = Result.getParentName();
3466 if (const RawComment *RC =
3468 Result.addBriefComment(RC->getBriefText(Ctx));
3469 Pattern->BriefComment = Result.getBriefComment();
3470 }
3471 }
3472
3473 return Pattern;
3474 }
3475
3476 if (Kind == RK_Keyword) {
3477 Result.AddTypedTextChunk(Keyword);
3478 return Result.TakeString();
3479 }
3480 assert(Kind == RK_Declaration && "Missed a result kind?");
3482 PP, Ctx, Result, IncludeBriefComments, CCContext, Policy);
3483}
3484
3486 std::string &BeforeName,
3487 std::string &NameAndSignature) {
3488 bool SeenTypedChunk = false;
3489 for (auto &Chunk : CCS) {
3490 if (Chunk.Kind == CodeCompletionString::CK_Optional) {
3491 assert(SeenTypedChunk && "optional parameter before name");
3492 // Note that we put all chunks inside into NameAndSignature.
3493 printOverrideString(*Chunk.Optional, NameAndSignature, NameAndSignature);
3494 continue;
3495 }
3496 SeenTypedChunk |= Chunk.Kind == CodeCompletionString::CK_TypedText;
3497 if (SeenTypedChunk)
3498 NameAndSignature += Chunk.Text;
3499 else
3500 BeforeName += Chunk.Text;
3501 }
3502}
3503
3507 bool IncludeBriefComments, const CodeCompletionContext &CCContext,
3508 PrintingPolicy &Policy) {
3509 auto *CCS = createCodeCompletionStringForDecl(PP, Ctx, Result,
3510 /*IncludeBriefComments=*/false,
3511 CCContext, Policy);
3512 std::string BeforeName;
3513 std::string NameAndSignature;
3514 // For overrides all chunks go into the result, none are informative.
3515 printOverrideString(*CCS, BeforeName, NameAndSignature);
3516 NameAndSignature += " override";
3517
3518 Result.AddTextChunk(Result.getAllocator().CopyString(BeforeName));
3520 Result.AddTypedTextChunk(Result.getAllocator().CopyString(NameAndSignature));
3521 return Result.TakeString();
3522}
3523
3524// FIXME: Right now this works well with lambdas. Add support for other functor
3525// types like std::function.
3527 const auto *VD = dyn_cast<VarDecl>(ND);
3528 if (!VD)
3529 return nullptr;
3530 const auto *RecordDecl = VD->getType()->getAsCXXRecordDecl();
3531 if (!RecordDecl || !RecordDecl->isLambda())
3532 return nullptr;
3533 return RecordDecl->getLambdaCallOperator();
3534}
3535
3538 bool IncludeBriefComments, const CodeCompletionContext &CCContext,
3539 PrintingPolicy &Policy) {
3540 const NamedDecl *ND = Declaration;
3541 Result.addParentContext(ND->getDeclContext());
3542
3543 if (IncludeBriefComments) {
3544 // Add documentation comment, if it exists.
3545 if (const RawComment *RC = getCompletionComment(Ctx, Declaration)) {
3546 Result.addBriefComment(RC->getBriefText(Ctx));
3547 }
3548 }
3549
3551 Result.AddTypedTextChunk(
3552 Result.getAllocator().CopyString(ND->getNameAsString()));
3553 Result.AddTextChunk("::");
3554 return Result.TakeString();
3555 }
3556
3557 for (const auto *I : ND->specific_attrs<AnnotateAttr>())
3558 Result.AddAnnotation(Result.getAllocator().CopyString(I->getAnnotation()));
3559
3560 auto AddFunctionTypeAndResult = [&](const FunctionDecl *Function) {
3561 AddResultTypeChunk(Ctx, Policy, Function, CCContext.getBaseType(), Result);
3563 Ctx, Policy);
3564 AddTypedNameChunk(Ctx, Policy, ND, Result);
3569 };
3570
3571 if (const auto *Function = dyn_cast<FunctionDecl>(ND)) {
3572 AddFunctionTypeAndResult(Function);
3573 return Result.TakeString();
3574 }
3575
3576 if (const auto *CallOperator =
3577 dyn_cast_or_null<FunctionDecl>(extractFunctorCallOperator(ND))) {
3578 AddFunctionTypeAndResult(CallOperator);
3579 return Result.TakeString();
3580 }
3581
3582 AddResultTypeChunk(Ctx, Policy, ND, CCContext.getBaseType(), Result);
3583
3584 if (const FunctionTemplateDecl *FunTmpl =
3585 dyn_cast<FunctionTemplateDecl>(ND)) {
3587 Ctx, Policy);
3588 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
3589 AddTypedNameChunk(Ctx, Policy, Function, Result);
3590
3591 // Figure out which template parameters are deduced (or have default
3592 // arguments).
3593 // Note that we're creating a non-empty bit vector so that we can go
3594 // through the loop below to omit default template parameters for non-call
3595 // cases.
3596 llvm::SmallBitVector Deduced(FunTmpl->getTemplateParameters()->size());
3597 // Avoid running it if this is not a call: We should emit *all* template
3598 // parameters.
3600 Sema::MarkDeducedTemplateParameters(Ctx, FunTmpl, Deduced);
3601 unsigned LastDeducibleArgument;
3602 for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0;
3603 --LastDeducibleArgument) {
3604 if (!Deduced[LastDeducibleArgument - 1]) {
3605 // C++0x: Figure out if the template argument has a default. If so,
3606 // the user doesn't need to type this argument.
3607 // FIXME: We need to abstract template parameters better!
3608 bool HasDefaultArg = false;
3609 NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam(
3610 LastDeducibleArgument - 1);
3611 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
3612 HasDefaultArg = TTP->hasDefaultArgument();
3613 else if (NonTypeTemplateParmDecl *NTTP =
3614 dyn_cast<NonTypeTemplateParmDecl>(Param))
3615 HasDefaultArg = NTTP->hasDefaultArgument();
3616 else {
3617 assert(isa<TemplateTemplateParmDecl>(Param));
3618 HasDefaultArg =
3619 cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument();
3620 }
3621
3622 if (!HasDefaultArg)
3623 break;
3624 }
3625 }
3626
3627 if (LastDeducibleArgument || !FunctionCanBeCall) {
3628 // Some of the function template arguments cannot be deduced from a
3629 // function call, so we introduce an explicit template argument list
3630 // containing all of the arguments up to the first deducible argument.
3631 //
3632 // Or, if this isn't a call, emit all the template arguments
3633 // to disambiguate the (potential) overloads.
3634 //
3635 // FIXME: Detect cases where the function parameters can be deduced from
3636 // the surrounding context, as per [temp.deduct.funcaddr].
3637 // e.g.,
3638 // template <class T> void foo(T);
3639 // void (*f)(int) = foo;
3641 AddTemplateParameterChunks(Ctx, Policy, FunTmpl, Result,
3642 LastDeducibleArgument);
3644 }
3645
3646 // Add the function parameters
3651 return Result.TakeString();
3652 }
3653
3654 if (const auto *Template = dyn_cast<TemplateDecl>(ND)) {
3656 Ctx, Policy);
3657 Result.AddTypedTextChunk(
3658 Result.getAllocator().CopyString(Template->getNameAsString()));
3660 AddTemplateParameterChunks(Ctx, Policy, Template, Result);
3662 return Result.TakeString();
3663 }
3664
3665 if (const auto *Method = dyn_cast<ObjCMethodDecl>(ND)) {
3666 Selector Sel = Method->getSelector();
3667 if (Sel.isUnarySelector()) {
3668 Result.AddTypedTextChunk(
3669 Result.getAllocator().CopyString(Sel.getNameForSlot(0)));
3670 return Result.TakeString();
3671 }
3672
3673 std::string SelName = Sel.getNameForSlot(0).str();
3674 SelName += ':';
3675 if (StartParameter == 0)
3676 Result.AddTypedTextChunk(Result.getAllocator().CopyString(SelName));
3677 else {
3678 Result.AddInformativeChunk(Result.getAllocator().CopyString(SelName));
3679
3680 // If there is only one parameter, and we're past it, add an empty
3681 // typed-text chunk since there is nothing to type.
3682 if (Method->param_size() == 1)
3683 Result.AddTypedTextChunk("");
3684 }
3685 unsigned Idx = 0;
3686 // The extra Idx < Sel.getNumArgs() check is needed due to legacy C-style
3687 // method parameters.
3689 PEnd = Method->param_end();
3690 P != PEnd && Idx < Sel.getNumArgs(); (void)++P, ++Idx) {
3691 if (Idx > 0) {
3692 std::string Keyword;
3693 if (Idx > StartParameter)
3695 if (const IdentifierInfo *II = Sel.getIdentifierInfoForSlot(Idx))
3696 Keyword += II->getName();
3697 Keyword += ":";
3699 Result.AddInformativeChunk(Result.getAllocator().CopyString(Keyword));
3700 else
3701 Result.AddTypedTextChunk(Result.getAllocator().CopyString(Keyword));
3702 }
3703
3704 // If we're before the starting parameter, skip the placeholder.
3705 if (Idx < StartParameter)
3706 continue;
3707
3708 std::string Arg;
3709 QualType ParamType = (*P)->getType();
3710 std::optional<ArrayRef<QualType>> ObjCSubsts;
3711 if (!CCContext.getBaseType().isNull())
3712 ObjCSubsts = CCContext.getBaseType()->getObjCSubstitutions(Method);
3713
3714 if (ParamType->isBlockPointerType() && !DeclaringEntity)
3715 Arg = FormatFunctionParameter(Policy, *P, true,
3716 /*SuppressBlock=*/false, ObjCSubsts);
3717 else {
3718 if (ObjCSubsts)
3719 ParamType = ParamType.substObjCTypeArgs(
3720 Ctx, *ObjCSubsts, ObjCSubstitutionContext::Parameter);
3721 Arg = "(" + formatObjCParamQualifiers((*P)->getObjCDeclQualifier(),
3722 ParamType);
3723 Arg += ParamType.getAsString(Policy) + ")";
3724 if (const IdentifierInfo *II = (*P)->getIdentifier())
3726 Arg += II->getName();
3727 }
3728
3729 if (Method->isVariadic() && (P + 1) == PEnd)
3730 Arg += ", ...";
3731
3732 if (DeclaringEntity)
3733 Result.AddTextChunk(Result.getAllocator().CopyString(Arg));
3735 Result.AddInformativeChunk(Result.getAllocator().CopyString(Arg));
3736 else
3737 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
3738 }
3739
3740 if (Method->isVariadic()) {
3741 if (Method->param_size() == 0) {
3742 if (DeclaringEntity)
3743 Result.AddTextChunk(", ...");
3745 Result.AddInformativeChunk(", ...");
3746 else
3747 Result.AddPlaceholderChunk(", ...");
3748 }
3749
3750 MaybeAddSentinel(PP, Method, Result);
3751 }
3752
3753 return Result.TakeString();
3754 }
3755
3756 if (Qualifier)
3758 Ctx, Policy);
3759
3760 Result.AddTypedTextChunk(
3761 Result.getAllocator().CopyString(ND->getNameAsString()));
3762 return Result.TakeString();
3763}
3764
3766 const NamedDecl *ND) {
3767 if (!ND)
3768 return nullptr;
3769 if (auto *RC = Ctx.getRawCommentForAnyRedecl(ND))
3770 return RC;
3771
3772 // Try to find comment from a property for ObjC methods.
3773 const auto *M = dyn_cast<ObjCMethodDecl>(ND);
3774 if (!M)
3775 return nullptr;
3776 const ObjCPropertyDecl *PDecl = M->findPropertyDecl();
3777 if (!PDecl)
3778 return nullptr;
3779
3780 return Ctx.getRawCommentForAnyRedecl(PDecl);
3781}
3782
3784 const NamedDecl *ND) {
3785 const auto *M = dyn_cast_or_null<ObjCMethodDecl>(ND);
3786 if (!M || !M->isPropertyAccessor())
3787 return nullptr;
3788
3789 // Provide code completion comment for self.GetterName where
3790 // GetterName is the getter method for a property with name
3791 // different from the property name (declared via a property
3792 // getter attribute.
3793 const ObjCPropertyDecl *PDecl = M->findPropertyDecl();
3794 if (!PDecl)
3795 return nullptr;
3796 if (PDecl->getGetterName() == M->getSelector() &&
3797 PDecl->getIdentifier() != M->getIdentifier()) {
3798 if (auto *RC = Ctx.getRawCommentForAnyRedecl(M))
3799 return RC;
3800 if (auto *RC = Ctx.getRawCommentForAnyRedecl(PDecl))
3801 return RC;
3802 }
3803 return nullptr;
3804}
3805
3807 const ASTContext &Ctx,
3808 const CodeCompleteConsumer::OverloadCandidate &Result, unsigned ArgIndex) {
3809 auto FDecl = Result.getFunction();
3810 if (!FDecl)
3811 return nullptr;
3812 if (ArgIndex < FDecl->getNumParams())
3813 return Ctx.getRawCommentForAnyRedecl(FDecl->getParamDecl(ArgIndex));
3814 return nullptr;
3815}
3816
3818 const PrintingPolicy &Policy,
3820 unsigned CurrentArg) {
3821 unsigned ChunkIndex = 0;
3822 auto AddChunk = [&](llvm::StringRef Placeholder) {
3823 if (ChunkIndex > 0)
3825 const char *Copy = Result.getAllocator().CopyString(Placeholder);
3826 if (ChunkIndex == CurrentArg)
3827 Result.AddCurrentParameterChunk(Copy);
3828 else
3829 Result.AddPlaceholderChunk(Copy);
3830 ++ChunkIndex;
3831 };
3832 // Aggregate initialization has all bases followed by all fields.
3833 // (Bases are not legal in C++11 but in that case we never get here).
3834 if (auto *CRD = llvm::dyn_cast<CXXRecordDecl>(RD)) {
3835 for (const auto &Base : CRD->bases())
3836 AddChunk(Base.getType().getAsString(Policy));
3837 }
3838 for (const auto &Field : RD->fields())
3839 AddChunk(FormatFunctionParameter(Policy, Field));
3840}
3841
3842/// Add function overload parameter chunks to the given code completion
3843/// string.
3845 ASTContext &Context, const PrintingPolicy &Policy,
3848 unsigned CurrentArg, unsigned Start = 0, bool InOptional = false) {
3849 if (!Function && !Prototype) {
3851 return;
3852 }
3853
3854 bool FirstParameter = true;
3855 unsigned NumParams =
3856 Function ? Function->getNumParams() : Prototype->getNumParams();
3857
3858 for (unsigned P = Start; P != NumParams; ++P) {
3859 if (Function && Function->getParamDecl(P)->hasDefaultArg() && !InOptional) {
3860 // When we see an optional default argument, put that argument and
3861 // the remaining default arguments into a new, optional string.
3862 CodeCompletionBuilder Opt(Result.getAllocator(),
3863 Result.getCodeCompletionTUInfo());
3864 if (!FirstParameter)
3866 // Optional sections are nested.
3868 PrototypeLoc, Opt, CurrentArg, P,
3869 /*InOptional=*/true);
3870 Result.AddOptionalChunk(Opt.TakeString());
3871 return;
3872 }
3873
3874 if (FirstParameter)
3875 FirstParameter = false;
3876 else
3878
3879 InOptional = false;
3880
3881 // Format the placeholder string.
3882 std::string Placeholder;
3883 assert(P < Prototype->getNumParams());
3884 if (Function || PrototypeLoc) {
3885 const ParmVarDecl *Param =
3886 Function ? Function->getParamDecl(P) : PrototypeLoc.getParam(P);
3887 Placeholder = FormatFunctionParameter(Policy, Param);
3888 if (Param->hasDefaultArg())
3889 Placeholder += GetDefaultValueString(Param, Context.getSourceManager(),
3890 Context.getLangOpts());
3891 } else {
3892 Placeholder = Prototype->getParamType(P).getAsString(Policy);
3893 }
3894
3895 if (P == CurrentArg)
3896 Result.AddCurrentParameterChunk(
3897 Result.getAllocator().CopyString(Placeholder));
3898 else
3899 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Placeholder));
3900 }
3901
3902 if (Prototype && Prototype->isVariadic()) {
3903 CodeCompletionBuilder Opt(Result.getAllocator(),
3904 Result.getCodeCompletionTUInfo());
3905 if (!FirstParameter)
3907
3908 if (CurrentArg < NumParams)
3909 Opt.AddPlaceholderChunk("...");
3910 else
3911 Opt.AddCurrentParameterChunk("...");
3912
3913 Result.AddOptionalChunk(Opt.TakeString());
3914 }
3915}
3916
3917static std::string
3919 const PrintingPolicy &Policy) {
3920 if (const auto *Type = dyn_cast<TemplateTypeParmDecl>(Param)) {
3921 Optional = Type->hasDefaultArgument();
3922 } else if (const auto *NonType = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3923 Optional = NonType->hasDefaultArgument();
3924 } else if (const auto *Template = dyn_cast<TemplateTemplateParmDecl>(Param)) {
3925 Optional = Template->hasDefaultArgument();
3926 }
3927 std::string Result;
3928 llvm::raw_string_ostream OS(Result);
3929 Param->print(OS, Policy);
3930 return Result;
3931}
3932
3933static std::string templateResultType(const TemplateDecl *TD,
3934 const PrintingPolicy &Policy) {
3935 if (const auto *CTD = dyn_cast<ClassTemplateDecl>(TD))
3936 return CTD->getTemplatedDecl()->getKindName().str();
3937 if (const auto *VTD = dyn_cast<VarTemplateDecl>(TD))
3938 return VTD->getTemplatedDecl()->getType().getAsString(Policy);
3939 if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(TD))
3940 return FTD->getTemplatedDecl()->getReturnType().getAsString(Policy);
3941 if (isa<TypeAliasTemplateDecl>(TD))
3942 return "type";
3943 if (isa<TemplateTemplateParmDecl>(TD))
3944 return "class";
3945 if (isa<ConceptDecl>(TD))
3946 return "concept";
3947 return "";
3948}
3949
3951 const TemplateDecl *TD, CodeCompletionBuilder &Builder, unsigned CurrentArg,
3952 const PrintingPolicy &Policy) {
3954 CodeCompletionBuilder OptionalBuilder(Builder.getAllocator(),
3955 Builder.getCodeCompletionTUInfo());
3956 std::string ResultType = templateResultType(TD, Policy);
3957 if (!ResultType.empty())
3958 Builder.AddResultTypeChunk(Builder.getAllocator().CopyString(ResultType));
3959 Builder.AddTextChunk(
3960 Builder.getAllocator().CopyString(TD->getNameAsString()));
3961 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
3962 // Initially we're writing into the main string. Once we see an optional arg
3963 // (with default), we're writing into the nested optional chunk.
3964 CodeCompletionBuilder *Current = &Builder;
3965 for (unsigned I = 0; I < Params.size(); ++I) {
3966 bool Optional = false;
3967 std::string Placeholder =
3968 formatTemplateParameterPlaceholder(Params[I], Optional, Policy);
3969 if (Optional)
3970 Current = &OptionalBuilder;
3971 if (I > 0)
3972 Current->AddChunk(CodeCompletionString::CK_Comma);
3973 Current->AddChunk(I == CurrentArg
3976 Current->getAllocator().CopyString(Placeholder));
3977 }
3978 // Add the optional chunk to the main string if we ever used it.
3979 if (Current == &OptionalBuilder)
3980 Builder.AddOptionalChunk(OptionalBuilder.TakeString());
3981 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
3982 // For function templates, ResultType was the function's return type.
3983 // Give some clue this is a function. (Don't show the possibly-bulky params).
3984 if (isa<FunctionTemplateDecl>(TD))
3985 Builder.AddInformativeChunk("()");
3986 return Builder.TakeString();
3987}
3988
3991 unsigned CurrentArg, Sema &S, CodeCompletionAllocator &Allocator,
3992 CodeCompletionTUInfo &CCTUInfo, bool IncludeBriefComments,
3993 bool Braced) const {
3995 // Show signatures of constructors as they are declared:
3996 // vector(int n) rather than vector<string>(int n)
3997 // This is less noisy without being less clear, and avoids tricky cases.
3999
4000 // FIXME: Set priority, availability appropriately.
4001 CodeCompletionBuilder Result(Allocator, CCTUInfo, 1,
4003
4004 if (getKind() == CK_Template)
4005 return createTemplateSignatureString(getTemplate(), Result, CurrentArg,
4006 Policy);
4007
4008 FunctionDecl *FDecl = getFunction();
4009 const FunctionProtoType *Proto =
4010 dyn_cast_or_null<FunctionProtoType>(getFunctionType());
4011
4012 // First, the name/type of the callee.
4013 if (getKind() == CK_Aggregate) {
4014 Result.AddTextChunk(
4015 Result.getAllocator().CopyString(getAggregate()->getName()));
4016 } else if (FDecl) {
4017 if (IncludeBriefComments) {
4018 if (auto RC = getParameterComment(S.getASTContext(), *this, CurrentArg))
4019 Result.addBriefComment(RC->getBriefText(S.getASTContext()));
4020 }
4021 AddResultTypeChunk(S.Context, Policy, FDecl, QualType(), Result);
4022
4023 std::string Name;
4024 llvm::raw_string_ostream OS(Name);
4025 FDecl->getDeclName().print(OS, Policy);
4026 Result.AddTextChunk(Result.getAllocator().CopyString(Name));
4027 } else {
4028 // Function without a declaration. Just give the return type.
4029 Result.AddResultTypeChunk(Result.getAllocator().CopyString(
4030 getFunctionType()->getReturnType().getAsString(Policy)));
4031 }
4032
4033 // Next, the brackets and parameters.
4036 if (getKind() == CK_Aggregate)
4037 AddOverloadAggregateChunks(getAggregate(), Policy, Result, CurrentArg);
4038 else
4039 AddOverloadParameterChunks(S.getASTContext(), Policy, FDecl, Proto,
4040 getFunctionProtoTypeLoc(), Result, CurrentArg);
4043
4044 return Result.TakeString();
4045}
4046
4047unsigned clang::getMacroUsagePriority(StringRef MacroName,
4048 const LangOptions &LangOpts,
4049 bool PreferredTypeIsPointer) {
4050 unsigned Priority = CCP_Macro;
4051
4052 // Treat the "nil", "Nil" and "NULL" macros as null pointer constants.
4053 if (MacroName == "nil" || MacroName == "NULL" || MacroName == "Nil") {
4055 if (PreferredTypeIsPointer)
4057 }
4058 // Treat "YES", "NO", "true", and "false" as constants.
4059 else if (MacroName == "YES" || MacroName == "NO" || MacroName == "true" ||
4060 MacroName == "false")
4062 // Treat "bool" as a type.
4063 else if (MacroName == "bool")
4064 Priority = CCP_Type + (LangOpts.ObjC ? CCD_bool_in_ObjC : 0);
4065
4066 return Priority;
4067}
4068
4070 if (!D)
4072
4073 switch (D->getKind()) {
4074 case Decl::Enum:
4075 return CXCursor_EnumDecl;
4076 case Decl::EnumConstant:
4078 case Decl::Field:
4079 return CXCursor_FieldDecl;
4080 case Decl::Function:
4081 return CXCursor_FunctionDecl;
4082 case Decl::ObjCCategory:
4084 case Decl::ObjCCategoryImpl:
4086 case Decl::ObjCImplementation:
4088
4089 case Decl::ObjCInterface:
4091 case Decl::ObjCIvar:
4092 return CXCursor_ObjCIvarDecl;
4093 case Decl::ObjCMethod:
4094 return cast<ObjCMethodDecl>(D)->isInstanceMethod()
4097 case Decl::CXXMethod:
4098 return CXCursor_CXXMethod;
4099 case Decl::CXXConstructor:
4100 return CXCursor_Constructor;
4101 case Decl::CXXDestructor:
4102 return CXCursor_Destructor;
4103 case Decl::CXXConversion:
4105 case Decl::ObjCProperty:
4107 case Decl::ObjCProtocol:
4109 case Decl::ParmVar:
4110 return CXCursor_ParmDecl;
4111 case Decl::Typedef:
4112 return CXCursor_TypedefDecl;
4113 case Decl::TypeAlias:
4115 case Decl::TypeAliasTemplate:
4117 case Decl::Var:
4118 return CXCursor_VarDecl;
4119 case Decl::Namespace:
4120 return CXCursor_Namespace;
4121 case Decl::NamespaceAlias:
4123 case Decl::TemplateTypeParm:
4125 case Decl::NonTypeTemplateParm:
4127 case Decl::TemplateTemplateParm:
4129 case Decl::FunctionTemplate:
4131 case Decl::ClassTemplate:
4133 case Decl::AccessSpec:
4135 case Decl::ClassTemplatePartialSpecialization:
4137 case Decl::UsingDirective:
4139 case Decl::StaticAssert:
4140 return CXCursor_StaticAssert;
4141 case Decl::Friend:
4142 return CXCursor_FriendDecl;
4143 case Decl::TranslationUnit:
4145
4146 case Decl::Using:
4147 case Decl::UnresolvedUsingValue:
4148 case Decl::UnresolvedUsingTypename:
4150
4151 case Decl::UsingEnum:
4152 return CXCursor_EnumDecl;
4153
4154 case Decl::ObjCPropertyImpl:
4155 switch (cast<ObjCPropertyImplDecl>(D)->getPropertyImplementation()) {
4158
4161 }
4162 llvm_unreachable("Unexpected Kind!");
4163
4164 case Decl::Import:
4166
4167 case Decl::ObjCTypeParam:
4169
4170 case Decl::Concept:
4171 return CXCursor_ConceptDecl;
4172
4173 case Decl::LinkageSpec:
4174 return CXCursor_LinkageSpec;
4175
4176 default:
4177 if (const auto *TD = dyn_cast<TagDecl>(D)) {
4178 switch (TD->getTagKind()) {
4179 case TagTypeKind::Interface: // fall through
4181 return CXCursor_StructDecl;
4182 case TagTypeKind::Class:
4183 return CXCursor_ClassDecl;
4184 case TagTypeKind::Union:
4185 return CXCursor_UnionDecl;
4186 case TagTypeKind::Enum:
4187 return CXCursor_EnumDecl;
4188 }
4189 }
4190 }
4191
4193}
4194
4195static void AddMacroResults(Preprocessor &PP, ResultBuilder &Results,
4196 bool LoadExternal, bool IncludeUndefined,
4197 bool TargetTypeIsPointer = false) {
4199
4200 Results.EnterNewScope();
4201
4202 for (Preprocessor::macro_iterator M = PP.macro_begin(LoadExternal),
4203 MEnd = PP.macro_end(LoadExternal);
4204 M != MEnd; ++M) {
4205 auto MD = PP.getMacroDefinition(M->first);
4206 if (IncludeUndefined || MD) {
4207 MacroInfo *MI = MD.getMacroInfo();
4208 if (MI && MI->isUsedForHeaderGuard())
4209 continue;
4210
4211 Results.AddResult(
4212 Result(M->first, MI,
4213 getMacroUsagePriority(M->first->getName(), PP.getLangOpts(),
4214 TargetTypeIsPointer)));
4215 }
4216 }
4217
4218 Results.ExitScope();
4219}
4220
4221static void AddPrettyFunctionResults(const LangOptions &LangOpts,
4222 ResultBuilder &Results) {
4224
4225 Results.EnterNewScope();
4226
4227 Results.AddResult(Result("__PRETTY_FUNCTION__", CCP_Constant));
4228 Results.AddResult(Result("__FUNCTION__", CCP_Constant));
4229 if (LangOpts.C99 || LangOpts.CPlusPlus11)
4230 Results.AddResult(Result("__func__", CCP_Constant));
4231 Results.ExitScope();
4232}
4233
4235 CodeCompleteConsumer *CodeCompleter,
4236 const CodeCompletionContext &Context,
4237 CodeCompletionResult *Results,
4238 unsigned NumResults) {
4239 if (CodeCompleter)
4240 CodeCompleter->ProcessCodeCompleteResults(*S, Context, Results, NumResults);
4241}
4242
4246 switch (PCC) {
4249
4252
4255
4258
4261
4264 if (S.CurContext->isFileContext())
4266 if (S.CurContext->isRecord())
4269
4272
4274 if (S.getLangOpts().CPlusPlus || S.getLangOpts().C99 ||
4275 S.getLangOpts().ObjC)
4277 else
4279
4284 S.getASTContext().BoolTy);
4285
4288
4291
4294
4299 }
4300
4301 llvm_unreachable("Invalid ParserCompletionContext!");
4302}
4303
4304/// If we're in a C++ virtual member function, add completion results
4305/// that invoke the functions we override, since it's common to invoke the
4306/// overridden function as well as adding new functionality.
4307///
4308/// \param S The semantic analysis object for which we are generating results.
4309///
4310/// \param InContext This context in which the nested-name-specifier preceding
4311/// the code-completion point
4312static void MaybeAddOverrideCalls(Sema &S, DeclContext *InContext,
4313 ResultBuilder &Results) {
4314 // Look through blocks.
4315 DeclContext *CurContext = S.CurContext;
4316 while (isa<BlockDecl>(CurContext))
4317 CurContext = CurContext->getParent();
4318
4319 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(CurContext);
4320 if (!Method || !Method->isVirtual())
4321 return;
4322
4323 // We need to have names for all of the parameters, if we're going to
4324 // generate a forwarding call.
4325 for (auto *P : Method->parameters())
4326 if (!P->getDeclName())
4327 return;
4328
4330 for (const CXXMethodDecl *Overridden : Method->overridden_methods()) {
4331 CodeCompletionBuilder Builder(Results.getAllocator(),
4332 Results.getCodeCompletionTUInfo());
4333 if (Overridden->getCanonicalDecl() == Method->getCanonicalDecl())
4334 continue;
4335
4336 // If we need a nested-name-specifier, add one now.
4337 if (!InContext) {
4339 S.Context, CurContext, Overridden->getDeclContext());
4340 if (NNS) {
4341 std::string Str;
4342 llvm::raw_string_ostream OS(Str);
4343 NNS->print(OS, Policy);
4344 Builder.AddTextChunk(Results.getAllocator().CopyString(Str));
4345 }
4346 } else if (!InContext->Equals(Overridden->getDeclContext()))
4347 continue;
4348
4349 Builder.AddTypedTextChunk(
4350 Results.getAllocator().CopyString(Overridden->getNameAsString()));
4351 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4352 bool FirstParam = true;
4353 for (auto *P : Method->parameters()) {
4354 if (FirstParam)
4355 FirstParam = false;
4356 else
4357 Builder.AddChunk(CodeCompletionString::CK_Comma);
4358
4359 Builder.AddPlaceholderChunk(
4360 Results.getAllocator().CopyString(P->getIdentifier()->getName()));
4361 }
4362 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4363 Results.AddResult(CodeCompletionResult(
4364 Builder.TakeString(), CCP_SuperCompletion, CXCursor_CXXMethod,
4365 CXAvailability_Available, Overridden));
4366 Results.Ignore(Overridden);
4367 }
4368}
4369
4373 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(),
4374 CodeCompleter->getCodeCompletionTUInfo(),
4376 Results.EnterNewScope();
4377
4378 CodeCompletionAllocator &Allocator = Results.getAllocator();
4379 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
4381 if (Path.empty()) {
4382 // Enumerate all top-level modules.
4384 SemaRef.PP.getHeaderSearchInfo().collectAllModules(Modules);
4385 for (unsigned I = 0, N = Modules.size(); I != N; ++I) {
4386 Builder.AddTypedTextChunk(
4387 Builder.getAllocator().CopyString(Modules[I]->Name));
4388 Results.AddResult(Result(
4389 Builder.TakeString(), CCP_Declaration, CXCursor_ModuleImportDecl,
4390 Modules[I]->isAvailable() ? CXAvailability_Available
4392 }
4393 } else if (getLangOpts().Modules) {
4394 // Load the named module.
4395 Module *Mod = SemaRef.PP.getModuleLoader().loadModule(
4396 ImportLoc, Path, Module::AllVisible,
4397 /*IsInclusionDirective=*/false);
4398 // Enumerate submodules.
4399 if (Mod) {
4400 for (auto *Submodule : Mod->submodules()) {
4401 Builder.AddTypedTextChunk(
4402 Builder.getAllocator().CopyString(Submodule->Name));
4403 Results.AddResult(Result(
4404 Builder.TakeString(), CCP_Declaration, CXCursor_ModuleImportDecl,
4405 Submodule->isAvailable() ? CXAvailability_Available
4407 }
4408 }
4409 }
4410 Results.ExitScope();
4411 HandleCodeCompleteResults(&SemaRef, CodeCompleter,
4412 Results.getCompletionContext(), Results.data(),
4413 Results.size());
4414}
4415
4417 Scope *S, SemaCodeCompletion::ParserCompletionContext CompletionContext) {
4418 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(),
4419 CodeCompleter->getCodeCompletionTUInfo(),
4420 mapCodeCompletionContext(SemaRef, CompletionContext));
4421 Results.EnterNewScope();
4422
4423 // Determine how to filter results, e.g., so that the names of
4424 // values (functions, enumerators, function templates, etc.) are
4425 // only allowed where we can have an expression.
4426 switch (CompletionContext) {
4427 case PCC_Namespace:
4428 case PCC_Class:
4429 case PCC_ObjCInterface:
4430 case PCC_ObjCImplementation:
4431 case PCC_ObjCInstanceVariableList:
4432 case PCC_Template:
4433 case PCC_MemberTemplate:
4434 case PCC_Type:
4435 case PCC_LocalDeclarationSpecifiers:
4436 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
4437 break;
4438
4439 case PCC_Statement:
4440 case PCC_TopLevelOrExpression:
4441 case PCC_ParenthesizedExpression:
4442 case PCC_Expression:
4443 case PCC_ForInit:
4444 case PCC_Condition:
4445 if (WantTypesInContext(CompletionContext, getLangOpts()))
4446 Results.setFilter(&ResultBuilder::IsOrdinaryName);
4447 else
4448 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
4449
4450 if (getLangOpts().CPlusPlus)
4451 MaybeAddOverrideCalls(SemaRef, /*InContext=*/nullptr, Results);
4452 break;
4453
4454 case PCC_RecoveryInFunction:
4455 // Unfiltered
4456 break;
4457 }
4458
4459 // If we are in a C++ non-static member function, check the qualifiers on
4460 // the member function to filter/prioritize the results list.
4461 auto ThisType = SemaRef.getCurrentThisType();
4462 if (!ThisType.isNull())
4463 Results.setObjectTypeQualifiers(ThisType->getPointeeType().getQualifiers(),
4464 VK_LValue);
4465
4466 CodeCompletionDeclConsumer Consumer(Results, SemaRef.CurContext);
4467 SemaRef.LookupVisibleDecls(S, SemaRef.LookupOrdinaryName, Consumer,
4468 CodeCompleter->includeGlobals(),
4469 CodeCompleter->loadExternal());
4470
4471 AddOrdinaryNameResults(CompletionContext, S, SemaRef, Results);
4472 Results.ExitScope();
4473
4474 switch (CompletionContext) {
4475 case PCC_ParenthesizedExpression:
4476 case PCC_Expression:
4477 case PCC_Statement:
4478 case PCC_TopLevelOrExpression:
4479 case PCC_RecoveryInFunction:
4480 if (S->getFnParent())
4481 AddPrettyFunctionResults(getLangOpts(), Results);
4482 break;
4483
4484 case PCC_Namespace:
4485 case PCC_Class:
4486 case PCC_ObjCInterface:
4487 case PCC_ObjCImplementation:
4488 case PCC_ObjCInstanceVariableList:
4489 case PCC_Template:
4490 case PCC_MemberTemplate:
4491 case PCC_ForInit:
4492 case PCC_Condition:
4493 case PCC_Type:
4494 case PCC_LocalDeclarationSpecifiers:
4495 break;
4496 }
4497
4498 if (CodeCompleter->includeMacros())
4499 AddMacroResults(SemaRef.PP, Results, CodeCompleter->loadExternal(), false);
4500
4501 HandleCodeCompleteResults(&SemaRef, CodeCompleter,
4502 Results.getCompletionContext(), Results.data(),
4503 Results.size());
4504}
4505
4506static void
4507AddClassMessageCompletions(Sema &SemaRef, Scope *S, ParsedType Receiver,
4509 bool AtArgumentExpression, bool IsSuper,
4510 ResultBuilder &Results);
4511
4513 bool AllowNonIdentifiers,
4514 bool AllowNestedNameSpecifiers) {
4516 ResultBuilder Results(
4517 SemaRef, CodeCompleter->getAllocator(),
4518 CodeCompleter->getCodeCompletionTUInfo(),
4519 AllowNestedNameSpecifiers
4520 // FIXME: Try to separate codepath leading here to deduce whether we
4521 // need an existing symbol or a new one.
4524 Results.EnterNewScope();
4525
4526 // Type qualifiers can come after names.
4527 Results.AddResult(Result("const"));
4528 Results.AddResult(Result("volatile"));
4529 if (getLangOpts().C99)
4530 Results.AddResult(Result("restrict"));
4531
4532 if (getLangOpts().CPlusPlus) {
4533 if (getLangOpts().CPlusPlus11 &&
4536 Results.AddResult("final");
4537
4538 if (AllowNonIdentifiers) {
4539 Results.AddResult(Result("operator"));
4540 }
4541
4542 // Add nested-name-specifiers.
4543 if (AllowNestedNameSpecifiers) {
4544 Results.allowNestedNameSpecifiers();
4545 Results.setFilter(&ResultBuilder::IsImpossibleToSatisfy);
4546 CodeCompletionDeclConsumer Consumer(Results, SemaRef.CurContext);
4548 Consumer, CodeCompleter->includeGlobals(),
4549 CodeCompleter->loadExternal());
4550 Results.setFilter(nullptr);
4551 }
4552 }
4553 Results.ExitScope();
4554
4555 // If we're in a context where we might have an expression (rather than a
4556 // declaration), and what we've seen so far is an Objective-C type that could
4557 // be a receiver of a class message, this may be a class message send with
4558 // the initial opening bracket '[' missing. Add appropriate completions.
4559 if (AllowNonIdentifiers && !AllowNestedNameSpecifiers &&
4564 !DS.isTypeAltiVecVector() && S &&
4565 (S->getFlags() & Scope::DeclScope) != 0 &&
4566 (S->getFlags() & (Scope::ClassScope | Scope::TemplateParamScope |
4568 0) {
4569 ParsedType T = DS.getRepAsType();
4570 if (!T.get().isNull() && T.get()->isObjCObjectOrInterfaceType())
4571 AddClassMessageCompletions(SemaRef, S, T, std::nullopt, false, false,
4572 Results);
4573 }
4574
4575 // Note that we intentionally suppress macro results here, since we do not
4576 // encourage using macros to produce the names of entities.
4577
4578 HandleCodeCompleteResults(&SemaRef, CodeCompleter,
4579 Results.getCompletionContext(), Results.data(),
4580 Results.size());
4581}
4582
4583static const char *underscoreAttrScope(llvm::StringRef Scope) {
4584 if (Scope == "clang")
4585 return "_Clang";
4586 if (Scope == "gnu")
4587 return "__gnu__";
4588 return nullptr;
4589}
4590
4591static const char *noUnderscoreAttrScope(llvm::StringRef Scope) {
4592 if (Scope == "_Clang")
4593 return "clang";
4594 if (Scope == "__gnu__")
4595 return "gnu";
4596 return nullptr;
4597}
4598
4601 const IdentifierInfo *InScope) {
4602 if (Completion == AttributeCompletion::None)
4603 return;
4604 ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(),
4605 CodeCompleter->getCodeCompletionTUInfo(),
4607
4608 // We're going to iterate over the normalized spellings of the attribute.
4609 // These don't include "underscore guarding": the normalized spelling is
4610 // clang::foo but you can also write _Clang::__foo__.
4611 //
4612 // (Clang supports a mix like clang::__foo__ but we won't suggest it: either
4613 // you care about clashing with macros or you don't).
4614 //
4615 // So if we're already in a scope, we determine its canonical spellings
4616 // (for comparison with normalized attr spelling) and remember whether it was
4617 // underscore-guarded (so we know how to spell contained attributes).
4618 llvm::StringRef InScopeName;
4619 bool InScopeUnderscore = false;
4620 if (InScope) {
4621 InScopeName = InScope->getName();
4622 if (const char *NoUnderscore = noUnderscoreAttrScope(InScopeName)) {
4623 InScopeName = NoUnderscore;
4624 InScopeUnderscore = true;
4625 }
4626 }
4627 bool SyntaxSupportsGuards = Syntax == AttributeCommonInfo::AS_GNU ||
4630
4631 llvm::DenseSet<llvm::StringRef> FoundScopes;
4632 auto AddCompletions = [&](const ParsedAttrInfo &A) {
4633 if (A.IsTargetSpecific &&
4634 !A.existsInTarget(getASTContext().getTargetInfo()))
4635 return;
4636 if (!A.acceptsLangOpts(getLangOpts()))
4637 return;
4638 for (const auto &S : A.Spellings) {
4639 if (S.Syntax != Syntax)
4640 continue;
4641 llvm::StringRef Name = S.NormalizedFullName;
4642 llvm::StringRef Scope;
4643 if ((Syntax == AttributeCommonInfo::AS_CXX11 ||
4644 Syntax == AttributeCommonInfo::AS_C23)) {
4645 std::tie(Scope, Name) = Name.split("::");
4646 if (Name.empty()) // oops, unscoped
4647 std::swap(Name, Scope);
4648 }
4649
4650 // Do we just want a list of scopes rather than attributes?
4651 if (Completion == AttributeCompletion::Scope) {
4652 // Make sure to emit each scope only once.
4653 if (!Scope.empty() && FoundScopes.insert(Scope).second) {
4654 Results.AddResult(
4655 CodeCompletionResult(Results.getAllocator().CopyString(Scope)));
4656 // Include alternate form (__gnu__ instead of gnu).
4657 if (const char *Scope2 = underscoreAttrScope(Scope))
4658 Results.AddResult(CodeCompletionResult(Scope2));
4659 }
4660 continue;
4661 }
4662
4663 // If a scope was specified, it must match but we don't need to print it.
4664 if (!InScopeName.empty()) {
4665 if (Scope != InScopeName)
4666 continue;
4667 Scope = "";
4668 }
4669
4670 auto Add = [&](llvm::StringRef Scope, llvm::StringRef Name,
4671 bool Underscores) {
4672 CodeCompletionBuilder Builder(Results.getAllocator(),
4673 Results.getCodeCompletionTUInfo());
4675 if (!Scope.empty()) {
4676 Text.append(Scope);
4677 Text.append("::");
4678 }
4679 if (Underscores)
4680 Text.append("__");
4681 Text.append(Name);
4682 if (Underscores)
4683 Text.append("__");
4684 Builder.AddTypedTextChunk(Results.getAllocator().CopyString(Text));
4685
4686 if (!A.ArgNames.empty()) {
4687 Builder.AddChunk(CodeCompletionString::CK_LeftParen, "(");
4688 bool First = true;
4689 for (const char *Arg : A.ArgNames) {
4690 if (!First)
4691 Builder.AddChunk(CodeCompletionString::CK_Comma, ", ");
4692 First = false;
4693 Builder.AddPlaceholderChunk(Arg);
4694 }
4695 Builder.AddChunk(CodeCompletionString::CK_RightParen, ")");
4696 }
4697
4698 Results.AddResult(Builder.TakeString());
4699 };
4700
4701 // Generate the non-underscore-guarded result.
4702 // Note this is (a suffix of) the NormalizedFullName, no need to copy.
4703 // If an underscore-guarded scope was specified, only the
4704 // underscore-guarded attribute name is relevant.
4705 if (!InScopeUnderscore)
4706 Add(Scope, Name, /*Underscores=*/false);
4707
4708 // Generate the underscore-guarded version, for syntaxes that support it.
4709 // We skip this if the scope was already spelled and not guarded, or
4710 // we must spell it and can't guard it.
4711 if (!(InScope && !InScopeUnderscore) && SyntaxSupportsGuards) {
4712 llvm::SmallString<32> Guarded;
4713 if (Scope.empty()) {
4714 Add(Scope, Name, /*Underscores=*/true);
4715 } else {
4716 const char *GuardedScope = underscoreAttrScope(Scope);
4717 if (!GuardedScope)
4718 continue;
4719 Add(GuardedScope, Name, /*Underscores=*/true);
4720 }
4721 }
4722
4723 // It may be nice to include the Kind so we can look up the docs later.
4724 }
4725 };
4726
4727 for (const auto *A : ParsedAttrInfo::getAllBuiltin())
4728 AddCompletions(*A);
4729 for (const auto &Entry : ParsedAttrInfoRegistry::entries())
4730 AddCompletions(*Entry.instantiate());
4731
4732 HandleCodeCompleteResults(&SemaRef, CodeCompleter,
4733 Results.getCompletionContext(), Results.data(),
4734 Results.size());
4735}
4736
4739 bool IsParenthesized = false)
4740 : PreferredType(PreferredType), IntegralConstantExpression(false),
4741 ObjCCollection(false), IsParenthesized(IsParenthesized) {}
4742
4748};
4749
4750namespace {
4751/// Information that allows to avoid completing redundant enumerators.
4752struct CoveredEnumerators {
4754 NestedNameSpecifier *SuggestedQualifier = nullptr;
4755};
4756} // namespace
4757
4758static void AddEnumerators(ResultBuilder &Results, ASTContext &Context,
4759 EnumDecl *Enum, DeclContext *CurContext,
4760 const CoveredEnumerators &Enumerators) {
4761 NestedNameSpecifier *Qualifier = Enumerators.SuggestedQualifier;
4762 if (Context.getLangOpts().CPlusPlus && !Qualifier && Enumerators.Seen.empty()) {
4763 // If there are no prior enumerators in C++, check whether we have to
4764 // qualify the names of the enumerators that we suggest, because they
4765 // may not be visible in this scope.
4766 Qualifier = getRequiredQualification(Context, CurContext, Enum);
4767 }
4768
4769 Results.EnterNewScope();
4770 for (auto *E : Enum->enumerators()) {
4771 if (Enumerators.Seen.count(E))
4772 continue;
4773
4774 CodeCompletionResult R(E, CCP_EnumInCase, Qualifier);
4775 Results.AddResult(R, CurContext, nullptr, false);
4776 }
4777 Results.ExitScope();
4778}
4779
4780/// Try to find a corresponding FunctionProtoType for function-like types (e.g.
4781/// function pointers, std::function, etc).
4783 assert(!T.isNull());
4784 // Try to extract first template argument from std::function<> and similar.
4785 // Note we only handle the sugared types, they closely match what users wrote.
4786 // We explicitly choose to not handle ClassTemplateSpecializationDecl.
4788 if (Specialization->template_arguments().size() != 1)
4789 return nullptr;
4790 const TemplateArgument &Argument = Specialization->template_arguments()[0];
4791 if (Argument.getKind() != TemplateArgument::Type)
4792 return nullptr;
4793 return Argument.getAsType()->getAs<FunctionProtoType>();
4794 }
4795 // Handle other cases.
4796 if (T->isPointerType())
4797 T = T->getPointeeType();
4798 return T->getAs<FunctionProtoType>();
4799}
4800
4801/// Adds a pattern completion for a lambda expression with the specified
4802/// parameter types and placeholders for parameter names.
4803static void AddLambdaCompletion(ResultBuilder &Results,
4804 llvm::ArrayRef<QualType> Parameters,
4805 const LangOptions &LangOpts) {
4806 if (!Results.includeCodePatterns())
4807 return;
4808 CodeCompletionBuilder Completion(Results.getAllocator(),
4809 Results.getCodeCompletionTUInfo());
4810 // [](<parameters>) {}
4812 Completion.AddPlaceholderChunk("=");
4814 if (!Parameters.empty()) {
4816 bool First = true;
4817 for (auto Parameter : Parameters) {
4818 if (!First)
4820 else
4821 First = false;
4822
4823 constexpr llvm::StringLiteral NamePlaceholder = "!#!NAME_GOES_HERE!#!";
4824 std::string Type = std::string(NamePlaceholder);
4825 Parameter.getAsStringInternal(Type, PrintingPolicy(LangOpts));
4826 llvm::StringRef Prefix, Suffix;
4827 std::tie(Prefix, Suffix) = llvm::StringRef(Type).split(NamePlaceholder);
4828 Prefix = Prefix.rtrim();
4829 Suffix = Suffix.ltrim();
4830
4831 Completion.AddTextChunk(Completion.getAllocator().CopyString(Prefix));
4833 Completion.AddPlaceholderChunk("parameter");
4834 Completion.AddTextChunk(Completion.getAllocator().CopyString(Suffix));
4835 };
4837 }
4841 Completion.AddPlaceholderChunk("body");
4844
4845 Results.AddResult(Completion.TakeString());
4846}
4847
4848/// Perform code-completion in an expression context when we know what
4849/// type we're looking for.
4852 ResultBuilder Results(
4853 SemaRef, CodeCompleter->getAllocator(),
4854 CodeCompleter->getCodeCompletionTUInfo(),
4856 Data.IsParenthesized
4859 Data.PreferredType));
4860 auto PCC =
4861 Data.IsParenthesized ? PCC_ParenthesizedExpression : PCC_Expression;
4862 if (Data.ObjCCollection)
4863 Results.setFilter(&ResultBuilder::IsObjCCollection);
4864 else if (Data.IntegralConstantExpression)
4865 Results.setFilter(&ResultBuilder::IsIntegralConstantValue);
4866 else if (WantTypesInContext(PCC, getLangOpts()))
4867 Results.setFilter(&ResultBuilder::IsOrdinaryName);
4868 else
4869 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
4870
4871 if (!Data.PreferredType.isNull())
4872 Results.setPreferredType(Data.PreferredType.getNonReferenceType());
4873
4874 // Ignore any declarations that we were told that we don't care about.
4875 for (unsigned I = 0, N = Data.IgnoreDecls.size(); I != N; ++I)
4876 Results.Ignore(Data.IgnoreDecls[I]);
4877
4878 CodeCompletionDeclConsumer Consumer(Results, SemaRef.CurContext);
4879 SemaRef.LookupVisibleDecls(S, Sema::LookupOrdinaryName, Consumer,
4880 CodeCompleter->includeGlobals(),
4881 CodeCompleter->loadExternal());
4882
4883 Results.EnterNewScope();
4884 AddOrdinaryNameResults(PCC, S, SemaRef, Results);
4885 Results.ExitScope();
4886
4887 bool PreferredTypeIsPointer = false;
4888 if (!Data.PreferredType.isNull()) {
4889 PreferredT