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