1 // Copyright 2015 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.
12 * This module contains the code to convert from the wacky tcx data
13 * structures into the hair. The `builder` is generally ignorant of
14 * the tcx etc, and instead goes through the `Cx` for most of its
19 use rustc::mir::repr::*;
20 use rustc::mir::transform::MirSource;
22 use rustc::middle::const_val::ConstVal;
23 use rustc_const_eval as const_eval;
24 use rustc_data_structures::indexed_vec::Idx;
25 use rustc::hir::def_id::DefId;
26 use rustc::hir::intravisit::FnKind;
27 use rustc::hir::map::blocks::FnLikeNode;
28 use rustc::infer::InferCtxt;
29 use rustc::ty::subst::{Subst, Substs};
30 use rustc::ty::{self, Ty, TyCtxt};
31 use syntax::parse::token;
33 use rustc_const_math::{ConstInt, ConstUsize};
34 use syntax::attr::AttrMetaMethods;
36 #[derive(Copy, Clone)]
37 pub struct Cx<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
38 tcx: TyCtxt<'a, 'gcx, 'tcx>,
39 infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
40 constness: hir::Constness,
42 /// True if this constant/function needs overflow checks.
46 impl<'a, 'gcx, 'tcx> Cx<'a, 'gcx, 'tcx> {
47 pub fn new(infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
49 -> Cx<'a, 'gcx, 'tcx> {
50 let constness = match src {
52 MirSource::Static(..) => hir::Constness::Const,
53 MirSource::Fn(id) => {
54 let fn_like = FnLikeNode::from_node(infcx.tcx.map.get(id));
55 match fn_like.map(|f| f.kind()) {
56 Some(FnKind::ItemFn(_, _, _, c, _, _, _)) => c,
57 Some(FnKind::Method(_, m, _, _)) => m.constness,
58 _ => hir::Constness::NotConst
61 MirSource::Promoted(..) => bug!()
64 let attrs = infcx.tcx.map.attrs(src.item_id());
66 // Some functions always have overflow checks enabled,
67 // however, they may not get codegen'd, depending on
68 // the settings for the crate they are translated in.
69 let mut check_overflow = attrs.iter().any(|item| {
70 item.check_name("rustc_inherit_overflow_checks")
73 // Respect -Z force-overflow-checks=on and -C debug-assertions.
74 check_overflow |= infcx.tcx.sess.opts.debugging_opts.force_overflow_checks
75 .unwrap_or(infcx.tcx.sess.opts.debug_assertions);
77 // Constants and const fn's always need overflow checks.
78 check_overflow |= constness == hir::Constness::Const;
84 check_overflow: check_overflow
89 impl<'a, 'gcx, 'tcx> Cx<'a, 'gcx, 'tcx> {
90 /// Normalizes `ast` into the appropriate `mirror` type.
91 pub fn mirror<M: Mirror<'tcx>>(&mut self, ast: M) -> M::Output {
95 pub fn usize_ty(&mut self) -> Ty<'tcx> {
99 pub fn usize_literal(&mut self, value: u64) -> Literal<'tcx> {
100 match ConstUsize::new(value, self.tcx.sess.target.uint_type) {
101 Ok(val) => Literal::Value { value: ConstVal::Integral(ConstInt::Usize(val))},
102 Err(_) => bug!("usize literal out of range for target"),
106 pub fn bool_ty(&mut self) -> Ty<'tcx> {
110 pub fn unit_ty(&mut self) -> Ty<'tcx> {
114 pub fn str_literal(&mut self, value: token::InternedString) -> Literal<'tcx> {
115 Literal::Value { value: ConstVal::Str(value) }
118 pub fn true_literal(&mut self) -> Literal<'tcx> {
119 Literal::Value { value: ConstVal::Bool(true) }
122 pub fn false_literal(&mut self) -> Literal<'tcx> {
123 Literal::Value { value: ConstVal::Bool(false) }
126 pub fn const_eval_literal(&mut self, e: &hir::Expr) -> Literal<'tcx> {
128 value: const_eval::eval_const_expr(self.tcx.global_tcx(), e)
132 pub fn try_const_eval_literal(&mut self, e: &hir::Expr) -> Option<Literal<'tcx>> {
133 let hint = const_eval::EvalHint::ExprTypeChecked;
134 let tcx = self.tcx.global_tcx();
135 const_eval::eval_const_expr_partial(tcx, e, hint, None).ok().and_then(|v| {
137 // All of these contain local IDs, unsuitable for storing in MIR.
138 ConstVal::Struct(_) | ConstVal::Tuple(_) |
139 ConstVal::Array(..) | ConstVal::Repeat(..) |
140 ConstVal::Function(_) => None,
142 _ => Some(Literal::Value { value: v })
147 pub fn trait_method(&mut self,
151 params: Vec<Ty<'tcx>>)
152 -> (Ty<'tcx>, Literal<'tcx>) {
153 let method_name = token::intern(method_name);
154 let substs = Substs::new_trait(params, vec![], self_ty);
155 for trait_item in self.tcx.trait_items(trait_def_id).iter() {
157 ty::ImplOrTraitItem::MethodTraitItem(ref method) => {
158 if method.name == method_name {
159 let method_ty = self.tcx.lookup_item_type(method.def_id);
160 let method_ty = method_ty.ty.subst(self.tcx, &substs);
161 return (method_ty, Literal::Item {
162 def_id: method.def_id,
163 substs: self.tcx.mk_substs(substs),
167 ty::ImplOrTraitItem::ConstTraitItem(..) |
168 ty::ImplOrTraitItem::TypeTraitItem(..) => {}
172 bug!("found no method `{}` in `{:?}`", method_name, trait_def_id);
175 pub fn num_variants(&mut self, adt_def: ty::AdtDef) -> usize {
176 adt_def.variants.len()
179 pub fn all_fields(&mut self, adt_def: ty::AdtDef, variant_index: usize) -> Vec<Field> {
180 (0..adt_def.variants[variant_index].fields.len())
185 pub fn needs_drop(&mut self, ty: Ty<'tcx>) -> bool {
186 let ty = self.tcx.lift_to_global(&ty).unwrap_or_else(|| {
187 bug!("MIR: Cx::needs_drop({}) got \
188 type with inference types/regions", ty);
190 self.tcx.type_needs_drop_given_env(ty, &self.infcx.parameter_environment)
193 pub fn tcx(&self) -> TyCtxt<'a, 'gcx, 'tcx> {
197 pub fn check_overflow(&self) -> bool {