Skip to content

lit_to_const: gracefully bubble up type errors. #69330

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Feb 21, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions src/librustc/mir/interpret/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,10 @@ pub struct LitToConstInput<'tcx> {
/// Error type for `tcx.lit_to_const`.
#[derive(Copy, Clone, Debug, Eq, PartialEq, HashStable)]
pub enum LitToConstError {
/// The literal's inferred type did not match the expected `ty` in the input.
/// This is used for graceful error handling (`delay_span_bug`) in
/// type checking (`AstConv::ast_const_to_const`).
TypeError,
UnparseableFloat,
Reported,
}
Expand Down
59 changes: 22 additions & 37 deletions src/librustc_mir_build/hair/constant.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use rustc::mir::interpret::{
truncate, Allocation, ConstValue, LitToConstError, LitToConstInput, Scalar,
};
use rustc::ty::{self, layout::Size, ParamEnv, TyCtxt};
use rustc::ty::{self, layout::Size, ParamEnv, TyCtxt, TyS};
use rustc_span::symbol::Symbol;
use syntax::ast;

Expand All @@ -20,50 +20,35 @@ crate fn lit_to_const<'tcx>(
Ok(ConstValue::Scalar(Scalar::from_uint(result, width)))
};

let lit = match *lit {
ast::LitKind::Str(ref s, _) => {
let lit = match (lit, &ty.kind) {
(ast::LitKind::Str(s, _), ty::Ref(_, TyS { kind: ty::Str, .. }, _)) => {
let s = s.as_str();
let allocation = Allocation::from_byte_aligned_bytes(s.as_bytes());
let allocation = tcx.intern_const_alloc(allocation);
ConstValue::Slice { data: allocation, start: 0, end: s.len() }
}
ast::LitKind::ByteStr(ref data) => {
if let ty::Ref(_, ref_ty, _) = ty.kind {
match ref_ty.kind {
ty::Slice(_) => {
let allocation = Allocation::from_byte_aligned_bytes(data as &Vec<u8>);
let allocation = tcx.intern_const_alloc(allocation);
ConstValue::Slice { data: allocation, start: 0, end: data.len() }
}
ty::Array(_, _) => {
let id = tcx.allocate_bytes(data);
ConstValue::Scalar(Scalar::Ptr(id.into()))
}
_ => {
bug!("bytestring should have type of either &[u8] or &[u8; _], not {}", ty)
}
}
} else {
bug!("bytestring should have type of either &[u8] or &[u8; _], not {}", ty)
}
(ast::LitKind::ByteStr(data), ty::Ref(_, TyS { kind: ty::Slice(_), .. }, _)) => {
let allocation = Allocation::from_byte_aligned_bytes(data as &Vec<u8>);
let allocation = tcx.intern_const_alloc(allocation);
ConstValue::Slice { data: allocation, start: 0, end: data.len() }
Comment on lines -30 to +33
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reminder to self that reviewing this is best done in "No Whitespace" mode.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Indeed :)

}
(ast::LitKind::ByteStr(data), ty::Ref(_, TyS { kind: ty::Array(_, _), .. }, _)) => {
let id = tcx.allocate_bytes(data);
ConstValue::Scalar(Scalar::Ptr(id.into()))
}
(ast::LitKind::Byte(n), ty::Uint(ast::UintTy::U8)) => {
ConstValue::Scalar(Scalar::from_uint(*n, Size::from_bytes(1)))
}
ast::LitKind::Byte(n) => ConstValue::Scalar(Scalar::from_uint(n, Size::from_bytes(1))),
ast::LitKind::Int(n, _) if neg => {
let n = n as i128;
let n = n.overflowing_neg().0;
trunc(n as u128)?
(ast::LitKind::Int(n, _), ty::Uint(_)) | (ast::LitKind::Int(n, _), ty::Int(_)) => {
trunc(if neg { (*n as i128).overflowing_neg().0 as u128 } else { *n })?
}
ast::LitKind::Int(n, _) => trunc(n)?,
ast::LitKind::Float(n, _) => {
let fty = match ty.kind {
ty::Float(fty) => fty,
_ => bug!(),
};
parse_float(n, fty, neg).map_err(|_| LitToConstError::UnparseableFloat)?
(ast::LitKind::Float(n, _), ty::Float(fty)) => {
parse_float(*n, *fty, neg).map_err(|_| LitToConstError::UnparseableFloat)?
}
ast::LitKind::Bool(b) => ConstValue::Scalar(Scalar::from_bool(b)),
ast::LitKind::Char(c) => ConstValue::Scalar(Scalar::from_char(c)),
ast::LitKind::Err(_) => return Err(LitToConstError::Reported),
(ast::LitKind::Bool(b), ty::Bool) => ConstValue::Scalar(Scalar::from_bool(*b)),
(ast::LitKind::Char(c), ty::Char) => ConstValue::Scalar(Scalar::from_char(*c)),
(ast::LitKind::Err(_), _) => return Err(LitToConstError::Reported),
_ => return Err(LitToConstError::TypeError),
};
Ok(ty::Const::from_value(tcx, lit, ty))
}
Expand Down
1 change: 1 addition & 0 deletions src/librustc_mir_build/hair/cx/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,7 @@ impl<'a, 'tcx> Cx<'a, 'tcx> {
// create a dummy value and continue compiling
Const::from_bits(self.tcx, 0, self.param_env.and(ty))
Comment on lines 148 to 149
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@oli-obk This isn't new in this PR but I wonder why this isn't undef or something (I guess that might cause ICEs?). Maybe we need a ty::ConstKind::Err (if we don't have it already)?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Adding one is probably a good idea (but can be done in a separate PR).

}
Err(LitToConstError::TypeError) => bug!("const_eval_literal: had type error"),
}
}

Expand Down
1 change: 1 addition & 0 deletions src/librustc_mir_build/hair/pattern/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -846,6 +846,7 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> {
PatKind::Wild
}
Err(LitToConstError::Reported) => PatKind::Wild,
Err(LitToConstError::TypeError) => bug!("lower_lit: had type error"),
}
}
}
Expand Down
2 changes: 2 additions & 0 deletions src/librustc_typeck/astconv.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2740,6 +2740,8 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
// mir.
if let Ok(c) = tcx.at(expr.span).lit_to_const(lit_input) {
return c;
} else {
tcx.sess.delay_span_bug(expr.span, "ast_const_to_const: couldn't lit_to_const");
}
}

Expand Down
11 changes: 11 additions & 0 deletions src/test/ui/consts/issue-69310-array-size-lit-wrong-ty.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
// This is a regression test for #69310, which was injected by #68118.
// The issue here was that as a performance optimization,
// we call the query `lit_to_const(input);`.
// However, the literal `input.lit` would not be of the type expected by `input.ty`.
// As a result, we immediately called `bug!(...)` instead of bubbling up the problem
// so that it could be handled by the caller of `lit_to_const` (`ast_const_to_const`).

fn main() {}

const A: [(); 0.1] = [()]; //~ ERROR mismatched types
const B: [(); b"a"] = [()]; //~ ERROR mismatched types
15 changes: 15 additions & 0 deletions src/test/ui/consts/issue-69310-array-size-lit-wrong-ty.stderr
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
error[E0308]: mismatched types
--> $DIR/issue-69310-array-size-lit-wrong-ty.rs:10:15
|
LL | const A: [(); 0.1] = [()];
| ^^^ expected `usize`, found floating-point number

error[E0308]: mismatched types
--> $DIR/issue-69310-array-size-lit-wrong-ty.rs:11:15
|
LL | const B: [(); b"a"] = [()];
| ^^^^ expected `usize`, found `&[u8; 1]`

error: aborting due to 2 previous errors

For more information about this error, try `rustc --explain E0308`.