Skip to content

Commit 0cccd9a

Browse files
Show better warning for trying to cast non-u8 scalar to char
1 parent 932c736 commit 0cccd9a

File tree

3 files changed

+57
-0
lines changed

3 files changed

+57
-0
lines changed

src/librustc_lint/types.rs

+17
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
#![allow(non_snake_case)]
1212

1313
use rustc::hir::def_id::DefId;
14+
use rustc::hir::map as hir_map;
1415
use rustc::ty::subst::Substs;
1516
use rustc::ty::{self, AdtKind, Ty, TyCtxt};
1617
use rustc::ty::layout::{self, LayoutOf};
@@ -176,6 +177,22 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TypeLimits {
176177
_ => bug!(),
177178
};
178179
if lit_val < min || lit_val > max {
180+
let parent_id = cx.tcx.hir.get_parent_node(e.id);
181+
if let hir_map::NodeExpr(parent_expr) = cx.tcx.hir.get(parent_id) {
182+
if let hir::ExprCast(..) = parent_expr.node {
183+
if let ty::TyChar = cx.tables.expr_ty(parent_expr).sty {
184+
let mut err = cx.struct_span_lint(
185+
OVERFLOWING_LITERALS,
186+
parent_expr.span,
187+
"only u8 can be casted into char");
188+
err.span_suggestion(parent_expr.span,
189+
&"use a char literal instead",
190+
format!("'\\u{{{:X}}}'", lit_val));
191+
err.emit();
192+
return
193+
}
194+
}
195+
}
179196
cx.span_lint(OVERFLOWING_LITERALS,
180197
e.span,
181198
&format!("literal out of range for {:?}", t));

src/test/ui/cast_char.rs

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT
2+
// file at the top-level directory of this distribution and at
3+
// http://rust-lang.org/COPYRIGHT.
4+
//
5+
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6+
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7+
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8+
// option. This file may not be copied, modified, or distributed
9+
// except according to those terms.
10+
11+
#![deny(overflowing_literals)]
12+
13+
fn main() {
14+
const XYZ: char = 0x1F888 as char;
15+
//~^ ERROR only u8 can be casted into char
16+
const XY: char = 129160 as char;
17+
//~^ ERROR only u8 can be casted into char
18+
const ZYX: char = '\u{01F888}';
19+
println!("{}", XYZ);
20+
}

src/test/ui/cast_char.stderr

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
error: only u8 can be casted into char
2+
--> $DIR/cast_char.rs:14:23
3+
|
4+
14 | const XYZ: char = 0x1F888 as char;
5+
| ^^^^^^^^^^^^^^^ help: use a char literal instead: `'/u{1F888}'`
6+
|
7+
note: lint level defined here
8+
--> $DIR/cast_char.rs:11:9
9+
|
10+
11 | #![deny(overflowing_literals)]
11+
| ^^^^^^^^^^^^^^^^^^^^
12+
13+
error: only u8 can be casted into char
14+
--> $DIR/cast_char.rs:16:22
15+
|
16+
16 | const XY: char = 129160 as char;
17+
| ^^^^^^^^^^^^^^ help: use a char literal instead: `'/u{1F888}'`
18+
19+
error: aborting due to 2 previous errors
20+

0 commit comments

Comments
 (0)