1 // Copyright 2012-2016 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.
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.
11 use rustc::middle::const_val::ConstVal::*;
12 use rustc::middle::const_val::ConstVal;
14 use self::EvalHint::*;
16 use rustc::hir::map as hir_map;
17 use rustc::hir::map::blocks::FnLikeNode;
19 use rustc::hir::def::Def;
20 use rustc::hir::def_id::DefId;
21 use rustc::ty::{self, Ty, TyCtxt};
22 use rustc::ty::util::IntTypeExt;
23 use rustc::ty::subst::Substs;
24 use rustc::traits::Reveal;
25 use rustc::util::common::ErrorReported;
26 use rustc::util::nodemap::DefIdMap;
28 use graphviz::IntoCow;
30 use rustc::hir::{self, Expr};
31 use syntax::attr::IntType;
35 use std::cmp::Ordering;
37 use rustc_const_math::*;
38 use rustc_errors::DiagnosticBuilder;
41 ($e:expr, $op:expr) => {
44 Err(e) => signal!($e, Math(e)),
49 fn lookup_variant_by_id<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
51 -> Option<(&'tcx Expr, Option<&'a ty::TypeckTables<'tcx>>)> {
52 if let Some(variant_node_id) = tcx.hir.as_local_node_id(variant_def) {
53 let enum_node_id = tcx.hir.get_parent(variant_node_id);
54 if let Some(hir_map::NodeItem(it)) = tcx.hir.find(enum_node_id) {
55 if let hir::ItemEnum(ref edef, _) = it.node {
56 for variant in &edef.variants {
57 if variant.node.data.id() == variant_node_id {
58 return variant.node.disr_expr.map(|e| {
59 let def_id = tcx.hir.body_owner_def_id(e);
60 (&tcx.hir.body(e).value,
61 tcx.tables.borrow().get(&def_id).cloned())
71 /// * `def_id` is the id of the constant.
72 /// * `substs` is the monomorphized substitutions for the expression.
74 /// `substs` is optional and is used for associated constants.
75 /// This generally happens in late/trans const evaluation.
76 pub fn lookup_const_by_id<'a, 'tcx: 'a>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
78 substs: Option<&'tcx Substs<'tcx>>)
79 -> Option<(&'tcx Expr,
80 Option<&'a ty::TypeckTables<'tcx>>,
81 Option<ty::Ty<'tcx>>)> {
82 if let Some(node_id) = tcx.hir.as_local_node_id(def_id) {
83 match tcx.hir.find(node_id) {
85 Some(hir_map::NodeItem(&hir::Item {
86 node: hir::ItemConst(ref ty, body), ..
88 Some(hir_map::NodeImplItem(&hir::ImplItem {
89 node: hir::ImplItemKind::Const(ref ty, body), ..
91 Some((&tcx.hir.body(body).value,
92 tcx.tables.borrow().get(&def_id).cloned(),
93 tcx.ast_ty_to_prim_ty(ty)))
95 Some(hir_map::NodeTraitItem(ti)) => match ti.node {
96 hir::TraitItemKind::Const(ref ty, default) => {
97 if let Some(substs) = substs {
98 // If we have a trait item and the substitutions for it,
99 // `resolve_trait_associated_const` will select an impl
101 let trait_id = tcx.hir.get_parent(node_id);
102 let trait_id = tcx.hir.local_def_id(trait_id);
103 let default_value = default.map(|body| {
104 (&tcx.hir.body(body).value,
105 tcx.tables.borrow().get(&def_id).cloned(),
106 tcx.ast_ty_to_prim_ty(ty))
108 resolve_trait_associated_const(tcx, def_id, default_value, trait_id, substs)
110 // Technically, without knowing anything about the
111 // expression that generates the obligation, we could
112 // still return the default if there is one. However,
113 // it's safer to return `None` than to return some value
114 // that may differ from what you would get from
115 // correctly selecting an impl.
124 let expr_tables_ty = tcx.sess.cstore.maybe_get_item_body(tcx, def_id).map(|body| {
125 (&body.value, Some(tcx.item_tables(def_id)),
126 Some(tcx.sess.cstore.item_type(tcx, def_id)))
128 match tcx.sess.cstore.describe_def(def_id) {
129 Some(Def::AssociatedConst(_)) => {
130 let trait_id = tcx.sess.cstore.trait_of_item(def_id);
131 // As mentioned in the comments above for in-crate
132 // constants, we only try to find the expression for a
133 // trait-associated const if the caller gives us the
134 // substitutions for the reference to it.
135 if let Some(trait_id) = trait_id {
136 if let Some(substs) = substs {
137 resolve_trait_associated_const(tcx, def_id, expr_tables_ty,
146 Some(Def::Const(..)) => expr_tables_ty,
152 fn lookup_const_fn_by_id<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId)
153 -> Option<(&'tcx hir::Body, Option<&'a ty::TypeckTables<'tcx>>)>
155 if let Some(node_id) = tcx.hir.as_local_node_id(def_id) {
156 FnLikeNode::from_node(tcx.hir.get(node_id)).and_then(|fn_like| {
157 if fn_like.constness() == hir::Constness::Const {
158 Some((tcx.hir.body(fn_like.body()),
159 tcx.tables.borrow().get(&def_id).cloned()))
165 if tcx.sess.cstore.is_const_fn(def_id) {
166 tcx.sess.cstore.maybe_get_item_body(tcx, def_id).map(|body| {
167 (body, Some(tcx.item_tables(def_id)))
175 pub fn report_const_eval_err<'a, 'tcx>(
176 tcx: TyCtxt<'a, 'tcx, 'tcx>,
180 -> DiagnosticBuilder<'tcx>
183 while let &ConstEvalErr { kind: ErroneousReferencedConstant(box ref i_err), .. } = err {
187 let mut diag = struct_span_err!(tcx.sess, err.span, E0080, "constant evaluation error");
188 note_const_eval_err(tcx, err, primary_span, primary_kind, &mut diag);
192 pub fn fatal_const_eval_err<'a, 'tcx>(
193 tcx: TyCtxt<'a, 'tcx, 'tcx>,
199 report_const_eval_err(tcx, err, primary_span, primary_kind).emit();
200 tcx.sess.abort_if_errors();
204 pub fn note_const_eval_err<'a, 'tcx>(
205 _tcx: TyCtxt<'a, 'tcx, 'tcx>,
209 diag: &mut DiagnosticBuilder)
211 match err.description() {
212 ConstEvalErrDescription::Simple(message) => {
213 diag.span_label(err.span, &message);
217 if !primary_span.contains(err.span) {
218 diag.span_note(primary_span,
219 &format!("for {} here", primary_kind));
223 pub struct ConstContext<'a, 'tcx: 'a> {
224 tcx: TyCtxt<'a, 'tcx, 'tcx>,
225 tables: Option<&'a ty::TypeckTables<'tcx>>,
226 fn_args: Option<DefIdMap<ConstVal>>
229 impl<'a, 'tcx> ConstContext<'a, 'tcx> {
230 pub fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>, body: hir::BodyId) -> Self {
231 let def_id = tcx.hir.body_owner_def_id(body);
234 tables: tcx.tables.borrow().get(&def_id).cloned(),
239 pub fn with_tables(tcx: TyCtxt<'a, 'tcx, 'tcx>, tables: &'a ty::TypeckTables<'tcx>) -> Self {
242 tables: Some(tables),
247 /// Evaluate a constant expression in a context where the expression isn't
248 /// guaranteed to be evaluatable. `ty_hint` is usually ExprTypeChecked,
249 /// but a few places need to evaluate constants during type-checking, like
250 /// computing the length of an array. (See also the FIXME above EvalHint.)
251 pub fn eval(&self, e: &Expr, ty_hint: EvalHint<'tcx>) -> EvalResult {
252 eval_const_expr_partial(self, e, ty_hint)
256 #[derive(Clone, Debug)]
257 pub struct ConstEvalErr {
262 #[derive(Clone, Debug)]
265 CannotCastTo(&'static str),
266 InvalidOpForInts(hir::BinOp_),
267 InvalidOpForBools(hir::BinOp_),
268 InvalidOpForFloats(hir::BinOp_),
269 InvalidOpForIntUint(hir::BinOp_),
270 InvalidOpForUintInt(hir::BinOp_),
277 UnimplementedConstVal(&'static str),
281 TupleIndexOutOfBounds,
285 IndexOutOfBounds { len: u64, index: u64 },
286 RepeatCountNotNatural,
295 IntermediateUnsignedNegative,
297 TypeMismatch(String, ConstInt),
300 ErroneousReferencedConstant(Box<ConstEvalErr>),
304 impl From<ConstMathErr> for ErrKind {
305 fn from(err: ConstMathErr) -> ErrKind {
310 #[derive(Clone, Debug)]
311 pub enum ConstEvalErrDescription<'a> {
312 Simple(Cow<'a, str>),
315 impl<'a> ConstEvalErrDescription<'a> {
316 /// Return a one-line description of the error, for lints and such
317 pub fn into_oneline(self) -> Cow<'a, str> {
319 ConstEvalErrDescription::Simple(simple) => simple,
325 pub fn description(&self) -> ConstEvalErrDescription {
326 use self::ErrKind::*;
327 use self::ConstEvalErrDescription::*;
329 macro_rules! simple {
330 ($msg:expr) => ({ Simple($msg.into_cow()) });
331 ($fmt:expr, $($arg:tt)+) => ({
332 Simple(format!($fmt, $($arg)+).into_cow())
337 CannotCast => simple!("can't cast this type"),
338 CannotCastTo(s) => simple!("can't cast this type to {}", s),
339 InvalidOpForInts(_) => simple!("can't do this op on integrals"),
340 InvalidOpForBools(_) => simple!("can't do this op on bools"),
341 InvalidOpForFloats(_) => simple!("can't do this op on floats"),
342 InvalidOpForIntUint(..) => simple!("can't do this op on an isize and usize"),
343 InvalidOpForUintInt(..) => simple!("can't do this op on a usize and isize"),
344 NegateOn(ref const_val) => simple!("negate on {}", const_val.description()),
345 NotOn(ref const_val) => simple!("not on {}", const_val.description()),
346 CallOn(ref const_val) => simple!("call on {}", const_val.description()),
348 MissingStructField => simple!("nonexistent struct field"),
349 NonConstPath => simple!("non-constant path in constant expression"),
350 UnimplementedConstVal(what) =>
351 simple!("unimplemented constant expression: {}", what),
352 UnresolvedPath => simple!("unresolved path in constant expression"),
353 ExpectedConstTuple => simple!("expected constant tuple"),
354 ExpectedConstStruct => simple!("expected constant struct"),
355 TupleIndexOutOfBounds => simple!("tuple index out of bounds"),
356 IndexedNonVec => simple!("indexing is only supported for arrays"),
357 IndexNegative => simple!("indices must be non-negative integers"),
358 IndexNotInt => simple!("indices must be integers"),
359 IndexOutOfBounds { len, index } => {
360 simple!("index out of bounds: the len is {} but the index is {}",
363 RepeatCountNotNatural => simple!("repeat count must be a natural number"),
364 RepeatCountNotInt => simple!("repeat count must be integers"),
366 MiscBinaryOp => simple!("bad operands for binary"),
367 MiscCatchAll => simple!("unsupported constant expr"),
368 IndexOpFeatureGated => simple!("the index operation on const values is unstable"),
369 Math(ref err) => Simple(err.description().into_cow()),
371 IntermediateUnsignedNegative => simple!(
372 "during the computation of an unsigned a negative \
373 number was encountered. This is most likely a bug in\
374 the constant evaluator"),
376 TypeMismatch(ref expected, ref got) => {
377 simple!("expected {}, found {}", expected, got.description())
379 BadType(ref i) => simple!("value of wrong type: {:?}", i),
380 ErroneousReferencedConstant(_) => simple!("could not evaluate referenced constant"),
381 CharCast(ref got) => {
382 simple!("only `u8` can be cast as `char`, not `{}`", got.description())
388 pub type EvalResult = Result<ConstVal, ConstEvalErr>;
389 pub type CastResult = Result<ConstVal, ErrKind>;
391 // FIXME: Long-term, this enum should go away: trying to evaluate
392 // an expression which hasn't been type-checked is a recipe for
393 // disaster. That said, it's not clear how to fix ast_ty_to_ty
394 // to avoid the ordering issue.
396 /// Hint to determine how to evaluate constant expressions which
397 /// might not be type-checked.
398 #[derive(Copy, Clone, Debug)]
399 pub enum EvalHint<'tcx> {
400 /// We have a type-checked expression.
402 /// We have an expression which hasn't been type-checked, but we have
403 /// an idea of what the type will be because of the context. For example,
404 /// the length of an array is always `usize`. (This is referred to as
405 /// a hint because it isn't guaranteed to be consistent with what
406 /// type-checking would compute.)
407 UncheckedExprHint(Ty<'tcx>),
408 /// We have an expression which has not yet been type-checked, and
409 /// and we have no clue what the type will be.
413 impl<'tcx> EvalHint<'tcx> {
414 fn erase_hint(&self) -> EvalHint<'tcx> {
416 ExprTypeChecked => ExprTypeChecked,
417 UncheckedExprHint(_) | UncheckedExprNoHint => UncheckedExprNoHint,
420 fn checked_or(&self, ty: Ty<'tcx>) -> EvalHint<'tcx> {
422 ExprTypeChecked => ExprTypeChecked,
423 _ => UncheckedExprHint(ty),
428 macro_rules! signal {
429 ($e:expr, $exn:expr) => {
430 return Err(ConstEvalErr { span: $e.span, kind: $exn })
434 fn eval_const_expr_partial<'a, 'tcx>(cx: &ConstContext<'a, 'tcx>,
436 ty_hint: EvalHint<'tcx>) -> EvalResult {
438 // Try to compute the type of the expression based on the EvalHint.
439 // (See also the definition of EvalHint, and the FIXME above EvalHint.)
440 let ety = match ty_hint {
442 // After type-checking, expr_ty is guaranteed to succeed.
443 cx.tables.map(|tables| tables.expr_ty(e))
445 UncheckedExprHint(ty) => {
446 // Use the type hint; it's not guaranteed to be right, but it's
447 // usually good enough.
450 UncheckedExprNoHint => {
451 // This expression might not be type-checked, and we have no hint.
452 // Try to query the context for a type anyway; we might get lucky
453 // (for example, if the expression was imported from another crate).
454 cx.tables.and_then(|tables| tables.expr_ty_opt(e))
457 let result = match e.node {
458 hir::ExprUnary(hir::UnNeg, ref inner) => {
459 // unary neg literals already got their sign during creation
460 if let hir::ExprLit(ref lit) = inner.node {
462 use syntax::ast::LitIntType::*;
463 const I8_OVERFLOW: u128 = i8::min_value() as u8 as u128;
464 const I16_OVERFLOW: u128 = i16::min_value() as u16 as u128;
465 const I32_OVERFLOW: u128 = i32::min_value() as u32 as u128;
466 const I64_OVERFLOW: u128 = i64::min_value() as u64 as u128;
467 const I128_OVERFLOW: u128 = i128::min_value() as u128;
468 match (&lit.node, ety.map(|t| &t.sty)) {
469 (&LitKind::Int(I8_OVERFLOW, _), Some(&ty::TyInt(IntTy::I8))) |
470 (&LitKind::Int(I8_OVERFLOW, Signed(IntTy::I8)), _) => {
471 return Ok(Integral(I8(i8::min_value())))
473 (&LitKind::Int(I16_OVERFLOW, _), Some(&ty::TyInt(IntTy::I16))) |
474 (&LitKind::Int(I16_OVERFLOW, Signed(IntTy::I16)), _) => {
475 return Ok(Integral(I16(i16::min_value())))
477 (&LitKind::Int(I32_OVERFLOW, _), Some(&ty::TyInt(IntTy::I32))) |
478 (&LitKind::Int(I32_OVERFLOW, Signed(IntTy::I32)), _) => {
479 return Ok(Integral(I32(i32::min_value())))
481 (&LitKind::Int(I64_OVERFLOW, _), Some(&ty::TyInt(IntTy::I64))) |
482 (&LitKind::Int(I64_OVERFLOW, Signed(IntTy::I64)), _) => {
483 return Ok(Integral(I64(i64::min_value())))
485 (&LitKind::Int(I128_OVERFLOW, _), Some(&ty::TyInt(IntTy::I128))) |
486 (&LitKind::Int(I128_OVERFLOW, Signed(IntTy::I128)), _) => {
487 return Ok(Integral(I128(i128::min_value())))
489 (&LitKind::Int(n, _), Some(&ty::TyInt(IntTy::Is))) |
490 (&LitKind::Int(n, Signed(IntTy::Is)), _) => {
491 match tcx.sess.target.int_type {
492 IntTy::I16 => if n == I16_OVERFLOW {
493 return Ok(Integral(Isize(Is16(i16::min_value()))));
495 IntTy::I32 => if n == I32_OVERFLOW {
496 return Ok(Integral(Isize(Is32(i32::min_value()))));
498 IntTy::I64 => if n == I64_OVERFLOW {
499 return Ok(Integral(Isize(Is64(i64::min_value()))));
507 match cx.eval(inner, ty_hint)? {
508 Float(f) => Float(-f),
509 Integral(i) => Integral(math!(e, -i)),
510 const_val => signal!(e, NegateOn(const_val)),
513 hir::ExprUnary(hir::UnNot, ref inner) => {
514 match cx.eval(inner, ty_hint)? {
515 Integral(i) => Integral(math!(e, !i)),
517 const_val => signal!(e, NotOn(const_val)),
520 hir::ExprUnary(hir::UnDeref, _) => signal!(e, UnimplementedConstVal("deref operation")),
521 hir::ExprBinary(op, ref a, ref b) => {
522 let b_ty = match op.node {
523 hir::BiShl | hir::BiShr => ty_hint.erase_hint(),
526 // technically, if we don't have type hints, but integral eval
527 // gives us a type through a type-suffix, cast or const def type
528 // we need to re-eval the other value of the BinOp if it was
530 match (cx.eval(a, ty_hint)?,
532 (Float(a), Float(b)) => {
533 use std::cmp::Ordering::*;
535 hir::BiAdd => Float(math!(e, a + b)),
536 hir::BiSub => Float(math!(e, a - b)),
537 hir::BiMul => Float(math!(e, a * b)),
538 hir::BiDiv => Float(math!(e, a / b)),
539 hir::BiRem => Float(math!(e, a % b)),
540 hir::BiEq => Bool(math!(e, a.try_cmp(b)) == Equal),
541 hir::BiLt => Bool(math!(e, a.try_cmp(b)) == Less),
542 hir::BiLe => Bool(math!(e, a.try_cmp(b)) != Greater),
543 hir::BiNe => Bool(math!(e, a.try_cmp(b)) != Equal),
544 hir::BiGe => Bool(math!(e, a.try_cmp(b)) != Less),
545 hir::BiGt => Bool(math!(e, a.try_cmp(b)) == Greater),
546 _ => signal!(e, InvalidOpForFloats(op.node)),
549 (Integral(a), Integral(b)) => {
550 use std::cmp::Ordering::*;
552 hir::BiAdd => Integral(math!(e, a + b)),
553 hir::BiSub => Integral(math!(e, a - b)),
554 hir::BiMul => Integral(math!(e, a * b)),
555 hir::BiDiv => Integral(math!(e, a / b)),
556 hir::BiRem => Integral(math!(e, a % b)),
557 hir::BiBitAnd => Integral(math!(e, a & b)),
558 hir::BiBitOr => Integral(math!(e, a | b)),
559 hir::BiBitXor => Integral(math!(e, a ^ b)),
560 hir::BiShl => Integral(math!(e, a << b)),
561 hir::BiShr => Integral(math!(e, a >> b)),
562 hir::BiEq => Bool(math!(e, a.try_cmp(b)) == Equal),
563 hir::BiLt => Bool(math!(e, a.try_cmp(b)) == Less),
564 hir::BiLe => Bool(math!(e, a.try_cmp(b)) != Greater),
565 hir::BiNe => Bool(math!(e, a.try_cmp(b)) != Equal),
566 hir::BiGe => Bool(math!(e, a.try_cmp(b)) != Less),
567 hir::BiGt => Bool(math!(e, a.try_cmp(b)) == Greater),
568 _ => signal!(e, InvalidOpForInts(op.node)),
571 (Bool(a), Bool(b)) => {
573 hir::BiAnd => a && b,
575 hir::BiBitXor => a ^ b,
576 hir::BiBitAnd => a & b,
577 hir::BiBitOr => a | b,
584 _ => signal!(e, InvalidOpForBools(op.node)),
588 _ => signal!(e, MiscBinaryOp),
591 hir::ExprCast(ref base, ref target_ty) => {
592 let ety = tcx.ast_ty_to_prim_ty(&target_ty).or(ety)
594 tcx.sess.span_fatal(target_ty.span,
595 "target type not found for const cast")
598 let base_hint = if let ExprTypeChecked = ty_hint {
601 match cx.tables.and_then(|tables| tables.expr_ty_opt(&base)) {
602 Some(t) => UncheckedExprHint(t),
607 let val = match cx.eval(base, base_hint) {
609 Err(ConstEvalErr { kind: ErroneousReferencedConstant(
610 box ConstEvalErr { kind: TypeMismatch(_, val), .. }), .. }) |
611 Err(ConstEvalErr { kind: TypeMismatch(_, val), .. }) => {
612 // Something like `5i8 as usize` doesn't need a type hint for the base
613 // instead take the type hint from the inner value
614 let hint = match val.int_type() {
615 Some(IntType::UnsignedInt(ty)) => ty_hint.checked_or(tcx.mk_mach_uint(ty)),
616 Some(IntType::SignedInt(ty)) => ty_hint.checked_or(tcx.mk_mach_int(ty)),
617 // we had a type hint, so we can't have an unknown type
622 Err(e) => return Err(e),
624 match cast_const(tcx, val, ety) {
626 Err(kind) => return Err(ConstEvalErr { span: e.span, kind: kind }),
629 hir::ExprPath(ref qpath) => {
630 let def = cx.tables.map(|tables| tables.qpath_def(qpath, e.id)).unwrap_or_else(|| {
631 // There are no tables so we can only handle already-resolved HIR.
633 hir::QPath::Resolved(_, ref path) => path.def,
634 hir::QPath::TypeRelative(..) => Def::Err
639 Def::AssociatedConst(def_id) => {
640 let substs = if let ExprTypeChecked = ty_hint {
641 Some(cx.tables.and_then(|tables| tables.node_id_item_substs(e.id))
642 .unwrap_or_else(|| tcx.intern_substs(&[])))
646 if let Some((expr, tables, ty)) = lookup_const_by_id(tcx, def_id, substs) {
647 let item_hint = match ty {
648 Some(ty) => ty_hint.checked_or(ty),
651 let cx = ConstContext { tcx: tcx, tables: tables, fn_args: None };
652 match cx.eval(expr, item_hint) {
655 debug!("bad reference: {:?}, {:?}", err.description(), err.span);
656 signal!(e, ErroneousReferencedConstant(box err))
660 signal!(e, NonConstPath);
663 Def::VariantCtor(variant_def, ..) => {
664 if let Some((expr, tables)) = lookup_variant_by_id(tcx, variant_def) {
665 let cx = ConstContext { tcx: tcx, tables: tables, fn_args: None };
666 match cx.eval(expr, ty_hint) {
669 debug!("bad reference: {:?}, {:?}", err.description(), err.span);
670 signal!(e, ErroneousReferencedConstant(box err))
674 signal!(e, UnimplementedConstVal("enum variants"));
677 Def::StructCtor(..) => {
678 ConstVal::Struct(Default::default())
680 Def::Local(def_id) => {
681 debug!("Def::Local({:?}): {:?}", def_id, cx.fn_args);
682 if let Some(val) = cx.fn_args.as_ref().and_then(|args| args.get(&def_id)) {
685 signal!(e, NonConstPath);
688 Def::Method(id) | Def::Fn(id) => Function(id),
689 Def::Err => signal!(e, UnresolvedPath),
690 _ => signal!(e, NonConstPath),
693 hir::ExprCall(ref callee, ref args) => {
694 let sub_ty_hint = ty_hint.erase_hint();
695 let callee_val = cx.eval(callee, sub_ty_hint)?;
696 let did = match callee_val {
697 Function(did) => did,
698 Struct(_) => signal!(e, UnimplementedConstVal("tuple struct constructors")),
699 callee => signal!(e, CallOn(callee)),
701 let (body, tables) = match lookup_const_fn_by_id(tcx, did) {
703 None => signal!(e, NonConstPath),
706 let arg_defs = body.arguments.iter().map(|arg| match arg.pat.node {
707 hir::PatKind::Binding(_, def_id, _, _) => Some(def_id),
709 }).collect::<Vec<_>>();
710 assert_eq!(arg_defs.len(), args.len());
712 let mut call_args = DefIdMap();
713 for (arg, arg_expr) in arg_defs.into_iter().zip(args.iter()) {
714 let arg_hint = ty_hint.erase_hint();
715 let arg_val = cx.eval(arg_expr, arg_hint)?;
716 debug!("const call arg: {:?}", arg);
717 if let Some(def_id) = arg {
718 assert!(call_args.insert(def_id, arg_val).is_none());
721 debug!("const call({:?})", call_args);
722 let callee_cx = ConstContext {
725 fn_args: Some(call_args)
727 callee_cx.eval(&body.value, ty_hint)?
729 hir::ExprLit(ref lit) => match lit_to_const(&lit.node, tcx, ety) {
731 Err(err) => signal!(e, err),
733 hir::ExprBlock(ref block) => {
735 Some(ref expr) => cx.eval(expr, ty_hint)?,
736 None => signal!(e, UnimplementedConstVal("empty block")),
739 hir::ExprType(ref e, _) => cx.eval(e, ty_hint)?,
740 hir::ExprTup(ref fields) => {
741 let field_hint = ty_hint.erase_hint();
742 Tuple(fields.iter().map(|e| cx.eval(e, field_hint)).collect::<Result<_, _>>()?)
744 hir::ExprStruct(_, ref fields, _) => {
745 let field_hint = ty_hint.erase_hint();
746 Struct(fields.iter().map(|f| {
747 cx.eval(&f.expr, field_hint).map(|v| (f.name.node, v))
748 }).collect::<Result<_, _>>()?)
750 hir::ExprIndex(ref arr, ref idx) => {
751 if !tcx.sess.features.borrow().const_indexing {
752 signal!(e, IndexOpFeatureGated);
754 let arr_hint = ty_hint.erase_hint();
755 let arr = cx.eval(arr, arr_hint)?;
756 let idx_hint = ty_hint.checked_or(tcx.types.usize);
757 let idx = match cx.eval(idx, idx_hint)? {
758 Integral(Usize(i)) => i.as_u64(tcx.sess.target.uint_type),
759 Integral(_) => bug!(),
760 _ => signal!(idx, IndexNotInt),
762 assert_eq!(idx as usize as u64, idx);
765 if let Some(elem) = v.get(idx as usize) {
768 let n = v.len() as u64;
769 assert_eq!(n as usize as u64, n);
770 signal!(e, IndexOutOfBounds { len: n, index: idx })
774 Repeat(.., n) if idx >= n => {
775 signal!(e, IndexOutOfBounds { len: n, index: idx })
777 Repeat(ref elem, _) => (**elem).clone(),
779 ByteStr(ref data) if idx >= data.len() as u64 => {
780 signal!(e, IndexOutOfBounds { len: data.len() as u64, index: idx })
783 Integral(U8(data[idx as usize]))
786 _ => signal!(e, IndexedNonVec),
789 hir::ExprArray(ref v) => {
790 let elem_hint = ty_hint.erase_hint();
791 Array(v.iter().map(|e| cx.eval(e, elem_hint)).collect::<Result<_, _>>()?)
793 hir::ExprRepeat(ref elem, count) => {
794 let elem_hint = ty_hint.erase_hint();
795 let len_hint = ty_hint.checked_or(tcx.types.usize);
796 let n = if let Some(ty) = ety {
797 // For cross-crate constants, we have the type already,
798 // but not the body for `count`, so use the type.
800 ty::TyArray(_, n) => n as u64,
804 let n = &tcx.hir.body(count).value;
805 match ConstContext::new(tcx, count).eval(n, len_hint)? {
806 Integral(Usize(i)) => i.as_u64(tcx.sess.target.uint_type),
807 Integral(_) => signal!(e, RepeatCountNotNatural),
808 _ => signal!(e, RepeatCountNotInt),
811 Repeat(Box::new(cx.eval(elem, elem_hint)?), n)
813 hir::ExprTupField(ref base, index) => {
814 let base_hint = ty_hint.erase_hint();
815 let c = cx.eval(base, base_hint)?;
816 if let Tuple(ref fields) = c {
817 if let Some(elem) = fields.get(index.node) {
820 signal!(e, TupleIndexOutOfBounds);
823 signal!(base, ExpectedConstTuple);
826 hir::ExprField(ref base, field_name) => {
827 let base_hint = ty_hint.erase_hint();
828 let c = cx.eval(base, base_hint)?;
829 if let Struct(ref fields) = c {
830 if let Some(f) = fields.get(&field_name.node) {
833 signal!(e, MissingStructField);
836 signal!(base, ExpectedConstStruct);
839 hir::ExprAddrOf(..) => signal!(e, UnimplementedConstVal("address operator")),
840 _ => signal!(e, MiscCatchAll)
843 match (ety.map(|t| &t.sty), result) {
844 (Some(ref ty_hint), Integral(i)) => match infer(i, tcx, ty_hint) {
845 Ok(inferred) => Ok(Integral(inferred)),
846 Err(err) => signal!(e, err),
848 (_, result) => Ok(result),
852 fn infer<'a, 'tcx>(i: ConstInt,
853 tcx: TyCtxt<'a, 'tcx, 'tcx>,
854 ty_hint: &ty::TypeVariants<'tcx>)
855 -> Result<ConstInt, ErrKind> {
859 (&ty::TyInt(IntTy::I8), result @ I8(_)) => Ok(result),
860 (&ty::TyInt(IntTy::I16), result @ I16(_)) => Ok(result),
861 (&ty::TyInt(IntTy::I32), result @ I32(_)) => Ok(result),
862 (&ty::TyInt(IntTy::I64), result @ I64(_)) => Ok(result),
863 (&ty::TyInt(IntTy::I128), result @ I128(_)) => Ok(result),
864 (&ty::TyInt(IntTy::Is), result @ Isize(_)) => Ok(result),
866 (&ty::TyUint(UintTy::U8), result @ U8(_)) => Ok(result),
867 (&ty::TyUint(UintTy::U16), result @ U16(_)) => Ok(result),
868 (&ty::TyUint(UintTy::U32), result @ U32(_)) => Ok(result),
869 (&ty::TyUint(UintTy::U64), result @ U64(_)) => Ok(result),
870 (&ty::TyUint(UintTy::U128), result @ U128(_)) => Ok(result),
871 (&ty::TyUint(UintTy::Us), result @ Usize(_)) => Ok(result),
873 (&ty::TyInt(IntTy::I8), Infer(i)) => Ok(I8(i as i128 as i8)),
874 (&ty::TyInt(IntTy::I16), Infer(i)) => Ok(I16(i as i128 as i16)),
875 (&ty::TyInt(IntTy::I32), Infer(i)) => Ok(I32(i as i128 as i32)),
876 (&ty::TyInt(IntTy::I64), Infer(i)) => Ok(I64(i as i128 as i64)),
877 (&ty::TyInt(IntTy::I128), Infer(i)) => Ok(I128(i as i128)),
878 (&ty::TyInt(IntTy::Is), Infer(i)) => {
879 Ok(Isize(ConstIsize::new_truncating(i as i128, tcx.sess.target.int_type)))
882 (&ty::TyInt(IntTy::I8), InferSigned(i)) => Ok(I8(i as i8)),
883 (&ty::TyInt(IntTy::I16), InferSigned(i)) => Ok(I16(i as i16)),
884 (&ty::TyInt(IntTy::I32), InferSigned(i)) => Ok(I32(i as i32)),
885 (&ty::TyInt(IntTy::I64), InferSigned(i)) => Ok(I64(i as i64)),
886 (&ty::TyInt(IntTy::I128), InferSigned(i)) => Ok(I128(i)),
887 (&ty::TyInt(IntTy::Is), InferSigned(i)) => {
888 Ok(Isize(ConstIsize::new_truncating(i, tcx.sess.target.int_type)))
891 (&ty::TyUint(UintTy::U8), Infer(i)) => Ok(U8(i as u8)),
892 (&ty::TyUint(UintTy::U16), Infer(i)) => Ok(U16(i as u16)),
893 (&ty::TyUint(UintTy::U32), Infer(i)) => Ok(U32(i as u32)),
894 (&ty::TyUint(UintTy::U64), Infer(i)) => Ok(U64(i as u64)),
895 (&ty::TyUint(UintTy::U128), Infer(i)) => Ok(U128(i)),
896 (&ty::TyUint(UintTy::Us), Infer(i)) => {
897 Ok(Usize(ConstUsize::new_truncating(i, tcx.sess.target.uint_type)))
899 (&ty::TyUint(_), InferSigned(_)) => Err(IntermediateUnsignedNegative),
901 (&ty::TyInt(ity), i) => Err(TypeMismatch(ity.to_string(), i)),
902 (&ty::TyUint(ity), i) => Err(TypeMismatch(ity.to_string(), i)),
904 (&ty::TyAdt(adt, _), i) if adt.is_enum() => {
905 let hints = tcx.lookup_repr_hints(adt.did);
906 let int_ty = tcx.enum_repr_type(hints.iter().next());
907 infer(i, tcx, &int_ty.to_ty(tcx).sty)
909 (_, i) => Err(BadType(ConstVal::Integral(i))),
913 fn resolve_trait_associated_const<'a, 'tcx: 'a>(
914 tcx: TyCtxt<'a, 'tcx, 'tcx>,
915 trait_item_id: DefId,
916 default_value: Option<(&'tcx Expr, Option<&'a ty::TypeckTables<'tcx>>, Option<ty::Ty<'tcx>>)>,
918 rcvr_substs: &'tcx Substs<'tcx>
919 ) -> Option<(&'tcx Expr, Option<&'a ty::TypeckTables<'tcx>>, Option<ty::Ty<'tcx>>)>
921 let trait_ref = ty::Binder(ty::TraitRef::new(trait_id, rcvr_substs));
922 debug!("resolve_trait_associated_const: trait_ref={:?}",
925 tcx.populate_implementations_for_trait_if_necessary(trait_id);
926 tcx.infer_ctxt((), Reveal::NotSpecializable).enter(|infcx| {
927 let mut selcx = traits::SelectionContext::new(&infcx);
928 let obligation = traits::Obligation::new(traits::ObligationCause::dummy(),
929 trait_ref.to_poly_trait_predicate());
930 let selection = match selcx.select(&obligation) {
931 Ok(Some(vtable)) => vtable,
932 // Still ambiguous, so give up and let the caller decide whether this
933 // expression is really needed yet. Some associated constant values
934 // can't be evaluated until monomorphization is done in trans.
943 // NOTE: this code does not currently account for specialization, but when
944 // it does so, it should hook into the Reveal to determine when the
945 // constant should resolve; this will also require plumbing through to this
946 // function whether we are in "trans mode" to pick the right Reveal
947 // when constructing the inference context above.
949 traits::VtableImpl(ref impl_data) => {
950 let name = tcx.associated_item(trait_item_id).name;
951 let ac = tcx.associated_items(impl_data.impl_def_id)
952 .find(|item| item.kind == ty::AssociatedKind::Const && item.name == name);
954 Some(ic) => lookup_const_by_id(tcx, ic.def_id, None),
955 None => default_value,
959 bug!("resolve_trait_associated_const: unexpected vtable type")
965 fn cast_const_int<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, val: ConstInt, ty: ty::Ty) -> CastResult {
966 let v = val.to_u128_unchecked();
968 ty::TyBool if v == 0 => Ok(Bool(false)),
969 ty::TyBool if v == 1 => Ok(Bool(true)),
970 ty::TyInt(ast::IntTy::I8) => Ok(Integral(I8(v as i128 as i8))),
971 ty::TyInt(ast::IntTy::I16) => Ok(Integral(I16(v as i128 as i16))),
972 ty::TyInt(ast::IntTy::I32) => Ok(Integral(I32(v as i128 as i32))),
973 ty::TyInt(ast::IntTy::I64) => Ok(Integral(I64(v as i128 as i64))),
974 ty::TyInt(ast::IntTy::I128) => Ok(Integral(I128(v as i128))),
975 ty::TyInt(ast::IntTy::Is) => {
976 Ok(Integral(Isize(ConstIsize::new_truncating(v as i128, tcx.sess.target.int_type))))
978 ty::TyUint(ast::UintTy::U8) => Ok(Integral(U8(v as u8))),
979 ty::TyUint(ast::UintTy::U16) => Ok(Integral(U16(v as u16))),
980 ty::TyUint(ast::UintTy::U32) => Ok(Integral(U32(v as u32))),
981 ty::TyUint(ast::UintTy::U64) => Ok(Integral(U64(v as u64))),
982 ty::TyUint(ast::UintTy::U128) => Ok(Integral(U128(v as u128))),
983 ty::TyUint(ast::UintTy::Us) => {
984 Ok(Integral(Usize(ConstUsize::new_truncating(v, tcx.sess.target.uint_type))))
986 ty::TyFloat(ast::FloatTy::F64) => match val.erase_type() {
987 Infer(u) => Ok(Float(F64(u as f64))),
988 InferSigned(i) => Ok(Float(F64(i as f64))),
989 _ => bug!("ConstInt::erase_type returned something other than Infer/InferSigned"),
991 ty::TyFloat(ast::FloatTy::F32) => match val.erase_type() {
992 Infer(u) => Ok(Float(F32(u as f32))),
993 InferSigned(i) => Ok(Float(F32(i as f32))),
994 _ => bug!("ConstInt::erase_type returned something other than Infer/InferSigned"),
996 ty::TyRawPtr(_) => Err(ErrKind::UnimplementedConstVal("casting an address to a raw ptr")),
997 ty::TyChar => match infer(val, tcx, &ty::TyUint(ast::UintTy::U8)) {
998 Ok(U8(u)) => Ok(Char(u as char)),
999 // can only occur before typeck, typeck blocks `T as char` for `T` != `u8`
1000 _ => Err(CharCast(val)),
1002 _ => Err(CannotCast),
1006 fn cast_const_float<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1008 ty: ty::Ty) -> CastResult {
1010 ty::TyInt(_) | ty::TyUint(_) => {
1012 F32(f) if f >= 0.0 => Infer(f as u128),
1013 FInfer { f64: f, .. } |
1014 F64(f) if f >= 0.0 => Infer(f as u128),
1016 F32(f) => InferSigned(f as i128),
1017 FInfer { f64: f, .. } |
1018 F64(f) => InferSigned(f as i128)
1021 if let (InferSigned(_), &ty::TyUint(_)) = (i, &ty.sty) {
1022 return Err(CannotCast);
1025 cast_const_int(tcx, i, ty)
1027 ty::TyFloat(ast::FloatTy::F64) => Ok(Float(F64(match val {
1029 FInfer { f64: f, .. } | F64(f) => f
1031 ty::TyFloat(ast::FloatTy::F32) => Ok(Float(F32(match val {
1033 FInfer { f32: f, .. } | F32(f) => f
1035 _ => Err(CannotCast),
1039 fn cast_const<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, val: ConstVal, ty: ty::Ty) -> CastResult {
1041 Integral(i) => cast_const_int(tcx, i, ty),
1042 Bool(b) => cast_const_int(tcx, Infer(b as u128), ty),
1043 Float(f) => cast_const_float(tcx, f, ty),
1044 Char(c) => cast_const_int(tcx, Infer(c as u128), ty),
1045 Function(_) => Err(UnimplementedConstVal("casting fn pointers")),
1046 ByteStr(b) => match ty.sty {
1047 ty::TyRawPtr(_) => {
1048 Err(ErrKind::UnimplementedConstVal("casting a bytestr to a raw ptr"))
1050 ty::TyRef(_, ty::TypeAndMut { ref ty, mutbl: hir::MutImmutable }) => match ty.sty {
1051 ty::TyArray(ty, n) if ty == tcx.types.u8 && n == b.len() => Ok(ByteStr(b)),
1053 Err(ErrKind::UnimplementedConstVal("casting a bytestr to slice"))
1055 _ => Err(CannotCast),
1057 _ => Err(CannotCast),
1059 Str(s) => match ty.sty {
1060 ty::TyRawPtr(_) => Err(ErrKind::UnimplementedConstVal("casting a str to a raw ptr")),
1061 ty::TyRef(_, ty::TypeAndMut { ref ty, mutbl: hir::MutImmutable }) => match ty.sty {
1062 ty::TyStr => Ok(Str(s)),
1063 _ => Err(CannotCast),
1065 _ => Err(CannotCast),
1067 _ => Err(CannotCast),
1071 fn lit_to_const<'a, 'tcx>(lit: &ast::LitKind,
1072 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1073 ty_hint: Option<Ty<'tcx>>)
1074 -> Result<ConstVal, ErrKind> {
1076 use syntax::ast::LitIntType::*;
1078 LitKind::Str(ref s, _) => Ok(Str(s.as_str())),
1079 LitKind::ByteStr(ref data) => Ok(ByteStr(data.clone())),
1080 LitKind::Byte(n) => Ok(Integral(U8(n))),
1081 LitKind::Int(n, Signed(ity)) => {
1082 infer(InferSigned(n as i128), tcx, &ty::TyInt(ity)).map(Integral)
1085 // FIXME: this should become u128.
1086 LitKind::Int(n, Unsuffixed) => {
1087 match ty_hint.map(|t| &t.sty) {
1088 Some(&ty::TyInt(ity)) => {
1089 infer(InferSigned(n as i128), tcx, &ty::TyInt(ity)).map(Integral)
1091 Some(&ty::TyUint(uty)) => {
1092 infer(Infer(n as u128), tcx, &ty::TyUint(uty)).map(Integral)
1094 None => Ok(Integral(Infer(n as u128))),
1095 Some(&ty::TyAdt(adt, _)) => {
1096 let hints = tcx.lookup_repr_hints(adt.did);
1097 let int_ty = tcx.enum_repr_type(hints.iter().next());
1098 infer(Infer(n as u128), tcx, &int_ty.to_ty(tcx).sty).map(Integral)
1100 Some(ty_hint) => bug!("bad ty_hint: {:?}, {:?}", ty_hint, lit),
1103 LitKind::Int(n, Unsigned(ity)) => {
1104 infer(Infer(n as u128), tcx, &ty::TyUint(ity)).map(Integral)
1107 LitKind::Float(n, fty) => {
1108 parse_float(&n.as_str(), Some(fty)).map(Float)
1110 LitKind::FloatUnsuffixed(n) => {
1111 let fty_hint = match ty_hint.map(|t| &t.sty) {
1112 Some(&ty::TyFloat(fty)) => Some(fty),
1115 parse_float(&n.as_str(), fty_hint).map(Float)
1117 LitKind::Bool(b) => Ok(Bool(b)),
1118 LitKind::Char(c) => Ok(Char(c)),
1122 fn parse_float(num: &str, fty_hint: Option<ast::FloatTy>)
1123 -> Result<ConstFloat, ErrKind> {
1124 let val = match fty_hint {
1125 Some(ast::FloatTy::F32) => num.parse::<f32>().map(F32),
1126 Some(ast::FloatTy::F64) => num.parse::<f64>().map(F64),
1128 num.parse::<f32>().and_then(|f32| {
1129 num.parse::<f64>().map(|f64| {
1130 FInfer { f32: f32, f64: f64 }
1136 // FIXME(#31407) this is only necessary because float parsing is buggy
1137 UnimplementedConstVal("could not evaluate float literal (see issue #31407)")
1141 pub fn compare_const_vals(tcx: TyCtxt, span: Span, a: &ConstVal, b: &ConstVal)
1142 -> Result<Ordering, ErrorReported>
1144 let result = match (a, b) {
1145 (&Integral(a), &Integral(b)) => a.try_cmp(b).ok(),
1146 (&Float(a), &Float(b)) => a.try_cmp(b).ok(),
1147 (&Str(ref a), &Str(ref b)) => Some(a.cmp(b)),
1148 (&Bool(a), &Bool(b)) => Some(a.cmp(&b)),
1149 (&ByteStr(ref a), &ByteStr(ref b)) => Some(a.cmp(b)),
1150 (&Char(a), &Char(ref b)) => Some(a.cmp(b)),
1155 Some(result) => Ok(result),
1157 // FIXME: can this ever be reached?
1158 span_err!(tcx.sess, span, E0298,
1159 "type mismatch comparing {} and {}",
1167 impl<'a, 'tcx> ConstContext<'a, 'tcx> {
1168 pub fn compare_lit_exprs(&self,
1171 b: &Expr) -> Result<Ordering, ErrorReported> {
1173 let a = match self.eval(a, ExprTypeChecked) {
1176 report_const_eval_err(tcx, &e, a.span, "expression").emit();
1177 return Err(ErrorReported);
1180 let b = match self.eval(b, ExprTypeChecked) {
1183 report_const_eval_err(tcx, &e, b.span, "expression").emit();
1184 return Err(ErrorReported);
1187 compare_const_vals(tcx, span, &a, &b)
1192 /// Returns the value of the length-valued expression
1193 pub fn eval_length<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1196 -> Result<usize, ErrorReported>
1198 let hint = UncheckedExprHint(tcx.types.usize);
1199 let count_expr = &tcx.hir.body(count).value;
1200 match ConstContext::new(tcx, count).eval(count_expr, hint) {
1201 Ok(Integral(Usize(count))) => {
1202 let val = count.as_u64(tcx.sess.target.uint_type);
1203 assert_eq!(val as usize as u64, val);
1207 struct_span_err!(tcx.sess, count_expr.span, E0306,
1208 "expected `usize` for {}, found {}",
1210 const_val.description())
1211 .span_label(count_expr.span, &format!("expected `usize`"))
1217 let mut diag = report_const_eval_err(
1218 tcx, &err, count_expr.span, reason);
1220 if let hir::ExprPath(hir::QPath::Resolved(None, ref path)) = count_expr.node {
1221 if let Def::Local(..) = path.def {
1222 diag.note(&format!("`{}` is a variable",
1223 tcx.hir.node_to_pretty_string(count_expr.id)));