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>
37
38namespace clang {
39namespace clangd {
40namespace {
41
42// For now, inlay hints are always anchored at the left or right of their range.
43enum class HintSide { Left, Right };
44
45// Helper class to iterate over the designator names of an aggregate type.
46//
47// For an array type, yields [0], [1], [2]...
48// For aggregate classes, yields null for each base, then .field1, .field2, ...
49class AggregateDesignatorNames {
50public:
51 AggregateDesignatorNames(QualType T) {
52 if (!T.isNull()) {
53 T = T.getCanonicalType();
54 if (T->isArrayType()) {
55 IsArray = true;
56 Valid = true;
57 return;
58 }
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();
67 }
68 OneField = Valid && BasesIt == BasesEnd && FieldsIt != FieldsEnd &&
69 std::next(FieldsIt) == FieldsEnd;
70 }
71 }
72 }
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;
83 }
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;
92 }
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();
99
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;
106
107 if (!FieldName.empty() && !isReservedName(FieldName)) {
108 Out.push_back('.');
109 Out.append(FieldName.begin(), FieldName.end());
110 return true;
111 }
112 return false;
113 }
114 return false;
115 }
116
117private:
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;
126};
127
128// Collect designator labels describing the elements of an init list.
129//
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.
135//
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:'.
143void 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());
150
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.
160 });
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;
165
166 const auto *BraceElidedSubobject = llvm::dyn_cast<InitListExpr>(Init);
167 if (BraceElidedSubobject &&
168 NestedBraces.contains(BraceElidedSubobject->getLBraceLoc()))
169 BraceElidedSubobject = nullptr; // there were braces!
170
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;
180 }
181 Out.try_emplace(Init->getBeginLoc(), Prefix);
182 }
183}
184
185// Get designators describing the elements of a (syntactic) init list.
186// This does not produce designators for any explicitly-written nested lists.
187llvm::DenseMap<SourceLocation, std::string>
188getDesignators(const InitListExpr *Syn) {
189 assert(Syn->isSyntacticForm());
190
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());
198
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;
206}
207
208void stripLeadingUnderscores(StringRef &Name) { Name = Name.ltrim('_'); }
209
210// getDeclForType() returns the decl responsible for Type's spelling.
211// This is the inverse of ASTContext::getTypeDeclType().
212template <typename Ty, typename = decltype(((Ty *)nullptr)->getDecl())>
213const NamedDecl *getDeclForTypeImpl(const Ty *T) {
214 return T->getDecl();
215}
216const NamedDecl *getDeclForTypeImpl(const void *T) { return nullptr; }
217const 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"
224 }
225 llvm_unreachable("Unknown TypeClass enum");
226}
227
228// getSimpleName() returns the plain identifier for an entity, if any.
229llvm::StringRef getSimpleName(const DeclarationName &DN) {
230 if (IdentifierInfo *Ident = DN.getAsIdentifierInfo())
231 return Ident->getName();
232 return "";
233}
234llvm::StringRef getSimpleName(const NamedDecl &D) {
235 return getSimpleName(D.getDeclName());
236}
237llvm::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);
244 }
245 if (const auto *D = getDeclForType(T.getTypePtr()))
246 return getSimpleName(D->getDeclName());
247 return "";
248}
249
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.
253std::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());
259 }
260
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();
264 }
265 std::string VisitDeclRefExpr(const DeclRefExpr *E) {
266 return getSimpleName(*E->getFoundDecl()).str();
267 }
268 std::string VisitCallExpr(const CallExpr *E) {
269 return Visit(E->getCallee());
270 }
271 std::string
272 VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E) {
273 return getSimpleName(E->getMember()).str();
274 }
275 std::string
276 VisitDependentScopeMemberExpr(const DependentScopeDeclRefExpr *E) {
277 return getSimpleName(E->getDeclName()).str();
278 }
279 std::string VisitCXXFunctionalCastExpr(const CXXFunctionalCastExpr *E) {
280 return getSimpleName(E->getType()).str();
281 }
282 std::string VisitCXXTemporaryObjectExpr(const CXXTemporaryObjectExpr *E) {
283 return getSimpleName(E->getType()).str();
284 }
285
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);
296 }
297 std::string VisitCXXConstructExpr(const CXXConstructExpr *E) {
298 if (E->getNumArgs() == 1)
299 return Visit(E->getArg(0));
300 return "";
301 }
302
303 // Literals are just printed
304 std::string VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
305 return E->getValue() ? "true" : "false";
306 }
307 std::string VisitIntegerLiteral(const IntegerLiteral *E) {
308 return llvm::to_string(E->getValue());
309 }
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;
317 }
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);
328 }
329 Result.push_back('"');
330 return Result;
331 }
332
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;
343 }
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);
350
351 std::string LHS = Visit(LHSOp);
352 std::string RHS = Visit(RHSOp);
353 if (LHS.empty() && RHS.empty())
354 return "";
355
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;
366 }
367 std::string VisitUnaryOperator(const UnaryOperator *E) {
368 return printUnary(E->getOpcodeStr(E->getOpcode()), E->getSubExpr(),
369 !E->isPostfix());
370 }
371 std::string VisitBinaryOperator(const BinaryOperator *E) {
372 return printBinary(E->getOpcodeStr(E->getOpcode()), E->getLHS(),
373 E->getRHS());
374 }
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;
397 }
398 }
399 return "";
400 }
401 };
402 return Namer{}.Visit(E);
403}
404
405// Determines if any intermediate type in desugaring QualType QT is of
406// substituted template parameter type. Ignore pointer or reference wrappers.
407bool isSugaredTemplateParameter(QualType QT) {
408 static auto PeelWrappers = [](QualType QT) {
409 // Neither `PointerType` nor `ReferenceType` is considered as sugared
410 // type. Peel it.
411 QualType Next;
412 while (!(Next = QT->getPointeeType()).isNull())
413 QT = Next;
414 return QT;
415 };
416 while (true) {
417 QualType Desugared =
418 PeelWrappers(QT->getLocallyUnqualifiedSingleStepDesugaredType());
419 if (Desugared == QT)
420 break;
421 if (Desugared->getAs<SubstTemplateTypeParmType>())
422 return true;
423 QT = Desugared;
424 }
425 return false;
426}
427
428// A simple wrapper for `clang::desugarForDiagnostic` that provides optional
429// semantic.
430std::optional<QualType> desugar(ASTContext &AST, QualType QT) {
431 bool ShouldAKA = false;
432 auto Desugared = clang::desugarForDiagnostic(AST, QT, ShouldAKA);
433 if (!ShouldAKA)
434 return std::nullopt;
435 return Desugared;
436}
437
438// Apply a series of heuristic methods to determine whether or not a QualType QT
439// is suitable for desugaring (e.g. getting the real name behind the using-alias
440// name). If so, return the desugared type. Otherwise, return the unchanged
441// parameter QT.
442//
443// This could be refined further. See
444// https://github.com/clangd/clangd/issues/1298.
445QualType maybeDesugar(ASTContext &AST, QualType QT) {
446 // Prefer desugared type for name that aliases the template parameters.
447 // This can prevent things like printing opaque `: type` when accessing std
448 // containers.
449 if (isSugaredTemplateParameter(QT))
450 return desugar(AST, QT).value_or(QT);
451
452 // Prefer desugared type for `decltype(expr)` specifiers.
453 if (QT->isDecltypeType())
454 return QT.getCanonicalType();
455 if (const AutoType *AT = QT->getContainedAutoType())
456 if (!AT->getDeducedType().isNull() &&
457 AT->getDeducedType()->isDecltypeType())
458 return QT.getCanonicalType();
459
460 return QT;
461}
462
463class InlayHintVisitor : public RecursiveASTVisitor<InlayHintVisitor> {
464public:
465 InlayHintVisitor(std::vector<InlayHint> &Results, ParsedAST &AST,
466 const Config &Cfg, std::optional<Range> RestrictRange)
467 : Results(Results), AST(AST.getASTContext()), Tokens(AST.getTokens()),
468 Cfg(Cfg), RestrictRange(std::move(RestrictRange)),
469 MainFileID(AST.getSourceManager().getMainFileID()),
470 Resolver(AST.getHeuristicResolver()),
471 TypeHintPolicy(this->AST.getPrintingPolicy()) {
472 bool Invalid = false;
473 llvm::StringRef Buf =
474 AST.getSourceManager().getBufferData(MainFileID, &Invalid);
475 MainFileBuf = Invalid ? StringRef{} : Buf;
476
477 TypeHintPolicy.SuppressScope = true; // keep type names short
478 TypeHintPolicy.AnonymousTagLocations =
479 false; // do not print lambda locations
480
481 // Not setting PrintCanonicalTypes for "auto" allows
482 // SuppressDefaultTemplateArgs (set by default) to have an effect.
483 }
484
485 bool VisitTypeLoc(TypeLoc TL) {
486 if (const auto *DT = llvm::dyn_cast<DecltypeType>(TL.getType()))
487 if (QualType UT = DT->getUnderlyingType(); !UT->isDependentType())
488 addTypeHint(TL.getSourceRange(), UT, ": ");
489 return true;
490 }
491
492 bool VisitCXXConstructExpr(CXXConstructExpr *E) {
493 // Weed out constructor calls that don't look like a function call with
494 // an argument list, by checking the validity of getParenOrBraceRange().
495 // Also weed out std::initializer_list constructors as there are no names
496 // for the individual arguments.
497 if (!E->getParenOrBraceRange().isValid() ||
498 E->isStdInitListInitialization()) {
499 return true;
500 }
501
502 processCall(E->getConstructor(), {E->getArgs(), E->getNumArgs()});
503 return true;
504 }
505
506 bool VisitCallExpr(CallExpr *E) {
507 if (!Cfg.InlayHints.Parameters)
508 return true;
509
510 // Do not show parameter hints for operator calls written using operator
511 // syntax or user-defined literals. (Among other reasons, the resulting
512 // hints can look awkard, e.g. the expression can itself be a function
513 // argument and then we'd get two hints side by side).
514 if (isa<CXXOperatorCallExpr>(E) || isa<UserDefinedLiteral>(E))
515 return true;
516
517 auto CalleeDecls = Resolver->resolveCalleeOfCallExpr(E);
518 if (CalleeDecls.size() != 1)
519 return true;
520 const FunctionDecl *Callee = nullptr;
521 if (const auto *FD = dyn_cast<FunctionDecl>(CalleeDecls[0]))
522 Callee = FD;
523 else if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(CalleeDecls[0]))
524 Callee = FTD->getTemplatedDecl();
525 if (!Callee)
526 return true;
527
528 processCall(Callee, {E->getArgs(), E->getNumArgs()});
529 return true;
530 }
531
532 bool VisitFunctionDecl(FunctionDecl *D) {
533 if (auto *FPT =
534 llvm::dyn_cast<FunctionProtoType>(D->getType().getTypePtr())) {
535 if (!FPT->hasTrailingReturn()) {
536 if (auto FTL = D->getFunctionTypeLoc())
537 addReturnTypeHint(D, FTL.getRParenLoc());
538 }
539 }
540 if (Cfg.InlayHints.BlockEnd && D->isThisDeclarationADefinition()) {
541 // We use `printName` here to properly print name of ctor/dtor/operator
542 // overload.
543 if (const Stmt *Body = D->getBody())
544 addBlockEndHint(Body->getSourceRange(), "", printName(AST, *D), "");
545 }
546 return true;
547 }
548
549 bool VisitForStmt(ForStmt *S) {
550 if (Cfg.InlayHints.BlockEnd) {
551 std::string Name;
552 // Common case: for (int I = 0; I < N; I++). Use "I" as the name.
553 if (auto *DS = llvm::dyn_cast_or_null<DeclStmt>(S->getInit());
554 DS && DS->isSingleDecl())
555 Name = getSimpleName(llvm::cast<NamedDecl>(*DS->getSingleDecl()));
556 else
557 Name = summarizeExpr(S->getCond());
558 markBlockEnd(S->getBody(), "for", Name);
559 }
560 return true;
561 }
562
563 bool VisitCXXForRangeStmt(CXXForRangeStmt *S) {
564 if (Cfg.InlayHints.BlockEnd)
565 markBlockEnd(S->getBody(), "for", getSimpleName(*S->getLoopVariable()));
566 return true;
567 }
568
569 bool VisitWhileStmt(WhileStmt *S) {
570 if (Cfg.InlayHints.BlockEnd)
571 markBlockEnd(S->getBody(), "while", summarizeExpr(S->getCond()));
572 return true;
573 }
574
575 bool VisitSwitchStmt(SwitchStmt *S) {
576 if (Cfg.InlayHints.BlockEnd)
577 markBlockEnd(S->getBody(), "switch", summarizeExpr(S->getCond()));
578 return true;
579 }
580
581 // If/else chains are tricky.
582 // if (cond1) {
583 // } else if (cond2) {
584 // } // mark as "cond1" or "cond2"?
585 // For now, the answer is neither, just mark as "if".
586 // The ElseIf is a different IfStmt that doesn't know about the outer one.
587 llvm::DenseSet<const IfStmt *> ElseIfs; // not eligible for names
588 bool VisitIfStmt(IfStmt *S) {
589 if (Cfg.InlayHints.BlockEnd) {
590 if (const auto *ElseIf = llvm::dyn_cast_or_null<IfStmt>(S->getElse()))
591 ElseIfs.insert(ElseIf);
592 // Don't use markBlockEnd: the relevant range is [then.begin, else.end].
593 if (const auto *EndCS = llvm::dyn_cast<CompoundStmt>(
594 S->getElse() ? S->getElse() : S->getThen())) {
595 addBlockEndHint(
596 {S->getThen()->getBeginLoc(), EndCS->getRBracLoc()}, "if",
597 ElseIfs.contains(S) ? "" : summarizeExpr(S->getCond()), "");
598 }
599 }
600 return true;
601 }
602
603 void markBlockEnd(const Stmt *Body, llvm::StringRef Label,
604 llvm::StringRef Name = "") {
605 if (const auto *CS = llvm::dyn_cast_or_null<CompoundStmt>(Body))
606 addBlockEndHint(CS->getSourceRange(), Label, Name, "");
607 }
608
609 bool VisitTagDecl(TagDecl *D) {
610 if (Cfg.InlayHints.BlockEnd && D->isThisDeclarationADefinition()) {
611 std::string DeclPrefix = D->getKindName().str();
612 if (const auto *ED = dyn_cast<EnumDecl>(D)) {
613 if (ED->isScoped())
614 DeclPrefix += ED->isScopedUsingClassTag() ? " class" : " struct";
615 };
616 addBlockEndHint(D->getBraceRange(), DeclPrefix, getSimpleName(*D), ";");
617 }
618 return true;
619 }
620
621 bool VisitNamespaceDecl(NamespaceDecl *D) {
622 if (Cfg.InlayHints.BlockEnd) {
623 // For namespace, the range actually starts at the namespace keyword. But
624 // it should be fine since it's usually very short.
625 addBlockEndHint(D->getSourceRange(), "namespace", getSimpleName(*D), "");
626 }
627 return true;
628 }
629
630 bool VisitLambdaExpr(LambdaExpr *E) {
631 FunctionDecl *D = E->getCallOperator();
632 if (!E->hasExplicitResultType())
633 addReturnTypeHint(D, E->hasExplicitParameters()
634 ? D->getFunctionTypeLoc().getRParenLoc()
635 : E->getIntroducerRange().getEnd());
636 return true;
637 }
638
639 void addReturnTypeHint(FunctionDecl *D, SourceRange Range) {
640 auto *AT = D->getReturnType()->getContainedAutoType();
641 if (!AT || AT->getDeducedType().isNull())
642 return;
643 addTypeHint(Range, D->getReturnType(), /*Prefix=*/"-> ");
644 }
645
646 bool VisitVarDecl(VarDecl *D) {
647 // Do not show hints for the aggregate in a structured binding,
648 // but show hints for the individual bindings.
649 if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
650 for (auto *Binding : DD->bindings()) {
651 // For structured bindings, print canonical types. This is important
652 // because for bindings that use the tuple_element protocol, the
653 // non-canonical types would be "tuple_element<I, A>::type".
654 if (auto Type = Binding->getType(); !Type.isNull())
655 addTypeHint(Binding->getLocation(), Type.getCanonicalType(),
656 /*Prefix=*/": ");
657 }
658 return true;
659 }
660
661 if (auto *AT = D->getType()->getContainedAutoType()) {
662 if (AT->isDeduced() && !D->getType()->isDependentType()) {
663 // Our current approach is to place the hint on the variable
664 // and accordingly print the full type
665 // (e.g. for `const auto& x = 42`, print `const int&`).
666 // Alternatively, we could place the hint on the `auto`
667 // (and then just print the type deduced for the `auto`).
668 addTypeHint(D->getLocation(), D->getType(), /*Prefix=*/": ");
669 }
670 }
671
672 // Handle templates like `int foo(auto x)` with exactly one instantiation.
673 if (auto *PVD = llvm::dyn_cast<ParmVarDecl>(D)) {
674 if (D->getIdentifier() && PVD->getType()->isDependentType() &&
675 !getContainedAutoParamType(D->getTypeSourceInfo()->getTypeLoc())
676 .isNull()) {
677 if (auto *IPVD = getOnlyParamInstantiation(PVD))
678 addTypeHint(D->getLocation(), IPVD->getType(), /*Prefix=*/": ");
679 }
680 }
681
682 return true;
683 }
684
685 ParmVarDecl *getOnlyParamInstantiation(ParmVarDecl *D) {
686 auto *TemplateFunction = llvm::dyn_cast<FunctionDecl>(D->getDeclContext());
687 if (!TemplateFunction)
688 return nullptr;
689 auto *InstantiatedFunction = llvm::dyn_cast_or_null<FunctionDecl>(
690 getOnlyInstantiation(TemplateFunction));
691 if (!InstantiatedFunction)
692 return nullptr;
693
694 unsigned ParamIdx = 0;
695 for (auto *Param : TemplateFunction->parameters()) {
696 // Can't reason about param indexes in the presence of preceding packs.
697 // And if this param is a pack, it may expand to multiple params.
698 if (Param->isParameterPack())
699 return nullptr;
700 if (Param == D)
701 break;
702 ++ParamIdx;
703 }
704 assert(ParamIdx < TemplateFunction->getNumParams() &&
705 "Couldn't find param in list?");
706 assert(ParamIdx < InstantiatedFunction->getNumParams() &&
707 "Instantiated function has fewer (non-pack) parameters?");
708 return InstantiatedFunction->getParamDecl(ParamIdx);
709 }
710
711 bool VisitInitListExpr(InitListExpr *Syn) {
712 // We receive the syntactic form here (shouldVisitImplicitCode() is false).
713 // This is the one we will ultimately attach designators to.
714 // It may have subobject initializers inlined without braces. The *semantic*
715 // form of the init-list has nested init-lists for these.
716 // getDesignators will look at the semantic form to determine the labels.
717 assert(Syn->isSyntacticForm() && "RAV should not visit implicit code!");
718 if (!Cfg.InlayHints.Designators)
719 return true;
720 if (Syn->isIdiomaticZeroInitializer(AST.getLangOpts()))
721 return true;
722 llvm::DenseMap<SourceLocation, std::string> Designators =
723 getDesignators(Syn);
724 for (const Expr *Init : Syn->inits()) {
725 if (llvm::isa<DesignatedInitExpr>(Init))
726 continue;
727 auto It = Designators.find(Init->getBeginLoc());
728 if (It != Designators.end() &&
729 !isPrecededByParamNameComment(Init, It->second))
730 addDesignatorHint(Init->getSourceRange(), It->second);
731 }
732 return true;
733 }
734
735 // FIXME: Handle RecoveryExpr to try to hint some invalid calls.
736
737private:
738 using NameVec = SmallVector<StringRef, 8>;
739
740 void processCall(const FunctionDecl *Callee,
741 llvm::ArrayRef<const Expr *> Args) {
742 if (!Cfg.InlayHints.Parameters || Args.size() == 0 || !Callee)
743 return;
744
745 // The parameter name of a move or copy constructor is not very interesting.
746 if (auto *Ctor = dyn_cast<CXXConstructorDecl>(Callee))
747 if (Ctor->isCopyOrMoveConstructor())
748 return;
749
750 // Resolve parameter packs to their forwarded parameter
751 auto ForwardedParams = resolveForwardingParameters(Callee);
752
753 NameVec ParameterNames = chooseParameterNames(ForwardedParams);
754
755 // Exclude setters (i.e. functions with one argument whose name begins with
756 // "set"), and builtins like std::move/forward/... as their parameter name
757 // is also not likely to be interesting.
758 if (isSetter(Callee, ParameterNames) || isSimpleBuiltin(Callee))
759 return;
760
761 for (size_t I = 0; I < ParameterNames.size() && I < Args.size(); ++I) {
762 // Pack expansion expressions cause the 1:1 mapping between arguments and
763 // parameters to break down, so we don't add further inlay hints if we
764 // encounter one.
765 if (isa<PackExpansionExpr>(Args[I])) {
766 break;
767 }
768
769 StringRef Name = ParameterNames[I];
770 bool NameHint = shouldHintName(Args[I], Name);
771 bool ReferenceHint =
772 shouldHintReference(Callee->getParamDecl(I), ForwardedParams[I]);
773
774 if (NameHint || ReferenceHint) {
775 addInlayHint(Args[I]->getSourceRange(), HintSide::Left,
776 InlayHintKind::Parameter, ReferenceHint ? "&" : "",
777 NameHint ? Name : "", ": ");
778 }
779 }
780 }
781
782 static bool isSetter(const FunctionDecl *Callee, const NameVec &ParamNames) {
783 if (ParamNames.size() != 1)
784 return false;
785
786 StringRef Name = getSimpleName(*Callee);
787 if (!Name.starts_with_insensitive("set"))
788 return false;
789
790 // In addition to checking that the function has one parameter and its
791 // name starts with "set", also check that the part after "set" matches
792 // the name of the parameter (ignoring case). The idea here is that if
793 // the parameter name differs, it may contain extra information that
794 // may be useful to show in a hint, as in:
795 // void setTimeout(int timeoutMillis);
796 // This currently doesn't handle cases where params use snake_case
797 // and functions don't, e.g.
798 // void setExceptionHandler(EHFunc exception_handler);
799 // We could improve this by replacing `equals_insensitive` with some
800 // `sloppy_equals` which ignores case and also skips underscores.
801 StringRef WhatItIsSetting = Name.substr(3).ltrim("_");
802 return WhatItIsSetting.equals_insensitive(ParamNames[0]);
803 }
804
805 // Checks if the callee is one of the builtins
806 // addressof, as_const, forward, move(_if_noexcept)
807 static bool isSimpleBuiltin(const FunctionDecl *Callee) {
808 switch (Callee->getBuiltinID()) {
809 case Builtin::BIaddressof:
810 case Builtin::BIas_const:
811 case Builtin::BIforward:
812 case Builtin::BImove:
813 case Builtin::BImove_if_noexcept:
814 return true;
815 default:
816 return false;
817 }
818 }
819
820 bool shouldHintName(const Expr *Arg, StringRef ParamName) {
821 if (ParamName.empty())
822 return false;
823
824 // If the argument expression is a single name and it matches the
825 // parameter name exactly, omit the name hint.
826 if (ParamName == getSpelledIdentifier(Arg))
827 return false;
828
829 // Exclude argument expressions preceded by a /*paramName*/.
830 if (isPrecededByParamNameComment(Arg, ParamName))
831 return false;
832
833 return true;
834 }
835
836 bool shouldHintReference(const ParmVarDecl *Param,
837 const ParmVarDecl *ForwardedParam) {
838 // We add a & hint only when the argument is passed as mutable reference.
839 // For parameters that are not part of an expanded pack, this is
840 // straightforward. For expanded pack parameters, it's likely that they will
841 // be forwarded to another function. In this situation, we only want to add
842 // the reference hint if the argument is actually being used via mutable
843 // reference. This means we need to check
844 // 1. whether the value category of the argument is preserved, i.e. each
845 // pack expansion uses std::forward correctly.
846 // 2. whether the argument is ever copied/cast instead of passed
847 // by-reference
848 // Instead of checking this explicitly, we use the following proxy:
849 // 1. the value category can only change from rvalue to lvalue during
850 // forwarding, so checking whether both the parameter of the forwarding
851 // function and the forwarded function are lvalue references detects such
852 // a conversion.
853 // 2. if the argument is copied/cast somewhere in the chain of forwarding
854 // calls, it can only be passed on to an rvalue reference or const lvalue
855 // reference parameter. Thus if the forwarded parameter is a mutable
856 // lvalue reference, it cannot have been copied/cast to on the way.
857 // Additionally, we should not add a reference hint if the forwarded
858 // parameter was only partially resolved, i.e. points to an expanded pack
859 // parameter, since we do not know how it will be used eventually.
860 auto Type = Param->getType();
861 auto ForwardedType = ForwardedParam->getType();
862 return Type->isLValueReferenceType() &&
863 ForwardedType->isLValueReferenceType() &&
864 !ForwardedType.getNonReferenceType().isConstQualified() &&
865 !isExpandedFromParameterPack(ForwardedParam);
866 }
867
868 // Checks if "E" is spelled in the main file and preceded by a C-style comment
869 // whose contents match ParamName (allowing for whitespace and an optional "="
870 // at the end.
871 bool isPrecededByParamNameComment(const Expr *E, StringRef ParamName) {
872 auto &SM = AST.getSourceManager();
873 auto FileLoc = SM.getFileLoc(E->getBeginLoc());
874 auto Decomposed = SM.getDecomposedLoc(FileLoc);
875 if (Decomposed.first != MainFileID)
876 return false;
877
878 StringRef SourcePrefix = MainFileBuf.substr(0, Decomposed.second);
879 // Allow whitespace between comment and expression.
880 SourcePrefix = SourcePrefix.rtrim();
881 // Check for comment ending.
882 if (!SourcePrefix.consume_back("*/"))
883 return false;
884 // Ignore some punctuation and whitespace around comment.
885 // In particular this allows designators to match nicely.
886 llvm::StringLiteral IgnoreChars = " =.";
887 SourcePrefix = SourcePrefix.rtrim(IgnoreChars);
888 ParamName = ParamName.trim(IgnoreChars);
889 // Other than that, the comment must contain exactly ParamName.
890 if (!SourcePrefix.consume_back(ParamName))
891 return false;
892 SourcePrefix = SourcePrefix.rtrim(IgnoreChars);
893 return SourcePrefix.endswith("/*");
894 }
895
896 // If "E" spells a single unqualified identifier, return that name.
897 // Otherwise, return an empty string.
898 static StringRef getSpelledIdentifier(const Expr *E) {
899 E = E->IgnoreUnlessSpelledInSource();
900
901 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
902 if (!DRE->getQualifier())
903 return getSimpleName(*DRE->getDecl());
904
905 if (auto *ME = dyn_cast<MemberExpr>(E))
906 if (!ME->getQualifier() && ME->isImplicitAccess())
907 return getSimpleName(*ME->getMemberDecl());
908
909 return {};
910 }
911
912 NameVec chooseParameterNames(SmallVector<const ParmVarDecl *> Parameters) {
913 NameVec ParameterNames;
914 for (const auto *P : Parameters) {
915 if (isExpandedFromParameterPack(P)) {
916 // If we haven't resolved a pack paramater (e.g. foo(Args... args)) to a
917 // non-pack parameter, then hinting as foo(args: 1, args: 2, args: 3) is
918 // unlikely to be useful.
919 ParameterNames.emplace_back();
920 } else {
921 auto SimpleName = getSimpleName(*P);
922 // If the parameter is unnamed in the declaration:
923 // attempt to get its name from the definition
924 if (SimpleName.empty()) {
925 if (const auto *PD = getParamDefinition(P)) {
926 SimpleName = getSimpleName(*PD);
927 }
928 }
929 ParameterNames.emplace_back(SimpleName);
930 }
931 }
932
933 // Standard library functions often have parameter names that start
934 // with underscores, which makes the hints noisy, so strip them out.
935 for (auto &Name : ParameterNames)
936 stripLeadingUnderscores(Name);
937
938 return ParameterNames;
939 }
940
941 // for a ParmVarDecl from a function declaration, returns the corresponding
942 // ParmVarDecl from the definition if possible, nullptr otherwise.
943 static const ParmVarDecl *getParamDefinition(const ParmVarDecl *P) {
944 if (auto *Callee = dyn_cast<FunctionDecl>(P->getDeclContext())) {
945 if (auto *Def = Callee->getDefinition()) {
946 auto I = std::distance(Callee->param_begin(),
947 llvm::find(Callee->parameters(), P));
948 if (I < Callee->getNumParams()) {
949 return Def->getParamDecl(I);
950 }
951 }
952 }
953 return nullptr;
954 }
955
956 // We pass HintSide rather than SourceLocation because we want to ensure
957 // it is in the same file as the common file range.
958 void addInlayHint(SourceRange R, HintSide Side, InlayHintKind Kind,
959 llvm::StringRef Prefix, llvm::StringRef Label,
960 llvm::StringRef Suffix) {
961 auto LSPRange = getHintRange(R);
962 if (!LSPRange)
963 return;
964
965 addInlayHint(*LSPRange, Side, Kind, Prefix, Label, Suffix);
966 }
967
968 void addInlayHint(Range LSPRange, HintSide Side, InlayHintKind Kind,
969 llvm::StringRef Prefix, llvm::StringRef Label,
970 llvm::StringRef Suffix) {
971 // We shouldn't get as far as adding a hint if the category is disabled.
972 // We'd like to disable as much of the analysis as possible above instead.
973 // Assert in debug mode but add a dynamic check in production.
974 assert(Cfg.InlayHints.Enabled && "Shouldn't get here if disabled!");
975 switch (Kind) {
976#define CHECK_KIND(Enumerator, ConfigProperty) \
977 case InlayHintKind::Enumerator: \
978 assert(Cfg.InlayHints.ConfigProperty && \
979 "Shouldn't get here if kind is disabled!"); \
980 if (!Cfg.InlayHints.ConfigProperty) \
981 return; \
982 break
983 CHECK_KIND(Parameter, Parameters);
984 CHECK_KIND(Type, DeducedTypes);
985 CHECK_KIND(Designator, Designators);
986 CHECK_KIND(BlockEnd, BlockEnd);
987#undef CHECK_KIND
988 }
989
990 Position LSPPos = Side == HintSide::Left ? LSPRange.start : LSPRange.end;
991 if (RestrictRange &&
992 (LSPPos < RestrictRange->start || !(LSPPos < RestrictRange->end)))
993 return;
994 bool PadLeft = Prefix.consume_front(" ");
995 bool PadRight = Suffix.consume_back(" ");
996 Results.push_back(InlayHint{LSPPos, (Prefix + Label + Suffix).str(), Kind,
997 PadLeft, PadRight, LSPRange});
998 }
999
1000 // Get the range of the main file that *exactly* corresponds to R.
1001 std::optional<Range> getHintRange(SourceRange R) {
1002 const auto &SM = AST.getSourceManager();
1003 auto Spelled = Tokens.spelledForExpanded(Tokens.expandedTokens(R));
1004 // TokenBuffer will return null if e.g. R corresponds to only part of a
1005 // macro expansion.
1006 if (!Spelled || Spelled->empty())
1007 return std::nullopt;
1008 // Hint must be within the main file, not e.g. a non-preamble include.
1009 if (SM.getFileID(Spelled->front().location()) != SM.getMainFileID() ||
1010 SM.getFileID(Spelled->back().location()) != SM.getMainFileID())
1011 return std::nullopt;
1012 return Range{sourceLocToPosition(SM, Spelled->front().location()),
1013 sourceLocToPosition(SM, Spelled->back().endLocation())};
1014 }
1015
1016 void addTypeHint(SourceRange R, QualType T, llvm::StringRef Prefix) {
1017 if (!Cfg.InlayHints.DeducedTypes || T.isNull())
1018 return;
1019
1020 // The sugared type is more useful in some cases, and the canonical
1021 // type in other cases.
1022 auto Desugared = maybeDesugar(AST, T);
1023 std::string TypeName = Desugared.getAsString(TypeHintPolicy);
1024 if (T != Desugared && !shouldPrintTypeHint(TypeName)) {
1025 // If the desugared type is too long to display, fallback to the sugared
1026 // type.
1027 TypeName = T.getAsString(TypeHintPolicy);
1028 }
1029 if (shouldPrintTypeHint(TypeName))
1030 addInlayHint(R, HintSide::Right, InlayHintKind::Type, Prefix, TypeName,
1031 /*Suffix=*/"");
1032 }
1033
1034 void addDesignatorHint(SourceRange R, llvm::StringRef Text) {
1035 addInlayHint(R, HintSide::Left, InlayHintKind::Designator,
1036 /*Prefix=*/"", Text, /*Suffix=*/"=");
1037 }
1038
1039 bool shouldPrintTypeHint(llvm::StringRef TypeName) const noexcept {
1040 return Cfg.InlayHints.TypeNameLimit == 0 ||
1041 TypeName.size() < Cfg.InlayHints.TypeNameLimit;
1042 }
1043
1044 void addBlockEndHint(SourceRange BraceRange, StringRef DeclPrefix,
1045 StringRef Name, StringRef OptionalPunctuation) {
1046 auto HintRange = computeBlockEndHintRange(BraceRange, OptionalPunctuation);
1047 if (!HintRange)
1048 return;
1049
1050 std::string Label = DeclPrefix.str();
1051 if (!Label.empty() && !Name.empty())
1052 Label += ' ';
1053 Label += Name;
1054
1055 constexpr unsigned HintMaxLengthLimit = 60;
1056 if (Label.length() > HintMaxLengthLimit)
1057 return;
1058
1059 addInlayHint(*HintRange, HintSide::Right, InlayHintKind::BlockEnd, " // ",
1060 Label, "");
1061 }
1062
1063 // Compute the LSP range to attach the block end hint to, if any allowed.
1064 // 1. "}" is the last non-whitespace character on the line. The range of "}"
1065 // is returned.
1066 // 2. After "}", if the trimmed trailing text is exactly
1067 // `OptionalPunctuation`, say ";". The range of "} ... ;" is returned.
1068 // Otherwise, the hint shouldn't be shown.
1069 std::optional<Range> computeBlockEndHintRange(SourceRange BraceRange,
1070 StringRef OptionalPunctuation) {
1071 constexpr unsigned HintMinLineLimit = 2;
1072
1073 auto &SM = AST.getSourceManager();
1074 auto [BlockBeginFileId, BlockBeginOffset] =
1075 SM.getDecomposedLoc(SM.getFileLoc(BraceRange.getBegin()));
1076 auto RBraceLoc = SM.getFileLoc(BraceRange.getEnd());
1077 auto [RBraceFileId, RBraceOffset] = SM.getDecomposedLoc(RBraceLoc);
1078
1079 // Because we need to check the block satisfies the minimum line limit, we
1080 // require both source location to be in the main file. This prevents hint
1081 // to be shown in weird cases like '{' is actually in a "#include", but it's
1082 // rare anyway.
1083 if (BlockBeginFileId != MainFileID || RBraceFileId != MainFileID)
1084 return std::nullopt;
1085
1086 StringRef RestOfLine = MainFileBuf.substr(RBraceOffset).split('\n').first;
1087 if (!RestOfLine.starts_with("}"))
1088 return std::nullopt;
1089
1090 StringRef TrimmedTrailingText = RestOfLine.drop_front().trim();
1091 if (!TrimmedTrailingText.empty() &&
1092 TrimmedTrailingText != OptionalPunctuation)
1093 return std::nullopt;
1094
1095 auto BlockBeginLine = SM.getLineNumber(BlockBeginFileId, BlockBeginOffset);
1096 auto RBraceLine = SM.getLineNumber(RBraceFileId, RBraceOffset);
1097
1098 // Don't show hint on trivial blocks like `class X {};`
1099 if (BlockBeginLine + HintMinLineLimit - 1 > RBraceLine)
1100 return std::nullopt;
1101
1102 // This is what we attach the hint to, usually "}" or "};".
1103 StringRef HintRangeText = RestOfLine.take_front(
1104 TrimmedTrailingText.empty()
1105 ? 1
1106 : TrimmedTrailingText.bytes_end() - RestOfLine.bytes_begin());
1107
1108 Position HintStart = sourceLocToPosition(SM, RBraceLoc);
1109 Position HintEnd = sourceLocToPosition(
1110 SM, RBraceLoc.getLocWithOffset(HintRangeText.size()));
1111 return Range{HintStart, HintEnd};
1112 }
1113
1114 std::vector<InlayHint> &Results;
1115 ASTContext &AST;
1116 const syntax::TokenBuffer &Tokens;
1117 const Config &Cfg;
1118 std::optional<Range> RestrictRange;
1119 FileID MainFileID;
1120 StringRef MainFileBuf;
1121 const HeuristicResolver *Resolver;
1122 PrintingPolicy TypeHintPolicy;
1123};
1124
1125} // namespace
1126
1127std::vector<InlayHint> inlayHints(ParsedAST &AST,
1128 std::optional<Range> RestrictRange) {
1129 std::vector<InlayHint> Results;
1130 const auto &Cfg = Config::current();
1131 if (!Cfg.InlayHints.Enabled)
1132 return Results;
1133 InlayHintVisitor Visitor(Results, AST, Cfg, std::move(RestrictRange));
1134 Visitor.TraverseAST(AST.getASTContext());
1135
1136 // De-duplicate hints. Duplicates can sometimes occur due to e.g. explicit
1137 // template instantiations.
1138 llvm::sort(Results);
1139 Results.erase(std::unique(Results.begin(), Results.end()), Results.end());
1140
1141 return Results;
1142}
1143
1144} // namespace clangd
1145} // namespace clang
1146