Skip to content

Commit 9a5725c

Browse files
Rollup merge of rust-lang#56312 - oli-obk:const_eval_literal, r=eddyb
Deduplicate literal -> constant lowering
2 parents ad6434e + afb8cba commit 9a5725c

File tree

4 files changed

+122
-185
lines changed

4 files changed

+122
-185
lines changed

src/librustc_mir/hair/constant.rs

+102
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
use syntax::ast;
2+
use rustc::ty::{self, Ty, TyCtxt, ParamEnv};
3+
use syntax_pos::symbol::Symbol;
4+
use rustc::mir::interpret::{ConstValue, Scalar};
5+
6+
#[derive(PartialEq)]
7+
crate enum LitToConstError {
8+
UnparseableFloat,
9+
Reported,
10+
}
11+
12+
crate fn lit_to_const<'a, 'gcx, 'tcx>(
13+
lit: &'tcx ast::LitKind,
14+
tcx: TyCtxt<'a, 'gcx, 'tcx>,
15+
ty: Ty<'tcx>,
16+
neg: bool,
17+
) -> Result<&'tcx ty::Const<'tcx>, LitToConstError> {
18+
use syntax::ast::*;
19+
20+
let trunc = |n| {
21+
let param_ty = ParamEnv::reveal_all().and(tcx.lift_to_global(&ty).unwrap());
22+
let width = tcx.layout_of(param_ty).map_err(|_| LitToConstError::Reported)?.size;
23+
trace!("trunc {} with size {} and shift {}", n, width.bits(), 128 - width.bits());
24+
let shift = 128 - width.bits();
25+
let result = (n << shift) >> shift;
26+
trace!("trunc result: {}", result);
27+
Ok(ConstValue::Scalar(Scalar::Bits {
28+
bits: result,
29+
size: width.bytes() as u8,
30+
}))
31+
};
32+
33+
use rustc::mir::interpret::*;
34+
let lit = match *lit {
35+
LitKind::Str(ref s, _) => {
36+
let s = s.as_str();
37+
let id = tcx.allocate_bytes(s.as_bytes());
38+
ConstValue::new_slice(Scalar::Ptr(id.into()), s.len() as u64, &tcx)
39+
},
40+
LitKind::ByteStr(ref data) => {
41+
let id = tcx.allocate_bytes(data);
42+
ConstValue::Scalar(Scalar::Ptr(id.into()))
43+
},
44+
LitKind::Byte(n) => ConstValue::Scalar(Scalar::Bits {
45+
bits: n as u128,
46+
size: 1,
47+
}),
48+
LitKind::Int(n, _) if neg => {
49+
let n = n as i128;
50+
let n = n.overflowing_neg().0;
51+
trunc(n as u128)?
52+
},
53+
LitKind::Int(n, _) => trunc(n)?,
54+
LitKind::Float(n, fty) => {
55+
parse_float(n, fty, neg).map_err(|_| LitToConstError::UnparseableFloat)?
56+
}
57+
LitKind::FloatUnsuffixed(n) => {
58+
let fty = match ty.sty {
59+
ty::Float(fty) => fty,
60+
_ => bug!()
61+
};
62+
parse_float(n, fty, neg).map_err(|_| LitToConstError::UnparseableFloat)?
63+
}
64+
LitKind::Bool(b) => ConstValue::Scalar(Scalar::from_bool(b)),
65+
LitKind::Char(c) => ConstValue::Scalar(Scalar::from_char(c)),
66+
};
67+
Ok(ty::Const::from_const_value(tcx, lit, ty))
68+
}
69+
70+
fn parse_float<'tcx>(
71+
num: Symbol,
72+
fty: ast::FloatTy,
73+
neg: bool,
74+
) -> Result<ConstValue<'tcx>, ()> {
75+
let num = num.as_str();
76+
use rustc_apfloat::ieee::{Single, Double};
77+
use rustc_apfloat::Float;
78+
let (bits, size) = match fty {
79+
ast::FloatTy::F32 => {
80+
num.parse::<f32>().map_err(|_| ())?;
81+
let mut f = num.parse::<Single>().unwrap_or_else(|e| {
82+
panic!("apfloat::ieee::Single failed to parse `{}`: {:?}", num, e)
83+
});
84+
if neg {
85+
f = -f;
86+
}
87+
(f.to_bits(), 4)
88+
}
89+
ast::FloatTy::F64 => {
90+
num.parse::<f64>().map_err(|_| ())?;
91+
let mut f = num.parse::<Double>().unwrap_or_else(|e| {
92+
panic!("apfloat::ieee::Single failed to parse `{}`: {:?}", num, e)
93+
});
94+
if neg {
95+
f = -f;
96+
}
97+
(f.to_bits(), 8)
98+
}
99+
};
100+
101+
Ok(ConstValue::Scalar(Scalar::Bits { bits, size }))
102+
}

src/librustc_mir/hair/cx/mod.rs

+12-55
Original file line numberDiff line numberDiff line change
@@ -26,12 +26,12 @@ use rustc::ty::subst::Subst;
2626
use rustc::ty::{self, Ty, TyCtxt};
2727
use rustc::ty::subst::{Kind, Substs};
2828
use rustc::ty::layout::VariantIdx;
29-
use syntax::ast::{self, LitKind};
29+
use syntax::ast;
3030
use syntax::attr;
3131
use syntax::symbol::Symbol;
3232
use rustc::hir;
3333
use rustc_data_structures::sync::Lrc;
34-
use hair::pattern::parse_float;
34+
use hair::constant::{lit_to_const, LitToConstError};
3535

3636
#[derive(Clone)]
3737
pub struct Cx<'a, 'gcx: 'a + 'tcx, 'tcx: 'a> {
@@ -131,7 +131,6 @@ impl<'a, 'gcx, 'tcx> Cx<'a, 'gcx, 'tcx> {
131131
ty::Const::from_bool(self.tcx, false)
132132
}
133133

134-
// FIXME: Combine with rustc_mir::hair::pattern::lit_to_const
135134
pub fn const_eval_literal(
136135
&mut self,
137136
lit: &'tcx ast::LitKind,
@@ -141,61 +140,19 @@ impl<'a, 'gcx, 'tcx> Cx<'a, 'gcx, 'tcx> {
141140
) -> &'tcx ty::Const<'tcx> {
142141
trace!("const_eval_literal: {:#?}, {:?}, {:?}, {:?}", lit, ty, sp, neg);
143142

144-
let parse_float = |num, fty| -> ConstValue<'tcx> {
145-
parse_float(num, fty, neg).unwrap_or_else(|_| {
143+
match lit_to_const(lit, self.tcx, ty, neg) {
144+
Ok(c) => c,
145+
Err(LitToConstError::UnparseableFloat) => {
146146
// FIXME(#31407) this is only necessary because float parsing is buggy
147-
self.tcx.sess.span_fatal(sp, "could not evaluate float literal (see issue #31407)");
148-
})
149-
};
150-
151-
let trunc = |n| {
152-
let param_ty = self.param_env.and(self.tcx.lift_to_global(&ty).unwrap());
153-
let width = self.tcx.layout_of(param_ty).unwrap().size;
154-
trace!("trunc {} with size {} and shift {}", n, width.bits(), 128 - width.bits());
155-
let shift = 128 - width.bits();
156-
let result = (n << shift) >> shift;
157-
trace!("trunc result: {}", result);
158-
ConstValue::Scalar(Scalar::Bits {
159-
bits: result,
160-
size: width.bytes() as u8,
161-
})
162-
};
163-
164-
use rustc::mir::interpret::*;
165-
let lit = match *lit {
166-
LitKind::Str(ref s, _) => {
167-
let s = s.as_str();
168-
let id = self.tcx.allocate_bytes(s.as_bytes());
169-
ConstValue::new_slice(Scalar::Ptr(id.into()), s.len() as u64, &self.tcx)
170-
},
171-
LitKind::ByteStr(ref data) => {
172-
let id = self.tcx.allocate_bytes(data);
173-
ConstValue::Scalar(Scalar::Ptr(id.into()))
147+
self.tcx.sess.span_err(sp, "could not evaluate float literal (see issue #31407)");
148+
// create a dummy value and continue compiling
149+
Const::from_bits(self.tcx, 0, self.param_env.and(ty))
174150
},
175-
LitKind::Byte(n) => ConstValue::Scalar(Scalar::Bits {
176-
bits: n as u128,
177-
size: 1,
178-
}),
179-
LitKind::Int(n, _) if neg => {
180-
let n = n as i128;
181-
let n = n.overflowing_neg().0;
182-
trunc(n as u128)
183-
},
184-
LitKind::Int(n, _) => trunc(n),
185-
LitKind::Float(n, fty) => {
186-
parse_float(n, fty)
187-
}
188-
LitKind::FloatUnsuffixed(n) => {
189-
let fty = match ty.sty {
190-
ty::Float(fty) => fty,
191-
_ => bug!()
192-
};
193-
parse_float(n, fty)
151+
Err(LitToConstError::Reported) => {
152+
// create a dummy value and continue compiling
153+
Const::from_bits(self.tcx, 0, self.param_env.and(ty))
194154
}
195-
LitKind::Bool(b) => ConstValue::Scalar(Scalar::from_bool(b)),
196-
LitKind::Char(c) => ConstValue::Scalar(Scalar::from_char(c)),
197-
};
198-
ty::Const::from_const_value(self.tcx, lit, ty)
155+
}
199156
}
200157

201158
pub fn pattern_from_hir(&mut self, p: &hir::Pat) -> Pattern<'tcx> {

src/librustc_mir/hair/mod.rs

+1
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ use syntax_pos::Span;
2626
use self::cx::Cx;
2727

2828
pub mod cx;
29+
mod constant;
2930

3031
pub mod pattern;
3132
pub use self::pattern::{BindingMode, Pattern, PatternKind, FieldPattern};

src/librustc_mir/hair/pattern/mod.rs

+7-130
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ pub(crate) use self::check_match::check_match;
1919
use const_eval::{const_field, const_variant_index};
2020

2121
use hair::util::UserAnnotatedTyHelpers;
22+
use hair::constant::*;
2223

2324
use rustc::mir::{fmt_const_val, Field, BorrowKind, Mutability};
2425
use rustc::mir::{ProjectionElem, UserTypeAnnotation, UserTypeProjection, UserTypeProjections};
@@ -37,7 +38,6 @@ use std::fmt;
3738
use syntax::ast;
3839
use syntax::ptr::P;
3940
use syntax_pos::Span;
40-
use syntax_pos::symbol::Symbol;
4141

4242
#[derive(Clone, Debug)]
4343
pub enum PatternError {
@@ -891,12 +891,11 @@ impl<'a, 'tcx> PatternContext<'a, 'tcx> {
891891
);
892892
*self.const_to_pat(instance, val, expr.hir_id, lit.span).kind
893893
},
894-
Err(e) => {
895-
if e == LitToConstError::UnparseableFloat {
896-
self.errors.push(PatternError::FloatBug);
897-
}
894+
Err(LitToConstError::UnparseableFloat) => {
895+
self.errors.push(PatternError::FloatBug);
898896
PatternKind::Wild
899897
},
898+
Err(LitToConstError::Reported) => PatternKind::Wild,
900899
}
901900
},
902901
hir::ExprKind::Path(ref qpath) => *self.lower_path(qpath, expr.hir_id, expr.span).kind,
@@ -914,12 +913,11 @@ impl<'a, 'tcx> PatternContext<'a, 'tcx> {
914913
);
915914
*self.const_to_pat(instance, val, expr.hir_id, lit.span).kind
916915
},
917-
Err(e) => {
918-
if e == LitToConstError::UnparseableFloat {
919-
self.errors.push(PatternError::FloatBug);
920-
}
916+
Err(LitToConstError::UnparseableFloat) => {
917+
self.errors.push(PatternError::FloatBug);
921918
PatternKind::Wild
922919
},
920+
Err(LitToConstError::Reported) => PatternKind::Wild,
923921
}
924922
}
925923
_ => span_bug!(expr.span, "not a literal: {:?}", expr),
@@ -1294,124 +1292,3 @@ pub fn compare_const_vals<'a, 'tcx>(
12941292

12951293
fallback()
12961294
}
1297-
1298-
#[derive(PartialEq)]
1299-
enum LitToConstError {
1300-
UnparseableFloat,
1301-
Propagated,
1302-
}
1303-
1304-
// FIXME: Combine with rustc_mir::hair::cx::const_eval_literal
1305-
fn lit_to_const<'a, 'tcx>(lit: &'tcx ast::LitKind,
1306-
tcx: TyCtxt<'a, 'tcx, 'tcx>,
1307-
ty: Ty<'tcx>,
1308-
neg: bool)
1309-
-> Result<&'tcx ty::Const<'tcx>, LitToConstError> {
1310-
use syntax::ast::*;
1311-
1312-
use rustc::mir::interpret::*;
1313-
let lit = match *lit {
1314-
LitKind::Str(ref s, _) => {
1315-
let s = s.as_str();
1316-
let id = tcx.allocate_bytes(s.as_bytes());
1317-
ConstValue::new_slice(Scalar::Ptr(id.into()), s.len() as u64, &tcx)
1318-
},
1319-
LitKind::ByteStr(ref data) => {
1320-
let id = tcx.allocate_bytes(data);
1321-
ConstValue::Scalar(Scalar::Ptr(id.into()))
1322-
},
1323-
LitKind::Byte(n) => ConstValue::Scalar(Scalar::Bits {
1324-
bits: n as u128,
1325-
size: 1,
1326-
}),
1327-
LitKind::Int(n, _) => {
1328-
enum Int {
1329-
Signed(IntTy),
1330-
Unsigned(UintTy),
1331-
}
1332-
let ity = match ty.sty {
1333-
ty::Int(IntTy::Isize) => Int::Signed(tcx.sess.target.isize_ty),
1334-
ty::Int(other) => Int::Signed(other),
1335-
ty::Uint(UintTy::Usize) => Int::Unsigned(tcx.sess.target.usize_ty),
1336-
ty::Uint(other) => Int::Unsigned(other),
1337-
ty::Error => { // Avoid ICE (#51963)
1338-
return Err(LitToConstError::Propagated);
1339-
}
1340-
_ => bug!("literal integer type with bad type ({:?})", ty.sty),
1341-
};
1342-
// This converts from LitKind::Int (which is sign extended) to
1343-
// Scalar::Bytes (which is zero extended)
1344-
let n = match ity {
1345-
// FIXME(oli-obk): are these casts correct?
1346-
Int::Signed(IntTy::I8) if neg =>
1347-
(n as i8).overflowing_neg().0 as u8 as u128,
1348-
Int::Signed(IntTy::I16) if neg =>
1349-
(n as i16).overflowing_neg().0 as u16 as u128,
1350-
Int::Signed(IntTy::I32) if neg =>
1351-
(n as i32).overflowing_neg().0 as u32 as u128,
1352-
Int::Signed(IntTy::I64) if neg =>
1353-
(n as i64).overflowing_neg().0 as u64 as u128,
1354-
Int::Signed(IntTy::I128) if neg =>
1355-
(n as i128).overflowing_neg().0 as u128,
1356-
Int::Signed(IntTy::I8) | Int::Unsigned(UintTy::U8) => n as u8 as u128,
1357-
Int::Signed(IntTy::I16) | Int::Unsigned(UintTy::U16) => n as u16 as u128,
1358-
Int::Signed(IntTy::I32) | Int::Unsigned(UintTy::U32) => n as u32 as u128,
1359-
Int::Signed(IntTy::I64) | Int::Unsigned(UintTy::U64) => n as u64 as u128,
1360-
Int::Signed(IntTy::I128)| Int::Unsigned(UintTy::U128) => n,
1361-
_ => bug!(),
1362-
};
1363-
let size = tcx.layout_of(ty::ParamEnv::empty().and(ty)).unwrap().size.bytes() as u8;
1364-
ConstValue::Scalar(Scalar::Bits {
1365-
bits: n,
1366-
size,
1367-
})
1368-
},
1369-
LitKind::Float(n, fty) => {
1370-
parse_float(n, fty, neg).map_err(|_| LitToConstError::UnparseableFloat)?
1371-
}
1372-
LitKind::FloatUnsuffixed(n) => {
1373-
let fty = match ty.sty {
1374-
ty::Float(fty) => fty,
1375-
_ => bug!()
1376-
};
1377-
parse_float(n, fty, neg).map_err(|_| LitToConstError::UnparseableFloat)?
1378-
}
1379-
LitKind::Bool(b) => ConstValue::Scalar(Scalar::from_bool(b)),
1380-
LitKind::Char(c) => ConstValue::Scalar(Scalar::from_char(c)),
1381-
};
1382-
Ok(ty::Const::from_const_value(tcx, lit, ty))
1383-
}
1384-
1385-
pub fn parse_float<'tcx>(
1386-
num: Symbol,
1387-
fty: ast::FloatTy,
1388-
neg: bool,
1389-
) -> Result<ConstValue<'tcx>, ()> {
1390-
let num = num.as_str();
1391-
use rustc_apfloat::ieee::{Single, Double};
1392-
use rustc_apfloat::Float;
1393-
let (bits, size) = match fty {
1394-
ast::FloatTy::F32 => {
1395-
num.parse::<f32>().map_err(|_| ())?;
1396-
let mut f = num.parse::<Single>().unwrap_or_else(|e| {
1397-
panic!("apfloat::ieee::Single failed to parse `{}`: {:?}", num, e)
1398-
});
1399-
if neg {
1400-
f = -f;
1401-
}
1402-
(f.to_bits(), 4)
1403-
}
1404-
ast::FloatTy::F64 => {
1405-
num.parse::<f64>().map_err(|_| ())?;
1406-
let mut f = num.parse::<Double>().unwrap_or_else(|e| {
1407-
panic!("apfloat::ieee::Single failed to parse `{}`: {:?}", num, e)
1408-
});
1409-
if neg {
1410-
f = -f;
1411-
}
1412-
(f.to_bits(), 8)
1413-
}
1414-
};
1415-
1416-
Ok(ConstValue::Scalar(Scalar::Bits { bits, size }))
1417-
}

0 commit comments

Comments
 (0)