Skip to content

Commit e8ac079

Browse files
committed
improve const eval error reporting on "" and b"" casts
1 parent e7c822c commit e8ac079

File tree

2 files changed

+20
-3
lines changed

2 files changed

+20
-3
lines changed

src/librustc_const_eval/eval.rs

+16-2
Original file line numberDiff line numberDiff line change
@@ -1105,11 +1105,25 @@ fn cast_const<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, val: ConstVal, ty: ty::Ty)
11051105
Float(f) => cast_const_float(tcx, f, ty),
11061106
Char(c) => cast_const_int(tcx, Infer(c as u64), ty),
11071107
Function(_) => Err(UnimplementedConstVal("casting fn pointers")),
1108-
ByteStr(_) => match ty.sty {
1108+
ByteStr(b) => match ty.sty {
11091109
ty::TyRawPtr(_) => {
11101110
Err(ErrKind::UnimplementedConstVal("casting a bytestr to a raw ptr"))
11111111
},
1112-
ty::TyRef(..) => Err(ErrKind::UnimplementedConstVal("casting a bytestr to slice")),
1112+
ty::TyRef(_, ty::TypeAndMut { ref ty, mutbl: hir::MutImmutable }) => match ty.sty {
1113+
ty::TyArray(ty, n) if ty == tcx.types.u8 && n == b.len() => Ok(ByteStr(b)),
1114+
ty::TySlice(_) => {
1115+
Err(ErrKind::UnimplementedConstVal("casting a bytestr to slice"))
1116+
},
1117+
_ => Err(CannotCast),
1118+
},
1119+
_ => Err(CannotCast),
1120+
},
1121+
Str(s) => match ty.sty {
1122+
ty::TyRawPtr(_) => Err(ErrKind::UnimplementedConstVal("casting a str to a raw ptr")),
1123+
ty::TyRef(_, ty::TypeAndMut { ref ty, mutbl: hir::MutImmutable }) => match ty.sty {
1124+
ty::TyStr => Ok(Str(s)),
1125+
_ => Err(CannotCast),
1126+
},
11131127
_ => Err(CannotCast),
11141128
},
11151129
_ => Err(CannotCast),

src/test/run-pass/const-byte-str-cast.rs

+4-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
1+
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT
22
// file at the top-level directory of this distribution and at
33
// http://rust-lang.org/COPYRIGHT.
44
//
@@ -12,4 +12,7 @@
1212

1313
pub fn main() {
1414
let _ = b"x" as &[u8];
15+
let _ = b"y" as &[u8; 1];
16+
let _ = b"z" as *const u8;
17+
let _ = "ä" as *const str;
1518
}

0 commit comments

Comments
 (0)