[clangd] don't add inlay hint for dependent type in structured binding
[llvm-project.git] / clang-tools-extra / clangd / InlayHints.cpp
blob56f85ee155cb2368421c26047bfacdc71dae2db2
1 //===--- InlayHints.cpp ------------------------------------------*- 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 #include "InlayHints.h"
9 #include "AST.h"
10 #include "Config.h"
11 #include "HeuristicResolver.h"
12 #include "ParsedAST.h"
13 #include "SourceCode.h"
14 #include "clang/AST/ASTDiagnostic.h"
15 #include "clang/AST/Decl.h"
16 #include "clang/AST/DeclarationName.h"
17 #include "clang/AST/Expr.h"
18 #include "clang/AST/ExprCXX.h"
19 #include "clang/AST/RecursiveASTVisitor.h"
20 #include "clang/AST/Stmt.h"
21 #include "clang/AST/StmtVisitor.h"
22 #include "clang/AST/Type.h"
23 #include "clang/Basic/Builtins.h"
24 #include "clang/Basic/OperatorKinds.h"
25 #include "clang/Basic/SourceManager.h"
26 #include "llvm/ADT/DenseSet.h"
27 #include "llvm/ADT/ScopeExit.h"
28 #include "llvm/ADT/StringExtras.h"
29 #include "llvm/ADT/StringRef.h"
30 #include "llvm/ADT/Twine.h"
31 #include "llvm/Support/Casting.h"
32 #include "llvm/Support/SaveAndRestore.h"
33 #include "llvm/Support/ScopedPrinter.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include <optional>
36 #include <string>
38 namespace clang {
39 namespace clangd {
40 namespace {
42 // For now, inlay hints are always anchored at the left or right of their range.
43 enum class HintSide { Left, Right };
45 // Helper class to iterate over the designator names of an aggregate type.
47 // For an array type, yields [0], [1], [2]...
48 // For aggregate classes, yields null for each base, then .field1, .field2, ...
49 class AggregateDesignatorNames {
50 public:
51 AggregateDesignatorNames(QualType T) {
52 if (!T.isNull()) {
53 T = T.getCanonicalType();
54 if (T->isArrayType()) {
55 IsArray = true;
56 Valid = true;
57 return;
59 if (const RecordDecl *RD = T->getAsRecordDecl()) {
60 Valid = true;
61 FieldsIt = RD->field_begin();
62 FieldsEnd = RD->field_end();
63 if (const auto *CRD = llvm::dyn_cast<CXXRecordDecl>(RD)) {
64 BasesIt = CRD->bases_begin();
65 BasesEnd = CRD->bases_end();
66 Valid = CRD->isAggregate();
68 OneField = Valid && BasesIt == BasesEnd && FieldsIt != FieldsEnd &&
69 std::next(FieldsIt) == FieldsEnd;
73 // Returns false if the type was not an aggregate.
74 operator bool() { return Valid; }
75 // Advance to the next element in the aggregate.
76 void next() {
77 if (IsArray)
78 ++Index;
79 else if (BasesIt != BasesEnd)
80 ++BasesIt;
81 else if (FieldsIt != FieldsEnd)
82 ++FieldsIt;
84 // Print the designator to Out.
85 // Returns false if we could not produce a designator for this element.
86 bool append(std::string &Out, bool ForSubobject) {
87 if (IsArray) {
88 Out.push_back('[');
89 Out.append(std::to_string(Index));
90 Out.push_back(']');
91 return true;
93 if (BasesIt != BasesEnd)
94 return false; // Bases can't be designated. Should we make one up?
95 if (FieldsIt != FieldsEnd) {
96 llvm::StringRef FieldName;
97 if (const IdentifierInfo *II = FieldsIt->getIdentifier())
98 FieldName = II->getName();
100 // For certain objects, their subobjects may be named directly.
101 if (ForSubobject &&
102 (FieldsIt->isAnonymousStructOrUnion() ||
103 // std::array<int,3> x = {1,2,3}. Designators not strictly valid!
104 (OneField && isReservedName(FieldName))))
105 return true;
107 if (!FieldName.empty() && !isReservedName(FieldName)) {
108 Out.push_back('.');
109 Out.append(FieldName.begin(), FieldName.end());
110 return true;
112 return false;
114 return false;
117 private:
118 bool Valid = false;
119 bool IsArray = false;
120 bool OneField = false; // e.g. std::array { T __elements[N]; }
121 unsigned Index = 0;
122 CXXRecordDecl::base_class_const_iterator BasesIt;
123 CXXRecordDecl::base_class_const_iterator BasesEnd;
124 RecordDecl::field_iterator FieldsIt;
125 RecordDecl::field_iterator FieldsEnd;
128 // Collect designator labels describing the elements of an init list.
130 // This function contributes the designators of some (sub)object, which is
131 // represented by the semantic InitListExpr Sem.
132 // This includes any nested subobjects, but *only* if they are part of the same
133 // original syntactic init list (due to brace elision).
134 // In other words, it may descend into subobjects but not written init-lists.
136 // For example: struct Outer { Inner a,b; }; struct Inner { int x, y; }
137 // Outer o{{1, 2}, 3};
138 // This function will be called with Sem = { {1, 2}, {3, ImplicitValue} }
139 // It should generate designators '.a:' and '.b.x:'.
140 // '.a:' is produced directly without recursing into the written sublist.
141 // (The written sublist will have a separate collectDesignators() call later).
142 // Recursion with Prefix='.b' and Sem = {3, ImplicitValue} produces '.b.x:'.
143 void collectDesignators(const InitListExpr *Sem,
144 llvm::DenseMap<SourceLocation, std::string> &Out,
145 const llvm::DenseSet<SourceLocation> &NestedBraces,
146 std::string &Prefix) {
147 if (!Sem || Sem->isTransparent())
148 return;
149 assert(Sem->isSemanticForm());
151 // The elements of the semantic form all correspond to direct subobjects of
152 // the aggregate type. `Fields` iterates over these subobject names.
153 AggregateDesignatorNames Fields(Sem->getType());
154 if (!Fields)
155 return;
156 for (const Expr *Init : Sem->inits()) {
157 auto Next = llvm::make_scope_exit([&, Size(Prefix.size())] {
158 Fields.next(); // Always advance to the next subobject name.
159 Prefix.resize(Size); // Erase any designator we appended.
161 // Skip for a broken initializer or if it is a "hole" in a subobject that
162 // was not explicitly initialized.
163 if (!Init || llvm::isa<ImplicitValueInitExpr>(Init))
164 continue;
166 const auto *BraceElidedSubobject = llvm::dyn_cast<InitListExpr>(Init);
167 if (BraceElidedSubobject &&
168 NestedBraces.contains(BraceElidedSubobject->getLBraceLoc()))
169 BraceElidedSubobject = nullptr; // there were braces!
171 if (!Fields.append(Prefix, BraceElidedSubobject != nullptr))
172 continue; // no designator available for this subobject
173 if (BraceElidedSubobject) {
174 // If the braces were elided, this aggregate subobject is initialized
175 // inline in the same syntactic list.
176 // Descend into the semantic list describing the subobject.
177 // (NestedBraces are still correct, they're from the same syntactic list).
178 collectDesignators(BraceElidedSubobject, Out, NestedBraces, Prefix);
179 continue;
181 Out.try_emplace(Init->getBeginLoc(), Prefix);
185 // Get designators describing the elements of a (syntactic) init list.
186 // This does not produce designators for any explicitly-written nested lists.
187 llvm::DenseMap<SourceLocation, std::string>
188 getDesignators(const InitListExpr *Syn) {
189 assert(Syn->isSyntacticForm());
191 // collectDesignators needs to know which InitListExprs in the semantic tree
192 // were actually written, but InitListExpr::isExplicit() lies.
193 // Instead, record where braces of sub-init-lists occur in the syntactic form.
194 llvm::DenseSet<SourceLocation> NestedBraces;
195 for (const Expr *Init : Syn->inits())
196 if (auto *Nested = llvm::dyn_cast<InitListExpr>(Init))
197 NestedBraces.insert(Nested->getLBraceLoc());
199 // Traverse the semantic form to find the designators.
200 // We use their SourceLocation to correlate with the syntactic form later.
201 llvm::DenseMap<SourceLocation, std::string> Designators;
202 std::string EmptyPrefix;
203 collectDesignators(Syn->isSemanticForm() ? Syn : Syn->getSemanticForm(),
204 Designators, NestedBraces, EmptyPrefix);
205 return Designators;
208 void stripLeadingUnderscores(StringRef &Name) { Name = Name.ltrim('_'); }
210 // getDeclForType() returns the decl responsible for Type's spelling.
211 // This is the inverse of ASTContext::getTypeDeclType().
212 template <typename Ty, typename = decltype(((Ty *)nullptr)->getDecl())>
213 const NamedDecl *getDeclForTypeImpl(const Ty *T) {
214 return T->getDecl();
216 const NamedDecl *getDeclForTypeImpl(const void *T) { return nullptr; }
217 const NamedDecl *getDeclForType(const Type *T) {
218 switch (T->getTypeClass()) {
219 #define ABSTRACT_TYPE(TY, BASE)
220 #define TYPE(TY, BASE) \
221 case Type::TY: \
222 return getDeclForTypeImpl(llvm::cast<TY##Type>(T));
223 #include "clang/AST/TypeNodes.inc"
225 llvm_unreachable("Unknown TypeClass enum");
228 // getSimpleName() returns the plain identifier for an entity, if any.
229 llvm::StringRef getSimpleName(const DeclarationName &DN) {
230 if (IdentifierInfo *Ident = DN.getAsIdentifierInfo())
231 return Ident->getName();
232 return "";
234 llvm::StringRef getSimpleName(const NamedDecl &D) {
235 return getSimpleName(D.getDeclName());
237 llvm::StringRef getSimpleName(QualType T) {
238 if (const auto *ET = llvm::dyn_cast<ElaboratedType>(T))
239 return getSimpleName(ET->getNamedType());
240 if (const auto *BT = llvm::dyn_cast<BuiltinType>(T)) {
241 PrintingPolicy PP(LangOptions{});
242 PP.adjustForCPlusPlus();
243 return BT->getName(PP);
245 if (const auto *D = getDeclForType(T.getTypePtr()))
246 return getSimpleName(D->getDeclName());
247 return "";
250 // Returns a very abbreviated form of an expression, or "" if it's too complex.
251 // For example: `foo->bar()` would produce "bar".
252 // This is used to summarize e.g. the condition of a while loop.
253 std::string summarizeExpr(const Expr *E) {
254 struct Namer : ConstStmtVisitor<Namer, std::string> {
255 std::string Visit(const Expr *E) {
256 if (E == nullptr)
257 return "";
258 return ConstStmtVisitor::Visit(E->IgnoreImplicit());
261 // Any sort of decl reference, we just use the unqualified name.
262 std::string VisitMemberExpr(const MemberExpr *E) {
263 return getSimpleName(*E->getMemberDecl()).str();
265 std::string VisitDeclRefExpr(const DeclRefExpr *E) {
266 return getSimpleName(*E->getFoundDecl()).str();
268 std::string VisitCallExpr(const CallExpr *E) {
269 return Visit(E->getCallee());
271 std::string
272 VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E) {
273 return getSimpleName(E->getMember()).str();
275 std::string
276 VisitDependentScopeDeclRefExpr(const DependentScopeDeclRefExpr *E) {
277 return getSimpleName(E->getDeclName()).str();
279 std::string VisitCXXFunctionalCastExpr(const CXXFunctionalCastExpr *E) {
280 return getSimpleName(E->getType()).str();
282 std::string VisitCXXTemporaryObjectExpr(const CXXTemporaryObjectExpr *E) {
283 return getSimpleName(E->getType()).str();
286 // Step through implicit nodes that clang doesn't classify as such.
287 std::string VisitCXXMemberCallExpr(const CXXMemberCallExpr *E) {
288 // Call to operator bool() inside if (X): dispatch to X.
289 if (E->getNumArgs() == 0 &&
290 E->getMethodDecl()->getDeclName().getNameKind() ==
291 DeclarationName::CXXConversionFunctionName &&
292 E->getSourceRange() ==
293 E->getImplicitObjectArgument()->getSourceRange())
294 return Visit(E->getImplicitObjectArgument());
295 return ConstStmtVisitor::VisitCXXMemberCallExpr(E);
297 std::string VisitCXXConstructExpr(const CXXConstructExpr *E) {
298 if (E->getNumArgs() == 1)
299 return Visit(E->getArg(0));
300 return "";
303 // Literals are just printed
304 std::string VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
305 return E->getValue() ? "true" : "false";
307 std::string VisitIntegerLiteral(const IntegerLiteral *E) {
308 return llvm::to_string(E->getValue());
310 std::string VisitFloatingLiteral(const FloatingLiteral *E) {
311 std::string Result;
312 llvm::raw_string_ostream OS(Result);
313 E->getValue().print(OS);
314 // Printer adds newlines?!
315 Result.resize(llvm::StringRef(Result).rtrim().size());
316 return Result;
318 std::string VisitStringLiteral(const StringLiteral *E) {
319 std::string Result = "\"";
320 if (E->containsNonAscii()) {
321 Result += "...";
322 } else if (E->getLength() > 10) {
323 Result += E->getString().take_front(7);
324 Result += "...";
325 } else {
326 llvm::raw_string_ostream OS(Result);
327 llvm::printEscapedString(E->getString(), OS);
329 Result.push_back('"');
330 return Result;
333 // Simple operators. Motivating cases are `!x` and `I < Length`.
334 std::string printUnary(llvm::StringRef Spelling, const Expr *Operand,
335 bool Prefix) {
336 std::string Sub = Visit(Operand);
337 if (Sub.empty())
338 return "";
339 if (Prefix)
340 return (Spelling + Sub).str();
341 Sub += Spelling;
342 return Sub;
344 bool InsideBinary = false; // No recursing into binary expressions.
345 std::string printBinary(llvm::StringRef Spelling, const Expr *LHSOp,
346 const Expr *RHSOp) {
347 if (InsideBinary)
348 return "";
349 llvm::SaveAndRestore InBinary(InsideBinary, true);
351 std::string LHS = Visit(LHSOp);
352 std::string RHS = Visit(RHSOp);
353 if (LHS.empty() && RHS.empty())
354 return "";
356 if (LHS.empty())
357 LHS = "...";
358 LHS.push_back(' ');
359 LHS += Spelling;
360 LHS.push_back(' ');
361 if (RHS.empty())
362 LHS += "...";
363 else
364 LHS += RHS;
365 return LHS;
367 std::string VisitUnaryOperator(const UnaryOperator *E) {
368 return printUnary(E->getOpcodeStr(E->getOpcode()), E->getSubExpr(),
369 !E->isPostfix());
371 std::string VisitBinaryOperator(const BinaryOperator *E) {
372 return printBinary(E->getOpcodeStr(E->getOpcode()), E->getLHS(),
373 E->getRHS());
375 std::string VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *E) {
376 const char *Spelling = getOperatorSpelling(E->getOperator());
377 // Handle weird unary-that-look-like-binary postfix operators.
378 if ((E->getOperator() == OO_PlusPlus ||
379 E->getOperator() == OO_MinusMinus) &&
380 E->getNumArgs() == 2)
381 return printUnary(Spelling, E->getArg(0), false);
382 if (E->isInfixBinaryOp())
383 return printBinary(Spelling, E->getArg(0), E->getArg(1));
384 if (E->getNumArgs() == 1) {
385 switch (E->getOperator()) {
386 case OO_Plus:
387 case OO_Minus:
388 case OO_Star:
389 case OO_Amp:
390 case OO_Tilde:
391 case OO_Exclaim:
392 case OO_PlusPlus:
393 case OO_MinusMinus:
394 return printUnary(Spelling, E->getArg(0), true);
395 default:
396 break;
399 return "";
402 return Namer{}.Visit(E);
405 // Determines if any intermediate type in desugaring QualType QT is of
406 // substituted template parameter type. Ignore pointer or reference wrappers.
407 bool isSugaredTemplateParameter(QualType QT) {
408 static auto PeelWrapper = [](QualType QT) {
409 // Neither `PointerType` nor `ReferenceType` is considered as sugared
410 // type. Peel it.
411 QualType Peeled = QT->getPointeeType();
412 return Peeled.isNull() ? QT : Peeled;
415 // This is a bit tricky: we traverse the type structure and find whether or
416 // not a type in the desugaring process is of SubstTemplateTypeParmType.
417 // During the process, we may encounter pointer or reference types that are
418 // not marked as sugared; therefore, the desugar function won't apply. To
419 // move forward the traversal, we retrieve the pointees using
420 // QualType::getPointeeType().
422 // However, getPointeeType could leap over our interests: The QT::getAs<T>()
423 // invoked would implicitly desugar the type. Consequently, if the
424 // SubstTemplateTypeParmType is encompassed within a TypedefType, we may lose
425 // the chance to visit it.
426 // For example, given a QT that represents `std::vector<int *>::value_type`:
427 // `-ElaboratedType 'value_type' sugar
428 // `-TypedefType 'vector<int *>::value_type' sugar
429 // |-Typedef 'value_type'
430 // `-SubstTemplateTypeParmType 'int *' sugar class depth 0 index 0 T
431 // |-ClassTemplateSpecialization 'vector'
432 // `-PointerType 'int *'
433 // `-BuiltinType 'int'
434 // Applying `getPointeeType` to QT results in 'int', a child of our target
435 // node SubstTemplateTypeParmType.
437 // As such, we always prefer the desugared over the pointee for next type
438 // in the iteration. It could avoid the getPointeeType's implicit desugaring.
439 while (true) {
440 if (QT->getAs<SubstTemplateTypeParmType>())
441 return true;
442 QualType Desugared = QT->getLocallyUnqualifiedSingleStepDesugaredType();
443 if (Desugared != QT)
444 QT = Desugared;
445 else if (auto Peeled = PeelWrapper(Desugared); Peeled != QT)
446 QT = Peeled;
447 else
448 break;
450 return false;
453 // A simple wrapper for `clang::desugarForDiagnostic` that provides optional
454 // semantic.
455 std::optional<QualType> desugar(ASTContext &AST, QualType QT) {
456 bool ShouldAKA = false;
457 auto Desugared = clang::desugarForDiagnostic(AST, QT, ShouldAKA);
458 if (!ShouldAKA)
459 return std::nullopt;
460 return Desugared;
463 // Apply a series of heuristic methods to determine whether or not a QualType QT
464 // is suitable for desugaring (e.g. getting the real name behind the using-alias
465 // name). If so, return the desugared type. Otherwise, return the unchanged
466 // parameter QT.
468 // This could be refined further. See
469 // https://github.com/clangd/clangd/issues/1298.
470 QualType maybeDesugar(ASTContext &AST, QualType QT) {
471 // Prefer desugared type for name that aliases the template parameters.
472 // This can prevent things like printing opaque `: type` when accessing std
473 // containers.
474 if (isSugaredTemplateParameter(QT))
475 return desugar(AST, QT).value_or(QT);
477 // Prefer desugared type for `decltype(expr)` specifiers.
478 if (QT->isDecltypeType())
479 return QT.getCanonicalType();
480 if (const AutoType *AT = QT->getContainedAutoType())
481 if (!AT->getDeducedType().isNull() &&
482 AT->getDeducedType()->isDecltypeType())
483 return QT.getCanonicalType();
485 return QT;
488 // Given a callee expression `Fn`, if the call is through a function pointer,
489 // try to find the declaration of the corresponding function pointer type,
490 // so that we can recover argument names from it.
491 // FIXME: This function is mostly duplicated in SemaCodeComplete.cpp; unify.
492 static FunctionProtoTypeLoc getPrototypeLoc(Expr *Fn) {
493 TypeLoc Target;
494 Expr *NakedFn = Fn->IgnoreParenCasts();
495 if (const auto *T = NakedFn->getType().getTypePtr()->getAs<TypedefType>()) {
496 Target = T->getDecl()->getTypeSourceInfo()->getTypeLoc();
497 } else if (const auto *DR = dyn_cast<DeclRefExpr>(NakedFn)) {
498 const auto *D = DR->getDecl();
499 if (const auto *const VD = dyn_cast<VarDecl>(D)) {
500 Target = VD->getTypeSourceInfo()->getTypeLoc();
504 if (!Target)
505 return {};
507 // Unwrap types that may be wrapping the function type
508 while (true) {
509 if (auto P = Target.getAs<PointerTypeLoc>()) {
510 Target = P.getPointeeLoc();
511 continue;
513 if (auto A = Target.getAs<AttributedTypeLoc>()) {
514 Target = A.getModifiedLoc();
515 continue;
517 if (auto P = Target.getAs<ParenTypeLoc>()) {
518 Target = P.getInnerLoc();
519 continue;
521 break;
524 if (auto F = Target.getAs<FunctionProtoTypeLoc>()) {
525 return F;
528 return {};
531 struct Callee {
532 // Only one of Decl or Loc is set.
533 // Loc is for calls through function pointers.
534 const FunctionDecl *Decl = nullptr;
535 FunctionProtoTypeLoc Loc;
538 class InlayHintVisitor : public RecursiveASTVisitor<InlayHintVisitor> {
539 public:
540 InlayHintVisitor(std::vector<InlayHint> &Results, ParsedAST &AST,
541 const Config &Cfg, std::optional<Range> RestrictRange)
542 : Results(Results), AST(AST.getASTContext()), Tokens(AST.getTokens()),
543 Cfg(Cfg), RestrictRange(std::move(RestrictRange)),
544 MainFileID(AST.getSourceManager().getMainFileID()),
545 Resolver(AST.getHeuristicResolver()),
546 TypeHintPolicy(this->AST.getPrintingPolicy()) {
547 bool Invalid = false;
548 llvm::StringRef Buf =
549 AST.getSourceManager().getBufferData(MainFileID, &Invalid);
550 MainFileBuf = Invalid ? StringRef{} : Buf;
552 TypeHintPolicy.SuppressScope = true; // keep type names short
553 TypeHintPolicy.AnonymousTagLocations =
554 false; // do not print lambda locations
556 // Not setting PrintCanonicalTypes for "auto" allows
557 // SuppressDefaultTemplateArgs (set by default) to have an effect.
560 bool VisitTypeLoc(TypeLoc TL) {
561 if (const auto *DT = llvm::dyn_cast<DecltypeType>(TL.getType()))
562 if (QualType UT = DT->getUnderlyingType(); !UT->isDependentType())
563 addTypeHint(TL.getSourceRange(), UT, ": ");
564 return true;
567 bool VisitCXXConstructExpr(CXXConstructExpr *E) {
568 // Weed out constructor calls that don't look like a function call with
569 // an argument list, by checking the validity of getParenOrBraceRange().
570 // Also weed out std::initializer_list constructors as there are no names
571 // for the individual arguments.
572 if (!E->getParenOrBraceRange().isValid() ||
573 E->isStdInitListInitialization()) {
574 return true;
577 Callee Callee;
578 Callee.Decl = E->getConstructor();
579 if (!Callee.Decl)
580 return true;
581 processCall(Callee, {E->getArgs(), E->getNumArgs()});
582 return true;
585 bool VisitCallExpr(CallExpr *E) {
586 if (!Cfg.InlayHints.Parameters)
587 return true;
589 // Do not show parameter hints for operator calls written using operator
590 // syntax or user-defined literals. (Among other reasons, the resulting
591 // hints can look awkward, e.g. the expression can itself be a function
592 // argument and then we'd get two hints side by side).
593 if (isa<CXXOperatorCallExpr>(E) || isa<UserDefinedLiteral>(E))
594 return true;
596 auto CalleeDecls = Resolver->resolveCalleeOfCallExpr(E);
597 if (CalleeDecls.size() != 1)
598 return true;
600 Callee Callee;
601 if (const auto *FD = dyn_cast<FunctionDecl>(CalleeDecls[0]))
602 Callee.Decl = FD;
603 else if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(CalleeDecls[0]))
604 Callee.Decl = FTD->getTemplatedDecl();
605 else if (FunctionProtoTypeLoc Loc = getPrototypeLoc(E->getCallee()))
606 Callee.Loc = Loc;
607 else
608 return true;
610 processCall(Callee, {E->getArgs(), E->getNumArgs()});
611 return true;
614 bool VisitFunctionDecl(FunctionDecl *D) {
615 if (auto *FPT =
616 llvm::dyn_cast<FunctionProtoType>(D->getType().getTypePtr())) {
617 if (!FPT->hasTrailingReturn()) {
618 if (auto FTL = D->getFunctionTypeLoc())
619 addReturnTypeHint(D, FTL.getRParenLoc());
622 if (Cfg.InlayHints.BlockEnd && D->isThisDeclarationADefinition()) {
623 // We use `printName` here to properly print name of ctor/dtor/operator
624 // overload.
625 if (const Stmt *Body = D->getBody())
626 addBlockEndHint(Body->getSourceRange(), "", printName(AST, *D), "");
628 return true;
631 bool VisitForStmt(ForStmt *S) {
632 if (Cfg.InlayHints.BlockEnd) {
633 std::string Name;
634 // Common case: for (int I = 0; I < N; I++). Use "I" as the name.
635 if (auto *DS = llvm::dyn_cast_or_null<DeclStmt>(S->getInit());
636 DS && DS->isSingleDecl())
637 Name = getSimpleName(llvm::cast<NamedDecl>(*DS->getSingleDecl()));
638 else
639 Name = summarizeExpr(S->getCond());
640 markBlockEnd(S->getBody(), "for", Name);
642 return true;
645 bool VisitCXXForRangeStmt(CXXForRangeStmt *S) {
646 if (Cfg.InlayHints.BlockEnd)
647 markBlockEnd(S->getBody(), "for", getSimpleName(*S->getLoopVariable()));
648 return true;
651 bool VisitWhileStmt(WhileStmt *S) {
652 if (Cfg.InlayHints.BlockEnd)
653 markBlockEnd(S->getBody(), "while", summarizeExpr(S->getCond()));
654 return true;
657 bool VisitSwitchStmt(SwitchStmt *S) {
658 if (Cfg.InlayHints.BlockEnd)
659 markBlockEnd(S->getBody(), "switch", summarizeExpr(S->getCond()));
660 return true;
663 // If/else chains are tricky.
664 // if (cond1) {
665 // } else if (cond2) {
666 // } // mark as "cond1" or "cond2"?
667 // For now, the answer is neither, just mark as "if".
668 // The ElseIf is a different IfStmt that doesn't know about the outer one.
669 llvm::DenseSet<const IfStmt *> ElseIfs; // not eligible for names
670 bool VisitIfStmt(IfStmt *S) {
671 if (Cfg.InlayHints.BlockEnd) {
672 if (const auto *ElseIf = llvm::dyn_cast_or_null<IfStmt>(S->getElse()))
673 ElseIfs.insert(ElseIf);
674 // Don't use markBlockEnd: the relevant range is [then.begin, else.end].
675 if (const auto *EndCS = llvm::dyn_cast<CompoundStmt>(
676 S->getElse() ? S->getElse() : S->getThen())) {
677 addBlockEndHint(
678 {S->getThen()->getBeginLoc(), EndCS->getRBracLoc()}, "if",
679 ElseIfs.contains(S) ? "" : summarizeExpr(S->getCond()), "");
682 return true;
685 void markBlockEnd(const Stmt *Body, llvm::StringRef Label,
686 llvm::StringRef Name = "") {
687 if (const auto *CS = llvm::dyn_cast_or_null<CompoundStmt>(Body))
688 addBlockEndHint(CS->getSourceRange(), Label, Name, "");
691 bool VisitTagDecl(TagDecl *D) {
692 if (Cfg.InlayHints.BlockEnd && D->isThisDeclarationADefinition()) {
693 std::string DeclPrefix = D->getKindName().str();
694 if (const auto *ED = dyn_cast<EnumDecl>(D)) {
695 if (ED->isScoped())
696 DeclPrefix += ED->isScopedUsingClassTag() ? " class" : " struct";
698 addBlockEndHint(D->getBraceRange(), DeclPrefix, getSimpleName(*D), ";");
700 return true;
703 bool VisitNamespaceDecl(NamespaceDecl *D) {
704 if (Cfg.InlayHints.BlockEnd) {
705 // For namespace, the range actually starts at the namespace keyword. But
706 // it should be fine since it's usually very short.
707 addBlockEndHint(D->getSourceRange(), "namespace", getSimpleName(*D), "");
709 return true;
712 bool VisitLambdaExpr(LambdaExpr *E) {
713 FunctionDecl *D = E->getCallOperator();
714 if (!E->hasExplicitResultType())
715 addReturnTypeHint(D, E->hasExplicitParameters()
716 ? D->getFunctionTypeLoc().getRParenLoc()
717 : E->getIntroducerRange().getEnd());
718 return true;
721 void addReturnTypeHint(FunctionDecl *D, SourceRange Range) {
722 auto *AT = D->getReturnType()->getContainedAutoType();
723 if (!AT || AT->getDeducedType().isNull())
724 return;
725 addTypeHint(Range, D->getReturnType(), /*Prefix=*/"-> ");
728 bool VisitVarDecl(VarDecl *D) {
729 // Do not show hints for the aggregate in a structured binding,
730 // but show hints for the individual bindings.
731 if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
732 for (auto *Binding : DD->bindings()) {
733 // For structured bindings, print canonical types. This is important
734 // because for bindings that use the tuple_element protocol, the
735 // non-canonical types would be "tuple_element<I, A>::type".
736 if (auto Type = Binding->getType();
737 !Type.isNull() && !Type->isDependentType())
738 addTypeHint(Binding->getLocation(), Type.getCanonicalType(),
739 /*Prefix=*/": ");
741 return true;
744 if (auto *AT = D->getType()->getContainedAutoType()) {
745 if (AT->isDeduced() && !D->getType()->isDependentType()) {
746 // Our current approach is to place the hint on the variable
747 // and accordingly print the full type
748 // (e.g. for `const auto& x = 42`, print `const int&`).
749 // Alternatively, we could place the hint on the `auto`
750 // (and then just print the type deduced for the `auto`).
751 addTypeHint(D->getLocation(), D->getType(), /*Prefix=*/": ");
755 // Handle templates like `int foo(auto x)` with exactly one instantiation.
756 if (auto *PVD = llvm::dyn_cast<ParmVarDecl>(D)) {
757 if (D->getIdentifier() && PVD->getType()->isDependentType() &&
758 !getContainedAutoParamType(D->getTypeSourceInfo()->getTypeLoc())
759 .isNull()) {
760 if (auto *IPVD = getOnlyParamInstantiation(PVD))
761 addTypeHint(D->getLocation(), IPVD->getType(), /*Prefix=*/": ");
765 return true;
768 ParmVarDecl *getOnlyParamInstantiation(ParmVarDecl *D) {
769 auto *TemplateFunction = llvm::dyn_cast<FunctionDecl>(D->getDeclContext());
770 if (!TemplateFunction)
771 return nullptr;
772 auto *InstantiatedFunction = llvm::dyn_cast_or_null<FunctionDecl>(
773 getOnlyInstantiation(TemplateFunction));
774 if (!InstantiatedFunction)
775 return nullptr;
777 unsigned ParamIdx = 0;
778 for (auto *Param : TemplateFunction->parameters()) {
779 // Can't reason about param indexes in the presence of preceding packs.
780 // And if this param is a pack, it may expand to multiple params.
781 if (Param->isParameterPack())
782 return nullptr;
783 if (Param == D)
784 break;
785 ++ParamIdx;
787 assert(ParamIdx < TemplateFunction->getNumParams() &&
788 "Couldn't find param in list?");
789 assert(ParamIdx < InstantiatedFunction->getNumParams() &&
790 "Instantiated function has fewer (non-pack) parameters?");
791 return InstantiatedFunction->getParamDecl(ParamIdx);
794 bool VisitInitListExpr(InitListExpr *Syn) {
795 // We receive the syntactic form here (shouldVisitImplicitCode() is false).
796 // This is the one we will ultimately attach designators to.
797 // It may have subobject initializers inlined without braces. The *semantic*
798 // form of the init-list has nested init-lists for these.
799 // getDesignators will look at the semantic form to determine the labels.
800 assert(Syn->isSyntacticForm() && "RAV should not visit implicit code!");
801 if (!Cfg.InlayHints.Designators)
802 return true;
803 if (Syn->isIdiomaticZeroInitializer(AST.getLangOpts()))
804 return true;
805 llvm::DenseMap<SourceLocation, std::string> Designators =
806 getDesignators(Syn);
807 for (const Expr *Init : Syn->inits()) {
808 if (llvm::isa<DesignatedInitExpr>(Init))
809 continue;
810 auto It = Designators.find(Init->getBeginLoc());
811 if (It != Designators.end() &&
812 !isPrecededByParamNameComment(Init, It->second))
813 addDesignatorHint(Init->getSourceRange(), It->second);
815 return true;
818 // FIXME: Handle RecoveryExpr to try to hint some invalid calls.
820 private:
821 using NameVec = SmallVector<StringRef, 8>;
823 void processCall(Callee Callee, llvm::ArrayRef<const Expr *> Args) {
824 assert(Callee.Decl || Callee.Loc);
826 if (!Cfg.InlayHints.Parameters || Args.size() == 0)
827 return;
829 // The parameter name of a move or copy constructor is not very interesting.
830 if (Callee.Decl)
831 if (auto *Ctor = dyn_cast<CXXConstructorDecl>(Callee.Decl))
832 if (Ctor->isCopyOrMoveConstructor())
833 return;
835 auto Params =
836 Callee.Decl ? Callee.Decl->parameters() : Callee.Loc.getParams();
838 // Resolve parameter packs to their forwarded parameter
839 SmallVector<const ParmVarDecl *> ForwardedParams;
840 if (Callee.Decl)
841 ForwardedParams = resolveForwardingParameters(Callee.Decl);
842 else
843 ForwardedParams = {Params.begin(), Params.end()};
845 NameVec ParameterNames = chooseParameterNames(ForwardedParams);
847 // Exclude setters (i.e. functions with one argument whose name begins with
848 // "set"), and builtins like std::move/forward/... as their parameter name
849 // is also not likely to be interesting.
850 if (Callee.Decl &&
851 (isSetter(Callee.Decl, ParameterNames) || isSimpleBuiltin(Callee.Decl)))
852 return;
854 for (size_t I = 0; I < ParameterNames.size() && I < Args.size(); ++I) {
855 // Pack expansion expressions cause the 1:1 mapping between arguments and
856 // parameters to break down, so we don't add further inlay hints if we
857 // encounter one.
858 if (isa<PackExpansionExpr>(Args[I])) {
859 break;
862 StringRef Name = ParameterNames[I];
863 bool NameHint = shouldHintName(Args[I], Name);
864 bool ReferenceHint = shouldHintReference(Params[I], ForwardedParams[I]);
866 if (NameHint || ReferenceHint) {
867 addInlayHint(Args[I]->getSourceRange(), HintSide::Left,
868 InlayHintKind::Parameter, ReferenceHint ? "&" : "",
869 NameHint ? Name : "", ": ");
874 static bool isSetter(const FunctionDecl *Callee, const NameVec &ParamNames) {
875 if (ParamNames.size() != 1)
876 return false;
878 StringRef Name = getSimpleName(*Callee);
879 if (!Name.starts_with_insensitive("set"))
880 return false;
882 // In addition to checking that the function has one parameter and its
883 // name starts with "set", also check that the part after "set" matches
884 // the name of the parameter (ignoring case). The idea here is that if
885 // the parameter name differs, it may contain extra information that
886 // may be useful to show in a hint, as in:
887 // void setTimeout(int timeoutMillis);
888 // This currently doesn't handle cases where params use snake_case
889 // and functions don't, e.g.
890 // void setExceptionHandler(EHFunc exception_handler);
891 // We could improve this by replacing `equals_insensitive` with some
892 // `sloppy_equals` which ignores case and also skips underscores.
893 StringRef WhatItIsSetting = Name.substr(3).ltrim("_");
894 return WhatItIsSetting.equals_insensitive(ParamNames[0]);
897 // Checks if the callee is one of the builtins
898 // addressof, as_const, forward, move(_if_noexcept)
899 static bool isSimpleBuiltin(const FunctionDecl *Callee) {
900 switch (Callee->getBuiltinID()) {
901 case Builtin::BIaddressof:
902 case Builtin::BIas_const:
903 case Builtin::BIforward:
904 case Builtin::BImove:
905 case Builtin::BImove_if_noexcept:
906 return true;
907 default:
908 return false;
912 bool shouldHintName(const Expr *Arg, StringRef ParamName) {
913 if (ParamName.empty())
914 return false;
916 // If the argument expression is a single name and it matches the
917 // parameter name exactly, omit the name hint.
918 if (ParamName == getSpelledIdentifier(Arg))
919 return false;
921 // Exclude argument expressions preceded by a /*paramName*/.
922 if (isPrecededByParamNameComment(Arg, ParamName))
923 return false;
925 return true;
928 bool shouldHintReference(const ParmVarDecl *Param,
929 const ParmVarDecl *ForwardedParam) {
930 // We add a & hint only when the argument is passed as mutable reference.
931 // For parameters that are not part of an expanded pack, this is
932 // straightforward. For expanded pack parameters, it's likely that they will
933 // be forwarded to another function. In this situation, we only want to add
934 // the reference hint if the argument is actually being used via mutable
935 // reference. This means we need to check
936 // 1. whether the value category of the argument is preserved, i.e. each
937 // pack expansion uses std::forward correctly.
938 // 2. whether the argument is ever copied/cast instead of passed
939 // by-reference
940 // Instead of checking this explicitly, we use the following proxy:
941 // 1. the value category can only change from rvalue to lvalue during
942 // forwarding, so checking whether both the parameter of the forwarding
943 // function and the forwarded function are lvalue references detects such
944 // a conversion.
945 // 2. if the argument is copied/cast somewhere in the chain of forwarding
946 // calls, it can only be passed on to an rvalue reference or const lvalue
947 // reference parameter. Thus if the forwarded parameter is a mutable
948 // lvalue reference, it cannot have been copied/cast to on the way.
949 // Additionally, we should not add a reference hint if the forwarded
950 // parameter was only partially resolved, i.e. points to an expanded pack
951 // parameter, since we do not know how it will be used eventually.
952 auto Type = Param->getType();
953 auto ForwardedType = ForwardedParam->getType();
954 return Type->isLValueReferenceType() &&
955 ForwardedType->isLValueReferenceType() &&
956 !ForwardedType.getNonReferenceType().isConstQualified() &&
957 !isExpandedFromParameterPack(ForwardedParam);
960 // Checks if "E" is spelled in the main file and preceded by a C-style comment
961 // whose contents match ParamName (allowing for whitespace and an optional "="
962 // at the end.
963 bool isPrecededByParamNameComment(const Expr *E, StringRef ParamName) {
964 auto &SM = AST.getSourceManager();
965 auto FileLoc = SM.getFileLoc(E->getBeginLoc());
966 auto Decomposed = SM.getDecomposedLoc(FileLoc);
967 if (Decomposed.first != MainFileID)
968 return false;
970 StringRef SourcePrefix = MainFileBuf.substr(0, Decomposed.second);
971 // Allow whitespace between comment and expression.
972 SourcePrefix = SourcePrefix.rtrim();
973 // Check for comment ending.
974 if (!SourcePrefix.consume_back("*/"))
975 return false;
976 // Ignore some punctuation and whitespace around comment.
977 // In particular this allows designators to match nicely.
978 llvm::StringLiteral IgnoreChars = " =.";
979 SourcePrefix = SourcePrefix.rtrim(IgnoreChars);
980 ParamName = ParamName.trim(IgnoreChars);
981 // Other than that, the comment must contain exactly ParamName.
982 if (!SourcePrefix.consume_back(ParamName))
983 return false;
984 SourcePrefix = SourcePrefix.rtrim(IgnoreChars);
985 return SourcePrefix.endswith("/*");
988 // If "E" spells a single unqualified identifier, return that name.
989 // Otherwise, return an empty string.
990 static StringRef getSpelledIdentifier(const Expr *E) {
991 E = E->IgnoreUnlessSpelledInSource();
993 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
994 if (!DRE->getQualifier())
995 return getSimpleName(*DRE->getDecl());
997 if (auto *ME = dyn_cast<MemberExpr>(E))
998 if (!ME->getQualifier() && ME->isImplicitAccess())
999 return getSimpleName(*ME->getMemberDecl());
1001 return {};
1004 NameVec chooseParameterNames(SmallVector<const ParmVarDecl *> Parameters) {
1005 NameVec ParameterNames;
1006 for (const auto *P : Parameters) {
1007 if (isExpandedFromParameterPack(P)) {
1008 // If we haven't resolved a pack paramater (e.g. foo(Args... args)) to a
1009 // non-pack parameter, then hinting as foo(args: 1, args: 2, args: 3) is
1010 // unlikely to be useful.
1011 ParameterNames.emplace_back();
1012 } else {
1013 auto SimpleName = getSimpleName(*P);
1014 // If the parameter is unnamed in the declaration:
1015 // attempt to get its name from the definition
1016 if (SimpleName.empty()) {
1017 if (const auto *PD = getParamDefinition(P)) {
1018 SimpleName = getSimpleName(*PD);
1021 ParameterNames.emplace_back(SimpleName);
1025 // Standard library functions often have parameter names that start
1026 // with underscores, which makes the hints noisy, so strip them out.
1027 for (auto &Name : ParameterNames)
1028 stripLeadingUnderscores(Name);
1030 return ParameterNames;
1033 // for a ParmVarDecl from a function declaration, returns the corresponding
1034 // ParmVarDecl from the definition if possible, nullptr otherwise.
1035 static const ParmVarDecl *getParamDefinition(const ParmVarDecl *P) {
1036 if (auto *Callee = dyn_cast<FunctionDecl>(P->getDeclContext())) {
1037 if (auto *Def = Callee->getDefinition()) {
1038 auto I = std::distance(Callee->param_begin(),
1039 llvm::find(Callee->parameters(), P));
1040 if (I < Callee->getNumParams()) {
1041 return Def->getParamDecl(I);
1045 return nullptr;
1048 // We pass HintSide rather than SourceLocation because we want to ensure
1049 // it is in the same file as the common file range.
1050 void addInlayHint(SourceRange R, HintSide Side, InlayHintKind Kind,
1051 llvm::StringRef Prefix, llvm::StringRef Label,
1052 llvm::StringRef Suffix) {
1053 auto LSPRange = getHintRange(R);
1054 if (!LSPRange)
1055 return;
1057 addInlayHint(*LSPRange, Side, Kind, Prefix, Label, Suffix);
1060 void addInlayHint(Range LSPRange, HintSide Side, InlayHintKind Kind,
1061 llvm::StringRef Prefix, llvm::StringRef Label,
1062 llvm::StringRef Suffix) {
1063 // We shouldn't get as far as adding a hint if the category is disabled.
1064 // We'd like to disable as much of the analysis as possible above instead.
1065 // Assert in debug mode but add a dynamic check in production.
1066 assert(Cfg.InlayHints.Enabled && "Shouldn't get here if disabled!");
1067 switch (Kind) {
1068 #define CHECK_KIND(Enumerator, ConfigProperty) \
1069 case InlayHintKind::Enumerator: \
1070 assert(Cfg.InlayHints.ConfigProperty && \
1071 "Shouldn't get here if kind is disabled!"); \
1072 if (!Cfg.InlayHints.ConfigProperty) \
1073 return; \
1074 break
1075 CHECK_KIND(Parameter, Parameters);
1076 CHECK_KIND(Type, DeducedTypes);
1077 CHECK_KIND(Designator, Designators);
1078 CHECK_KIND(BlockEnd, BlockEnd);
1079 #undef CHECK_KIND
1082 Position LSPPos = Side == HintSide::Left ? LSPRange.start : LSPRange.end;
1083 if (RestrictRange &&
1084 (LSPPos < RestrictRange->start || !(LSPPos < RestrictRange->end)))
1085 return;
1086 bool PadLeft = Prefix.consume_front(" ");
1087 bool PadRight = Suffix.consume_back(" ");
1088 Results.push_back(InlayHint{LSPPos, (Prefix + Label + Suffix).str(), Kind,
1089 PadLeft, PadRight, LSPRange});
1092 // Get the range of the main file that *exactly* corresponds to R.
1093 std::optional<Range> getHintRange(SourceRange R) {
1094 const auto &SM = AST.getSourceManager();
1095 auto Spelled = Tokens.spelledForExpanded(Tokens.expandedTokens(R));
1096 // TokenBuffer will return null if e.g. R corresponds to only part of a
1097 // macro expansion.
1098 if (!Spelled || Spelled->empty())
1099 return std::nullopt;
1100 // Hint must be within the main file, not e.g. a non-preamble include.
1101 if (SM.getFileID(Spelled->front().location()) != SM.getMainFileID() ||
1102 SM.getFileID(Spelled->back().location()) != SM.getMainFileID())
1103 return std::nullopt;
1104 return Range{sourceLocToPosition(SM, Spelled->front().location()),
1105 sourceLocToPosition(SM, Spelled->back().endLocation())};
1108 void addTypeHint(SourceRange R, QualType T, llvm::StringRef Prefix) {
1109 if (!Cfg.InlayHints.DeducedTypes || T.isNull())
1110 return;
1112 // The sugared type is more useful in some cases, and the canonical
1113 // type in other cases.
1114 auto Desugared = maybeDesugar(AST, T);
1115 std::string TypeName = Desugared.getAsString(TypeHintPolicy);
1116 if (T != Desugared && !shouldPrintTypeHint(TypeName)) {
1117 // If the desugared type is too long to display, fallback to the sugared
1118 // type.
1119 TypeName = T.getAsString(TypeHintPolicy);
1121 if (shouldPrintTypeHint(TypeName))
1122 addInlayHint(R, HintSide::Right, InlayHintKind::Type, Prefix, TypeName,
1123 /*Suffix=*/"");
1126 void addDesignatorHint(SourceRange R, llvm::StringRef Text) {
1127 addInlayHint(R, HintSide::Left, InlayHintKind::Designator,
1128 /*Prefix=*/"", Text, /*Suffix=*/"=");
1131 bool shouldPrintTypeHint(llvm::StringRef TypeName) const noexcept {
1132 return Cfg.InlayHints.TypeNameLimit == 0 ||
1133 TypeName.size() < Cfg.InlayHints.TypeNameLimit;
1136 void addBlockEndHint(SourceRange BraceRange, StringRef DeclPrefix,
1137 StringRef Name, StringRef OptionalPunctuation) {
1138 auto HintRange = computeBlockEndHintRange(BraceRange, OptionalPunctuation);
1139 if (!HintRange)
1140 return;
1142 std::string Label = DeclPrefix.str();
1143 if (!Label.empty() && !Name.empty())
1144 Label += ' ';
1145 Label += Name;
1147 constexpr unsigned HintMaxLengthLimit = 60;
1148 if (Label.length() > HintMaxLengthLimit)
1149 return;
1151 addInlayHint(*HintRange, HintSide::Right, InlayHintKind::BlockEnd, " // ",
1152 Label, "");
1155 // Compute the LSP range to attach the block end hint to, if any allowed.
1156 // 1. "}" is the last non-whitespace character on the line. The range of "}"
1157 // is returned.
1158 // 2. After "}", if the trimmed trailing text is exactly
1159 // `OptionalPunctuation`, say ";". The range of "} ... ;" is returned.
1160 // Otherwise, the hint shouldn't be shown.
1161 std::optional<Range> computeBlockEndHintRange(SourceRange BraceRange,
1162 StringRef OptionalPunctuation) {
1163 constexpr unsigned HintMinLineLimit = 2;
1165 auto &SM = AST.getSourceManager();
1166 auto [BlockBeginFileId, BlockBeginOffset] =
1167 SM.getDecomposedLoc(SM.getFileLoc(BraceRange.getBegin()));
1168 auto RBraceLoc = SM.getFileLoc(BraceRange.getEnd());
1169 auto [RBraceFileId, RBraceOffset] = SM.getDecomposedLoc(RBraceLoc);
1171 // Because we need to check the block satisfies the minimum line limit, we
1172 // require both source location to be in the main file. This prevents hint
1173 // to be shown in weird cases like '{' is actually in a "#include", but it's
1174 // rare anyway.
1175 if (BlockBeginFileId != MainFileID || RBraceFileId != MainFileID)
1176 return std::nullopt;
1178 StringRef RestOfLine = MainFileBuf.substr(RBraceOffset).split('\n').first;
1179 if (!RestOfLine.starts_with("}"))
1180 return std::nullopt;
1182 StringRef TrimmedTrailingText = RestOfLine.drop_front().trim();
1183 if (!TrimmedTrailingText.empty() &&
1184 TrimmedTrailingText != OptionalPunctuation)
1185 return std::nullopt;
1187 auto BlockBeginLine = SM.getLineNumber(BlockBeginFileId, BlockBeginOffset);
1188 auto RBraceLine = SM.getLineNumber(RBraceFileId, RBraceOffset);
1190 // Don't show hint on trivial blocks like `class X {};`
1191 if (BlockBeginLine + HintMinLineLimit - 1 > RBraceLine)
1192 return std::nullopt;
1194 // This is what we attach the hint to, usually "}" or "};".
1195 StringRef HintRangeText = RestOfLine.take_front(
1196 TrimmedTrailingText.empty()
1198 : TrimmedTrailingText.bytes_end() - RestOfLine.bytes_begin());
1200 Position HintStart = sourceLocToPosition(SM, RBraceLoc);
1201 Position HintEnd = sourceLocToPosition(
1202 SM, RBraceLoc.getLocWithOffset(HintRangeText.size()));
1203 return Range{HintStart, HintEnd};
1206 std::vector<InlayHint> &Results;
1207 ASTContext &AST;
1208 const syntax::TokenBuffer &Tokens;
1209 const Config &Cfg;
1210 std::optional<Range> RestrictRange;
1211 FileID MainFileID;
1212 StringRef MainFileBuf;
1213 const HeuristicResolver *Resolver;
1214 PrintingPolicy TypeHintPolicy;
1217 } // namespace
1219 std::vector<InlayHint> inlayHints(ParsedAST &AST,
1220 std::optional<Range> RestrictRange) {
1221 std::vector<InlayHint> Results;
1222 const auto &Cfg = Config::current();
1223 if (!Cfg.InlayHints.Enabled)
1224 return Results;
1225 InlayHintVisitor Visitor(Results, AST, Cfg, std::move(RestrictRange));
1226 Visitor.TraverseAST(AST.getASTContext());
1228 // De-duplicate hints. Duplicates can sometimes occur due to e.g. explicit
1229 // template instantiations.
1230 llvm::sort(Results);
1231 Results.erase(std::unique(Results.begin(), Results.end()), Results.end());
1233 return Results;
1236 } // namespace clangd
1237 } // namespace clang