Skip to content

Commit 6791b7a

Browse files
[clangd] Show type hint for simple cases of dependent 'auto'
Fixes clangd/clangd#2275
1 parent 45bcf1e commit 6791b7a

File tree

2 files changed

+26
-8
lines changed

2 files changed

+26
-8
lines changed

clang-tools-extra/clangd/InlayHints.cpp

Lines changed: 24 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -633,13 +633,30 @@ class InlayHintVisitor : public RecursiveASTVisitor<InlayHintVisitor> {
633633
}
634634

635635
if (auto *AT = D->getType()->getContainedAutoType()) {
636-
if (AT->isDeduced() && !D->getType()->isDependentType()) {
637-
// Our current approach is to place the hint on the variable
638-
// and accordingly print the full type
639-
// (e.g. for `const auto& x = 42`, print `const int&`).
640-
// Alternatively, we could place the hint on the `auto`
641-
// (and then just print the type deduced for the `auto`).
642-
addTypeHint(D->getLocation(), D->getType(), /*Prefix=*/": ");
636+
if (AT->isDeduced()) {
637+
QualType T;
638+
// If the type is dependent, HeuristicResolver *may* be able to
639+
// resolve it to something that's useful to print. In other
640+
// cases, it can't, and the resultng type would just be printed
641+
// as "<dependent type>", in which case don't hint it at all.
642+
if (D->getType()->isDependentType()) {
643+
if (D->hasInit()) {
644+
QualType Resolved = Resolver->resolveExprToType(D->getInit());
645+
if (Resolved != AST.DependentTy) {
646+
T = Resolved;
647+
}
648+
}
649+
} else {
650+
T = D->getType();
651+
}
652+
if (!T.isNull()) {
653+
// Our current approach is to place the hint on the variable
654+
// and accordingly print the full type
655+
// (e.g. for `const auto& x = 42`, print `const int&`).
656+
// Alternatively, we could place the hint on the `auto`
657+
// (and then just print the type deduced for the `auto`).
658+
addTypeHint(D->getLocation(), T, /*Prefix=*/": ");
659+
}
643660
}
644661
}
645662

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

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1441,7 +1441,8 @@ TEST(TypeHints, DependentType) {
14411441
void bar(T arg) {
14421442
auto [a, b] = arg;
14431443
}
1444-
)cpp");
1444+
)cpp",
1445+
ExpectedHint{": T", "var2"});
14451446
}
14461447

14471448
TEST(TypeHints, LongTypeName) {

0 commit comments

Comments
 (0)