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 hir_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::TypeckTables<'tcx>>)> {
56 if let Some(variant_node_id) = tcx.hir.as_local_node_id(variant_def) {
57 let enum_node_id = tcx.hir.get_parent(variant_node_id);
58 if let Some(hir_map::NodeItem(it)) = tcx.hir.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.hir.body_owner_def_id(e);
64 (&tcx.hir.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::TypeckTables<'tcx>>,
85 Option<ty::Ty<'tcx>>)> {
86 if let Some(node_id) = tcx.hir.as_local_node_id(def_id) {
87 match tcx.hir.find(node_id) {
89 Some(hir_map::NodeItem(&hir::Item {
90 node: hir::ItemConst(ref ty, body), ..
92 Some(hir_map::NodeImplItem(&hir::ImplItem {
93 node: hir::ImplItemKind::Const(ref ty, body), ..
95 Some((&tcx.hir.body(body).value,
96 tcx.tables.borrow().get(&def_id).cloned(),
97 tcx.ast_ty_to_prim_ty(ty)))
99 Some(hir_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.hir.get_parent(node_id);
106 let trait_id = tcx.hir.local_def_id(trait_id);
107 let default_value = default.map(|body| {
108 (&tcx.hir.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::TypeckTables<'tcx>>)>
159 if let Some(node_id) = tcx.hir.as_local_node_id(def_id) {
160 FnLikeNode::from_node(tcx.hir.get(node_id)).and_then(|fn_like| {
161 if fn_like.constness() == hir::Constness::Const {
162 Some((tcx.hir.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::TypeckTables<'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.hir.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::TypeckTables<'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::min_value() as u8 as u128;
468 const I16_OVERFLOW: u128 = i16::min_value() as u16 as u128;
469 const I32_OVERFLOW: u128 = i32::min_value() as u32 as u128;
470 const I64_OVERFLOW: u128 = i64::min_value() as u64 as u128;
471 const I128_OVERFLOW: u128 = i128::min_value() as u128;
472 match (&lit.node, ety.map(|t| &t.sty)) {
473 (&LitKind::Int(I8_OVERFLOW, _), 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, _), 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, _), 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, _), Some(&ty::TyInt(IntTy::I64))) |
486 (&LitKind::Int(I64_OVERFLOW, Signed(IntTy::I64)), _) => {
487 return Ok(Integral(I64(i64::min_value())))
489 (&LitKind::Int(n, _), Some(&ty::TyInt(IntTy::I128))) |
490 (&LitKind::Int(n, Signed(IntTy::I128)), _) => {
491 // SNAP: replace n in pattern with I128_OVERFLOW and remove this if.
492 if n == I128_OVERFLOW {
493 return Ok(Integral(I128(i128::min_value())))
496 (&LitKind::Int(n, _), Some(&ty::TyInt(IntTy::Is))) |
497 (&LitKind::Int(n, Signed(IntTy::Is)), _) => {
498 match tcx.sess.target.int_type {
499 IntTy::I16 => if n == I16_OVERFLOW {
500 return Ok(Integral(Isize(Is16(i16::min_value()))));
502 IntTy::I32 => if n == I32_OVERFLOW {
503 return Ok(Integral(Isize(Is32(i32::min_value()))));
505 IntTy::I64 => if n == I64_OVERFLOW {
506 return Ok(Integral(Isize(Is64(i64::min_value()))));
514 match cx.eval(inner, ty_hint)? {
515 Float(f) => Float(-f),
516 Integral(i) => Integral(math!(e, -i)),
517 const_val => signal!(e, NegateOn(const_val)),
520 hir::ExprUnary(hir::UnNot, ref inner) => {
521 match cx.eval(inner, ty_hint)? {
522 Integral(i) => Integral(math!(e, !i)),
524 const_val => signal!(e, NotOn(const_val)),
527 hir::ExprUnary(hir::UnDeref, _) => signal!(e, UnimplementedConstVal("deref operation")),
528 hir::ExprBinary(op, ref a, ref b) => {
529 let b_ty = match op.node {
530 hir::BiShl | hir::BiShr => ty_hint.erase_hint(),
533 // technically, if we don't have type hints, but integral eval
534 // gives us a type through a type-suffix, cast or const def type
535 // we need to re-eval the other value of the BinOp if it was
537 match (cx.eval(a, ty_hint)?,
539 (Float(a), Float(b)) => {
540 use std::cmp::Ordering::*;
542 hir::BiAdd => Float(math!(e, a + b)),
543 hir::BiSub => Float(math!(e, a - b)),
544 hir::BiMul => Float(math!(e, a * b)),
545 hir::BiDiv => Float(math!(e, a / b)),
546 hir::BiRem => Float(math!(e, a % b)),
547 hir::BiEq => Bool(math!(e, a.try_cmp(b)) == Equal),
548 hir::BiLt => Bool(math!(e, a.try_cmp(b)) == Less),
549 hir::BiLe => Bool(math!(e, a.try_cmp(b)) != Greater),
550 hir::BiNe => Bool(math!(e, a.try_cmp(b)) != Equal),
551 hir::BiGe => Bool(math!(e, a.try_cmp(b)) != Less),
552 hir::BiGt => Bool(math!(e, a.try_cmp(b)) == Greater),
553 _ => signal!(e, InvalidOpForFloats(op.node)),
556 (Integral(a), Integral(b)) => {
557 use std::cmp::Ordering::*;
559 hir::BiAdd => Integral(math!(e, a + b)),
560 hir::BiSub => Integral(math!(e, a - b)),
561 hir::BiMul => Integral(math!(e, a * b)),
562 hir::BiDiv => Integral(math!(e, a / b)),
563 hir::BiRem => Integral(math!(e, a % b)),
564 hir::BiBitAnd => Integral(math!(e, a & b)),
565 hir::BiBitOr => Integral(math!(e, a | b)),
566 hir::BiBitXor => Integral(math!(e, a ^ b)),
567 hir::BiShl => Integral(math!(e, a << b)),
568 hir::BiShr => Integral(math!(e, a >> b)),
569 hir::BiEq => Bool(math!(e, a.try_cmp(b)) == Equal),
570 hir::BiLt => Bool(math!(e, a.try_cmp(b)) == Less),
571 hir::BiLe => Bool(math!(e, a.try_cmp(b)) != Greater),
572 hir::BiNe => Bool(math!(e, a.try_cmp(b)) != Equal),
573 hir::BiGe => Bool(math!(e, a.try_cmp(b)) != Less),
574 hir::BiGt => Bool(math!(e, a.try_cmp(b)) == Greater),
575 _ => signal!(e, InvalidOpForInts(op.node)),
578 (Bool(a), Bool(b)) => {
580 hir::BiAnd => a && b,
582 hir::BiBitXor => a ^ b,
583 hir::BiBitAnd => a & b,
584 hir::BiBitOr => a | b,
591 _ => signal!(e, InvalidOpForBools(op.node)),
595 _ => signal!(e, MiscBinaryOp),
598 hir::ExprCast(ref base, ref target_ty) => {
599 let ety = tcx.ast_ty_to_prim_ty(&target_ty).or(ety)
601 tcx.sess.span_fatal(target_ty.span,
602 "target type not found for const cast")
605 let base_hint = if let ExprTypeChecked = ty_hint {
608 match cx.tables.and_then(|tables| tables.expr_ty_opt(&base)) {
609 Some(t) => UncheckedExprHint(t),
614 let val = match cx.eval(base, base_hint) {
616 Err(ConstEvalErr { kind: ErroneousReferencedConstant(
617 box ConstEvalErr { kind: TypeMismatch(_, val), .. }), .. }) |
618 Err(ConstEvalErr { kind: TypeMismatch(_, val), .. }) => {
619 // Something like `5i8 as usize` doesn't need a type hint for the base
620 // instead take the type hint from the inner value
621 let hint = match val.int_type() {
622 Some(IntType::UnsignedInt(ty)) => ty_hint.checked_or(tcx.mk_mach_uint(ty)),
623 Some(IntType::SignedInt(ty)) => ty_hint.checked_or(tcx.mk_mach_int(ty)),
624 // we had a type hint, so we can't have an unknown type
629 Err(e) => return Err(e),
631 match cast_const(tcx, val, ety) {
633 Err(kind) => return Err(ConstEvalErr { span: e.span, kind: kind }),
636 hir::ExprPath(ref qpath) => {
637 let def = cx.tables.map(|tables| tables.qpath_def(qpath, e.id)).unwrap_or_else(|| {
638 // There are no tables so we can only handle already-resolved HIR.
640 hir::QPath::Resolved(_, ref path) => path.def,
641 hir::QPath::TypeRelative(..) => Def::Err
646 Def::AssociatedConst(def_id) => {
647 let substs = if let ExprTypeChecked = ty_hint {
648 Some(cx.tables.and_then(|tables| tables.node_id_item_substs(e.id))
649 .unwrap_or_else(|| tcx.intern_substs(&[])))
653 if let Some((expr, tables, ty)) = lookup_const_by_id(tcx, def_id, substs) {
654 let item_hint = match ty {
655 Some(ty) => ty_hint.checked_or(ty),
658 let cx = ConstContext { tcx: tcx, tables: tables, fn_args: None };
659 match cx.eval(expr, item_hint) {
662 debug!("bad reference: {:?}, {:?}", err.description(), err.span);
663 signal!(e, ErroneousReferencedConstant(box err))
667 signal!(e, NonConstPath);
670 Def::VariantCtor(variant_def, ..) => {
671 if let Some((expr, tables)) = lookup_variant_by_id(tcx, variant_def) {
672 let cx = ConstContext { tcx: tcx, tables: tables, fn_args: None };
673 match cx.eval(expr, ty_hint) {
676 debug!("bad reference: {:?}, {:?}", err.description(), err.span);
677 signal!(e, ErroneousReferencedConstant(box err))
681 signal!(e, UnimplementedConstVal("enum variants"));
684 Def::StructCtor(..) => {
685 ConstVal::Struct(Default::default())
687 Def::Local(def_id) => {
688 debug!("Def::Local({:?}): {:?}", def_id, cx.fn_args);
689 if let Some(val) = cx.fn_args.as_ref().and_then(|args| args.get(&def_id)) {
692 signal!(e, NonConstPath);
695 Def::Method(id) | Def::Fn(id) => Function(id),
696 Def::Err => signal!(e, UnresolvedPath),
697 _ => signal!(e, NonConstPath),
700 hir::ExprCall(ref callee, ref args) => {
701 let sub_ty_hint = ty_hint.erase_hint();
702 let callee_val = cx.eval(callee, sub_ty_hint)?;
703 let did = match callee_val {
704 Function(did) => did,
705 Struct(_) => signal!(e, UnimplementedConstVal("tuple struct constructors")),
706 callee => signal!(e, CallOn(callee)),
708 let (body, tables) = match lookup_const_fn_by_id(tcx, did) {
710 None => signal!(e, NonConstPath),
713 let arg_defs = body.arguments.iter().map(|arg| match arg.pat.node {
714 hir::PatKind::Binding(_, def_id, _, _) => Some(def_id),
716 }).collect::<Vec<_>>();
717 assert_eq!(arg_defs.len(), args.len());
719 let mut call_args = DefIdMap();
720 for (arg, arg_expr) in arg_defs.into_iter().zip(args.iter()) {
721 let arg_hint = ty_hint.erase_hint();
722 let arg_val = cx.eval(arg_expr, arg_hint)?;
723 debug!("const call arg: {:?}", arg);
724 if let Some(def_id) = arg {
725 assert!(call_args.insert(def_id, arg_val).is_none());
728 debug!("const call({:?})", call_args);
729 let callee_cx = ConstContext {
732 fn_args: Some(call_args)
734 callee_cx.eval(&body.value, ty_hint)?
736 hir::ExprLit(ref lit) => match lit_to_const(&lit.node, tcx, ety) {
738 Err(err) => signal!(e, err),
740 hir::ExprBlock(ref block) => {
742 Some(ref expr) => cx.eval(expr, ty_hint)?,
743 None => signal!(e, UnimplementedConstVal("empty block")),
746 hir::ExprType(ref e, _) => cx.eval(e, ty_hint)?,
747 hir::ExprTup(ref fields) => {
748 let field_hint = ty_hint.erase_hint();
749 Tuple(fields.iter().map(|e| cx.eval(e, field_hint)).collect::<Result<_, _>>()?)
751 hir::ExprStruct(_, ref fields, _) => {
752 let field_hint = ty_hint.erase_hint();
753 Struct(fields.iter().map(|f| {
754 cx.eval(&f.expr, field_hint).map(|v| (f.name.node, v))
755 }).collect::<Result<_, _>>()?)
757 hir::ExprIndex(ref arr, ref idx) => {
758 if !tcx.sess.features.borrow().const_indexing {
759 signal!(e, IndexOpFeatureGated);
761 let arr_hint = ty_hint.erase_hint();
762 let arr = cx.eval(arr, arr_hint)?;
763 let idx_hint = ty_hint.checked_or(tcx.types.usize);
764 let idx = match cx.eval(idx, idx_hint)? {
765 Integral(Usize(i)) => i.as_u64(tcx.sess.target.uint_type),
766 Integral(_) => bug!(),
767 _ => signal!(idx, IndexNotInt),
769 assert_eq!(idx as usize as u64, idx);
772 if let Some(elem) = v.get(idx as usize) {
775 let n = v.len() as u64;
776 assert_eq!(n as usize as u64, n);
777 signal!(e, IndexOutOfBounds { len: n, index: idx })
781 Repeat(.., n) if idx >= n => {
782 signal!(e, IndexOutOfBounds { len: n, index: idx })
784 Repeat(ref elem, _) => (**elem).clone(),
786 ByteStr(ref data) if idx >= data.len() as u64 => {
787 signal!(e, IndexOutOfBounds { len: data.len() as u64, index: idx })
790 Integral(U8(data[idx as usize]))
793 _ => signal!(e, IndexedNonVec),
796 hir::ExprArray(ref v) => {
797 let elem_hint = ty_hint.erase_hint();
798 Array(v.iter().map(|e| cx.eval(e, elem_hint)).collect::<Result<_, _>>()?)
800 hir::ExprRepeat(ref elem, count) => {
801 let elem_hint = ty_hint.erase_hint();
802 let len_hint = ty_hint.checked_or(tcx.types.usize);
803 let n = if let Some(ty) = ety {
804 // For cross-crate constants, we have the type already,
805 // but not the body for `count`, so use the type.
807 ty::TyArray(_, n) => n as u64,
811 let n = &tcx.hir.body(count).value;
812 match ConstContext::new(tcx, count).eval(n, len_hint)? {
813 Integral(Usize(i)) => i.as_u64(tcx.sess.target.uint_type),
814 Integral(_) => signal!(e, RepeatCountNotNatural),
815 _ => signal!(e, RepeatCountNotInt),
818 Repeat(Box::new(cx.eval(elem, elem_hint)?), n)
820 hir::ExprTupField(ref base, index) => {
821 let base_hint = ty_hint.erase_hint();
822 let c = cx.eval(base, base_hint)?;
823 if let Tuple(ref fields) = c {
824 if let Some(elem) = fields.get(index.node) {
827 signal!(e, TupleIndexOutOfBounds);
830 signal!(base, ExpectedConstTuple);
833 hir::ExprField(ref base, field_name) => {
834 let base_hint = ty_hint.erase_hint();
835 let c = cx.eval(base, base_hint)?;
836 if let Struct(ref fields) = c {
837 if let Some(f) = fields.get(&field_name.node) {
840 signal!(e, MissingStructField);
843 signal!(base, ExpectedConstStruct);
846 hir::ExprAddrOf(..) => signal!(e, UnimplementedConstVal("address operator")),
847 _ => signal!(e, MiscCatchAll)
850 match (ety.map(|t| &t.sty), result) {
851 (Some(ref ty_hint), Integral(i)) => match infer(i, tcx, ty_hint) {
852 Ok(inferred) => Ok(Integral(inferred)),
853 Err(err) => signal!(e, err),
855 (_, result) => Ok(result),
859 fn infer<'a, 'tcx>(i: ConstInt,
860 tcx: TyCtxt<'a, 'tcx, 'tcx>,
861 ty_hint: &ty::TypeVariants<'tcx>)
862 -> Result<ConstInt, ErrKind> {
866 (&ty::TyInt(IntTy::I8), result @ I8(_)) => Ok(result),
867 (&ty::TyInt(IntTy::I16), result @ I16(_)) => Ok(result),
868 (&ty::TyInt(IntTy::I32), result @ I32(_)) => Ok(result),
869 (&ty::TyInt(IntTy::I64), result @ I64(_)) => Ok(result),
870 (&ty::TyInt(IntTy::I128), result @ I128(_)) => Ok(result),
871 (&ty::TyInt(IntTy::Is), result @ Isize(_)) => Ok(result),
873 (&ty::TyUint(UintTy::U8), result @ U8(_)) => Ok(result),
874 (&ty::TyUint(UintTy::U16), result @ U16(_)) => Ok(result),
875 (&ty::TyUint(UintTy::U32), result @ U32(_)) => Ok(result),
876 (&ty::TyUint(UintTy::U64), result @ U64(_)) => Ok(result),
877 (&ty::TyUint(UintTy::U128), result @ U128(_)) => Ok(result),
878 (&ty::TyUint(UintTy::Us), result @ Usize(_)) => Ok(result),
880 (&ty::TyInt(IntTy::I8), Infer(i)) => Ok(I8(i as i128 as i8)),
881 (&ty::TyInt(IntTy::I16), Infer(i)) => Ok(I16(i as i128 as i16)),
882 (&ty::TyInt(IntTy::I32), Infer(i)) => Ok(I32(i as i128 as i32)),
883 (&ty::TyInt(IntTy::I64), Infer(i)) => Ok(I64(i as i128 as i64)),
884 (&ty::TyInt(IntTy::I128), Infer(i)) => Ok(I128(i as i128)),
885 (&ty::TyInt(IntTy::Is), Infer(i)) => {
886 Ok(Isize(ConstIsize::new_truncating(i as i128, tcx.sess.target.int_type)))
889 (&ty::TyInt(IntTy::I8), InferSigned(i)) => Ok(I8(i as i8)),
890 (&ty::TyInt(IntTy::I16), InferSigned(i)) => Ok(I16(i as i16)),
891 (&ty::TyInt(IntTy::I32), InferSigned(i)) => Ok(I32(i as i32)),
892 (&ty::TyInt(IntTy::I64), InferSigned(i)) => Ok(I64(i as i64)),
893 (&ty::TyInt(IntTy::I128), InferSigned(i)) => Ok(I128(i)),
894 (&ty::TyInt(IntTy::Is), InferSigned(i)) => {
895 Ok(Isize(ConstIsize::new_truncating(i, tcx.sess.target.int_type)))
898 (&ty::TyUint(UintTy::U8), Infer(i)) => Ok(U8(i as u8)),
899 (&ty::TyUint(UintTy::U16), Infer(i)) => Ok(U16(i as u16)),
900 (&ty::TyUint(UintTy::U32), Infer(i)) => Ok(U32(i as u32)),
901 (&ty::TyUint(UintTy::U64), Infer(i)) => Ok(U64(i as u64)),
902 (&ty::TyUint(UintTy::U128), Infer(i)) => Ok(U128(i)),
903 (&ty::TyUint(UintTy::Us), Infer(i)) => {
904 Ok(Usize(ConstUsize::new_truncating(i, tcx.sess.target.uint_type)))
906 (&ty::TyUint(_), InferSigned(_)) => Err(IntermediateUnsignedNegative),
908 (&ty::TyInt(ity), i) => Err(TypeMismatch(ity.to_string(), i)),
909 (&ty::TyUint(ity), i) => Err(TypeMismatch(ity.to_string(), i)),
911 (&ty::TyAdt(adt, _), i) if adt.is_enum() => {
912 let hints = tcx.lookup_repr_hints(adt.did);
913 let int_ty = tcx.enum_repr_type(hints.iter().next());
914 infer(i, tcx, &int_ty.to_ty(tcx).sty)
916 (_, i) => Err(BadType(ConstVal::Integral(i))),
920 fn resolve_trait_associated_const<'a, 'tcx: 'a>(
921 tcx: TyCtxt<'a, 'tcx, 'tcx>,
922 trait_item_id: DefId,
923 default_value: Option<(&'tcx Expr, Option<&'a ty::TypeckTables<'tcx>>, Option<ty::Ty<'tcx>>)>,
925 rcvr_substs: &'tcx Substs<'tcx>
926 ) -> Option<(&'tcx Expr, Option<&'a ty::TypeckTables<'tcx>>, Option<ty::Ty<'tcx>>)>
928 let trait_ref = ty::Binder(ty::TraitRef::new(trait_id, rcvr_substs));
929 debug!("resolve_trait_associated_const: trait_ref={:?}",
932 tcx.populate_implementations_for_trait_if_necessary(trait_id);
933 tcx.infer_ctxt((), Reveal::NotSpecializable).enter(|infcx| {
934 let mut selcx = traits::SelectionContext::new(&infcx);
935 let obligation = traits::Obligation::new(traits::ObligationCause::dummy(),
936 trait_ref.to_poly_trait_predicate());
937 let selection = match selcx.select(&obligation) {
938 Ok(Some(vtable)) => vtable,
939 // Still ambiguous, so give up and let the caller decide whether this
940 // expression is really needed yet. Some associated constant values
941 // can't be evaluated until monomorphization is done in trans.
950 // NOTE: this code does not currently account for specialization, but when
951 // it does so, it should hook into the Reveal to determine when the
952 // constant should resolve; this will also require plumbing through to this
953 // function whether we are in "trans mode" to pick the right Reveal
954 // when constructing the inference context above.
956 traits::VtableImpl(ref impl_data) => {
957 let name = tcx.associated_item(trait_item_id).name;
958 let ac = tcx.associated_items(impl_data.impl_def_id)
959 .find(|item| item.kind == ty::AssociatedKind::Const && item.name == name);
961 Some(ic) => lookup_const_by_id(tcx, ic.def_id, None),
962 None => default_value,
966 bug!("resolve_trait_associated_const: unexpected vtable type")
972 fn cast_const_int<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, val: ConstInt, ty: ty::Ty) -> CastResult {
973 let v = val.to_u128_unchecked();
975 ty::TyBool if v == 0 => Ok(Bool(false)),
976 ty::TyBool if v == 1 => Ok(Bool(true)),
977 ty::TyInt(ast::IntTy::I8) => Ok(Integral(I8(v as i128 as i8))),
978 ty::TyInt(ast::IntTy::I16) => Ok(Integral(I16(v as i128 as i16))),
979 ty::TyInt(ast::IntTy::I32) => Ok(Integral(I32(v as i128 as i32))),
980 ty::TyInt(ast::IntTy::I64) => Ok(Integral(I64(v as i128 as i64))),
981 ty::TyInt(ast::IntTy::I128) => Ok(Integral(I128(v as i128))),
982 ty::TyInt(ast::IntTy::Is) => {
983 Ok(Integral(Isize(ConstIsize::new_truncating(v as i128, tcx.sess.target.int_type))))
985 ty::TyUint(ast::UintTy::U8) => Ok(Integral(U8(v as u8))),
986 ty::TyUint(ast::UintTy::U16) => Ok(Integral(U16(v as u16))),
987 ty::TyUint(ast::UintTy::U32) => Ok(Integral(U32(v as u32))),
988 ty::TyUint(ast::UintTy::U64) => Ok(Integral(U64(v as u64))),
989 ty::TyUint(ast::UintTy::U128) => Ok(Integral(U128(v as u128))),
990 ty::TyUint(ast::UintTy::Us) => {
991 Ok(Integral(Usize(ConstUsize::new_truncating(v, tcx.sess.target.uint_type))))
993 ty::TyFloat(ast::FloatTy::F64) => match val.erase_type() {
994 Infer(u) => Ok(Float(F64(u as f64))),
995 InferSigned(i) => Ok(Float(F64(i as f64))),
996 _ => bug!("ConstInt::erase_type returned something other than Infer/InferSigned"),
998 ty::TyFloat(ast::FloatTy::F32) => match val.erase_type() {
999 Infer(u) => Ok(Float(F32(u as f32))),
1000 InferSigned(i) => Ok(Float(F32(i as f32))),
1001 _ => bug!("ConstInt::erase_type returned something other than Infer/InferSigned"),
1003 ty::TyRawPtr(_) => Err(ErrKind::UnimplementedConstVal("casting an address to a raw ptr")),
1004 ty::TyChar => match infer(val, tcx, &ty::TyUint(ast::UintTy::U8)) {
1005 Ok(U8(u)) => Ok(Char(u as char)),
1006 // can only occur before typeck, typeck blocks `T as char` for `T` != `u8`
1007 _ => Err(CharCast(val)),
1009 _ => Err(CannotCast),
1013 fn cast_const_float<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1015 ty: ty::Ty) -> CastResult {
1017 ty::TyInt(_) | ty::TyUint(_) => {
1019 F32(f) if f >= 0.0 => Infer(f as u128),
1020 FInfer { f64: f, .. } |
1021 F64(f) if f >= 0.0 => Infer(f as u128),
1023 F32(f) => InferSigned(f as i128),
1024 FInfer { f64: f, .. } |
1025 F64(f) => InferSigned(f as i128)
1028 if let (InferSigned(_), &ty::TyUint(_)) = (i, &ty.sty) {
1029 return Err(CannotCast);
1032 cast_const_int(tcx, i, ty)
1034 ty::TyFloat(ast::FloatTy::F64) => Ok(Float(F64(match val {
1036 FInfer { f64: f, .. } | F64(f) => f
1038 ty::TyFloat(ast::FloatTy::F32) => Ok(Float(F32(match val {
1040 FInfer { f32: f, .. } | F32(f) => f
1042 _ => Err(CannotCast),
1046 fn cast_const<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, val: ConstVal, ty: ty::Ty) -> CastResult {
1048 Integral(i) => cast_const_int(tcx, i, ty),
1049 Bool(b) => cast_const_int(tcx, Infer(b as u128), ty),
1050 Float(f) => cast_const_float(tcx, f, ty),
1051 Char(c) => cast_const_int(tcx, Infer(c as u128), ty),
1052 Function(_) => Err(UnimplementedConstVal("casting fn pointers")),
1053 ByteStr(b) => match ty.sty {
1054 ty::TyRawPtr(_) => {
1055 Err(ErrKind::UnimplementedConstVal("casting a bytestr to a raw ptr"))
1057 ty::TyRef(_, ty::TypeAndMut { ref ty, mutbl: hir::MutImmutable }) => match ty.sty {
1058 ty::TyArray(ty, n) if ty == tcx.types.u8 && n == b.len() => Ok(ByteStr(b)),
1060 Err(ErrKind::UnimplementedConstVal("casting a bytestr to slice"))
1062 _ => Err(CannotCast),
1064 _ => Err(CannotCast),
1066 Str(s) => match ty.sty {
1067 ty::TyRawPtr(_) => Err(ErrKind::UnimplementedConstVal("casting a str to a raw ptr")),
1068 ty::TyRef(_, ty::TypeAndMut { ref ty, mutbl: hir::MutImmutable }) => match ty.sty {
1069 ty::TyStr => Ok(Str(s)),
1070 _ => Err(CannotCast),
1072 _ => Err(CannotCast),
1074 _ => Err(CannotCast),
1078 fn lit_to_const<'a, 'tcx>(lit: &ast::LitKind,
1079 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1080 ty_hint: Option<Ty<'tcx>>)
1081 -> Result<ConstVal, ErrKind> {
1083 use syntax::ast::LitIntType::*;
1085 LitKind::Str(ref s, _) => Ok(Str(s.as_str())),
1086 LitKind::ByteStr(ref data) => Ok(ByteStr(data.clone())),
1087 LitKind::Byte(n) => Ok(Integral(U8(n))),
1088 LitKind::Int(n, Signed(ity)) => {
1089 infer(InferSigned(n as i128), tcx, &ty::TyInt(ity)).map(Integral)
1092 // FIXME: this should become u128.
1093 LitKind::Int(n, Unsuffixed) => {
1094 match ty_hint.map(|t| &t.sty) {
1095 Some(&ty::TyInt(ity)) => {
1096 infer(InferSigned(n as i128), tcx, &ty::TyInt(ity)).map(Integral)
1098 Some(&ty::TyUint(uty)) => {
1099 infer(Infer(n as u128), tcx, &ty::TyUint(uty)).map(Integral)
1101 None => Ok(Integral(Infer(n as u128))),
1102 Some(&ty::TyAdt(adt, _)) => {
1103 let hints = tcx.lookup_repr_hints(adt.did);
1104 let int_ty = tcx.enum_repr_type(hints.iter().next());
1105 infer(Infer(n as u128), tcx, &int_ty.to_ty(tcx).sty).map(Integral)
1107 Some(ty_hint) => bug!("bad ty_hint: {:?}, {:?}", ty_hint, lit),
1110 LitKind::Int(n, Unsigned(ity)) => {
1111 infer(Infer(n as u128), tcx, &ty::TyUint(ity)).map(Integral)
1114 LitKind::Float(n, fty) => {
1115 parse_float(&n.as_str(), Some(fty)).map(Float)
1117 LitKind::FloatUnsuffixed(n) => {
1118 let fty_hint = match ty_hint.map(|t| &t.sty) {
1119 Some(&ty::TyFloat(fty)) => Some(fty),
1122 parse_float(&n.as_str(), fty_hint).map(Float)
1124 LitKind::Bool(b) => Ok(Bool(b)),
1125 LitKind::Char(c) => Ok(Char(c)),
1129 fn parse_float(num: &str, fty_hint: Option<ast::FloatTy>)
1130 -> Result<ConstFloat, ErrKind> {
1131 let val = match fty_hint {
1132 Some(ast::FloatTy::F32) => num.parse::<f32>().map(F32),
1133 Some(ast::FloatTy::F64) => num.parse::<f64>().map(F64),
1135 num.parse::<f32>().and_then(|f32| {
1136 num.parse::<f64>().map(|f64| {
1137 FInfer { f32: f32, f64: f64 }
1143 // FIXME(#31407) this is only necessary because float parsing is buggy
1144 UnimplementedConstVal("could not evaluate float literal (see issue #31407)")
1148 pub fn compare_const_vals(tcx: TyCtxt, span: Span, a: &ConstVal, b: &ConstVal)
1149 -> Result<Ordering, ErrorReported>
1151 let result = match (a, b) {
1152 (&Integral(a), &Integral(b)) => a.try_cmp(b).ok(),
1153 (&Float(a), &Float(b)) => a.try_cmp(b).ok(),
1154 (&Str(ref a), &Str(ref b)) => Some(a.cmp(b)),
1155 (&Bool(a), &Bool(b)) => Some(a.cmp(&b)),
1156 (&ByteStr(ref a), &ByteStr(ref b)) => Some(a.cmp(b)),
1157 (&Char(a), &Char(ref b)) => Some(a.cmp(b)),
1162 Some(result) => Ok(result),
1164 // FIXME: can this ever be reached?
1165 span_err!(tcx.sess, span, E0298,
1166 "type mismatch comparing {} and {}",
1174 impl<'a, 'tcx> ConstContext<'a, 'tcx> {
1175 pub fn compare_lit_exprs(&self,
1178 b: &Expr) -> Result<Ordering, ErrorReported> {
1180 let a = match self.eval(a, ExprTypeChecked) {
1183 report_const_eval_err(tcx, &e, a.span, "expression").emit();
1184 return Err(ErrorReported);
1187 let b = match self.eval(b, ExprTypeChecked) {
1190 report_const_eval_err(tcx, &e, b.span, "expression").emit();
1191 return Err(ErrorReported);
1194 compare_const_vals(tcx, span, &a, &b)
1199 /// Returns the value of the length-valued expression
1200 pub fn eval_length<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1203 -> Result<usize, ErrorReported>
1205 let hint = UncheckedExprHint(tcx.types.usize);
1206 let count_expr = &tcx.hir.body(count).value;
1207 match ConstContext::new(tcx, count).eval(count_expr, hint) {
1208 Ok(Integral(Usize(count))) => {
1209 let val = count.as_u64(tcx.sess.target.uint_type);
1210 assert_eq!(val as usize as u64, val);
1214 struct_span_err!(tcx.sess, count_expr.span, E0306,
1215 "expected `usize` for {}, found {}",
1217 const_val.description())
1218 .span_label(count_expr.span, &format!("expected `usize`"))
1224 let mut diag = report_const_eval_err(
1225 tcx, &err, count_expr.span, reason);
1227 if let hir::ExprPath(hir::QPath::Resolved(None, ref path)) = count_expr.node {
1228 if let Def::Local(..) = path.def {
1229 diag.note(&format!("`{}` is a variable",
1230 tcx.hir.node_to_pretty_string(count_expr.id)));