Skip to content

Commit 2eb1699

Browse files
authored
[clangd] Add inlay hints for default function arguments (#95712)
The new inlay hints have the `DefaultArguments` kind and can be enabled in config similar to other inlay kint kinds.
1 parent b26df3e commit 2eb1699

File tree

9 files changed

+170
-10
lines changed

9 files changed

+170
-10
lines changed

clang-tools-extra/clangd/Config.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -162,6 +162,7 @@ struct Config {
162162
bool DeducedTypes = true;
163163
bool Designators = true;
164164
bool BlockEnd = false;
165+
bool DefaultArguments = false;
165166
// Limit the length of type names in inlay hints. (0 means no limit)
166167
uint32_t TypeNameLimit = 32;
167168
} InlayHints;

clang-tools-extra/clangd/ConfigCompile.cpp

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,6 @@
4343
#include "llvm/Support/Regex.h"
4444
#include "llvm/Support/SMLoc.h"
4545
#include "llvm/Support/SourceMgr.h"
46-
#include <algorithm>
4746
#include <memory>
4847
#include <optional>
4948
#include <string>
@@ -669,6 +668,11 @@ struct FragmentCompiler {
669668
Out.Apply.push_back([Value(**F.BlockEnd)](const Params &, Config &C) {
670669
C.InlayHints.BlockEnd = Value;
671670
});
671+
if (F.DefaultArguments)
672+
Out.Apply.push_back(
673+
[Value(**F.DefaultArguments)](const Params &, Config &C) {
674+
C.InlayHints.DefaultArguments = Value;
675+
});
672676
if (F.TypeNameLimit)
673677
Out.Apply.push_back(
674678
[Value(**F.TypeNameLimit)](const Params &, Config &C) {

clang-tools-extra/clangd/ConfigFragment.h

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -339,6 +339,9 @@ struct Fragment {
339339
std::optional<Located<bool>> Designators;
340340
/// Show defined symbol names at the end of a definition block.
341341
std::optional<Located<bool>> BlockEnd;
342+
/// Show parameter names and default values of default arguments after all
343+
/// of the explicit arguments.
344+
std::optional<Located<bool>> DefaultArguments;
342345
/// Limit the length of type name hints. (0 means no limit)
343346
std::optional<Located<uint32_t>> TypeNameLimit;
344347
};

clang-tools-extra/clangd/ConfigYAML.cpp

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,6 @@
1414
#include "llvm/Support/YAMLParser.h"
1515
#include <optional>
1616
#include <string>
17-
#include <system_error>
1817

1918
namespace clang {
2019
namespace clangd {
@@ -268,6 +267,10 @@ class Parser {
268267
if (auto Value = boolValue(N, "BlockEnd"))
269268
F.BlockEnd = *Value;
270269
});
270+
Dict.handle("DefaultArguments", [&](Node &N) {
271+
if (auto Value = boolValue(N, "DefaultArguments"))
272+
F.DefaultArguments = *Value;
273+
});
271274
Dict.handle("TypeNameLimit", [&](Node &N) {
272275
if (auto Value = uint32Value(N, "TypeNameLimit"))
273276
F.TypeNameLimit = *Value;

clang-tools-extra/clangd/InlayHints.cpp

Lines changed: 70 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,11 @@
1111
#include "Config.h"
1212
#include "HeuristicResolver.h"
1313
#include "ParsedAST.h"
14+
#include "Protocol.h"
1415
#include "SourceCode.h"
1516
#include "clang/AST/ASTDiagnostic.h"
1617
#include "clang/AST/Decl.h"
18+
#include "clang/AST/DeclBase.h"
1719
#include "clang/AST/DeclarationName.h"
1820
#include "clang/AST/Expr.h"
1921
#include "clang/AST/ExprCXX.h"
@@ -23,15 +25,22 @@
2325
#include "clang/AST/Type.h"
2426
#include "clang/Basic/Builtins.h"
2527
#include "clang/Basic/OperatorKinds.h"
28+
#include "clang/Basic/SourceLocation.h"
2629
#include "clang/Basic/SourceManager.h"
2730
#include "llvm/ADT/DenseSet.h"
31+
#include "llvm/ADT/STLExtras.h"
32+
#include "llvm/ADT/SmallVector.h"
2833
#include "llvm/ADT/StringExtras.h"
2934
#include "llvm/ADT/StringRef.h"
3035
#include "llvm/ADT/Twine.h"
3136
#include "llvm/Support/Casting.h"
37+
#include "llvm/Support/ErrorHandling.h"
38+
#include "llvm/Support/FormatVariadic.h"
3239
#include "llvm/Support/SaveAndRestore.h"
3340
#include "llvm/Support/ScopedPrinter.h"
3441
#include "llvm/Support/raw_ostream.h"
42+
#include <algorithm>
43+
#include <iterator>
3544
#include <optional>
3645
#include <string>
3746

@@ -372,6 +381,23 @@ maybeDropCxxExplicitObjectParameters(ArrayRef<const ParmVarDecl *> Params) {
372381
return Params;
373382
}
374383

384+
template <typename R>
385+
std::string joinAndTruncate(const R &Range, size_t MaxLength) {
386+
std::string Out;
387+
llvm::raw_string_ostream OS(Out);
388+
llvm::ListSeparator Sep(", ");
389+
for (auto &&Element : Range) {
390+
OS << Sep;
391+
if (Out.size() + Element.size() >= MaxLength) {
392+
OS << "...";
393+
break;
394+
}
395+
OS << Element;
396+
}
397+
OS.flush();
398+
return Out;
399+
}
400+
375401
struct Callee {
376402
// Only one of Decl or Loc is set.
377403
// Loc is for calls through function pointers.
@@ -422,7 +448,8 @@ class InlayHintVisitor : public RecursiveASTVisitor<InlayHintVisitor> {
422448
Callee.Decl = E->getConstructor();
423449
if (!Callee.Decl)
424450
return true;
425-
processCall(Callee, {E->getArgs(), E->getNumArgs()});
451+
processCall(Callee, E->getParenOrBraceRange().getEnd(),
452+
{E->getArgs(), E->getNumArgs()});
426453
return true;
427454
}
428455

@@ -495,7 +522,7 @@ class InlayHintVisitor : public RecursiveASTVisitor<InlayHintVisitor> {
495522
dyn_cast_or_null<CXXMethodDecl>(Callee.Decl))
496523
if (IsFunctor || Method->hasCXXExplicitFunctionObjectParameter())
497524
Args = Args.drop_front(1);
498-
processCall(Callee, Args);
525+
processCall(Callee, E->getRParenLoc(), Args);
499526
return true;
500527
}
501528

@@ -709,10 +736,12 @@ class InlayHintVisitor : public RecursiveASTVisitor<InlayHintVisitor> {
709736
private:
710737
using NameVec = SmallVector<StringRef, 8>;
711738

712-
void processCall(Callee Callee, llvm::ArrayRef<const Expr *> Args) {
739+
void processCall(Callee Callee, SourceLocation RParenOrBraceLoc,
740+
llvm::ArrayRef<const Expr *> Args) {
713741
assert(Callee.Decl || Callee.Loc);
714742

715-
if (!Cfg.InlayHints.Parameters || Args.size() == 0)
743+
if ((!Cfg.InlayHints.Parameters && !Cfg.InlayHints.DefaultArguments) ||
744+
Args.size() == 0)
716745
return;
717746

718747
// The parameter name of a move or copy constructor is not very interesting.
@@ -721,6 +750,9 @@ class InlayHintVisitor : public RecursiveASTVisitor<InlayHintVisitor> {
721750
if (Ctor->isCopyOrMoveConstructor())
722751
return;
723752

753+
SmallVector<std::string> FormattedDefaultArgs;
754+
bool HasNonDefaultArgs = false;
755+
724756
ArrayRef<const ParmVarDecl *> Params, ForwardedParams;
725757
// Resolve parameter packs to their forwarded parameter
726758
SmallVector<const ParmVarDecl *> ForwardedParamsStorage;
@@ -752,15 +784,44 @@ class InlayHintVisitor : public RecursiveASTVisitor<InlayHintVisitor> {
752784
}
753785

754786
StringRef Name = ParameterNames[I];
755-
bool NameHint = shouldHintName(Args[I], Name);
756-
bool ReferenceHint = shouldHintReference(Params[I], ForwardedParams[I]);
757-
758-
if (NameHint || ReferenceHint) {
787+
const bool NameHint =
788+
shouldHintName(Args[I], Name) && Cfg.InlayHints.Parameters;
789+
const bool ReferenceHint =
790+
shouldHintReference(Params[I], ForwardedParams[I]) &&
791+
Cfg.InlayHints.Parameters;
792+
793+
const bool IsDefault = isa<CXXDefaultArgExpr>(Args[I]);
794+
HasNonDefaultArgs |= !IsDefault;
795+
if (IsDefault) {
796+
if (Cfg.InlayHints.DefaultArguments) {
797+
const auto SourceText = Lexer::getSourceText(
798+
CharSourceRange::getTokenRange(Params[I]->getDefaultArgRange()),
799+
AST.getSourceManager(), AST.getLangOpts());
800+
const auto Abbrev =
801+
(SourceText.size() > Cfg.InlayHints.TypeNameLimit ||
802+
SourceText.contains("\n"))
803+
? "..."
804+
: SourceText;
805+
if (NameHint)
806+
FormattedDefaultArgs.emplace_back(
807+
llvm::formatv("{0}: {1}", Name, Abbrev));
808+
else
809+
FormattedDefaultArgs.emplace_back(llvm::formatv("{0}", Abbrev));
810+
}
811+
} else if (NameHint || ReferenceHint) {
759812
addInlayHint(Args[I]->getSourceRange(), HintSide::Left,
760813
InlayHintKind::Parameter, ReferenceHint ? "&" : "",
761814
NameHint ? Name : "", ": ");
762815
}
763816
}
817+
818+
if (!FormattedDefaultArgs.empty()) {
819+
std::string Hint =
820+
joinAndTruncate(FormattedDefaultArgs, Cfg.InlayHints.TypeNameLimit);
821+
addInlayHint(SourceRange{RParenOrBraceLoc}, HintSide::Left,
822+
InlayHintKind::DefaultArgument,
823+
HasNonDefaultArgs ? ", " : "", Hint, "");
824+
}
764825
}
765826

766827
static bool isSetter(const FunctionDecl *Callee, const NameVec &ParamNames) {
@@ -968,6 +1029,7 @@ class InlayHintVisitor : public RecursiveASTVisitor<InlayHintVisitor> {
9681029
CHECK_KIND(Type, DeducedTypes);
9691030
CHECK_KIND(Designator, Designators);
9701031
CHECK_KIND(BlockEnd, BlockEnd);
1032+
CHECK_KIND(DefaultArgument, DefaultArguments);
9711033
#undef CHECK_KIND
9721034
}
9731035

clang-tools-extra/clangd/Protocol.cpp

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1477,6 +1477,7 @@ llvm::json::Value toJSON(const InlayHintKind &Kind) {
14771477
return 2;
14781478
case InlayHintKind::Designator:
14791479
case InlayHintKind::BlockEnd:
1480+
case InlayHintKind::DefaultArgument:
14801481
// This is an extension, don't serialize.
14811482
return nullptr;
14821483
}
@@ -1517,6 +1518,8 @@ llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, InlayHintKind Kind) {
15171518
return "designator";
15181519
case InlayHintKind::BlockEnd:
15191520
return "block-end";
1521+
case InlayHintKind::DefaultArgument:
1522+
return "default-argument";
15201523
}
15211524
llvm_unreachable("Unknown clang.clangd.InlayHintKind");
15221525
};

clang-tools-extra/clangd/Protocol.h

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1681,6 +1681,15 @@ enum class InlayHintKind {
16811681
/// This is a clangd extension.
16821682
BlockEnd = 4,
16831683

1684+
/// An inlay hint that is for a default argument.
1685+
///
1686+
/// An example of a parameter hint for a default argument:
1687+
/// void foo(bool A = true);
1688+
/// foo(^);
1689+
/// Adds an inlay hint "A: true".
1690+
/// This is a clangd extension.
1691+
DefaultArgument = 6,
1692+
16841693
/// Other ideas for hints that are not currently implemented:
16851694
///
16861695
/// * Chaining hints, showing the types of intermediate expressions

clang-tools-extra/clangd/unittests/InlayHintTests.cpp

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,12 @@
1515
#include "support/Context.h"
1616
#include "llvm/ADT/StringRef.h"
1717
#include "llvm/Support/ScopedPrinter.h"
18+
#include "llvm/Support/raw_ostream.h"
1819
#include "gmock/gmock.h"
1920
#include "gtest/gtest.h"
21+
#include <optional>
2022
#include <string>
23+
#include <utility>
2124
#include <vector>
2225

2326
namespace clang {
@@ -81,6 +84,7 @@ Config noHintsConfig() {
8184
C.InlayHints.DeducedTypes = false;
8285
C.InlayHints.Designators = false;
8386
C.InlayHints.BlockEnd = false;
87+
C.InlayHints.DefaultArguments = false;
8488
return C;
8589
}
8690

@@ -1465,6 +1469,75 @@ TEST(TypeHints, DefaultTemplateArgs) {
14651469
ExpectedHint{": A<float>", "binding"});
14661470
}
14671471

1472+
TEST(DefaultArguments, Smoke) {
1473+
Config Cfg;
1474+
Cfg.InlayHints.Parameters =
1475+
true; // To test interplay of parameters and default parameters
1476+
Cfg.InlayHints.DeducedTypes = false;
1477+
Cfg.InlayHints.Designators = false;
1478+
Cfg.InlayHints.BlockEnd = false;
1479+
1480+
Cfg.InlayHints.DefaultArguments = true;
1481+
WithContextValue WithCfg(Config::Key, std::move(Cfg));
1482+
1483+
const auto *Code = R"cpp(
1484+
int foo(int A = 4) { return A; }
1485+
int bar(int A, int B = 1, bool C = foo($default1[[)]]) { return A; }
1486+
int A = bar($explicit[[2]]$default2[[)]];
1487+
1488+
void baz(int = 5) { if (false) baz($unnamed[[)]]; };
1489+
)cpp";
1490+
1491+
assertHints(InlayHintKind::DefaultArgument, Code,
1492+
ExpectedHint{"A: 4", "default1", Left},
1493+
ExpectedHint{", B: 1, C: foo()", "default2", Left},
1494+
ExpectedHint{"5", "unnamed", Left});
1495+
1496+
assertHints(InlayHintKind::Parameter, Code,
1497+
ExpectedHint{"A: ", "explicit", Left});
1498+
}
1499+
1500+
TEST(DefaultArguments, WithoutParameterNames) {
1501+
Config Cfg;
1502+
Cfg.InlayHints.Parameters = false; // To test just default args this time
1503+
Cfg.InlayHints.DeducedTypes = false;
1504+
Cfg.InlayHints.Designators = false;
1505+
Cfg.InlayHints.BlockEnd = false;
1506+
1507+
Cfg.InlayHints.DefaultArguments = true;
1508+
WithContextValue WithCfg(Config::Key, std::move(Cfg));
1509+
1510+
const auto *Code = R"cpp(
1511+
struct Baz {
1512+
Baz(float a = 3 //
1513+
+ 2);
1514+
};
1515+
struct Foo {
1516+
Foo(int, Baz baz = //
1517+
Baz{$abbreviated[[}]]
1518+
1519+
//
1520+
) {}
1521+
};
1522+
1523+
int main() {
1524+
Foo foo1(1$paren[[)]];
1525+
Foo foo2{2$brace1[[}]];
1526+
Foo foo3 = {3$brace2[[}]];
1527+
auto foo4 = Foo{4$brace3[[}]];
1528+
}
1529+
)cpp";
1530+
1531+
assertHints(InlayHintKind::DefaultArgument, Code,
1532+
ExpectedHint{"...", "abbreviated", Left},
1533+
ExpectedHint{", Baz{}", "paren", Left},
1534+
ExpectedHint{", Baz{}", "brace1", Left},
1535+
ExpectedHint{", Baz{}", "brace2", Left},
1536+
ExpectedHint{", Baz{}", "brace3", Left});
1537+
1538+
assertHints(InlayHintKind::Parameter, Code);
1539+
}
1540+
14681541
TEST(TypeHints, Deduplication) {
14691542
assertTypeHints(R"cpp(
14701543
template <typename T>

clang-tools-extra/docs/ReleaseNotes.rst

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,8 @@ Improvements to clangd
5656
Inlay hints
5757
^^^^^^^^^^^
5858

59+
- Added `DefaultArguments` Inlay Hints option.
60+
5961
Diagnostics
6062
^^^^^^^^^^^
6163

0 commit comments

Comments
 (0)