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