Skip to content

Commit d544092

Browse files
committed
Suggest replacing typeof(...) with an actual type
This commit suggests replacing typeof(...) with an actual type of "...", for example in case of `typeof(1)` we suggest replacing it with `i32`. If the expression - Is not const (`{ let a = 1; let _: typeof(a); }`) - Can't be found (`let _: typeof(this_variable_does_not_exist)`) - Or has non-suggestable type (closure, generator, error, etc) we don't suggest anything.
1 parent fa72316 commit d544092

File tree

3 files changed

+17
-3
lines changed

3 files changed

+17
-3
lines changed

compiler/rustc_error_messages/locales/en-US/diagnostics.ftl

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,7 @@ typeck-functional-record-update-on-non-struct =
6262
6363
typeck-typeof-reserved-keyword-used =
6464
`typeof` is a reserved keyword but unimplemented
65+
.suggestion = consider replacing `typeof(...)` with an actual type
6566
.label = reserved keyword
6667
6768
typeck-return-stmt-outside-of-fn-body =

compiler/rustc_typeck/src/astconv/mod.rs

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2462,8 +2462,16 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
24622462
self.normalize_ty(ast_ty.span, array_ty)
24632463
}
24642464
hir::TyKind::Typeof(ref e) => {
2465-
tcx.sess.emit_err(TypeofReservedKeywordUsed { span: ast_ty.span });
2466-
tcx.type_of(tcx.hir().local_def_id(e.hir_id))
2465+
let ty = tcx.type_of(tcx.hir().local_def_id(e.hir_id));
2466+
let span = ast_ty.span;
2467+
tcx.sess.emit_err(TypeofReservedKeywordUsed {
2468+
span,
2469+
ty,
2470+
opt_sugg: Some((span, Applicability::MachineApplicable))
2471+
.filter(|_| ty.is_suggestable()),
2472+
});
2473+
2474+
ty
24672475
}
24682476
hir::TyKind::Infer => {
24692477
// Infer also appears as the type of arguments or return

compiler/rustc_typeck/src/errors.rs

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
//! Errors emitted by typeck.
2+
use rustc_errors::Applicability;
23
use rustc_macros::SessionDiagnostic;
4+
use rustc_middle::ty::Ty;
35
use rustc_span::{symbol::Ident, Span, Symbol};
46

57
#[derive(SessionDiagnostic)]
@@ -127,10 +129,13 @@ pub struct FunctionalRecordUpdateOnNonStruct {
127129

128130
#[derive(SessionDiagnostic)]
129131
#[error(code = "E0516", slug = "typeck-typeof-reserved-keyword-used")]
130-
pub struct TypeofReservedKeywordUsed {
132+
pub struct TypeofReservedKeywordUsed<'tcx> {
133+
pub ty: Ty<'tcx>,
131134
#[primary_span]
132135
#[label]
133136
pub span: Span,
137+
#[suggestion_verbose(message = "suggestion", code = "{ty}")]
138+
pub opt_sugg: Option<(Span, Applicability)>,
134139
}
135140

136141
#[derive(SessionDiagnostic)]

0 commit comments

Comments
 (0)