Skip to content

Commit e37653d

Browse files
[clangd] Type hints for C++14 return type deduction
Differential Revision: https://reviews.llvm.org/D103789
1 parent 657aa3a commit e37653d

File tree

2 files changed

+38
-8
lines changed

2 files changed

+38
-8
lines changed

clang-tools-extra/clangd/InlayHints.cpp

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,19 @@ class InlayHintVisitor : public RecursiveASTVisitor<InlayHintVisitor> {
7272
return true;
7373
}
7474

75+
bool VisitFunctionDecl(FunctionDecl *D) {
76+
if (auto *AT = D->getReturnType()->getContainedAutoType()) {
77+
QualType Deduced = AT->getDeducedType();
78+
if (!Deduced.isNull()) {
79+
addInlayHint(D->getFunctionTypeLoc().getRParenLoc(),
80+
InlayHintKind::TypeHint,
81+
"-> " + D->getReturnType().getAsString(TypeHintPolicy));
82+
}
83+
}
84+
85+
return true;
86+
}
87+
7588
bool VisitVarDecl(VarDecl *D) {
7689
// Do not show hints for the aggregate in a structured binding.
7790
// In the future, we may show hints for the individual bindings.

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

Lines changed: 25 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -478,14 +478,31 @@ TEST(TypeHints, StructuredBindings) {
478478
}
479479

480480
TEST(TypeHints, ReturnTypeDeduction) {
481-
// FIXME: Not handled yet.
482-
// This test is currently here mostly because a naive implementation
483-
// might have us print something not super helpful like the function type.
484-
assertTypeHints(R"cpp(
485-
auto func(int x) {
486-
return x + 1;
487-
}
488-
)cpp");
481+
assertTypeHints(
482+
R"cpp(
483+
auto f1(int x$ret1a[[)]]; // Hint forward declaration too
484+
auto f1(int x$ret1b[[)]] { return x + 1; }
485+
486+
// Include pointer operators in hint
487+
int s;
488+
auto& f2($ret2[[)]] { return s; }
489+
490+
// Do not hint `auto` for trailing return type.
491+
auto f3() -> int;
492+
493+
// `auto` conversion operator
494+
struct A {
495+
operator auto($retConv[[)]] { return 42; }
496+
};
497+
498+
// FIXME: Dependent types do not work yet.
499+
template <typename T>
500+
struct S {
501+
auto method() { return T(); }
502+
};
503+
)cpp",
504+
ExpectedHint{"-> int", "ret1a"}, ExpectedHint{"-> int", "ret1b"},
505+
ExpectedHint{"-> int &", "ret2"}, ExpectedHint{"-> int", "retConv"});
489506
}
490507

491508
TEST(TypeHints, DependentType) {

0 commit comments

Comments
 (0)