clang-tools 23.0.0git
InlayHints.cpp
Go to the documentation of this file.
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"
10#include "AST.h"
11#include "Config.h"
12#include "ParsedAST.h"
13#include "Protocol.h"
14#include "SourceCode.h"
15#include "clang/AST/ASTDiagnostic.h"
16#include "clang/AST/Decl.h"
17#include "clang/AST/DeclBase.h"
18#include "clang/AST/DeclarationName.h"
19#include "clang/AST/Expr.h"
20#include "clang/AST/ExprCXX.h"
21#include "clang/AST/RecursiveASTVisitor.h"
22#include "clang/AST/Stmt.h"
23#include "clang/AST/StmtVisitor.h"
24#include "clang/AST/Type.h"
25#include "clang/Basic/Builtins.h"
26#include "clang/Basic/OperatorKinds.h"
27#include "clang/Basic/SourceLocation.h"
28#include "clang/Basic/SourceManager.h"
29#include "clang/Sema/HeuristicResolver.h"
30#include "llvm/ADT/DenseSet.h"
31#include "llvm/ADT/STLExtras.h"
32#include "llvm/ADT/SmallVector.h"
33#include "llvm/ADT/StringExtras.h"
34#include "llvm/ADT/StringRef.h"
35#include "llvm/ADT/Twine.h"
36#include "llvm/Support/Casting.h"
37#include "llvm/Support/ErrorHandling.h"
38#include "llvm/Support/FormatVariadic.h"
39#include "llvm/Support/SaveAndRestore.h"
40#include "llvm/Support/ScopedPrinter.h"
41#include "llvm/Support/raw_ostream.h"
42#include <algorithm>
43#include <iterator>
44#include <optional>
45#include <string>
46
47namespace clang {
48namespace clangd {
49namespace {
50
51// For now, inlay hints are always anchored at the left or right of their range.
52enum class HintSide { Left, Right };
53
54void stripLeadingUnderscores(StringRef &Name) { Name = Name.ltrim('_'); }
55
56// getDeclForType() returns the decl responsible for Type's spelling.
57// This is the inverse of ASTContext::getTypeDeclType().
58const NamedDecl *getDeclForType(const Type *T) {
59 switch (T->getTypeClass()) {
60 case Type::Enum:
61 case Type::Record:
62 case Type::InjectedClassName:
63 return cast<TagType>(T)->getDecl();
64 case Type::TemplateSpecialization:
65 return cast<TemplateSpecializationType>(T)
66 ->getTemplateName()
67 .getAsTemplateDecl(/*IgnoreDeduced=*/true);
68 case Type::Typedef:
69 return cast<TypedefType>(T)->getDecl();
70 case Type::UnresolvedUsing:
71 return cast<UnresolvedUsingType>(T)->getDecl();
72 case Type::Using:
73 return cast<UsingType>(T)->getDecl();
74 default:
75 return nullptr;
76 }
77 llvm_unreachable("Unknown TypeClass enum");
78}
79
80// getSimpleName() returns the plain identifier for an entity, if any.
81llvm::StringRef getSimpleName(const DeclarationName &DN) {
82 if (IdentifierInfo *Ident = DN.getAsIdentifierInfo())
83 return Ident->getName();
84 return "";
85}
86llvm::StringRef getSimpleName(const NamedDecl &D) {
87 return getSimpleName(D.getDeclName());
88}
89llvm::StringRef getSimpleName(QualType T) {
90 if (const auto *BT = llvm::dyn_cast<BuiltinType>(T)) {
91 PrintingPolicy PP(LangOptions{});
92 PP.adjustForCPlusPlus();
93 return BT->getName(PP);
94 }
95 if (const auto *D = getDeclForType(T.getTypePtr()))
96 return getSimpleName(D->getDeclName());
97 return "";
98}
99
100// Returns a very abbreviated form of an expression, or "" if it's too complex.
101// For example: `foo->bar()` would produce "bar".
102// This is used to summarize e.g. the condition of a while loop.
103std::string summarizeExpr(const Expr *E) {
104 struct Namer : ConstStmtVisitor<Namer, std::string> {
105 std::string Visit(const Expr *E) {
106 if (E == nullptr)
107 return "";
108 return ConstStmtVisitor::Visit(E->IgnoreImplicit());
109 }
110
111 // Any sort of decl reference, we just use the unqualified name.
112 std::string VisitMemberExpr(const MemberExpr *E) {
113 return getSimpleName(*E->getMemberDecl()).str();
114 }
115 std::string VisitDeclRefExpr(const DeclRefExpr *E) {
116 return getSimpleName(*E->getFoundDecl()).str();
117 }
118 std::string VisitCallExpr(const CallExpr *E) {
119 std::string Result = Visit(E->getCallee());
120 Result += E->getNumArgs() == 0 ? "()" : "(...)";
121 return Result;
122 }
123 std::string
124 VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E) {
125 return getSimpleName(E->getMember()).str();
126 }
127 std::string
128 VisitDependentScopeDeclRefExpr(const DependentScopeDeclRefExpr *E) {
129 return getSimpleName(E->getDeclName()).str();
130 }
131 std::string VisitCXXFunctionalCastExpr(const CXXFunctionalCastExpr *E) {
132 return getSimpleName(E->getType()).str();
133 }
134 std::string VisitCXXTemporaryObjectExpr(const CXXTemporaryObjectExpr *E) {
135 return getSimpleName(E->getType()).str();
136 }
137
138 // Step through implicit nodes that clang doesn't classify as such.
139 std::string VisitCXXMemberCallExpr(const CXXMemberCallExpr *E) {
140 // Call to operator bool() inside if (X): dispatch to X.
141 if (E->getNumArgs() == 0 && E->getMethodDecl() &&
142 E->getMethodDecl()->getDeclName().getNameKind() ==
143 DeclarationName::CXXConversionFunctionName &&
144 E->getSourceRange() ==
145 E->getImplicitObjectArgument()->getSourceRange())
146 return Visit(E->getImplicitObjectArgument());
147 return ConstStmtVisitor::VisitCXXMemberCallExpr(E);
148 }
149 std::string VisitCXXConstructExpr(const CXXConstructExpr *E) {
150 if (E->getNumArgs() == 1)
151 return Visit(E->getArg(0));
152 return "";
153 }
154
155 // Literals are just printed
156 std::string VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
157 return "nullptr";
158 }
159 std::string VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
160 return E->getValue() ? "true" : "false";
161 }
162 std::string VisitIntegerLiteral(const IntegerLiteral *E) {
163 return llvm::to_string(E->getValue());
164 }
165 std::string VisitFloatingLiteral(const FloatingLiteral *E) {
166 std::string Result;
167 llvm::raw_string_ostream OS(Result);
168 E->getValue().print(OS);
169 // Printer adds newlines?!
170 Result.resize(llvm::StringRef(Result).rtrim().size());
171 return Result;
172 }
173 std::string VisitStringLiteral(const StringLiteral *E) {
174 std::string Result = "\"";
175 if (E->containsNonAscii()) {
176 Result += "...";
177 } else {
178 llvm::raw_string_ostream OS(Result);
179 if (E->getLength() > 10) {
180 llvm::printEscapedString(E->getString().take_front(7), OS);
181 Result += "...";
182 } else {
183 llvm::printEscapedString(E->getString(), OS);
184 }
185 }
186 Result.push_back('"');
187 return Result;
188 }
189
190 // Simple operators. Motivating cases are `!x` and `I < Length`.
191 std::string printUnary(llvm::StringRef Spelling, const Expr *Operand,
192 bool Prefix) {
193 std::string Sub = Visit(Operand);
194 if (Sub.empty())
195 return "";
196 if (Prefix)
197 return (Spelling + Sub).str();
198 Sub += Spelling;
199 return Sub;
200 }
201 bool InsideBinary = false; // No recursing into binary expressions.
202 std::string printBinary(llvm::StringRef Spelling, const Expr *LHSOp,
203 const Expr *RHSOp) {
204 if (InsideBinary)
205 return "";
206 llvm::SaveAndRestore InBinary(InsideBinary, true);
207
208 std::string LHS = Visit(LHSOp);
209 std::string RHS = Visit(RHSOp);
210 if (LHS.empty() && RHS.empty())
211 return "";
212
213 if (LHS.empty())
214 LHS = "...";
215 LHS.push_back(' ');
216 LHS += Spelling;
217 LHS.push_back(' ');
218 if (RHS.empty())
219 LHS += "...";
220 else
221 LHS += RHS;
222 return LHS;
223 }
224 std::string VisitUnaryOperator(const UnaryOperator *E) {
225 return printUnary(E->getOpcodeStr(E->getOpcode()), E->getSubExpr(),
226 !E->isPostfix());
227 }
228 std::string VisitBinaryOperator(const BinaryOperator *E) {
229 return printBinary(E->getOpcodeStr(E->getOpcode()), E->getLHS(),
230 E->getRHS());
231 }
232 std::string VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *E) {
233 const char *Spelling = getOperatorSpelling(E->getOperator());
234 // Handle weird unary-that-look-like-binary postfix operators.
235 if ((E->getOperator() == OO_PlusPlus ||
236 E->getOperator() == OO_MinusMinus) &&
237 E->getNumArgs() == 2)
238 return printUnary(Spelling, E->getArg(0), false);
239 if (E->isInfixBinaryOp())
240 return printBinary(Spelling, E->getArg(0), E->getArg(1));
241 if (E->getNumArgs() == 1) {
242 switch (E->getOperator()) {
243 case OO_Plus:
244 case OO_Minus:
245 case OO_Star:
246 case OO_Amp:
247 case OO_Tilde:
248 case OO_Exclaim:
249 case OO_PlusPlus:
250 case OO_MinusMinus:
251 return printUnary(Spelling, E->getArg(0), true);
252 default:
253 break;
254 }
255 }
256 return "";
257 }
258 };
259 return Namer{}.Visit(E);
260}
261
262// Determines if any intermediate type in desugaring QualType QT is of
263// substituted template parameter type. Ignore pointer or reference wrappers.
264bool isSugaredTemplateParameter(QualType QT) {
265 static auto PeelWrapper = [](QualType QT) {
266 // Neither `PointerType` nor `ReferenceType` is considered as sugared
267 // type. Peel it.
268 QualType Peeled = QT->getPointeeType();
269 return Peeled.isNull() ? QT : Peeled;
270 };
271
272 // This is a bit tricky: we traverse the type structure and find whether or
273 // not a type in the desugaring process is of SubstTemplateTypeParmType.
274 // During the process, we may encounter pointer or reference types that are
275 // not marked as sugared; therefore, the desugar function won't apply. To
276 // move forward the traversal, we retrieve the pointees using
277 // QualType::getPointeeType().
278 //
279 // However, getPointeeType could leap over our interests: The QT::getAs<T>()
280 // invoked would implicitly desugar the type. Consequently, if the
281 // SubstTemplateTypeParmType is encompassed within a TypedefType, we may lose
282 // the chance to visit it.
283 // For example, given a QT that represents `std::vector<int *>::value_type`:
284 // `-ElaboratedType 'value_type' sugar
285 // `-TypedefType 'vector<int *>::value_type' sugar
286 // |-Typedef 'value_type'
287 // `-SubstTemplateTypeParmType 'int *' sugar class depth 0 index 0 T
288 // |-ClassTemplateSpecialization 'vector'
289 // `-PointerType 'int *'
290 // `-BuiltinType 'int'
291 // Applying `getPointeeType` to QT results in 'int', a child of our target
292 // node SubstTemplateTypeParmType.
293 //
294 // As such, we always prefer the desugared over the pointee for next type
295 // in the iteration. It could avoid the getPointeeType's implicit desugaring.
296 while (true) {
297 if (QT->getAs<SubstTemplateTypeParmType>())
298 return true;
299 QualType Desugared = QT->getLocallyUnqualifiedSingleStepDesugaredType();
300 if (Desugared != QT)
301 QT = Desugared;
302 else if (auto Peeled = PeelWrapper(Desugared); Peeled != QT)
303 QT = Peeled;
304 else
305 break;
306 }
307 return false;
308}
309
310// A simple wrapper for `clang::desugarForDiagnostic` that provides optional
311// semantic.
312std::optional<QualType> desugar(ASTContext &AST, QualType QT) {
313 bool ShouldAKA = false;
314 auto Desugared = clang::desugarForDiagnostic(AST, QT, ShouldAKA);
315 if (!ShouldAKA)
316 return std::nullopt;
317 return Desugared;
318}
319
320// Apply a series of heuristic methods to determine whether or not a QualType QT
321// is suitable for desugaring (e.g. getting the real name behind the using-alias
322// name). If so, return the desugared type. Otherwise, return the unchanged
323// parameter QT.
324//
325// This could be refined further. See
326// https://github.com/clangd/clangd/issues/1298.
327QualType maybeDesugar(ASTContext &AST, QualType QT) {
328 // Prefer desugared type for name that aliases the template parameters.
329 // This can prevent things like printing opaque `: type` when accessing std
330 // containers.
331 if (isSugaredTemplateParameter(QT))
332 return desugar(AST, QT).value_or(QT);
333
334 // Prefer desugared type for `decltype(expr)` specifiers.
335 if (QT->isDecltypeType())
336 return QT.getCanonicalType();
337 if (const AutoType *AT = QT->getContainedAutoType())
338 if (!AT->getDeducedType().isNull() &&
339 AT->getDeducedType()->isDecltypeType())
340 return QT.getCanonicalType();
341
342 return QT;
343}
344
345ArrayRef<const ParmVarDecl *>
346maybeDropCxxExplicitObjectParameters(ArrayRef<const ParmVarDecl *> Params) {
347 if (!Params.empty() && Params.front()->isExplicitObjectParameter())
348 Params = Params.drop_front(1);
349 return Params;
350}
351
352template <typename R>
353std::string joinAndTruncate(const R &Range, size_t MaxLength) {
354 std::string Out;
355 llvm::raw_string_ostream OS(Out);
356 llvm::ListSeparator Sep(", ");
357 for (auto &&Element : Range) {
358 OS << Sep;
359 if (Out.size() + Element.size() >= MaxLength) {
360 OS << "...";
361 break;
362 }
363 OS << Element;
364 }
365 OS.flush();
366 return Out;
367}
368
369struct Callee {
370 // Only one of Decl or Loc is set.
371 // Loc is for calls through function pointers.
372 const FunctionDecl *Decl = nullptr;
373 FunctionProtoTypeLoc Loc;
374};
375
376class InlayHintVisitor : public RecursiveASTVisitor<InlayHintVisitor> {
377public:
378 InlayHintVisitor(std::vector<InlayHint> &Results, ParsedAST &AST,
379 const Config &Cfg, std::optional<Range> RestrictRange,
380 InlayHintOptions HintOptions)
381 : Results(Results), AST(AST.getASTContext()), Tokens(AST.getTokens()),
382 Cfg(Cfg), RestrictRange(std::move(RestrictRange)),
383 MainFileID(AST.getSourceManager().getMainFileID()),
384 Resolver(AST.getHeuristicResolver()),
385 TypeHintPolicy(this->AST.getPrintingPolicy()),
386 HintOptions(HintOptions) {
387 bool Invalid = false;
388 llvm::StringRef Buf =
389 AST.getSourceManager().getBufferData(MainFileID, &Invalid);
390 MainFileBuf = Invalid ? StringRef{} : Buf;
391
392 TypeHintPolicy.SuppressScope = true; // keep type names short
393 TypeHintPolicy.AnonymousTagNameStyle = llvm::to_underlying(
394 PrintingPolicy::AnonymousTagMode::Plain); // do not print lambda
395 // location
396
397 // Not setting PrintCanonicalTypes for "auto" allows
398 // SuppressDefaultTemplateArgs (set by default) to have an effect.
399 }
400
401 bool VisitTypeLoc(TypeLoc TL) {
402 if (const auto *DT = llvm::dyn_cast<DecltypeType>(TL.getType()))
403 if (QualType UT = DT->getUnderlyingType(); !UT->isDependentType())
404 addTypeHint(TL.getSourceRange(), UT, ": ");
405 return true;
406 }
407
408 bool VisitCXXConstructExpr(CXXConstructExpr *E) {
409 // Weed out constructor calls that don't look like a function call with
410 // an argument list, by checking the validity of getParenOrBraceRange().
411 // Also weed out std::initializer_list constructors as there are no names
412 // for the individual arguments.
413 if (!E->getParenOrBraceRange().isValid() ||
414 E->isStdInitListInitialization()) {
415 return true;
416 }
417
418 Callee Callee;
419 Callee.Decl = E->getConstructor();
420 if (!Callee.Decl)
421 return true;
422 processCall(Callee, E->getParenOrBraceRange().getEnd(),
423 {E->getArgs(), E->getNumArgs()});
424 return true;
425 }
426
427 // Carefully recurse into PseudoObjectExprs, which typically incorporate
428 // a syntactic expression and several semantic expressions.
429 bool TraversePseudoObjectExpr(PseudoObjectExpr *E) {
430 Expr *SyntacticExpr = E->getSyntacticForm();
431 if (isa<CallExpr>(SyntacticExpr))
432 // Since the counterpart semantics usually get the identical source
433 // locations as the syntactic one, visiting those would end up presenting
434 // confusing hints e.g., __builtin_dump_struct.
435 // Thus, only traverse the syntactic forms if this is written as a
436 // CallExpr. This leaves the door open in case the arguments in the
437 // syntactic form could possibly get parameter names.
438 return RecursiveASTVisitor<InlayHintVisitor>::TraverseStmt(SyntacticExpr);
439 // We don't want the hints for some of the MS property extensions.
440 // e.g.
441 // struct S {
442 // __declspec(property(get=GetX, put=PutX)) int x[];
443 // void PutX(int y);
444 // void Work(int y) { x = y; } // Bad: `x = y: y`.
445 // };
446 if (isa<BinaryOperator>(SyntacticExpr))
447 return true;
448 // FIXME: Handle other forms of a pseudo object expression.
449 return RecursiveASTVisitor<InlayHintVisitor>::TraversePseudoObjectExpr(E);
450 }
451
452 bool VisitCallExpr(CallExpr *E) {
453 if (!Cfg.InlayHints.Parameters)
454 return true;
455
456 bool IsFunctor = isFunctionObjectCallExpr(E);
457 // Do not show parameter hints for user-defined literals or
458 // operator calls except for operator(). (Among other reasons, the resulting
459 // hints can look awkward, e.g. the expression can itself be a function
460 // argument and then we'd get two hints side by side).
461 if ((isa<CXXOperatorCallExpr>(E) && !IsFunctor) ||
462 isa<UserDefinedLiteral>(E))
463 return true;
464
465 auto CalleeDecls = Resolver->resolveCalleeOfCallExpr(E);
466 if (CalleeDecls.size() != 1)
467 return true;
468
469 Callee Callee;
470 if (const auto *FD = dyn_cast<FunctionDecl>(CalleeDecls[0]))
471 Callee.Decl = FD;
472 else if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(CalleeDecls[0]))
473 Callee.Decl = FTD->getTemplatedDecl();
474 else if (FunctionProtoTypeLoc Loc =
475 Resolver->getFunctionProtoTypeLoc(E->getCallee()))
476 Callee.Loc = Loc;
477 else
478 return true;
479
480 // N4868 [over.call.object]p3 says,
481 // The argument list submitted to overload resolution consists of the
482 // argument expressions present in the function call syntax preceded by the
483 // implied object argument (E).
484 //
485 // As well as the provision from P0847R7 Deducing This [expr.call]p7:
486 // ...If the function is an explicit object member function and there is an
487 // implied object argument ([over.call.func]), the list of provided
488 // arguments is preceded by the implied object argument for the purposes of
489 // this correspondence...
490 llvm::ArrayRef<const Expr *> Args = {E->getArgs(), E->getNumArgs()};
491 // We don't have the implied object argument through a function pointer
492 // either.
493 if (const CXXMethodDecl *Method =
494 dyn_cast_or_null<CXXMethodDecl>(Callee.Decl))
495 if (IsFunctor || Method->hasCXXExplicitFunctionObjectParameter())
496 Args = Args.drop_front(1);
497 processCall(Callee, E->getRParenLoc(), Args);
498 return true;
499 }
500
501 bool VisitFunctionDecl(FunctionDecl *D) {
502 if (auto *FPT =
503 llvm::dyn_cast<FunctionProtoType>(D->getType().getTypePtr())) {
504 if (!FPT->hasTrailingReturn()) {
505 if (auto FTL = D->getFunctionTypeLoc())
506 addReturnTypeHint(D, FTL.getRParenLoc());
507 }
508 }
509 if (Cfg.InlayHints.BlockEnd && D->isThisDeclarationADefinition()) {
510 // We use `printName` here to properly print name of ctor/dtor/operator
511 // overload.
512 if (const Stmt *Body = D->getBody())
513 addBlockEndHint(Body->getSourceRange(), "", printName(AST, *D), "");
514 }
515 return true;
516 }
517
518 bool VisitForStmt(ForStmt *S) {
519 if (Cfg.InlayHints.BlockEnd) {
520 std::string Name;
521 // Common case: for (int I = 0; I < N; I++). Use "I" as the name.
522 if (auto *DS = llvm::dyn_cast_or_null<DeclStmt>(S->getInit());
523 DS && DS->isSingleDecl())
524 Name = getSimpleName(llvm::cast<NamedDecl>(*DS->getSingleDecl()));
525 else
526 Name = summarizeExpr(S->getCond());
527 markBlockEnd(S->getBody(), "for", Name);
528 }
529 return true;
530 }
531
532 bool VisitCXXForRangeStmt(CXXForRangeStmt *S) {
533 if (Cfg.InlayHints.BlockEnd)
534 markBlockEnd(S->getBody(), "for", getSimpleName(*S->getLoopVariable()));
535 return true;
536 }
537
538 bool VisitWhileStmt(WhileStmt *S) {
539 if (Cfg.InlayHints.BlockEnd)
540 markBlockEnd(S->getBody(), "while", summarizeExpr(S->getCond()));
541 return true;
542 }
543
544 bool VisitSwitchStmt(SwitchStmt *S) {
545 if (Cfg.InlayHints.BlockEnd)
546 markBlockEnd(S->getBody(), "switch", summarizeExpr(S->getCond()));
547 return true;
548 }
549
550 // If/else chains are tricky.
551 // if (cond1) {
552 // } else if (cond2) {
553 // } // mark as "cond1" or "cond2"?
554 // For now, the answer is neither, just mark as "if".
555 // The ElseIf is a different IfStmt that doesn't know about the outer one.
556 llvm::DenseSet<const IfStmt *> ElseIfs; // not eligible for names
557 bool VisitIfStmt(IfStmt *S) {
558 if (Cfg.InlayHints.BlockEnd) {
559 if (const auto *ElseIf = llvm::dyn_cast_or_null<IfStmt>(S->getElse()))
560 ElseIfs.insert(ElseIf);
561 // Don't use markBlockEnd: the relevant range is [then.begin, else.end].
562 if (const auto *EndCS = llvm::dyn_cast<CompoundStmt>(
563 S->getElse() ? S->getElse() : S->getThen())) {
564 addBlockEndHint(
565 {S->getThen()->getBeginLoc(), EndCS->getRBracLoc()}, "if",
566 ElseIfs.contains(S) ? "" : summarizeExpr(S->getCond()), "");
567 }
568 }
569 return true;
570 }
571
572 void markBlockEnd(const Stmt *Body, llvm::StringRef Label,
573 llvm::StringRef Name = "") {
574 if (const auto *CS = llvm::dyn_cast_or_null<CompoundStmt>(Body))
575 addBlockEndHint(CS->getSourceRange(), Label, Name, "");
576 }
577
578 bool VisitTagDecl(TagDecl *D) {
579 if (Cfg.InlayHints.BlockEnd && D->isThisDeclarationADefinition()) {
580 std::string DeclPrefix = D->getKindName().str();
581 if (const auto *ED = dyn_cast<EnumDecl>(D)) {
582 if (ED->isScoped())
583 DeclPrefix += ED->isScopedUsingClassTag() ? " class" : " struct";
584 };
585 addBlockEndHint(D->getBraceRange(), DeclPrefix, getSimpleName(*D), ";");
586 }
587 return true;
588 }
589
590 bool VisitNamespaceDecl(NamespaceDecl *D) {
591 if (Cfg.InlayHints.BlockEnd) {
592 // For namespace, the range actually starts at the namespace keyword. But
593 // it should be fine since it's usually very short.
594 addBlockEndHint(D->getSourceRange(), "namespace", getSimpleName(*D), "");
595 }
596 return true;
597 }
598
599 bool VisitLambdaExpr(LambdaExpr *E) {
600 FunctionDecl *D = E->getCallOperator();
601 if (!E->hasExplicitResultType()) {
602 SourceLocation TypeHintLoc;
603 if (!E->hasExplicitParameters())
604 TypeHintLoc = E->getIntroducerRange().getEnd();
605 else if (auto FTL = D->getFunctionTypeLoc())
606 TypeHintLoc = FTL.getRParenLoc();
607 if (TypeHintLoc.isValid())
608 addReturnTypeHint(D, TypeHintLoc);
609 }
610 return true;
611 }
612
613 void addReturnTypeHint(FunctionDecl *D, SourceRange Range) {
614 auto *AT = D->getReturnType()->getContainedAutoType();
615 if (!AT || AT->getDeducedType().isNull())
616 return;
617 addTypeHint(Range, D->getReturnType(), /*Prefix=*/"-> ");
618 }
619
620 bool VisitVarDecl(VarDecl *D) {
621 // Do not show hints for the aggregate in a structured binding,
622 // but show hints for the individual bindings.
623 if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
624 for (auto *Binding : DD->bindings()) {
625 // For structured bindings, print canonical types. This is important
626 // because for bindings that use the tuple_element protocol, the
627 // non-canonical types would be "tuple_element<I, A>::type".
628 if (auto Type = Binding->getType();
629 !Type.isNull() && !Type->isDependentType())
630 addTypeHint(Binding->getLocation(), Type.getCanonicalType(),
631 /*Prefix=*/": ");
632 }
633 return true;
634 }
635
636 if (auto *AT = D->getType()->getContainedAutoType()) {
637 if (AT->isDeduced()) {
638 QualType T;
639 // If the type is dependent, HeuristicResolver *may* be able to
640 // resolve it to something that's useful to print. In other
641 // cases, it can't, and the resultng type would just be printed
642 // as "<dependent type>", in which case don't hint it at all.
643 if (D->getType()->isDependentType()) {
644 if (D->hasInit()) {
645 QualType Resolved = Resolver->resolveExprToType(D->getInit());
646 if (Resolved != AST.DependentTy) {
647 T = Resolved;
648 }
649 }
650 } else {
651 T = D->getType();
652 }
653 if (!T.isNull()) {
654 // Our current approach is to place the hint on the variable
655 // and accordingly print the full type
656 // (e.g. for `const auto& x = 42`, print `const int&`).
657 // Alternatively, we could place the hint on the `auto`
658 // (and then just print the type deduced for the `auto`).
659 addTypeHint(D->getLocation(), T, /*Prefix=*/": ");
660 }
661 }
662 }
663
664 // Handle templates like `int foo(auto x)` with exactly one instantiation.
665 if (auto *PVD = llvm::dyn_cast<ParmVarDecl>(D)) {
666 if (D->getIdentifier() && PVD->getType()->isDependentType() &&
667 !getContainedAutoParamType(D->getTypeSourceInfo()->getTypeLoc())
668 .isNull()) {
669 if (auto *IPVD = getOnlyParamInstantiation(PVD))
670 addTypeHint(D->getLocation(), IPVD->getType(), /*Prefix=*/": ");
671 }
672 }
673
674 return true;
675 }
676
677 ParmVarDecl *getOnlyParamInstantiation(ParmVarDecl *D) {
678 auto *TemplateFunction = llvm::dyn_cast<FunctionDecl>(D->getDeclContext());
679 if (!TemplateFunction)
680 return nullptr;
681 auto *InstantiatedFunction = llvm::dyn_cast_or_null<FunctionDecl>(
682 getOnlyInstantiation(TemplateFunction));
683 if (!InstantiatedFunction)
684 return nullptr;
685
686 unsigned ParamIdx = 0;
687 for (auto *Param : TemplateFunction->parameters()) {
688 // Can't reason about param indexes in the presence of preceding packs.
689 // And if this param is a pack, it may expand to multiple params.
690 if (Param->isParameterPack())
691 return nullptr;
692 if (Param == D)
693 break;
694 ++ParamIdx;
695 }
696 assert(ParamIdx < TemplateFunction->getNumParams() &&
697 "Couldn't find param in list?");
698 assert(ParamIdx < InstantiatedFunction->getNumParams() &&
699 "Instantiated function has fewer (non-pack) parameters?");
700 return InstantiatedFunction->getParamDecl(ParamIdx);
701 }
702
703 bool VisitCXXParenListInitExpr(CXXParenListInitExpr *E) {
704 if (!Cfg.InlayHints.Designators)
705 return true;
706
707 if (const auto *CXXRecord = E->getType()->getAsCXXRecordDecl()) {
708 const auto &InitExprs = E->getUserSpecifiedInitExprs();
709
710 if (InitExprs.size() <= CXXRecord->getNumBases())
711 return true;
712
713 // Inherited members are first, skip hinting them for now.
714 // FIXME: '.base=' or 'base:' hint?
715 const auto &MemberInitExprs =
716 InitExprs.drop_front(CXXRecord->getNumBases());
717
718 // Then the fields in this record
719 for (const auto &[InitExpr, Field] :
720 llvm::zip(MemberInitExprs, CXXRecord->fields())) {
721 addDesignatorHint(InitExpr->getSourceRange(),
722 "." + Field->getName().str());
723 }
724 }
725
726 return true;
727 }
728
729 bool VisitInitListExpr(InitListExpr *Syn) {
730 // We receive the syntactic form here (shouldVisitImplicitCode() is false).
731 // This is the one we will ultimately attach designators to.
732 // It may have subobject initializers inlined without braces. The *semantic*
733 // form of the init-list has nested init-lists for these.
734 // getUnwrittenDesignators will look at the semantic form to determine the
735 // labels.
736 assert(Syn->isSyntacticForm() && "RAV should not visit implicit code!");
737 if (!Cfg.InlayHints.Designators)
738 return true;
739 if (Syn->isIdiomaticZeroInitializer(AST.getLangOpts()))
740 return true;
741 llvm::DenseMap<SourceLocation, std::string> Designators =
743 for (const Expr *Init : Syn->inits()) {
744 if (llvm::isa<DesignatedInitExpr>(Init))
745 continue;
746 auto It = Designators.find(Init->getBeginLoc());
747 if (It != Designators.end() &&
748 !isPrecededByParamNameComment(Init, It->second))
749 addDesignatorHint(Init->getSourceRange(), It->second);
750 }
751 return true;
752 }
753
754 // FIXME: Handle RecoveryExpr to try to hint some invalid calls.
755
756private:
757 using NameVec = SmallVector<StringRef, 8>;
758
759 void processCall(Callee Callee, SourceLocation RParenOrBraceLoc,
760 llvm::ArrayRef<const Expr *> Args) {
761 assert(Callee.Decl || Callee.Loc);
762
763 if ((!Cfg.InlayHints.Parameters && !Cfg.InlayHints.DefaultArguments) ||
764 Args.size() == 0)
765 return;
766
767 // The parameter name of a move or copy constructor is not very interesting.
768 if (Callee.Decl)
769 if (auto *Ctor = dyn_cast<CXXConstructorDecl>(Callee.Decl))
770 if (Ctor->isCopyOrMoveConstructor())
771 return;
772
773 SmallVector<std::string> FormattedDefaultArgs;
774 bool HasNonDefaultArgs = false;
775
776 ArrayRef<const ParmVarDecl *> Params, ForwardedParams;
777 // Resolve parameter packs to their forwarded parameter
778 SmallVector<const ParmVarDecl *> ForwardedParamsStorage;
779 if (Callee.Decl) {
780 Params = maybeDropCxxExplicitObjectParameters(Callee.Decl->parameters());
781 ForwardedParamsStorage = resolveForwardingParameters(Callee.Decl);
782 ForwardedParams =
783 maybeDropCxxExplicitObjectParameters(ForwardedParamsStorage);
784 } else {
785 Params = maybeDropCxxExplicitObjectParameters(Callee.Loc.getParams());
786 ForwardedParams = {Params.begin(), Params.end()};
787 }
788
789 NameVec ParameterNames = chooseParameterNames(ForwardedParams);
790
791 // Exclude setters (i.e. functions with one argument whose name begins with
792 // "set"), and builtins like std::move/forward/... as their parameter name
793 // is also not likely to be interesting.
794 if (Callee.Decl &&
795 (isSetter(Callee.Decl, ParameterNames) || isSimpleBuiltin(Callee.Decl)))
796 return;
797
798 for (size_t I = 0; I < ParameterNames.size() && I < Args.size(); ++I) {
799 // Pack expansion expressions cause the 1:1 mapping between arguments and
800 // parameters to break down, so we don't add further inlay hints if we
801 // encounter one.
802 if (isa<PackExpansionExpr>(Args[I])) {
803 break;
804 }
805
806 StringRef Name = ParameterNames[I];
807 const bool NameHint =
808 shouldHintName(Args[I], Name) && Cfg.InlayHints.Parameters;
809 const bool ReferenceHint =
810 shouldHintReference(Params[I], ForwardedParams[I]) &&
811 Cfg.InlayHints.Parameters;
812
813 const bool IsDefault = isa<CXXDefaultArgExpr>(Args[I]);
814 HasNonDefaultArgs |= !IsDefault;
815 if (IsDefault) {
816 if (Cfg.InlayHints.DefaultArguments) {
817 const auto SourceText = Lexer::getSourceText(
818 CharSourceRange::getTokenRange(Params[I]->getDefaultArgRange()),
819 AST.getSourceManager(), AST.getLangOpts());
820 const auto Abbrev =
821 (SourceText.size() > Cfg.InlayHints.TypeNameLimit ||
822 SourceText.contains("\n"))
823 ? "..."
824 : SourceText;
825 if (NameHint)
826 FormattedDefaultArgs.emplace_back(
827 llvm::formatv("{0}: {1}", Name, Abbrev));
828 else
829 FormattedDefaultArgs.emplace_back(llvm::formatv("{0}", Abbrev));
830 }
831 } else if (NameHint || ReferenceHint) {
832 addInlayHint(Args[I]->getSourceRange(), HintSide::Left,
833 InlayHintKind::Parameter, ReferenceHint ? "&" : "",
834 NameHint ? Name : "", ": ");
835 }
836 }
837
838 if (!FormattedDefaultArgs.empty()) {
839 std::string Hint =
840 joinAndTruncate(FormattedDefaultArgs, Cfg.InlayHints.TypeNameLimit);
841 addInlayHint(SourceRange{RParenOrBraceLoc}, HintSide::Left,
843 HasNonDefaultArgs ? ", " : "", Hint, "");
844 }
845 }
846
847 static bool isSetter(const FunctionDecl *Callee, const NameVec &ParamNames) {
848 if (ParamNames.size() != 1)
849 return false;
850
851 StringRef Name = getSimpleName(*Callee);
852 if (!Name.starts_with_insensitive("set"))
853 return false;
854
855 // In addition to checking that the function has one parameter and its
856 // name starts with "set", also check that the part after "set" matches
857 // the name of the parameter (ignoring case). The idea here is that if
858 // the parameter name differs, it may contain extra information that
859 // may be useful to show in a hint, as in:
860 // void setTimeout(int timeoutMillis);
861 // This currently doesn't handle cases where params use snake_case
862 // and functions don't, e.g.
863 // void setExceptionHandler(EHFunc exception_handler);
864 // We could improve this by replacing `equals_insensitive` with some
865 // `sloppy_equals` which ignores case and also skips underscores.
866 StringRef WhatItIsSetting = Name.substr(3).ltrim("_");
867 return WhatItIsSetting.equals_insensitive(ParamNames[0]);
868 }
869
870 // Checks if the callee is one of the builtins
871 // addressof, as_const, forward, move(_if_noexcept)
872 static bool isSimpleBuiltin(const FunctionDecl *Callee) {
873 switch (Callee->getBuiltinID()) {
874 case Builtin::BIaddressof:
875 case Builtin::BIas_const:
876 case Builtin::BIforward:
877 case Builtin::BImove:
878 case Builtin::BImove_if_noexcept:
879 return true;
880 default:
881 return false;
882 }
883 }
884
885 bool shouldHintName(const Expr *Arg, StringRef ParamName) {
886 if (ParamName.empty())
887 return false;
888
889 // If the argument expression is a single name and it matches the
890 // parameter name exactly, omit the name hint.
891 if (ParamName == getSpelledIdentifier(Arg))
892 return false;
893
894 // Exclude argument expressions preceded by a /*paramName*/.
895 if (isPrecededByParamNameComment(Arg, ParamName))
896 return false;
897
898 return true;
899 }
900
901 bool shouldHintReference(const ParmVarDecl *Param,
902 const ParmVarDecl *ForwardedParam) {
903 // We add a & hint only when the argument is passed as mutable reference.
904 // For parameters that are not part of an expanded pack, this is
905 // straightforward. For expanded pack parameters, it's likely that they will
906 // be forwarded to another function. In this situation, we only want to add
907 // the reference hint if the argument is actually being used via mutable
908 // reference. This means we need to check
909 // 1. whether the value category of the argument is preserved, i.e. each
910 // pack expansion uses std::forward correctly.
911 // 2. whether the argument is ever copied/cast instead of passed
912 // by-reference
913 // Instead of checking this explicitly, we use the following proxy:
914 // 1. the value category can only change from rvalue to lvalue during
915 // forwarding, so checking whether both the parameter of the forwarding
916 // function and the forwarded function are lvalue references detects such
917 // a conversion.
918 // 2. if the argument is copied/cast somewhere in the chain of forwarding
919 // calls, it can only be passed on to an rvalue reference or const lvalue
920 // reference parameter. Thus if the forwarded parameter is a mutable
921 // lvalue reference, it cannot have been copied/cast to on the way.
922 // Additionally, we should not add a reference hint if the forwarded
923 // parameter was only partially resolved, i.e. points to an expanded pack
924 // parameter, since we do not know how it will be used eventually.
925 auto Type = Param->getType();
926 auto ForwardedType = ForwardedParam->getType();
927 return Type->isLValueReferenceType() &&
928 ForwardedType->isLValueReferenceType() &&
929 !ForwardedType.getNonReferenceType().isConstQualified() &&
930 !isExpandedFromParameterPack(ForwardedParam);
931 }
932
933 // Checks if "E" is spelled in the main file and preceded by a C-style comment
934 // whose contents match ParamName (allowing for whitespace and an optional "="
935 // at the end.
936 bool isPrecededByParamNameComment(const Expr *E, StringRef ParamName) {
937 auto &SM = AST.getSourceManager();
938 auto FileLoc = SM.getFileLoc(E->getBeginLoc());
939 auto Decomposed = SM.getDecomposedLoc(FileLoc);
940 if (Decomposed.first != MainFileID)
941 return false;
942
943 StringRef SourcePrefix = MainFileBuf.substr(0, Decomposed.second);
944 // Allow whitespace between comment and expression.
945 SourcePrefix = SourcePrefix.rtrim();
946 // Check for comment ending.
947 if (!SourcePrefix.consume_back("*/"))
948 return false;
949 // Ignore some punctuation and whitespace around comment.
950 // In particular this allows designators to match nicely.
951 llvm::StringLiteral IgnoreChars = " =.";
952 SourcePrefix = SourcePrefix.rtrim(IgnoreChars);
953 ParamName = ParamName.trim(IgnoreChars);
954 // Other than that, the comment must contain exactly ParamName.
955 if (!SourcePrefix.consume_back(ParamName))
956 return false;
957 SourcePrefix = SourcePrefix.rtrim(IgnoreChars);
958 return SourcePrefix.ends_with("/*");
959 }
960
961 // If "E" spells a single unqualified identifier, return that name.
962 // Otherwise, return an empty string.
963 static StringRef getSpelledIdentifier(const Expr *E) {
964 E = E->IgnoreUnlessSpelledInSource();
965
966 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
967 if (!DRE->getQualifier())
968 return getSimpleName(*DRE->getDecl());
969
970 if (auto *ME = dyn_cast<MemberExpr>(E))
971 if (!ME->getQualifier() && ME->isImplicitAccess())
972 return getSimpleName(*ME->getMemberDecl());
973
974 return {};
975 }
976
977 NameVec chooseParameterNames(ArrayRef<const ParmVarDecl *> Parameters) {
978 NameVec ParameterNames;
979 for (const auto *P : Parameters) {
981 // If we haven't resolved a pack paramater (e.g. foo(Args... args)) to a
982 // non-pack parameter, then hinting as foo(args: 1, args: 2, args: 3) is
983 // unlikely to be useful.
984 ParameterNames.emplace_back();
985 } else {
986 auto SimpleName = getSimpleName(*P);
987 // If the parameter is unnamed in the declaration:
988 // attempt to get its name from the definition
989 if (SimpleName.empty()) {
990 if (const auto *PD = getParamDefinition(P)) {
991 SimpleName = getSimpleName(*PD);
992 }
993 }
994 ParameterNames.emplace_back(SimpleName);
995 }
996 }
997
998 // Standard library functions often have parameter names that start
999 // with underscores, which makes the hints noisy, so strip them out.
1000 for (auto &Name : ParameterNames)
1001 stripLeadingUnderscores(Name);
1002
1003 return ParameterNames;
1004 }
1005
1006 // for a ParmVarDecl from a function declaration, returns the corresponding
1007 // ParmVarDecl from the definition if possible, nullptr otherwise.
1008 static const ParmVarDecl *getParamDefinition(const ParmVarDecl *P) {
1009 if (auto *Callee = dyn_cast<FunctionDecl>(P->getDeclContext())) {
1010 if (auto *Def = Callee->getDefinition()) {
1011 auto I = std::distance(Callee->param_begin(),
1012 llvm::find(Callee->parameters(), P));
1013 if (I < (int)Callee->getNumParams()) {
1014 return Def->getParamDecl(I);
1015 }
1016 }
1017 }
1018 return nullptr;
1019 }
1020
1021 // We pass HintSide rather than SourceLocation because we want to ensure
1022 // it is in the same file as the common file range.
1023 void addInlayHint(SourceRange R, HintSide Side, InlayHintKind Kind,
1024 llvm::StringRef Prefix, llvm::StringRef Label,
1025 llvm::StringRef Suffix) {
1026 auto LSPRange = getHintRange(R);
1027 if (!LSPRange)
1028 return;
1029
1030 addInlayHint(*LSPRange, Side, Kind, Prefix, Label, Suffix);
1031 }
1032
1033 void addInlayHint(Range LSPRange, HintSide Side, InlayHintKind Kind,
1034 llvm::StringRef Prefix, llvm::StringRef Label,
1035 llvm::StringRef Suffix) {
1036 // We shouldn't get as far as adding a hint if the category is disabled.
1037 // We'd like to disable as much of the analysis as possible above instead.
1038 // Assert in debug mode but add a dynamic check in production.
1039 assert(Cfg.InlayHints.Enabled && "Shouldn't get here if disabled!");
1040 switch (Kind) {
1041#define CHECK_KIND(Enumerator, ConfigProperty) \
1042 case InlayHintKind::Enumerator: \
1043 assert(Cfg.InlayHints.ConfigProperty && \
1044 "Shouldn't get here if kind is disabled!"); \
1045 if (!Cfg.InlayHints.ConfigProperty) \
1046 return; \
1047 break
1048 CHECK_KIND(Parameter, Parameters);
1049 CHECK_KIND(Type, DeducedTypes);
1050 CHECK_KIND(Designator, Designators);
1052 CHECK_KIND(DefaultArgument, DefaultArguments);
1053#undef CHECK_KIND
1054 }
1055
1056 Position LSPPos = Side == HintSide::Left ? LSPRange.start : LSPRange.end;
1057 if (RestrictRange &&
1058 (LSPPos < RestrictRange->start || !(LSPPos < RestrictRange->end)))
1059 return;
1060 bool PadLeft = Prefix.consume_front(" ");
1061 bool PadRight = Suffix.consume_back(" ");
1062 Results.push_back(InlayHint{LSPPos,
1063 /*label=*/{(Prefix + Label + Suffix).str()},
1064 Kind, PadLeft, PadRight, LSPRange});
1065 }
1066
1067 // Get the range of the main file that *exactly* corresponds to R.
1068 std::optional<Range> getHintRange(SourceRange R) {
1069 const auto &SM = AST.getSourceManager();
1070 auto Spelled = Tokens.spelledForExpanded(Tokens.expandedTokens(R));
1071 // TokenBuffer will return null if e.g. R corresponds to only part of a
1072 // macro expansion.
1073 if (!Spelled || Spelled->empty())
1074 return std::nullopt;
1075 // Hint must be within the main file, not e.g. a non-preamble include.
1076 if (SM.getFileID(Spelled->front().location()) != SM.getMainFileID() ||
1077 SM.getFileID(Spelled->back().location()) != SM.getMainFileID())
1078 return std::nullopt;
1079 return Range{sourceLocToPosition(SM, Spelled->front().location()),
1080 sourceLocToPosition(SM, Spelled->back().endLocation())};
1081 }
1082
1083 void addTypeHint(SourceRange R, QualType T, llvm::StringRef Prefix) {
1084 if (!Cfg.InlayHints.DeducedTypes || T.isNull())
1085 return;
1086
1087 // The sugared type is more useful in some cases, and the canonical
1088 // type in other cases.
1089 auto Desugared = maybeDesugar(AST, T);
1090 std::string TypeName = Desugared.getAsString(TypeHintPolicy);
1091 if (T != Desugared && !shouldPrintTypeHint(TypeName)) {
1092 // If the desugared type is too long to display, fallback to the sugared
1093 // type.
1094 TypeName = T.getAsString(TypeHintPolicy);
1095 }
1096 if (shouldPrintTypeHint(TypeName))
1097 addInlayHint(R, HintSide::Right, InlayHintKind::Type, Prefix, TypeName,
1098 /*Suffix=*/"");
1099 }
1100
1101 void addDesignatorHint(SourceRange R, llvm::StringRef Text) {
1102 addInlayHint(R, HintSide::Left, InlayHintKind::Designator,
1103 /*Prefix=*/"", Text, /*Suffix=*/"=");
1104 }
1105
1106 bool shouldPrintTypeHint(llvm::StringRef TypeName) const noexcept {
1107 return Cfg.InlayHints.TypeNameLimit == 0 ||
1108 TypeName.size() < Cfg.InlayHints.TypeNameLimit;
1109 }
1110
1111 void addBlockEndHint(SourceRange BraceRange, StringRef DeclPrefix,
1112 StringRef Name, StringRef OptionalPunctuation) {
1113 auto HintRange = computeBlockEndHintRange(BraceRange, OptionalPunctuation);
1114 if (!HintRange)
1115 return;
1116
1117 std::string Label = DeclPrefix.str();
1118 if (!Label.empty() && !Name.empty())
1119 Label += ' ';
1120 Label += Name;
1121
1122 constexpr unsigned HintMaxLengthLimit = 60;
1123 if (Label.length() > HintMaxLengthLimit)
1124 return;
1125
1126 addInlayHint(*HintRange, HintSide::Right, InlayHintKind::BlockEnd, " // ",
1127 Label, "");
1128 }
1129
1130 // Compute the LSP range to attach the block end hint to, if any allowed.
1131 // 1. "}" is the last non-whitespace character on the line. The range of "}"
1132 // is returned.
1133 // 2. After "}", if the trimmed trailing text is exactly
1134 // `OptionalPunctuation`, say ";". The range of "} ... ;" is returned.
1135 // Otherwise, the hint shouldn't be shown.
1136 std::optional<Range> computeBlockEndHintRange(SourceRange BraceRange,
1137 StringRef OptionalPunctuation) {
1138
1139 auto &SM = AST.getSourceManager();
1140 auto [BlockBeginFileId, BlockBeginOffset] =
1141 SM.getDecomposedLoc(SM.getFileLoc(BraceRange.getBegin()));
1142 auto RBraceLoc = SM.getFileLoc(BraceRange.getEnd());
1143 auto [RBraceFileId, RBraceOffset] = SM.getDecomposedLoc(RBraceLoc);
1144
1145 // Because we need to check the block satisfies the minimum line limit, we
1146 // require both source location to be in the main file. This prevents hint
1147 // to be shown in weird cases like '{' is actually in a "#include", but it's
1148 // rare anyway.
1149 if (BlockBeginFileId != MainFileID || RBraceFileId != MainFileID)
1150 return std::nullopt;
1151
1152 StringRef RestOfLine = MainFileBuf.substr(RBraceOffset).split('\n').first;
1153 if (!RestOfLine.starts_with("}"))
1154 return std::nullopt;
1155
1156 StringRef TrimmedTrailingText = RestOfLine.drop_front().trim();
1157 if (!TrimmedTrailingText.empty() &&
1158 TrimmedTrailingText != OptionalPunctuation)
1159 return std::nullopt;
1160
1161 auto BlockBeginLine = SM.getLineNumber(BlockBeginFileId, BlockBeginOffset);
1162 auto RBraceLine = SM.getLineNumber(RBraceFileId, RBraceOffset);
1163
1164 // Don't show hint on trivial blocks like `class X {};`
1165 if (BlockBeginLine + HintOptions.HintMinLineLimit - 1 > RBraceLine)
1166 return std::nullopt;
1167
1168 // This is what we attach the hint to, usually "}" or "};".
1169 StringRef HintRangeText = RestOfLine.take_front(
1170 TrimmedTrailingText.empty()
1171 ? 1
1172 : TrimmedTrailingText.bytes_end() - RestOfLine.bytes_begin());
1173
1174 Position HintStart = sourceLocToPosition(SM, RBraceLoc);
1175 Position HintEnd = sourceLocToPosition(
1176 SM, RBraceLoc.getLocWithOffset(HintRangeText.size()));
1177 return Range{HintStart, HintEnd};
1178 }
1179
1180 static bool isFunctionObjectCallExpr(CallExpr *E) noexcept {
1181 if (auto *CallExpr = dyn_cast<CXXOperatorCallExpr>(E))
1182 return CallExpr->getOperator() == OverloadedOperatorKind::OO_Call;
1183 return false;
1184 }
1185
1186 std::vector<InlayHint> &Results;
1187 ASTContext &AST;
1188 const syntax::TokenBuffer &Tokens;
1189 const Config &Cfg;
1190 std::optional<Range> RestrictRange;
1191 FileID MainFileID;
1192 StringRef MainFileBuf;
1193 const HeuristicResolver *Resolver;
1194 PrintingPolicy TypeHintPolicy;
1195 InlayHintOptions HintOptions;
1196};
1197
1198} // namespace
1199
1200std::vector<InlayHint> inlayHints(ParsedAST &AST,
1201 std::optional<Range> RestrictRange,
1202 InlayHintOptions HintOptions) {
1203 std::vector<InlayHint> Results;
1204 const auto &Cfg = Config::current();
1205 if (!Cfg.InlayHints.Enabled)
1206 return Results;
1207 InlayHintVisitor Visitor(Results, AST, Cfg, std::move(RestrictRange),
1208 HintOptions);
1209 Visitor.TraverseAST(AST.getASTContext());
1210
1211 // De-duplicate hints. Duplicates can sometimes occur due to e.g. explicit
1212 // template instantiations.
1213 llvm::sort(Results);
1214 Results.erase(llvm::unique(Results), Results.end());
1215
1216 return Results;
1217}
1218
1219} // namespace clangd
1220} // namespace clang
static cl::opt< std::string > Config("config", desc(R"( Specifies a configuration in YAML/JSON format: -config="{Checks:' *', CheckOptions:{x:y}}" When the value is empty, clang-tidy will attempt to find a file named .clang-tidy for each source file in its parent directories. )"), cl::init(""), cl::cat(ClangTidyCategory))
This file provides utilities for designated initializers.
#define CHECK_KIND(Enumerator, ConfigProperty)
Stores and provides access to parsed AST.
Definition ParsedAST.h:46
FIXME: Skip testing on windows temporarily due to the different escaping code mode.
Definition AST.cpp:44
SmallVector< const ParmVarDecl * > resolveForwardingParameters(const FunctionDecl *D, unsigned MaxDepth)
Recursively resolves the parameters of a FunctionDecl that forwards its parameters to another functio...
Definition AST.cpp:982
std::string printName(const ASTContext &Ctx, const NamedDecl &ND)
Prints unqualified name of the decl for the purpose of displaying it to the user.
Definition AST.cpp:248
NamedDecl * getOnlyInstantiation(NamedDecl *TemplatedDecl)
Definition AST.cpp:662
Position sourceLocToPosition(const SourceManager &SM, SourceLocation Loc)
Turn a SourceLocation into a [line, column] pair.
bool isExpandedFromParameterPack(const ParmVarDecl *D)
Checks whether D is instantiated from a function parameter pack whose type is a bare type parameter p...
Definition AST.cpp:1039
InlayHintKind
Inlay hint kinds.
Definition Protocol.h:1704
@ BlockEnd
A hint after function, type or namespace definition, indicating the defined symbol name of the defini...
Definition Protocol.h:1734
@ DefaultArgument
An inlay hint that is for a default argument.
Definition Protocol.h:1743
@ Parameter
An inlay hint that is for a parameter.
Definition Protocol.h:1717
@ Type
An inlay hint that for a type annotation.
Definition Protocol.h:1710
@ Designator
A hint before an element of an aggregate braced initializer list, indicating what it is initializing.
Definition Protocol.h:1724
TemplateTypeParmTypeLoc getContainedAutoParamType(TypeLoc TL)
Definition AST.cpp:635
std::vector< InlayHint > inlayHints(ParsedAST &AST, std::optional< Range > RestrictRange, InlayHintOptions HintOptions)
Compute and return inlay hints for a file.
llvm::DenseMap< SourceLocation, std::string > getUnwrittenDesignators(const InitListExpr *Syn)
cppcoreguidelines::ProBoundsAvoidUncheckedContainerAccessCheck P
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
static const Config & current()
Returns the Config of the current Context, or an empty configuration.
Definition Config.cpp:17