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 //#![allow(non_camel_case_types)]
13 use rustc::middle::const_val::ConstVal::*;
14 use rustc::middle::const_val::ConstVal;
16 use self::EvalHint::*;
18 use rustc::hir::map as ast_map;
19 use rustc::hir::map::blocks::FnLikeNode;
21 use rustc::hir::def::Def;
22 use rustc::hir::def_id::DefId;
23 use rustc::ty::{self, Ty, TyCtxt};
24 use rustc::ty::util::IntTypeExt;
25 use rustc::ty::subst::Substs;
26 use rustc::traits::Reveal;
27 use rustc::util::common::ErrorReported;
28 use rustc::util::nodemap::DefIdMap;
30 use graphviz::IntoCow;
32 use rustc::hir::{self, Expr};
33 use syntax::attr::IntType;
37 use std::cmp::Ordering;
39 use rustc_const_math::*;
40 use rustc_errors::DiagnosticBuilder;
42 use rustc_i128::{i128, u128};
45 ($e:expr, $op:expr) => {
48 Err(e) => signal!($e, Math(e)),
53 fn lookup_variant_by_id<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
55 -> Option<(&'tcx Expr, Option<&'a ty::Tables<'tcx>>)> {
56 if let Some(variant_node_id) = tcx.map.as_local_node_id(variant_def) {
57 let enum_node_id = tcx.map.get_parent(variant_node_id);
58 if let Some(ast_map::NodeItem(it)) = tcx.map.find(enum_node_id) {
59 if let hir::ItemEnum(ref edef, _) = it.node {
60 for variant in &edef.variants {
61 if variant.node.data.id() == variant_node_id {
62 return variant.node.disr_expr.map(|e| {
63 let def_id = tcx.map.body_owner_def_id(e);
64 (&tcx.map.body(e).value,
65 tcx.tables.borrow().get(&def_id).cloned())
75 /// * `def_id` is the id of the constant.
76 /// * `substs` is the monomorphized substitutions for the expression.
78 /// `substs` is optional and is used for associated constants.
79 /// This generally happens in late/trans const evaluation.
80 pub fn lookup_const_by_id<'a, 'tcx: 'a>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
82 substs: Option<&'tcx Substs<'tcx>>)
83 -> Option<(&'tcx Expr,
84 Option<&'a ty::Tables<'tcx>>,
85 Option<ty::Ty<'tcx>>)> {
86 if let Some(node_id) = tcx.map.as_local_node_id(def_id) {
87 match tcx.map.find(node_id) {
89 Some(ast_map::NodeItem(&hir::Item {
90 node: hir::ItemConst(ref ty, body), ..
92 Some(ast_map::NodeImplItem(&hir::ImplItem {
93 node: hir::ImplItemKind::Const(ref ty, body), ..
95 Some((&tcx.map.body(body).value,
96 tcx.tables.borrow().get(&def_id).cloned(),
97 tcx.ast_ty_to_prim_ty(ty)))
99 Some(ast_map::NodeTraitItem(ti)) => match ti.node {
100 hir::TraitItemKind::Const(ref ty, default) => {
101 if let Some(substs) = substs {
102 // If we have a trait item and the substitutions for it,
103 // `resolve_trait_associated_const` will select an impl
105 let trait_id = tcx.map.get_parent(node_id);
106 let trait_id = tcx.map.local_def_id(trait_id);
107 let default_value = default.map(|body| {
108 (&tcx.map.body(body).value,
109 tcx.tables.borrow().get(&def_id).cloned(),
110 tcx.ast_ty_to_prim_ty(ty))
112 resolve_trait_associated_const(tcx, def_id, default_value, trait_id, substs)
114 // Technically, without knowing anything about the
115 // expression that generates the obligation, we could
116 // still return the default if there is one. However,
117 // it's safer to return `None` than to return some value
118 // that may differ from what you would get from
119 // correctly selecting an impl.
128 let expr_tables_ty = tcx.sess.cstore.maybe_get_item_body(tcx, def_id).map(|body| {
129 (&body.value, Some(tcx.item_tables(def_id)),
130 Some(tcx.sess.cstore.item_type(tcx, def_id)))
132 match tcx.sess.cstore.describe_def(def_id) {
133 Some(Def::AssociatedConst(_)) => {
134 let trait_id = tcx.sess.cstore.trait_of_item(def_id);
135 // As mentioned in the comments above for in-crate
136 // constants, we only try to find the expression for a
137 // trait-associated const if the caller gives us the
138 // substitutions for the reference to it.
139 if let Some(trait_id) = trait_id {
140 if let Some(substs) = substs {
141 resolve_trait_associated_const(tcx, def_id, expr_tables_ty,
150 Some(Def::Const(..)) => expr_tables_ty,
156 fn lookup_const_fn_by_id<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId)
157 -> Option<(&'tcx hir::Body, Option<&'a ty::Tables<'tcx>>)>
159 if let Some(node_id) = tcx.map.as_local_node_id(def_id) {
160 FnLikeNode::from_node(tcx.map.get(node_id)).and_then(|fn_like| {
161 if fn_like.constness() == hir::Constness::Const {
162 Some((tcx.map.body(fn_like.body()),
163 tcx.tables.borrow().get(&def_id).cloned()))
169 if tcx.sess.cstore.is_const_fn(def_id) {
170 tcx.sess.cstore.maybe_get_item_body(tcx, def_id).map(|body| {
171 (body, Some(tcx.item_tables(def_id)))
179 pub fn report_const_eval_err<'a, 'tcx>(
180 tcx: TyCtxt<'a, 'tcx, 'tcx>,
184 -> DiagnosticBuilder<'tcx>
187 while let &ConstEvalErr { kind: ErroneousReferencedConstant(box ref i_err), .. } = err {
191 let mut diag = struct_span_err!(tcx.sess, err.span, E0080, "constant evaluation error");
192 note_const_eval_err(tcx, err, primary_span, primary_kind, &mut diag);
196 pub fn fatal_const_eval_err<'a, 'tcx>(
197 tcx: TyCtxt<'a, 'tcx, 'tcx>,
203 report_const_eval_err(tcx, err, primary_span, primary_kind).emit();
204 tcx.sess.abort_if_errors();
208 pub fn note_const_eval_err<'a, 'tcx>(
209 _tcx: TyCtxt<'a, 'tcx, 'tcx>,
213 diag: &mut DiagnosticBuilder)
215 match err.description() {
216 ConstEvalErrDescription::Simple(message) => {
217 diag.span_label(err.span, &message);
221 if !primary_span.contains(err.span) {
222 diag.span_note(primary_span,
223 &format!("for {} here", primary_kind));
227 pub struct ConstContext<'a, 'tcx: 'a> {
228 tcx: TyCtxt<'a, 'tcx, 'tcx>,
229 tables: Option<&'a ty::Tables<'tcx>>,
230 fn_args: Option<DefIdMap<ConstVal>>
233 impl<'a, 'tcx> ConstContext<'a, 'tcx> {
234 pub fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>, body: hir::BodyId) -> Self {
235 let def_id = tcx.map.body_owner_def_id(body);
238 tables: tcx.tables.borrow().get(&def_id).cloned(),
243 pub fn with_tables(tcx: TyCtxt<'a, 'tcx, 'tcx>, tables: &'a ty::Tables<'tcx>) -> Self {
246 tables: Some(tables),
251 /// Evaluate a constant expression in a context where the expression isn't
252 /// guaranteed to be evaluatable. `ty_hint` is usually ExprTypeChecked,
253 /// but a few places need to evaluate constants during type-checking, like
254 /// computing the length of an array. (See also the FIXME above EvalHint.)
255 pub fn eval(&self, e: &Expr, ty_hint: EvalHint<'tcx>) -> EvalResult {
256 eval_const_expr_partial(self, e, ty_hint)
260 #[derive(Clone, Debug)]
261 pub struct ConstEvalErr {
266 #[derive(Clone, Debug)]
269 CannotCastTo(&'static str),
270 InvalidOpForInts(hir::BinOp_),
271 InvalidOpForBools(hir::BinOp_),
272 InvalidOpForFloats(hir::BinOp_),
273 InvalidOpForIntUint(hir::BinOp_),
274 InvalidOpForUintInt(hir::BinOp_),
281 UnimplementedConstVal(&'static str),
285 TupleIndexOutOfBounds,
289 IndexOutOfBounds { len: u64, index: u64 },
290 RepeatCountNotNatural,
299 IntermediateUnsignedNegative,
301 TypeMismatch(String, ConstInt),
304 ErroneousReferencedConstant(Box<ConstEvalErr>),
308 impl From<ConstMathErr> for ErrKind {
309 fn from(err: ConstMathErr) -> ErrKind {
314 #[derive(Clone, Debug)]
315 pub enum ConstEvalErrDescription<'a> {
316 Simple(Cow<'a, str>),
319 impl<'a> ConstEvalErrDescription<'a> {
320 /// Return a one-line description of the error, for lints and such
321 pub fn into_oneline(self) -> Cow<'a, str> {
323 ConstEvalErrDescription::Simple(simple) => simple,
329 pub fn description(&self) -> ConstEvalErrDescription {
330 use self::ErrKind::*;
331 use self::ConstEvalErrDescription::*;
333 macro_rules! simple {
334 ($msg:expr) => ({ Simple($msg.into_cow()) });
335 ($fmt:expr, $($arg:tt)+) => ({
336 Simple(format!($fmt, $($arg)+).into_cow())
341 CannotCast => simple!("can't cast this type"),
342 CannotCastTo(s) => simple!("can't cast this type to {}", s),
343 InvalidOpForInts(_) => simple!("can't do this op on integrals"),
344 InvalidOpForBools(_) => simple!("can't do this op on bools"),
345 InvalidOpForFloats(_) => simple!("can't do this op on floats"),
346 InvalidOpForIntUint(..) => simple!("can't do this op on an isize and usize"),
347 InvalidOpForUintInt(..) => simple!("can't do this op on a usize and isize"),
348 NegateOn(ref const_val) => simple!("negate on {}", const_val.description()),
349 NotOn(ref const_val) => simple!("not on {}", const_val.description()),
350 CallOn(ref const_val) => simple!("call on {}", const_val.description()),
352 MissingStructField => simple!("nonexistent struct field"),
353 NonConstPath => simple!("non-constant path in constant expression"),
354 UnimplementedConstVal(what) =>
355 simple!("unimplemented constant expression: {}", what),
356 UnresolvedPath => simple!("unresolved path in constant expression"),
357 ExpectedConstTuple => simple!("expected constant tuple"),
358 ExpectedConstStruct => simple!("expected constant struct"),
359 TupleIndexOutOfBounds => simple!("tuple index out of bounds"),
360 IndexedNonVec => simple!("indexing is only supported for arrays"),
361 IndexNegative => simple!("indices must be non-negative integers"),
362 IndexNotInt => simple!("indices must be integers"),
363 IndexOutOfBounds { len, index } => {
364 simple!("index out of bounds: the len is {} but the index is {}",
367 RepeatCountNotNatural => simple!("repeat count must be a natural number"),
368 RepeatCountNotInt => simple!("repeat count must be integers"),
370 MiscBinaryOp => simple!("bad operands for binary"),
371 MiscCatchAll => simple!("unsupported constant expr"),
372 IndexOpFeatureGated => simple!("the index operation on const values is unstable"),
373 Math(ref err) => Simple(err.description().into_cow()),
375 IntermediateUnsignedNegative => simple!(
376 "during the computation of an unsigned a negative \
377 number was encountered. This is most likely a bug in\
378 the constant evaluator"),
380 TypeMismatch(ref expected, ref got) => {
381 simple!("expected {}, found {}", expected, got.description())
383 BadType(ref i) => simple!("value of wrong type: {:?}", i),
384 ErroneousReferencedConstant(_) => simple!("could not evaluate referenced constant"),
385 CharCast(ref got) => {
386 simple!("only `u8` can be cast as `char`, not `{}`", got.description())
392 pub type EvalResult = Result<ConstVal, ConstEvalErr>;
393 pub type CastResult = Result<ConstVal, ErrKind>;
395 // FIXME: Long-term, this enum should go away: trying to evaluate
396 // an expression which hasn't been type-checked is a recipe for
397 // disaster. That said, it's not clear how to fix ast_ty_to_ty
398 // to avoid the ordering issue.
400 /// Hint to determine how to evaluate constant expressions which
401 /// might not be type-checked.
402 #[derive(Copy, Clone, Debug)]
403 pub enum EvalHint<'tcx> {
404 /// We have a type-checked expression.
406 /// We have an expression which hasn't been type-checked, but we have
407 /// an idea of what the type will be because of the context. For example,
408 /// the length of an array is always `usize`. (This is referred to as
409 /// a hint because it isn't guaranteed to be consistent with what
410 /// type-checking would compute.)
411 UncheckedExprHint(Ty<'tcx>),
412 /// We have an expression which has not yet been type-checked, and
413 /// and we have no clue what the type will be.
417 impl<'tcx> EvalHint<'tcx> {
418 fn erase_hint(&self) -> EvalHint<'tcx> {
420 ExprTypeChecked => ExprTypeChecked,
421 UncheckedExprHint(_) | UncheckedExprNoHint => UncheckedExprNoHint,
424 fn checked_or(&self, ty: Ty<'tcx>) -> EvalHint<'tcx> {
426 ExprTypeChecked => ExprTypeChecked,
427 _ => UncheckedExprHint(ty),
432 macro_rules! signal {
433 ($e:expr, $exn:expr) => {
434 return Err(ConstEvalErr { span: $e.span, kind: $exn })
438 fn eval_const_expr_partial<'a, 'tcx>(cx: &ConstContext<'a, 'tcx>,
440 ty_hint: EvalHint<'tcx>) -> EvalResult {
442 // Try to compute the type of the expression based on the EvalHint.
443 // (See also the definition of EvalHint, and the FIXME above EvalHint.)
444 let ety = match ty_hint {
446 // After type-checking, expr_ty is guaranteed to succeed.
447 cx.tables.map(|tables| tables.expr_ty(e))
449 UncheckedExprHint(ty) => {
450 // Use the type hint; it's not guaranteed to be right, but it's
451 // usually good enough.
454 UncheckedExprNoHint => {
455 // This expression might not be type-checked, and we have no hint.
456 // Try to query the context for a type anyway; we might get lucky
457 // (for example, if the expression was imported from another crate).
458 cx.tables.and_then(|tables| tables.expr_ty_opt(e))
461 let result = match e.node {
462 hir::ExprUnary(hir::UnNeg, ref inner) => {
463 // unary neg literals already got their sign during creation
464 if let hir::ExprLit(ref lit) = inner.node {
466 use syntax::ast::LitIntType::*;
467 const I8_OVERFLOW: u128 = i8::max_value() as u128 + 1;
468 const I16_OVERFLOW: u128 = i16::max_value() as u128 + 1;
469 const I32_OVERFLOW: u128 = i32::max_value() as u128 + 1;
470 const I64_OVERFLOW: u128 = i64::max_value() as u128 + 1;
471 const I128_OVERFLOW: u128 = i128::max_value() as u128 + 1;
472 match (&lit.node, ety.map(|t| &t.sty)) {
473 (&LitKind::Int(I8_OVERFLOW, Unsuffixed), Some(&ty::TyInt(IntTy::I8))) |
474 (&LitKind::Int(I8_OVERFLOW, Signed(IntTy::I8)), _) => {
475 return Ok(Integral(I8(i8::min_value())))
477 (&LitKind::Int(I16_OVERFLOW, Unsuffixed), Some(&ty::TyInt(IntTy::I16))) |
478 (&LitKind::Int(I16_OVERFLOW, Signed(IntTy::I16)), _) => {
479 return Ok(Integral(I16(i16::min_value())))
481 (&LitKind::Int(I32_OVERFLOW, Unsuffixed), Some(&ty::TyInt(IntTy::I32))) |
482 (&LitKind::Int(I32_OVERFLOW, Signed(IntTy::I32)), _) => {
483 return Ok(Integral(I32(i32::min_value())))
485 (&LitKind::Int(I64_OVERFLOW, Unsuffixed), Some(&ty::TyInt(IntTy::I64))) |
486 (&LitKind::Int(I64_OVERFLOW, Signed(IntTy::I64)), _) => {
487 return Ok(Integral(I64(i64::min_value())))
489 (&LitKind::Int(I128_OVERFLOW, Unsuffixed), Some(&ty::TyInt(IntTy::I128))) |
490 (&LitKind::Int(I128_OVERFLOW, Signed(IntTy::I128)), _) => {
491 return Ok(Integral(I128(i128::min_value())))
493 (&LitKind::Int(n, Unsuffixed), Some(&ty::TyInt(IntTy::Is))) |
494 (&LitKind::Int(n, Signed(IntTy::Is)), _) => {
495 match tcx.sess.target.int_type {
496 IntTy::I16 => if n == I16_OVERFLOW {
497 return Ok(Integral(Isize(Is16(i16::min_value()))));
499 IntTy::I32 => if n == I32_OVERFLOW {
500 return Ok(Integral(Isize(Is32(i32::min_value()))));
502 IntTy::I64 => if n == I64_OVERFLOW {
503 return Ok(Integral(Isize(Is64(i64::min_value()))));
511 match cx.eval(inner, ty_hint)? {
512 Float(f) => Float(-f),
513 Integral(i) => Integral(math!(e, -i)),
514 const_val => signal!(e, NegateOn(const_val)),
517 hir::ExprUnary(hir::UnNot, ref inner) => {
518 match cx.eval(inner, ty_hint)? {
519 Integral(i) => Integral(math!(e, !i)),
521 const_val => signal!(e, NotOn(const_val)),
524 hir::ExprUnary(hir::UnDeref, _) => signal!(e, UnimplementedConstVal("deref operation")),
525 hir::ExprBinary(op, ref a, ref b) => {
526 let b_ty = match op.node {
527 hir::BiShl | hir::BiShr => ty_hint.erase_hint(),
530 // technically, if we don't have type hints, but integral eval
531 // gives us a type through a type-suffix, cast or const def type
532 // we need to re-eval the other value of the BinOp if it was
534 match (cx.eval(a, ty_hint)?,
536 (Float(a), Float(b)) => {
537 use std::cmp::Ordering::*;
539 hir::BiAdd => Float(math!(e, a + b)),
540 hir::BiSub => Float(math!(e, a - b)),
541 hir::BiMul => Float(math!(e, a * b)),
542 hir::BiDiv => Float(math!(e, a / b)),
543 hir::BiRem => Float(math!(e, a % b)),
544 hir::BiEq => Bool(math!(e, a.try_cmp(b)) == Equal),
545 hir::BiLt => Bool(math!(e, a.try_cmp(b)) == Less),
546 hir::BiLe => Bool(math!(e, a.try_cmp(b)) != Greater),
547 hir::BiNe => Bool(math!(e, a.try_cmp(b)) != Equal),
548 hir::BiGe => Bool(math!(e, a.try_cmp(b)) != Less),
549 hir::BiGt => Bool(math!(e, a.try_cmp(b)) == Greater),
550 _ => signal!(e, InvalidOpForFloats(op.node)),
553 (Integral(a), Integral(b)) => {
554 use std::cmp::Ordering::*;
556 hir::BiAdd => Integral(math!(e, a + b)),
557 hir::BiSub => Integral(math!(e, a - b)),
558 hir::BiMul => Integral(math!(e, a * b)),
559 hir::BiDiv => Integral(math!(e, a / b)),
560 hir::BiRem => Integral(math!(e, a % b)),
561 hir::BiBitAnd => Integral(math!(e, a & b)),
562 hir::BiBitOr => Integral(math!(e, a | b)),
563 hir::BiBitXor => Integral(math!(e, a ^ b)),
564 hir::BiShl => Integral(math!(e, a << b)),
565 hir::BiShr => Integral(math!(e, a >> b)),
566 hir::BiEq => Bool(math!(e, a.try_cmp(b)) == Equal),
567 hir::BiLt => Bool(math!(e, a.try_cmp(b)) == Less),
568 hir::BiLe => Bool(math!(e, a.try_cmp(b)) != Greater),
569 hir::BiNe => Bool(math!(e, a.try_cmp(b)) != Equal),
570 hir::BiGe => Bool(math!(e, a.try_cmp(b)) != Less),
571 hir::BiGt => Bool(math!(e, a.try_cmp(b)) == Greater),
572 _ => signal!(e, InvalidOpForInts(op.node)),
575 (Bool(a), Bool(b)) => {
577 hir::BiAnd => a && b,
579 hir::BiBitXor => a ^ b,
580 hir::BiBitAnd => a & b,
581 hir::BiBitOr => a | b,
588 _ => signal!(e, InvalidOpForBools(op.node)),
592 _ => signal!(e, MiscBinaryOp),
595 hir::ExprCast(ref base, ref target_ty) => {
596 let ety = tcx.ast_ty_to_prim_ty(&target_ty).or(ety)
598 tcx.sess.span_fatal(target_ty.span,
599 "target type not found for const cast")
602 let base_hint = if let ExprTypeChecked = ty_hint {
605 match cx.tables.and_then(|tables| tables.expr_ty_opt(&base)) {
606 Some(t) => UncheckedExprHint(t),
611 let val = match cx.eval(base, base_hint) {
613 Err(ConstEvalErr { kind: ErroneousReferencedConstant(
614 box ConstEvalErr { kind: TypeMismatch(_, val), .. }), .. }) |
615 Err(ConstEvalErr { kind: TypeMismatch(_, val), .. }) => {
616 // Something like `5i8 as usize` doesn't need a type hint for the base
617 // instead take the type hint from the inner value
618 let hint = match val.int_type() {
619 Some(IntType::UnsignedInt(ty)) => ty_hint.checked_or(tcx.mk_mach_uint(ty)),
620 Some(IntType::SignedInt(ty)) => ty_hint.checked_or(tcx.mk_mach_int(ty)),
621 // we had a type hint, so we can't have an unknown type
626 Err(e) => return Err(e),
628 match cast_const(tcx, val, ety) {
630 Err(kind) => return Err(ConstEvalErr { span: e.span, kind: kind }),
633 hir::ExprPath(ref qpath) => {
634 let def = cx.tables.map(|tables| tables.qpath_def(qpath, e.id)).unwrap_or_else(|| {
635 // There are no tables so we can only handle already-resolved HIR.
637 hir::QPath::Resolved(_, ref path) => path.def,
638 hir::QPath::TypeRelative(..) => Def::Err
643 Def::AssociatedConst(def_id) => {
644 let substs = if let ExprTypeChecked = ty_hint {
645 Some(cx.tables.and_then(|tables| tables.node_id_item_substs(e.id))
646 .unwrap_or_else(|| tcx.intern_substs(&[])))
650 if let Some((expr, tables, ty)) = lookup_const_by_id(tcx, def_id, substs) {
651 let item_hint = match ty {
652 Some(ty) => ty_hint.checked_or(ty),
655 let cx = ConstContext { tcx: tcx, tables: tables, fn_args: None };
656 match cx.eval(expr, item_hint) {
659 debug!("bad reference: {:?}, {:?}", err.description(), err.span);
660 signal!(e, ErroneousReferencedConstant(box err))
664 signal!(e, NonConstPath);
667 Def::VariantCtor(variant_def, ..) => {
668 if let Some((expr, tables)) = lookup_variant_by_id(tcx, variant_def) {
669 let cx = ConstContext { tcx: tcx, tables: tables, fn_args: None };
670 match cx.eval(expr, ty_hint) {
673 debug!("bad reference: {:?}, {:?}", err.description(), err.span);
674 signal!(e, ErroneousReferencedConstant(box err))
678 signal!(e, UnimplementedConstVal("enum variants"));
681 Def::StructCtor(..) => {
682 ConstVal::Struct(Default::default())
684 Def::Local(def_id) => {
685 debug!("Def::Local({:?}): {:?}", def_id, cx.fn_args);
686 if let Some(val) = cx.fn_args.as_ref().and_then(|args| args.get(&def_id)) {
689 signal!(e, NonConstPath);
692 Def::Method(id) | Def::Fn(id) => Function(id),
693 Def::Err => signal!(e, UnresolvedPath),
694 _ => signal!(e, NonConstPath),
697 hir::ExprCall(ref callee, ref args) => {
698 let sub_ty_hint = ty_hint.erase_hint();
699 let callee_val = cx.eval(callee, sub_ty_hint)?;
700 let did = match callee_val {
701 Function(did) => did,
702 Struct(_) => signal!(e, UnimplementedConstVal("tuple struct constructors")),
703 callee => signal!(e, CallOn(callee)),
705 let (body, tables) = match lookup_const_fn_by_id(tcx, did) {
707 None => signal!(e, NonConstPath),
710 let arg_defs = body.arguments.iter().map(|arg| match arg.pat.node {
711 hir::PatKind::Binding(_, def_id, _, _) => Some(def_id),
713 }).collect::<Vec<_>>();
714 assert_eq!(arg_defs.len(), args.len());
716 let mut call_args = DefIdMap();
717 for (arg, arg_expr) in arg_defs.into_iter().zip(args.iter()) {
718 let arg_hint = ty_hint.erase_hint();
719 let arg_val = cx.eval(arg_expr, arg_hint)?;
720 debug!("const call arg: {:?}", arg);
721 if let Some(def_id) = arg {
722 assert!(call_args.insert(def_id, arg_val).is_none());
725 debug!("const call({:?})", call_args);
726 let callee_cx = ConstContext {
729 fn_args: Some(call_args)
731 callee_cx.eval(&body.value, ty_hint)?
733 hir::ExprLit(ref lit) => match lit_to_const(&lit.node, tcx, ety) {
735 Err(err) => signal!(e, err),
737 hir::ExprBlock(ref block) => {
739 Some(ref expr) => cx.eval(expr, ty_hint)?,
740 None => signal!(e, UnimplementedConstVal("empty block")),
743 hir::ExprType(ref e, _) => cx.eval(e, ty_hint)?,
744 hir::ExprTup(ref fields) => {
745 let field_hint = ty_hint.erase_hint();
746 Tuple(fields.iter().map(|e| cx.eval(e, field_hint)).collect::<Result<_, _>>()?)
748 hir::ExprStruct(_, ref fields, _) => {
749 let field_hint = ty_hint.erase_hint();
750 Struct(fields.iter().map(|f| {
751 cx.eval(&f.expr, field_hint).map(|v| (f.name.node, v))
752 }).collect::<Result<_, _>>()?)
754 hir::ExprIndex(ref arr, ref idx) => {
755 if !tcx.sess.features.borrow().const_indexing {
756 signal!(e, IndexOpFeatureGated);
758 let arr_hint = ty_hint.erase_hint();
759 let arr = cx.eval(arr, arr_hint)?;
760 let idx_hint = ty_hint.checked_or(tcx.types.usize);
761 let idx = match cx.eval(idx, idx_hint)? {
762 Integral(Usize(i)) => i.as_u64(tcx.sess.target.uint_type),
763 Integral(_) => bug!(),
764 _ => signal!(idx, IndexNotInt),
766 assert_eq!(idx as usize as u64, idx);
769 if let Some(elem) = v.get(idx as usize) {
772 let n = v.len() as u64;
773 assert_eq!(n as usize as u64, n);
774 signal!(e, IndexOutOfBounds { len: n, index: idx })
778 Repeat(.., n) if idx >= n => {
779 signal!(e, IndexOutOfBounds { len: n, index: idx })
781 Repeat(ref elem, _) => (**elem).clone(),
783 ByteStr(ref data) if idx >= data.len() as u64 => {
784 signal!(e, IndexOutOfBounds { len: data.len() as u64, index: idx })
787 Integral(U8(data[idx as usize]))
790 _ => signal!(e, IndexedNonVec),
793 hir::ExprArray(ref v) => {
794 let elem_hint = ty_hint.erase_hint();
795 Array(v.iter().map(|e| cx.eval(e, elem_hint)).collect::<Result<_, _>>()?)
797 hir::ExprRepeat(ref elem, count) => {
798 let elem_hint = ty_hint.erase_hint();
799 let len_hint = ty_hint.checked_or(tcx.types.usize);
800 let n = if let Some(ty) = ety {
801 // For cross-crate constants, we have the type already,
802 // but not the body for `count`, so use the type.
804 ty::TyArray(_, n) => n as u64,
808 let n = &tcx.map.body(count).value;
809 match ConstContext::new(tcx, count).eval(n, len_hint)? {
810 Integral(Usize(i)) => i.as_u64(tcx.sess.target.uint_type),
811 Integral(_) => signal!(e, RepeatCountNotNatural),
812 _ => signal!(e, RepeatCountNotInt),
815 Repeat(Box::new(cx.eval(elem, elem_hint)?), n)
817 hir::ExprTupField(ref base, index) => {
818 let base_hint = ty_hint.erase_hint();
819 let c = cx.eval(base, base_hint)?;
820 if let Tuple(ref fields) = c {
821 if let Some(elem) = fields.get(index.node) {
824 signal!(e, TupleIndexOutOfBounds);
827 signal!(base, ExpectedConstTuple);
830 hir::ExprField(ref base, field_name) => {
831 let base_hint = ty_hint.erase_hint();
832 let c = cx.eval(base, base_hint)?;
833 if let Struct(ref fields) = c {
834 if let Some(f) = fields.get(&field_name.node) {
837 signal!(e, MissingStructField);
840 signal!(base, ExpectedConstStruct);
843 hir::ExprAddrOf(..) => signal!(e, UnimplementedConstVal("address operator")),
844 _ => signal!(e, MiscCatchAll)
847 match (ety.map(|t| &t.sty), result) {
848 (Some(ref ty_hint), Integral(i)) => match infer(i, tcx, ty_hint) {
849 Ok(inferred) => Ok(Integral(inferred)),
850 Err(err) => signal!(e, err),
852 (_, result) => Ok(result),
856 fn infer<'a, 'tcx>(i: ConstInt,
857 tcx: TyCtxt<'a, 'tcx, 'tcx>,
858 ty_hint: &ty::TypeVariants<'tcx>)
859 -> Result<ConstInt, ErrKind> {
863 (&ty::TyInt(IntTy::I8), result @ I8(_)) => Ok(result),
864 (&ty::TyInt(IntTy::I16), result @ I16(_)) => Ok(result),
865 (&ty::TyInt(IntTy::I32), result @ I32(_)) => Ok(result),
866 (&ty::TyInt(IntTy::I64), result @ I64(_)) => Ok(result),
867 (&ty::TyInt(IntTy::I128), result @ I128(_)) => Ok(result),
868 (&ty::TyInt(IntTy::Is), result @ Isize(_)) => Ok(result),
870 (&ty::TyUint(UintTy::U8), result @ U8(_)) => Ok(result),
871 (&ty::TyUint(UintTy::U16), result @ U16(_)) => Ok(result),
872 (&ty::TyUint(UintTy::U32), result @ U32(_)) => Ok(result),
873 (&ty::TyUint(UintTy::U64), result @ U64(_)) => Ok(result),
874 (&ty::TyUint(UintTy::U128), result @ U128(_)) => Ok(result),
875 (&ty::TyUint(UintTy::Us), result @ Usize(_)) => Ok(result),
877 (&ty::TyInt(IntTy::I8), Infer(i)) => Ok(I8(i as i128 as i8)),
878 (&ty::TyInt(IntTy::I16), Infer(i)) => Ok(I16(i as i128 as i16)),
879 (&ty::TyInt(IntTy::I32), Infer(i)) => Ok(I32(i as i128 as i32)),
880 (&ty::TyInt(IntTy::I64), Infer(i)) => Ok(I64(i as i128 as i64)),
881 (&ty::TyInt(IntTy::I128), Infer(i)) => Ok(I128(i as i128)),
882 (&ty::TyInt(IntTy::Is), Infer(i)) => {
883 Ok(Isize(ConstIsize::new_truncating(i as i128, tcx.sess.target.int_type)))
886 (&ty::TyInt(IntTy::I8), InferSigned(i)) => Ok(I8(i as i8)),
887 (&ty::TyInt(IntTy::I16), InferSigned(i)) => Ok(I16(i as i16)),
888 (&ty::TyInt(IntTy::I32), InferSigned(i)) => Ok(I32(i as i32)),
889 (&ty::TyInt(IntTy::I64), InferSigned(i)) => Ok(I64(i as i64)),
890 (&ty::TyInt(IntTy::I128), InferSigned(i)) => Ok(I128(i)),
891 (&ty::TyInt(IntTy::Is), InferSigned(i)) => {
892 Ok(Isize(ConstIsize::new_truncating(i, tcx.sess.target.int_type)))
895 (&ty::TyUint(UintTy::U8), Infer(i)) => Ok(U8(i as u8)),
896 (&ty::TyUint(UintTy::U16), Infer(i)) => Ok(U16(i as u16)),
897 (&ty::TyUint(UintTy::U32), Infer(i)) => Ok(U32(i as u32)),
898 (&ty::TyUint(UintTy::U64), Infer(i)) => Ok(U64(i as u64)),
899 (&ty::TyUint(UintTy::U128), Infer(i)) => Ok(U128(i)),
900 (&ty::TyUint(UintTy::Us), Infer(i)) => {
901 Ok(Usize(ConstUsize::new_truncating(i, tcx.sess.target.uint_type)))
903 (&ty::TyUint(_), InferSigned(_)) => Err(IntermediateUnsignedNegative),
905 (&ty::TyInt(ity), i) => Err(TypeMismatch(ity.to_string(), i)),
906 (&ty::TyUint(ity), i) => Err(TypeMismatch(ity.to_string(), i)),
908 (&ty::TyAdt(adt, _), i) if adt.is_enum() => {
909 let hints = tcx.lookup_repr_hints(adt.did);
910 let int_ty = tcx.enum_repr_type(hints.iter().next());
911 infer(i, tcx, &int_ty.to_ty(tcx).sty)
913 (_, i) => Err(BadType(ConstVal::Integral(i))),
917 fn resolve_trait_associated_const<'a, 'tcx: 'a>(
918 tcx: TyCtxt<'a, 'tcx, 'tcx>,
919 trait_item_id: DefId,
920 default_value: Option<(&'tcx Expr, Option<&'a ty::Tables<'tcx>>, Option<ty::Ty<'tcx>>)>,
922 rcvr_substs: &'tcx Substs<'tcx>
923 ) -> Option<(&'tcx Expr, Option<&'a ty::Tables<'tcx>>, Option<ty::Ty<'tcx>>)>
925 let trait_ref = ty::Binder(ty::TraitRef::new(trait_id, rcvr_substs));
926 debug!("resolve_trait_associated_const: trait_ref={:?}",
929 tcx.populate_implementations_for_trait_if_necessary(trait_id);
930 tcx.infer_ctxt((), Reveal::NotSpecializable).enter(|infcx| {
931 let mut selcx = traits::SelectionContext::new(&infcx);
932 let obligation = traits::Obligation::new(traits::ObligationCause::dummy(),
933 trait_ref.to_poly_trait_predicate());
934 let selection = match selcx.select(&obligation) {
935 Ok(Some(vtable)) => vtable,
936 // Still ambiguous, so give up and let the caller decide whether this
937 // expression is really needed yet. Some associated constant values
938 // can't be evaluated until monomorphization is done in trans.
947 // NOTE: this code does not currently account for specialization, but when
948 // it does so, it should hook into the Reveal to determine when the
949 // constant should resolve; this will also require plumbing through to this
950 // function whether we are in "trans mode" to pick the right Reveal
951 // when constructing the inference context above.
953 traits::VtableImpl(ref impl_data) => {
954 let name = tcx.associated_item(trait_item_id).name;
955 let ac = tcx.associated_items(impl_data.impl_def_id)
956 .find(|item| item.kind == ty::AssociatedKind::Const && item.name == name);
958 Some(ic) => lookup_const_by_id(tcx, ic.def_id, None),
959 None => default_value,
963 bug!("resolve_trait_associated_const: unexpected vtable type")
969 fn cast_const_int<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, val: ConstInt, ty: ty::Ty) -> CastResult {
970 let v = val.to_u128_unchecked();
972 ty::TyBool if v == 0 => Ok(Bool(false)),
973 ty::TyBool if v == 1 => Ok(Bool(true)),
974 ty::TyInt(ast::IntTy::I8) => Ok(Integral(I8(v as i128 as i8))),
975 ty::TyInt(ast::IntTy::I16) => Ok(Integral(I16(v as i128 as i16))),
976 ty::TyInt(ast::IntTy::I32) => Ok(Integral(I32(v as i128 as i32))),
977 ty::TyInt(ast::IntTy::I64) => Ok(Integral(I64(v as i128 as i64))),
978 ty::TyInt(ast::IntTy::I128) => Ok(Integral(I128(v as i128))),
979 ty::TyInt(ast::IntTy::Is) => {
980 Ok(Integral(Isize(ConstIsize::new_truncating(v as i128, tcx.sess.target.int_type))))
982 ty::TyUint(ast::UintTy::U8) => Ok(Integral(U8(v as u8))),
983 ty::TyUint(ast::UintTy::U16) => Ok(Integral(U16(v as u16))),
984 ty::TyUint(ast::UintTy::U32) => Ok(Integral(U32(v as u32))),
985 ty::TyUint(ast::UintTy::U64) => Ok(Integral(U64(v as u64))),
986 ty::TyUint(ast::UintTy::U128) => Ok(Integral(U128(v as u128))),
987 ty::TyUint(ast::UintTy::Us) => {
988 Ok(Integral(Usize(ConstUsize::new_truncating(v, tcx.sess.target.uint_type))))
990 ty::TyFloat(ast::FloatTy::F64) => match val.erase_type() {
991 Infer(u) => Ok(Float(F64(u as f64))),
992 InferSigned(i) => Ok(Float(F64(i as f64))),
993 _ => bug!("ConstInt::erase_type returned something other than Infer/InferSigned"),
995 ty::TyFloat(ast::FloatTy::F32) => match val.erase_type() {
996 Infer(u) => Ok(Float(F32(u as f32))),
997 InferSigned(i) => Ok(Float(F32(i as f32))),
998 _ => bug!("ConstInt::erase_type returned something other than Infer/InferSigned"),
1000 ty::TyRawPtr(_) => Err(ErrKind::UnimplementedConstVal("casting an address to a raw ptr")),
1001 ty::TyChar => match infer(val, tcx, &ty::TyUint(ast::UintTy::U8)) {
1002 Ok(U8(u)) => Ok(Char(u as char)),
1003 // can only occur before typeck, typeck blocks `T as char` for `T` != `u8`
1004 _ => Err(CharCast(val)),
1006 _ => Err(CannotCast),
1010 fn cast_const_float<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1012 ty: ty::Ty) -> CastResult {
1014 ty::TyInt(_) | ty::TyUint(_) => {
1016 F32(f) if f >= 0.0 => Infer(f as u128),
1017 FInfer { f64: f, .. } |
1018 F64(f) if f >= 0.0 => Infer(f as u128),
1020 F32(f) => InferSigned(f as i128),
1021 FInfer { f64: f, .. } |
1022 F64(f) => InferSigned(f as i128)
1025 if let (InferSigned(_), &ty::TyUint(_)) = (i, &ty.sty) {
1026 return Err(CannotCast);
1029 cast_const_int(tcx, i, ty)
1031 ty::TyFloat(ast::FloatTy::F64) => Ok(Float(F64(match val {
1033 FInfer { f64: f, .. } | F64(f) => f
1035 ty::TyFloat(ast::FloatTy::F32) => Ok(Float(F32(match val {
1037 FInfer { f32: f, .. } | F32(f) => f
1039 _ => Err(CannotCast),
1043 fn cast_const<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, val: ConstVal, ty: ty::Ty) -> CastResult {
1045 Integral(i) => cast_const_int(tcx, i, ty),
1046 Bool(b) => cast_const_int(tcx, Infer(b as u128), ty),
1047 Float(f) => cast_const_float(tcx, f, ty),
1048 Char(c) => cast_const_int(tcx, Infer(c as u128), ty),
1049 Function(_) => Err(UnimplementedConstVal("casting fn pointers")),
1050 ByteStr(b) => match ty.sty {
1051 ty::TyRawPtr(_) => {
1052 Err(ErrKind::UnimplementedConstVal("casting a bytestr to a raw ptr"))
1054 ty::TyRef(_, ty::TypeAndMut { ref ty, mutbl: hir::MutImmutable }) => match ty.sty {
1055 ty::TyArray(ty, n) if ty == tcx.types.u8 && n == b.len() => Ok(ByteStr(b)),
1057 Err(ErrKind::UnimplementedConstVal("casting a bytestr to slice"))
1059 _ => Err(CannotCast),
1061 _ => Err(CannotCast),
1063 Str(s) => match ty.sty {
1064 ty::TyRawPtr(_) => Err(ErrKind::UnimplementedConstVal("casting a str to a raw ptr")),
1065 ty::TyRef(_, ty::TypeAndMut { ref ty, mutbl: hir::MutImmutable }) => match ty.sty {
1066 ty::TyStr => Ok(Str(s)),
1067 _ => Err(CannotCast),
1069 _ => Err(CannotCast),
1071 _ => Err(CannotCast),
1075 fn lit_to_const<'a, 'tcx>(lit: &ast::LitKind,
1076 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1077 ty_hint: Option<Ty<'tcx>>)
1078 -> Result<ConstVal, ErrKind> {
1080 use syntax::ast::LitIntType::*;
1082 LitKind::Str(ref s, _) => Ok(Str(s.as_str())),
1083 LitKind::ByteStr(ref data) => Ok(ByteStr(data.clone())),
1084 LitKind::Byte(n) => Ok(Integral(U8(n))),
1085 LitKind::Int(n, Signed(ity)) => {
1086 infer(InferSigned(n as i128), tcx, &ty::TyInt(ity)).map(Integral)
1089 // FIXME: this should become u128.
1090 LitKind::Int(n, Unsuffixed) => {
1091 match ty_hint.map(|t| &t.sty) {
1092 Some(&ty::TyInt(ity)) => {
1093 infer(InferSigned(n as i128), tcx, &ty::TyInt(ity)).map(Integral)
1095 Some(&ty::TyUint(uty)) => {
1096 infer(Infer(n as u128), tcx, &ty::TyUint(uty)).map(Integral)
1098 None => Ok(Integral(Infer(n as u128))),
1099 Some(&ty::TyAdt(adt, _)) => {
1100 let hints = tcx.lookup_repr_hints(adt.did);
1101 let int_ty = tcx.enum_repr_type(hints.iter().next());
1102 infer(Infer(n as u128), tcx, &int_ty.to_ty(tcx).sty).map(Integral)
1104 Some(ty_hint) => bug!("bad ty_hint: {:?}, {:?}", ty_hint, lit),
1107 LitKind::Int(n, Unsigned(ity)) => {
1108 infer(Infer(n as u128), tcx, &ty::TyUint(ity)).map(Integral)
1111 LitKind::Float(n, fty) => {
1112 parse_float(&n.as_str(), Some(fty)).map(Float)
1114 LitKind::FloatUnsuffixed(n) => {
1115 let fty_hint = match ty_hint.map(|t| &t.sty) {
1116 Some(&ty::TyFloat(fty)) => Some(fty),
1119 parse_float(&n.as_str(), fty_hint).map(Float)
1121 LitKind::Bool(b) => Ok(Bool(b)),
1122 LitKind::Char(c) => Ok(Char(c)),
1126 fn parse_float(num: &str, fty_hint: Option<ast::FloatTy>)
1127 -> Result<ConstFloat, ErrKind> {
1128 let val = match fty_hint {
1129 Some(ast::FloatTy::F32) => num.parse::<f32>().map(F32),
1130 Some(ast::FloatTy::F64) => num.parse::<f64>().map(F64),
1132 num.parse::<f32>().and_then(|f32| {
1133 num.parse::<f64>().map(|f64| {
1134 FInfer { f32: f32, f64: f64 }
1140 // FIXME(#31407) this is only necessary because float parsing is buggy
1141 UnimplementedConstVal("could not evaluate float literal (see issue #31407)")
1145 pub fn compare_const_vals(tcx: TyCtxt, span: Span, a: &ConstVal, b: &ConstVal)
1146 -> Result<Ordering, ErrorReported>
1148 let result = match (a, b) {
1149 (&Integral(a), &Integral(b)) => a.try_cmp(b).ok(),
1150 (&Float(a), &Float(b)) => a.try_cmp(b).ok(),
1151 (&Str(ref a), &Str(ref b)) => Some(a.cmp(b)),
1152 (&Bool(a), &Bool(b)) => Some(a.cmp(&b)),
1153 (&ByteStr(ref a), &ByteStr(ref b)) => Some(a.cmp(b)),
1154 (&Char(a), &Char(ref b)) => Some(a.cmp(b)),
1159 Some(result) => Ok(result),
1161 // FIXME: can this ever be reached?
1162 span_err!(tcx.sess, span, E0298,
1163 "type mismatch comparing {} and {}",
1171 impl<'a, 'tcx> ConstContext<'a, 'tcx> {
1172 pub fn compare_lit_exprs(&self,
1175 b: &Expr) -> Result<Ordering, ErrorReported> {
1177 let a = match self.eval(a, ExprTypeChecked) {
1180 report_const_eval_err(tcx, &e, a.span, "expression").emit();
1181 return Err(ErrorReported);
1184 let b = match self.eval(b, ExprTypeChecked) {
1187 report_const_eval_err(tcx, &e, b.span, "expression").emit();
1188 return Err(ErrorReported);
1191 compare_const_vals(tcx, span, &a, &b)
1196 /// Returns the value of the length-valued expression
1197 pub fn eval_length<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1200 -> Result<usize, ErrorReported>
1202 let hint = UncheckedExprHint(tcx.types.usize);
1203 let count_expr = &tcx.map.body(count).value;
1204 match ConstContext::new(tcx, count).eval(count_expr, hint) {
1205 Ok(Integral(Usize(count))) => {
1206 let val = count.as_u64(tcx.sess.target.uint_type);
1207 assert_eq!(val as usize as u64, val);
1211 struct_span_err!(tcx.sess, count_expr.span, E0306,
1212 "expected `usize` for {}, found {}",
1214 const_val.description())
1215 .span_label(count_expr.span, &format!("expected `usize`"))
1221 let mut diag = report_const_eval_err(
1222 tcx, &err, count_expr.span, reason);
1224 if let hir::ExprPath(hir::QPath::Resolved(None, ref path)) = count_expr.node {
1225 if let Def::Local(..) = path.def {
1226 diag.note(&format!("`{}` is a variable",
1227 tcx.map.node_to_pretty_string(count_expr.id)));