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