Debian Codegraph @

llvm-project/clang-tools-extra/clangd/InlayHints.cpp

raw
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/Decl.h"
15 #include "clang/AST/DeclarationName.h"
16 #include "clang/AST/ExprCXX.h"
17 #include "clang/AST/RecursiveASTVisitor.h"
18 #include "clang/Basic/Builtins.h"
19 #include "clang/Basic/SourceManager.h"
20 #include "llvm/ADT/ScopeExit.h"
21 #include <optional>
22
23 namespace clang {
24 namespace clangd {
25 namespace {
26
27 // For now, inlay hints are always anchored at the left or right of their range.
28 enum class HintSide { Left, Right };
29
30 // Helper class to iterate over the designator names of an aggregate type.
31 //
32 // For an array type, yields [0], [1], [2]...
33 // For aggregate classes, yields null for each base, then .field1, .field2, ...
34 class AggregateDesignatorNames {
35 public:
36 AggregateDesignatorNames(QualType T) {
37 if (!T.isNull()) {
38 T = T.getCanonicalType();
39 if (T->isArrayType()) {
40 IsArray = true;
41 Valid = true;
42 return;
43 }
44 if (const RecordDecl *RD = T->getAsRecordDecl()) {
45 Valid = true;
46 FieldsIt = RD->field_begin();
47 FieldsEnd = RD->field_end();
48 if (const auto *CRD = llvm::dyn_cast<CXXRecordDecl>(RD)) {
49 BasesIt = CRD->bases_begin();
50 BasesEnd = CRD->bases_end();
51 Valid = CRD->isAggregate();
52 }
53 OneField = Valid && BasesIt == BasesEnd && FieldsIt != FieldsEnd &&
54 std::next(FieldsIt) == FieldsEnd;
55 }
56 }
57 }
58 // Returns false if the type was not an aggregate.
59 operator bool() { return Valid; }
60 // Advance to the next element in the aggregate.
61 void next() {
62 if (IsArray)
63 ++Index;
64 else if (BasesIt != BasesEnd)
65 ++BasesIt;
66 else if (FieldsIt != FieldsEnd)
67 ++FieldsIt;
68 }
69 // Print the designator to Out.
70 // Returns false if we could not produce a designator for this element.
71 bool append(std::string &Out, bool ForSubobject) {
72 if (IsArray) {
73 Out.push_back('[');
74 Out.append(std::to_string(Index));
75 Out.push_back(']');
76 return true;
77 }
78 if (BasesIt != BasesEnd)
79 return false; // Bases can't be designated. Should we make one up?
80 if (FieldsIt != FieldsEnd) {
81 llvm::StringRef FieldName;
82 if (const IdentifierInfo *II = FieldsIt->getIdentifier())
83 FieldName = II->getName();
84
85 // For certain objects, their subobjects may be named directly.
86 if (ForSubobject &&
87 (FieldsIt->isAnonymousStructOrUnion() ||
88 // std::array<int,3> x = {1,2,3}. Designators not strictly valid!
89 (OneField && isReservedName(FieldName))))
90 return true;
91
92 if (!FieldName.empty() && !isReservedName(FieldName)) {
93 Out.push_back('.');
94 Out.append(FieldName.begin(), FieldName.end());
95 return true;
96 }
97 return false;
98 }
99 return false;
100 }
101
102 private:
103 bool Valid = false;
104 bool IsArray = false;
105 bool OneField = false; // e.g. std::array { T __elements[N]; }
106 unsigned Index = 0;
107 CXXRecordDecl::base_class_const_iterator BasesIt;
108 CXXRecordDecl::base_class_const_iterator BasesEnd;
109 RecordDecl::field_iterator FieldsIt;
110 RecordDecl::field_iterator FieldsEnd;
111 };
112
113 // Collect designator labels describing the elements of an init list.
114 //
115 // This function contributes the designators of some (sub)object, which is
116 // represented by the semantic InitListExpr Sem.
117 // This includes any nested subobjects, but *only* if they are part of the same
118 // original syntactic init list (due to brace elision).
119 // In other words, it may descend into subobjects but not written init-lists.
120 //
121 // For example: struct Outer { Inner a,b; }; struct Inner { int x, y; }
122 // Outer o{{1, 2}, 3};
123 // This function will be called with Sem = { {1, 2}, {3, ImplicitValue} }
124 // It should generate designators '.a:' and '.b.x:'.
125 // '.a:' is produced directly without recursing into the written sublist.
126 // (The written sublist will have a separate collectDesignators() call later).
127 // Recursion with Prefix='.b' and Sem = {3, ImplicitValue} produces '.b.x:'.
128 void collectDesignators(const InitListExpr *Sem,
129 llvm::DenseMap<SourceLocation, std::string> &Out,
130 const llvm::DenseSet<SourceLocation> &NestedBraces,
131 std::string &Prefix) {
132 if (!Sem || Sem->isTransparent())
133 return;
134 assert(Sem->isSemanticForm());
135
136 // The elements of the semantic form all correspond to direct subobjects of
137 // the aggregate type. `Fields` iterates over these subobject names.
138 AggregateDesignatorNames Fields(Sem->getType());
139 if (!Fields)
140 return;
141 for (const Expr *Init : Sem->inits()) {
142 auto Next = llvm::make_scope_exit([&, Size(Prefix.size())] {
143 Fields.next(); // Always advance to the next subobject name.
144 Prefix.resize(Size); // Erase any designator we appended.
145 });
146 // Skip for a broken initializer or if it is a "hole" in a subobject that
147 // was not explicitly initialized.
148 if (!Init || llvm::isa<ImplicitValueInitExpr>(Init))
149 continue;
150
151 const auto *BraceElidedSubobject = llvm::dyn_cast<InitListExpr>(Init);
152 if (BraceElidedSubobject &&
153 NestedBraces.contains(BraceElidedSubobject->getLBraceLoc()))
154 BraceElidedSubobject = nullptr; // there were braces!
155
156 if (!Fields.append(Prefix, BraceElidedSubobject != nullptr))
157 continue; // no designator available for this subobject
158 if (BraceElidedSubobject) {
159 // If the braces were elided, this aggregate subobject is initialized
160 // inline in the same syntactic list.
161 // Descend into the semantic list describing the subobject.
162 // (NestedBraces are still correct, they're from the same syntactic list).
163 collectDesignators(BraceElidedSubobject, Out, NestedBraces, Prefix);
164 continue;
165 }
166 Out.try_emplace(Init->getBeginLoc(), Prefix);
167 }
168 }
169
170 // Get designators describing the elements of a (syntactic) init list.
171 // This does not produce designators for any explicitly-written nested lists.
172 llvm::DenseMap<SourceLocation, std::string>
173 getDesignators(const InitListExpr *Syn) {
174 assert(Syn->isSyntacticForm());
175
176 // collectDesignators needs to know which InitListExprs in the semantic tree
177 // were actually written, but InitListExpr::isExplicit() lies.
178 // Instead, record where braces of sub-init-lists occur in the syntactic form.
179 llvm::DenseSet<SourceLocation> NestedBraces;
180 for (const Expr *Init : Syn->inits())
181 if (auto *Nested = llvm::dyn_cast<InitListExpr>(Init))
182 NestedBraces.insert(Nested->getLBraceLoc());
183
184 // Traverse the semantic form to find the designators.
185 // We use their SourceLocation to correlate with the syntactic form later.
186 llvm::DenseMap<SourceLocation, std::string> Designators;
187 std::string EmptyPrefix;
188 collectDesignators(Syn->isSemanticForm() ? Syn : Syn->getSemanticForm(),
189 Designators, NestedBraces, EmptyPrefix);
190 return Designators;
191 }
192
193 class InlayHintVisitor : public RecursiveASTVisitor<InlayHintVisitor> {
194 public:
195 InlayHintVisitor(std::vector<InlayHint> &Results, ParsedAST &AST,
196 const Config &Cfg, std::optional<Range> RestrictRange)
197 : Results(Results), AST(AST.getASTContext()), Tokens(AST.getTokens()),
198 Cfg(Cfg), RestrictRange(std::move(RestrictRange)),
199 MainFileID(AST.getSourceManager().getMainFileID()),
200 Resolver(AST.getHeuristicResolver()),
201 TypeHintPolicy(this->AST.getPrintingPolicy()),
202 StructuredBindingPolicy(this->AST.getPrintingPolicy()) {
203 bool Invalid = false;
204 llvm::StringRef Buf =
205 AST.getSourceManager().getBufferData(MainFileID, &Invalid);
206 MainFileBuf = Invalid ? StringRef{} : Buf;
207
208 TypeHintPolicy.SuppressScope = true; // keep type names short
209 TypeHintPolicy.AnonymousTagLocations =
210 false; // do not print lambda locations
211
212 // For structured bindings, print canonical types. This is important because
213 // for bindings that use the tuple_element protocol, the non-canonical types
214 // would be "tuple_element<I, A>::type".
215 // For "auto", we often prefer sugared types.
216 // Not setting PrintCanonicalTypes for "auto" allows
217 // SuppressDefaultTemplateArgs (set by default) to have an effect.
218 StructuredBindingPolicy = TypeHintPolicy;
219 StructuredBindingPolicy.PrintCanonicalTypes = true;
220 }
221
222 bool VisitTypeLoc(TypeLoc TL) {
223 if (const auto *DT = llvm::dyn_cast<DecltypeType>(TL.getType()))
224 if (QualType UT = DT->getUnderlyingType(); !UT->isDependentType())
225 addTypeHint(TL.getSourceRange(), UT, ": ");
226 return true;
227 }
228
229 bool VisitCXXConstructExpr(CXXConstructExpr *E) {
230 // Weed out constructor calls that don't look like a function call with
231 // an argument list, by checking the validity of getParenOrBraceRange().
232 // Also weed out std::initializer_list constructors as there are no names
233 // for the individual arguments.
234 if (!E->getParenOrBraceRange().isValid() ||
235 E->isStdInitListInitialization()) {
236 return true;
237 }
238
239 processCall(E->getConstructor(), {E->getArgs(), E->getNumArgs()});
240 return true;
241 }
242
243 bool VisitCallExpr(CallExpr *E) {
244 if (!Cfg.InlayHints.Parameters)
245 return true;
246
247 // Do not show parameter hints for operator calls written using operator
248 // syntax or user-defined literals. (Among other reasons, the resulting
249 // hints can look awkard, e.g. the expression can itself be a function
250 // argument and then we'd get two hints side by side).
251 if (isa<CXXOperatorCallExpr>(E) || isa<UserDefinedLiteral>(E))
252 return true;
253
254 auto CalleeDecls = Resolver->resolveCalleeOfCallExpr(E);
255 if (CalleeDecls.size() != 1)
256 return true;
257 const FunctionDecl *Callee = nullptr;
258 if (const auto *FD = dyn_cast<FunctionDecl>(CalleeDecls[0]))
259 Callee = FD;
260 else if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(CalleeDecls[0]))
261 Callee = FTD->getTemplatedDecl();
262 if (!Callee)
263 return true;
264
265 processCall(Callee, {E->getArgs(), E->getNumArgs()});
266 return true;
267 }
268
269 bool VisitFunctionDecl(FunctionDecl *D) {
270 if (auto *FPT =
271 llvm::dyn_cast<FunctionProtoType>(D->getType().getTypePtr())) {
272 if (!FPT->hasTrailingReturn()) {
273 if (auto FTL = D->getFunctionTypeLoc())
274 addReturnTypeHint(D, FTL.getRParenLoc());
275 }
276 }
277 return true;
278 }
279
280 bool VisitLambdaExpr(LambdaExpr *E) {
281 FunctionDecl *D = E->getCallOperator();
282 if (!E->hasExplicitResultType())
283 addReturnTypeHint(D, E->hasExplicitParameters()
284 ? D->getFunctionTypeLoc().getRParenLoc()
285 : E->getIntroducerRange().getEnd());
286 return true;
287 }
288
289 void addReturnTypeHint(FunctionDecl *D, SourceRange Range) {
290 auto *AT = D->getReturnType()->getContainedAutoType();
291 if (!AT || AT->getDeducedType().isNull())
292 return;
293 addTypeHint(Range, D->getReturnType(), /*Prefix=*/"-> ");
294 }
295
296 bool VisitVarDecl(VarDecl *D) {
297 // Do not show hints for the aggregate in a structured binding,
298 // but show hints for the individual bindings.
299 if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
300 for (auto *Binding : DD->bindings()) {
301 addTypeHint(Binding->getLocation(), Binding->getType(), /*Prefix=*/": ",
302 StructuredBindingPolicy);
303 }
304 return true;
305 }
306
307 if (D->getType()->getContainedAutoType()) {
308 if (!D->getType()->isDependentType()) {
309 // Our current approach is to place the hint on the variable
310 // and accordingly print the full type
311 // (e.g. for `const auto& x = 42`, print `const int&`).
312 // Alternatively, we could place the hint on the `auto`
313 // (and then just print the type deduced for the `auto`).
314 addTypeHint(D->getLocation(), D->getType(), /*Prefix=*/": ");
315 }
316 }
317
318 // Handle templates like `int foo(auto x)` with exactly one instantiation.
319 if (auto *PVD = llvm::dyn_cast<ParmVarDecl>(D)) {
320 if (D->getIdentifier() && PVD->getType()->isDependentType() &&
321 !getContainedAutoParamType(D->getTypeSourceInfo()->getTypeLoc())
322 .isNull()) {
323 if (auto *IPVD = getOnlyParamInstantiation(PVD))
324 addTypeHint(D->getLocation(), IPVD->getType(), /*Prefix=*/": ");
325 }
326 }
327
328 return true;
329 }
330
331 ParmVarDecl *getOnlyParamInstantiation(ParmVarDecl *D) {
332 auto *TemplateFunction = llvm::dyn_cast<FunctionDecl>(D->getDeclContext());
333 if (!TemplateFunction)
334 return nullptr;
335 auto *InstantiatedFunction = llvm::dyn_cast_or_null<FunctionDecl>(
336 getOnlyInstantiation(TemplateFunction));
337 if (!InstantiatedFunction)
338 return nullptr;
339
340 unsigned ParamIdx = 0;
341 for (auto *Param : TemplateFunction->parameters()) {
342 // Can't reason about param indexes in the presence of preceding packs.
343 // And if this param is a pack, it may expand to multiple params.
344 if (Param->isParameterPack())
345 return nullptr;
346 if (Param == D)
347 break;
348 ++ParamIdx;
349 }
350 assert(ParamIdx < TemplateFunction->getNumParams() &&
351 "Couldn't find param in list?");
352 assert(ParamIdx < InstantiatedFunction->getNumParams() &&
353 "Instantiated function has fewer (non-pack) parameters?");
354 return InstantiatedFunction->getParamDecl(ParamIdx);
355 }
356
357 bool VisitInitListExpr(InitListExpr *Syn) {
358 // We receive the syntactic form here (shouldVisitImplicitCode() is false).
359 // This is the one we will ultimately attach designators to.
360 // It may have subobject initializers inlined without braces. The *semantic*
361 // form of the init-list has nested init-lists for these.
362 // getDesignators will look at the semantic form to determine the labels.
363 assert(Syn->isSyntacticForm() && "RAV should not visit implicit code!");
364 if (!Cfg.InlayHints.Designators)
365 return true;
366 if (Syn->isIdiomaticZeroInitializer(AST.getLangOpts()))
367 return true;
368 llvm::DenseMap<SourceLocation, std::string> Designators =
369 getDesignators(Syn);
370 for (const Expr *Init : Syn->inits()) {
371 if (llvm::isa<DesignatedInitExpr>(Init))
372 continue;
373 auto It = Designators.find(Init->getBeginLoc());
374 if (It != Designators.end() &&
375 !isPrecededByParamNameComment(Init, It->second))
376 addDesignatorHint(Init->getSourceRange(), It->second);
377 }
378 return true;
379 }
380
381 // FIXME: Handle RecoveryExpr to try to hint some invalid calls.
382
383 private:
384 using NameVec = SmallVector<StringRef, 8>;
385
386 void processCall(const FunctionDecl *Callee,
387 llvm::ArrayRef<const Expr *> Args) {
388 if (!Cfg.InlayHints.Parameters || Args.size() == 0 || !Callee)
389 return;
390
391 // The parameter name of a move or copy constructor is not very interesting.
392 if (auto *Ctor = dyn_cast<CXXConstructorDecl>(Callee))
393 if (Ctor->isCopyOrMoveConstructor())
394 return;
395
396 // Resolve parameter packs to their forwarded parameter
397 auto ForwardedParams = resolveForwardingParameters(Callee);
398
399 NameVec ParameterNames = chooseParameterNames(ForwardedParams);
400
401 // Exclude setters (i.e. functions with one argument whose name begins with
402 // "set"), and builtins like std::move/forward/... as their parameter name
403 // is also not likely to be interesting.
404 if (isSetter(Callee, ParameterNames) || isSimpleBuiltin(Callee))
405 return;
406
407 for (size_t I = 0; I < ParameterNames.size() && I < Args.size(); ++I) {
408 // Pack expansion expressions cause the 1:1 mapping between arguments and
409 // parameters to break down, so we don't add further inlay hints if we
410 // encounter one.
411 if (isa<PackExpansionExpr>(Args[I])) {
412 break;
413 }
414
415 StringRef Name = ParameterNames[I];
416 bool NameHint = shouldHintName(Args[I], Name);
417 bool ReferenceHint =
418 shouldHintReference(Callee->getParamDecl(I), ForwardedParams[I]);
419
420 if (NameHint || ReferenceHint) {
421 addInlayHint(Args[I]->getSourceRange(), HintSide::Left,
422 InlayHintKind::Parameter, ReferenceHint ? "&" : "",
423 NameHint ? Name : "", ": ");
424 }
425 }
426 }
427
428 static bool isSetter(const FunctionDecl *Callee, const NameVec &ParamNames) {
429 if (ParamNames.size() != 1)
430 return false;
431
432 StringRef Name = getSimpleName(*Callee);
433 if (!Name.startswith_insensitive("set"))
434 return false;
435
436 // In addition to checking that the function has one parameter and its
437 // name starts with "set", also check that the part after "set" matches
438 // the name of the parameter (ignoring case). The idea here is that if
439 // the parameter name differs, it may contain extra information that
440 // may be useful to show in a hint, as in:
441 // void setTimeout(int timeoutMillis);
442 // This currently doesn't handle cases where params use snake_case
443 // and functions don't, e.g.
444 // void setExceptionHandler(EHFunc exception_handler);
445 // We could improve this by replacing `equals_insensitive` with some
446 // `sloppy_equals` which ignores case and also skips underscores.
447 StringRef WhatItIsSetting = Name.substr(3).ltrim("_");
448 return WhatItIsSetting.equals_insensitive(ParamNames[0]);
449 }
450
451 // Checks if the callee is one of the builtins
452 // addressof, as_const, forward, move(_if_noexcept)
453 static bool isSimpleBuiltin(const FunctionDecl *Callee) {
454 switch (Callee->getBuiltinID()) {
455 case Builtin::BIaddressof:
456 case Builtin::BIas_const:
457 case Builtin::BIforward:
458 case Builtin::BImove:
459 case Builtin::BImove_if_noexcept:
460 return true;
461 default:
462 return false;
463 }
464 }
465
466 bool shouldHintName(const Expr *Arg, StringRef ParamName) {
467 if (ParamName.empty())
468 return false;
469
470 // If the argument expression is a single name and it matches the
471 // parameter name exactly, omit the name hint.
472 if (ParamName == getSpelledIdentifier(Arg))
473 return false;
474
475 // Exclude argument expressions preceded by a /*paramName*/.
476 if (isPrecededByParamNameComment(Arg, ParamName))
477 return false;
478
479 return true;
480 }
481
482 bool shouldHintReference(const ParmVarDecl *Param,
483 const ParmVarDecl *ForwardedParam) {
484 // We add a & hint only when the argument is passed as mutable reference.
485 // For parameters that are not part of an expanded pack, this is
486 // straightforward. For expanded pack parameters, it's likely that they will
487 // be forwarded to another function. In this situation, we only want to add
488 // the reference hint if the argument is actually being used via mutable
489 // reference. This means we need to check
490 // 1. whether the value category of the argument is preserved, i.e. each
491 // pack expansion uses std::forward correctly.
492 // 2. whether the argument is ever copied/cast instead of passed
493 // by-reference
494 // Instead of checking this explicitly, we use the following proxy:
495 // 1. the value category can only change from rvalue to lvalue during
496 // forwarding, so checking whether both the parameter of the forwarding
497 // function and the forwarded function are lvalue references detects such
498 // a conversion.
499 // 2. if the argument is copied/cast somewhere in the chain of forwarding
500 // calls, it can only be passed on to an rvalue reference or const lvalue
501 // reference parameter. Thus if the forwarded parameter is a mutable
502 // lvalue reference, it cannot have been copied/cast to on the way.
503 // Additionally, we should not add a reference hint if the forwarded
504 // parameter was only partially resolved, i.e. points to an expanded pack
505 // parameter, since we do not know how it will be used eventually.
506 auto Type = Param->getType();
507 auto ForwardedType = ForwardedParam->getType();
508 return Type->isLValueReferenceType() &&
509 ForwardedType->isLValueReferenceType() &&
510 !ForwardedType.getNonReferenceType().isConstQualified() &&
511 !isExpandedFromParameterPack(ForwardedParam);
512 }
513
514 // Checks if "E" is spelled in the main file and preceded by a C-style comment
515 // whose contents match ParamName (allowing for whitespace and an optional "="
516 // at the end.
517 bool isPrecededByParamNameComment(const Expr *E, StringRef ParamName) {
518 auto &SM = AST.getSourceManager();
519 auto ExprStartLoc = SM.getTopMacroCallerLoc(E->getBeginLoc());
520 auto Decomposed = SM.getDecomposedLoc(ExprStartLoc);
521 if (Decomposed.first != MainFileID)
522 return false;
523
524 StringRef SourcePrefix = MainFileBuf.substr(0, Decomposed.second);
525 // Allow whitespace between comment and expression.
526 SourcePrefix = SourcePrefix.rtrim();
527 // Check for comment ending.
528 if (!SourcePrefix.consume_back("*/"))
529 return false;
530 // Ignore some punctuation and whitespace around comment.
531 // In particular this allows designators to match nicely.
532 llvm::StringLiteral IgnoreChars = " =.";
533 SourcePrefix = SourcePrefix.rtrim(IgnoreChars);
534 ParamName = ParamName.trim(IgnoreChars);
535 // Other than that, the comment must contain exactly ParamName.
536 if (!SourcePrefix.consume_back(ParamName))
537 return false;
538 SourcePrefix = SourcePrefix.rtrim(IgnoreChars);
539 return SourcePrefix.endswith("/*");
540 }
541
542 // If "E" spells a single unqualified identifier, return that name.
543 // Otherwise, return an empty string.
544 static StringRef getSpelledIdentifier(const Expr *E) {
545 E = E->IgnoreUnlessSpelledInSource();
546
547 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
548 if (!DRE->getQualifier())
549 return getSimpleName(*DRE->getDecl());
550
551 if (auto *ME = dyn_cast<MemberExpr>(E))
552 if (!ME->getQualifier() && ME->isImplicitAccess())
553 return getSimpleName(*ME->getMemberDecl());
554
555 return {};
556 }
557
558 NameVec chooseParameterNames(SmallVector<const ParmVarDecl *> Parameters) {
559 NameVec ParameterNames;
560 for (const auto *P : Parameters) {
561 if (isExpandedFromParameterPack(P)) {
562 // If we haven't resolved a pack paramater (e.g. foo(Args... args)) to a
563 // non-pack parameter, then hinting as foo(args: 1, args: 2, args: 3) is
564 // unlikely to be useful.
565 ParameterNames.emplace_back();
566 } else {
567 auto SimpleName = getSimpleName(*P);
568 // If the parameter is unnamed in the declaration:
569 // attempt to get its name from the definition
570 if (SimpleName.empty()) {
571 if (const auto *PD = getParamDefinition(P)) {
572 SimpleName = getSimpleName(*PD);
573 }
574 }
575 ParameterNames.emplace_back(SimpleName);
576 }
577 }
578
579 // Standard library functions often have parameter names that start
580 // with underscores, which makes the hints noisy, so strip them out.
581 for (auto &Name : ParameterNames)
582 stripLeadingUnderscores(Name);
583
584 return ParameterNames;
585 }
586
587 // for a ParmVarDecl from a function declaration, returns the corresponding
588 // ParmVarDecl from the definition if possible, nullptr otherwise.
589 static const ParmVarDecl *getParamDefinition(const ParmVarDecl *P) {
590 if (auto *Callee = dyn_cast<FunctionDecl>(P->getDeclContext())) {
591 if (auto *Def = Callee->getDefinition()) {
592 auto I = std::distance(Callee->param_begin(),
593 llvm::find(Callee->parameters(), P));
594 if (I < Callee->getNumParams()) {
595 return Def->getParamDecl(I);
596 }
597 }
598 }
599 return nullptr;
600 }
601
602 static void stripLeadingUnderscores(StringRef &Name) {
603 Name = Name.ltrim('_');
604 }
605
606 static StringRef getSimpleName(const NamedDecl &D) {
607 if (IdentifierInfo *Ident = D.getDeclName().getAsIdentifierInfo()) {
608 return Ident->getName();
609 }
610
611 return StringRef();
612 }
613
614 // We pass HintSide rather than SourceLocation because we want to ensure
615 // it is in the same file as the common file range.
616 void addInlayHint(SourceRange R, HintSide Side, InlayHintKind Kind,
617 llvm::StringRef Prefix, llvm::StringRef Label,
618 llvm::StringRef Suffix) {
619 // We shouldn't get as far as adding a hint if the category is disabled.
620 // We'd like to disable as much of the analysis as possible above instead.
621 // Assert in debug mode but add a dynamic check in production.
622 assert(Cfg.InlayHints.Enabled && "Shouldn't get here if disabled!");
623 switch (Kind) {
624 #define CHECK_KIND(Enumerator, ConfigProperty) \
625 case InlayHintKind::Enumerator: \
626 assert(Cfg.InlayHints.ConfigProperty && \
627 "Shouldn't get here if kind is disabled!"); \
628 if (!Cfg.InlayHints.ConfigProperty) \
629 return; \
630 break
631 CHECK_KIND(Parameter, Parameters);
632 CHECK_KIND(Type, DeducedTypes);
633 CHECK_KIND(Designator, Designators);
634 #undef CHECK_KIND
635 }
636
637 auto LSPRange = getHintRange(R);
638 if (!LSPRange)
639 return;
640 Position LSPPos = Side == HintSide::Left ? LSPRange->start : LSPRange->end;
641 if (RestrictRange &&
642 (LSPPos < RestrictRange->start || !(LSPPos < RestrictRange->end)))
643 return;
644 bool PadLeft = Prefix.consume_front(" ");
645 bool PadRight = Suffix.consume_back(" ");
646 Results.push_back(InlayHint{LSPPos, (Prefix + Label + Suffix).str(), Kind,
647 PadLeft, PadRight, *LSPRange});
648 }
649
650 // Get the range of the main file that *exactly* corresponds to R.
651 std::optional<Range> getHintRange(SourceRange R) {
652 const auto &SM = AST.getSourceManager();
653 auto Spelled = Tokens.spelledForExpanded(Tokens.expandedTokens(R));
654 // TokenBuffer will return null if e.g. R corresponds to only part of a
655 // macro expansion.
656 if (!Spelled || Spelled->empty())
657 return std::nullopt;
658 // Hint must be within the main file, not e.g. a non-preamble include.
659 if (SM.getFileID(Spelled->front().location()) != SM.getMainFileID() ||
660 SM.getFileID(Spelled->back().location()) != SM.getMainFileID())
661 return std::nullopt;
662 return Range{sourceLocToPosition(SM, Spelled->front().location()),
663 sourceLocToPosition(SM, Spelled->back().endLocation())};
664 }
665
666 static bool shouldPrintCanonicalType(QualType QT) {
667 // The sugared type is more useful in some cases, and the canonical
668 // type in other cases. For now, prefer the sugared type unless
669 // we are printing `decltype(expr)`. This could be refined further
670 // (see https://github.com/clangd/clangd/issues/1298).
671 if (QT->isDecltypeType())
672 return true;
673 if (const AutoType *AT = QT->getContainedAutoType())
674 if (!AT->getDeducedType().isNull() &&
675 AT->getDeducedType()->isDecltypeType())
676 return true;
677 return false;
678 }
679
680 void addTypeHint(SourceRange R, QualType T, llvm::StringRef Prefix) {
681 TypeHintPolicy.PrintCanonicalTypes = shouldPrintCanonicalType(T);
682 addTypeHint(R, T, Prefix, TypeHintPolicy);
683 }
684
685 void addTypeHint(SourceRange R, QualType T, llvm::StringRef Prefix,
686 const PrintingPolicy &Policy) {
687 if (!Cfg.InlayHints.DeducedTypes || T.isNull())
688 return;
689
690 std::string TypeName = T.getAsString(Policy);
691 if (TypeName.length() < TypeNameLimit)
692 addInlayHint(R, HintSide::Right, InlayHintKind::Type, Prefix, TypeName,
693 /*Suffix=*/"");
694 }
695
696 void addDesignatorHint(SourceRange R, llvm::StringRef Text) {
697 addInlayHint(R, HintSide::Left, InlayHintKind::Designator,
698 /*Prefix=*/"", Text, /*Suffix=*/"=");
699 }
700
701 std::vector<InlayHint> &Results;
702 ASTContext &AST;
703 const syntax::TokenBuffer &Tokens;
704 const Config &Cfg;
705 std::optional<Range> RestrictRange;
706 FileID MainFileID;
707 StringRef MainFileBuf;
708 const HeuristicResolver *Resolver;
709 // We want to suppress default template arguments, but otherwise print
710 // canonical types. Unfortunately, they're conflicting policies so we can't
711 // have both. For regular types, suppressing template arguments is more
712 // important, whereas printing canonical types is crucial for structured
713 // bindings, so we use two separate policies. (See the constructor where
714 // the policies are initialized for more details.)
715 PrintingPolicy TypeHintPolicy;
716 PrintingPolicy StructuredBindingPolicy;
717
718 static const size_t TypeNameLimit = 32;
719 };
720
721 } // namespace
722
723 std::vector<InlayHint> inlayHints(ParsedAST &AST,
724 std::optional<Range> RestrictRange) {
725 std::vector<InlayHint> Results;
726 const auto &Cfg = Config::current();
727 if (!Cfg.InlayHints.Enabled)
728 return Results;
729 InlayHintVisitor Visitor(Results, AST, Cfg, std::move(RestrictRange));
730 Visitor.TraverseAST(AST.getASTContext());
731
732 // De-duplicate hints. Duplicates can sometimes occur due to e.g. explicit
733 // template instantiations.
734 llvm::sort(Results);
735 Results.erase(std::unique(Results.begin(), Results.end()), Results.end());
736
737 return Results;
738 }
739
740 } // namespace clangd
741 } // namespace clang