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