From 65839fa622c623393893b5610b6d3b4151abe233 Mon Sep 17 00:00:00 2001 From: Tim Chevalier Date: Sat, 22 Dec 2012 15:56:16 -0800 Subject: [PATCH] Emit a type error for integer literals where the expected type is char For example, in let x: char = 42; This was an ICE and is now a proper type error, as per #3477 --- src/librustc/middle/ty.rs | 15 ++++++++++++++- src/librustc/middle/typeck/infer/unify.rs | 4 ++++ src/test/compile-fail/issue-3477.rs | 3 +++ 3 files changed, 21 insertions(+), 1 deletion(-) create mode 100644 src/test/compile-fail/issue-3477.rs diff --git a/src/librustc/middle/ty.rs b/src/librustc/middle/ty.rs index dc263215646..01e52cfa1d0 100644 --- a/src/librustc/middle/ty.rs +++ b/src/librustc/middle/ty.rs @@ -144,10 +144,11 @@ export kind_is_durable; export meta_kind, kind_lteq, type_kind, type_kind_ext; export operators; export type_err, terr_vstore_kind; -export terr_mismatch, terr_onceness_mismatch; +export terr_integer_as_char, terr_mismatch, terr_onceness_mismatch; export type_err_to_str, note_and_explain_type_err; export expected_found; export type_needs_drop; +export type_is_char; export type_is_empty; export type_is_integral; export type_is_numeric; @@ -696,6 +697,7 @@ enum type_err { terr_in_field(@type_err, ast::ident), terr_sorts(expected_found), terr_self_substs, + terr_integer_as_char, terr_no_integral_type, terr_no_floating_point_type, } @@ -2520,6 +2522,13 @@ fn type_is_integral(ty: t) -> bool { } } +fn type_is_char(ty: t) -> bool { + match get(ty).sty { + ty_int(ty_char) => true, + _ => false + } +} + fn type_is_fp(ty: t) -> bool { match get(ty).sty { ty_infer(FloatVar(_)) | ty_float(_) => true, @@ -3489,6 +3498,10 @@ fn type_err_to_str(cx: ctxt, err: &type_err) -> ~str { ~"couldn't determine an appropriate integral type for integer \ literal" } + terr_integer_as_char => { + ~"integer literals can't be inferred to char type \ + (try an explicit cast)" + } terr_no_floating_point_type => { ~"couldn't determine an appropriate floating point type for \ floating point literal" diff --git a/src/librustc/middle/typeck/infer/unify.rs b/src/librustc/middle/typeck/infer/unify.rs index 2ec356a6dc8..7ffd7e4720d 100644 --- a/src/librustc/middle/typeck/infer/unify.rs +++ b/src/librustc/middle/typeck/infer/unify.rs @@ -362,6 +362,10 @@ impl infer_ctxt { } fn int_var_sub_t(a_id: ty::IntVid, b: ty::t) -> ures { + if ty::type_is_char(b) { + return Err(ty::terr_integer_as_char); + } + assert ty::type_is_integral(b); let vb = &self.int_var_bindings; diff --git a/src/test/compile-fail/issue-3477.rs b/src/test/compile-fail/issue-3477.rs new file mode 100644 index 00000000000..7e189348db3 --- /dev/null +++ b/src/test/compile-fail/issue-3477.rs @@ -0,0 +1,3 @@ +fn main() { + let _p: char = 100; //~ ERROR mismatched types: expected `char` but found +} \ No newline at end of file