2 use crate::hair::cx::Cx;
3 use crate::hair::cx::block;
4 use crate::hair::cx::to_ref::ToRef;
5 use crate::hair::util::UserAnnotatedTyHelpers;
6 use rustc_data_structures::indexed_vec::Idx;
7 use rustc::hir::def::{CtorOf, Res, DefKind, CtorKind};
8 use rustc::mir::interpret::{GlobalId, ErrorHandled, ConstValue};
9 use rustc::ty::{self, AdtKind, Ty};
10 use rustc::ty::adjustment::{Adjustment, Adjust, AutoBorrow, AutoBorrowMutability, PointerCast};
11 use rustc::ty::subst::{InternalSubsts, SubstsRef};
13 use rustc::hir::def_id::LocalDefId;
14 use rustc::mir::BorrowKind;
17 impl<'tcx> Mirror<'tcx> for &'tcx hir::Expr {
18 type Output = Expr<'tcx>;
20 fn make_mirror<'a, 'gcx>(self, cx: &mut Cx<'a, 'gcx, 'tcx>) -> Expr<'tcx> {
21 let temp_lifetime = cx.region_scope_tree.temporary_scope(self.hir_id.local_id);
22 let expr_scope = region::Scope {
23 id: self.hir_id.local_id,
24 data: region::ScopeData::Node
27 debug!("Expr::make_mirror(): id={}, span={:?}", self.hir_id, self.span);
29 let mut expr = make_mirror_unadjusted(cx, self);
31 // Now apply adjustments, if any.
32 for adjustment in cx.tables().expr_adjustments(self) {
33 debug!("make_mirror: expr={:?} applying adjustment={:?}",
36 expr = apply_adjustment(cx, self, expr, adjustment);
39 // Next, wrap this up in the expr's scope.
44 kind: ExprKind::Scope {
45 region_scope: expr_scope,
47 lint_level: LintLevel::Explicit(self.hir_id),
51 // Finally, create a destruction scope, if any.
52 if let Some(region_scope) =
53 cx.region_scope_tree.opt_destruction_scope(self.hir_id.local_id) {
58 kind: ExprKind::Scope {
61 lint_level: LintLevel::Inherited,
71 fn apply_adjustment<'a, 'gcx, 'tcx>(cx: &mut Cx<'a, 'gcx, 'tcx>,
72 hir_expr: &'tcx hir::Expr,
74 adjustment: &Adjustment<'tcx>)
76 let Expr { temp_lifetime, mut span, .. } = expr;
78 // Adjust the span from the block, to the last expression of the
79 // block. This is a better span when returning a mutable reference
80 // with too short a lifetime. The error message will use the span
81 // from the assignment to the return place, which should only point
82 // at the returned value, not the entire function body.
84 // fn return_short_lived<'a>(x: &'a mut i32) -> &'static mut i32 {
86 // // ^ error message points at this expression.
88 let mut adjust_span = |expr: &mut Expr<'tcx>| {
89 if let ExprKind::Block { body } = expr.kind {
90 if let Some(ref last_expr) = body.expr {
91 span = last_expr.span;
97 let kind = match adjustment.kind {
98 Adjust::Pointer(PointerCast::Unsize) => {
99 adjust_span(&mut expr);
100 ExprKind::Pointer { cast: PointerCast::Unsize, source: expr.to_ref() }
102 Adjust::Pointer(cast) => {
103 ExprKind::Pointer { cast, source: expr.to_ref() }
105 Adjust::NeverToAny => {
106 ExprKind::NeverToAny { source: expr.to_ref() }
108 Adjust::Deref(None) => {
109 adjust_span(&mut expr);
110 ExprKind::Deref { arg: expr.to_ref() }
112 Adjust::Deref(Some(deref)) => {
113 // We don't need to do call adjust_span here since
114 // deref coercions always start with a built-in deref.
115 let call = deref.method_call(cx.tcx(), expr.ty);
119 ty: cx.tcx.mk_ref(deref.region,
125 kind: ExprKind::Borrow {
126 borrow_kind: deref.mutbl.to_borrow_kind(),
131 overloaded_place(cx, hir_expr, adjustment.target, Some(call), vec![expr.to_ref()])
133 Adjust::Borrow(AutoBorrow::Ref(_, m)) => {
135 borrow_kind: m.to_borrow_kind(),
139 Adjust::Borrow(AutoBorrow::RawPtr(m)) => {
140 // Convert this to a suitable `&foo` and
141 // then an unsafe coercion.
144 ty: cx.tcx.mk_ref(cx.tcx.lifetimes.re_erased,
150 kind: ExprKind::Borrow {
151 borrow_kind: m.to_borrow_kind(),
155 let cast_expr = Expr {
157 ty: adjustment.target,
159 kind: ExprKind::Cast { source: expr.to_ref() }
162 // To ensure that both implicit and explicit coercions are
163 // handled the same way, we insert an extra layer of indirection here.
164 // For explicit casts (e.g., 'foo as *const T'), the source of the 'Use'
165 // will be an ExprKind::Hair with the appropriate cast expression. Here,
166 // we make our Use source the generated Cast from the original coercion.
168 // In both cases, this outer 'Use' ensures that the inner 'Cast' is handled by
169 // as_operand, not by as_rvalue - causing the cast result to be stored in a temporary.
170 // Ordinary, this is identical to using the cast directly as an rvalue. However, if the
171 // source of the cast was previously borrowed as mutable, storing the cast in a
172 // temporary gives the source a chance to expire before the cast is used. For
173 // structs with a self-referential *mut ptr, this allows assignment to work as
176 // For example, consider the type 'struct Foo { field: *mut Foo }',
177 // The method 'fn bar(&mut self) { self.field = self }'
178 // triggers a coercion from '&mut self' to '*mut self'. In order
179 // for the assignment to be valid, the implicit borrow
180 // of 'self' involved in the coercion needs to end before the local
181 // containing the '*mut T' is assigned to 'self.field' - otherwise,
182 // we end up trying to assign to 'self.field' while we have another mutable borrow
185 // We only need to worry about this kind of thing for coercions from refs to ptrs,
186 // since they get rid of a borrow implicitly.
187 ExprKind::Use { source: cast_expr.to_ref() }
193 ty: adjustment.target,
199 fn make_mirror_unadjusted<'a, 'gcx, 'tcx>(cx: &mut Cx<'a, 'gcx, 'tcx>,
200 expr: &'tcx hir::Expr)
202 let expr_ty = cx.tables().expr_ty(expr);
203 let temp_lifetime = cx.region_scope_tree.temporary_scope(expr.hir_id.local_id);
205 let kind = match expr.node {
206 // Here comes the interesting stuff:
207 hir::ExprKind::MethodCall(_, method_span, ref args) => {
208 // Rewrite a.b(c) into UFCS form like Trait::b(a, c)
209 let expr = method_callee(cx, expr, method_span,None);
210 let args = args.iter()
221 hir::ExprKind::Call(ref fun, ref args) => {
222 if cx.tables().is_method_call(expr) {
223 // The callee is something implementing Fn, FnMut, or FnOnce.
224 // Find the actual method implementation being called and
225 // build the appropriate UFCS call expression with the
226 // callee-object as expr parameter.
228 // rewrite f(u, v) into FnOnce::call_once(f, (u, v))
230 let method = method_callee(cx, expr, fun.span,None);
232 let arg_tys = args.iter().map(|e| cx.tables().expr_ty_adjusted(e));
233 let tupled_args = Expr {
234 ty: cx.tcx.mk_tup(arg_tys),
237 kind: ExprKind::Tuple { fields: args.iter().map(ToRef::to_ref).collect() },
242 fun: method.to_ref(),
243 args: vec![fun.to_ref(), tupled_args.to_ref()],
247 let adt_data = if let hir::ExprKind::Path(hir::QPath::Resolved(_, ref path)) =
250 // Tuple-like ADTs are represented as ExprKind::Call. We convert them here.
251 expr_ty.ty_adt_def().and_then(|adt_def| {
253 Res::Def(DefKind::Ctor(_, CtorKind::Fn), ctor_id) =>
254 Some((adt_def, adt_def.variant_index_with_ctor_id(ctor_id))),
255 Res::SelfCtor(..) => Some((adt_def, VariantIdx::new(0))),
262 if let Some((adt_def, index)) = adt_data {
263 let substs = cx.tables().node_substs(fun.hir_id);
264 let user_provided_types = cx.tables().user_provided_types();
265 let user_ty = user_provided_types.get(fun.hir_id)
268 if let UserType::TypeOf(ref mut did, _) = &mut u_ty.value {
273 debug!("make_mirror_unadjusted: (call) user_ty={:?}", user_ty);
275 let field_refs = args.iter()
279 name: Field::new(idx),
287 variant_index: index,
294 ty: cx.tables().node_type(fun.hir_id),
303 hir::ExprKind::AddrOf(mutbl, ref expr) => {
305 borrow_kind: mutbl.to_borrow_kind(),
310 hir::ExprKind::Block(ref blk, _) => ExprKind::Block { body: &blk },
312 hir::ExprKind::Assign(ref lhs, ref rhs) => {
319 hir::ExprKind::AssignOp(op, ref lhs, ref rhs) => {
320 if cx.tables().is_method_call(expr) {
321 overloaded_operator(cx, expr, vec![lhs.to_ref(), rhs.to_ref()])
331 hir::ExprKind::Lit(ref lit) => ExprKind::Literal {
332 literal: cx.const_eval_literal(&lit.node, expr_ty, lit.span, false),
336 hir::ExprKind::Binary(op, ref lhs, ref rhs) => {
337 if cx.tables().is_method_call(expr) {
338 overloaded_operator(cx, expr, vec![lhs.to_ref(), rhs.to_ref()])
341 match (op.node, cx.constness) {
342 // FIXME(eddyb) use logical ops in constants when
343 // they can handle that kind of control-flow.
344 (hir::BinOpKind::And, hir::Constness::Const) => {
345 cx.control_flow_destroyed.push((
347 "`&&` operator".into(),
355 (hir::BinOpKind::Or, hir::Constness::Const) => {
356 cx.control_flow_destroyed.push((
358 "`||` operator".into(),
367 (hir::BinOpKind::And, hir::Constness::NotConst) => {
368 ExprKind::LogicalOp {
374 (hir::BinOpKind::Or, hir::Constness::NotConst) => {
375 ExprKind::LogicalOp {
383 let op = bin_op(op.node);
394 hir::ExprKind::Index(ref lhs, ref index) => {
395 if cx.tables().is_method_call(expr) {
396 overloaded_place(cx, expr, expr_ty, None, vec![lhs.to_ref(), index.to_ref()])
400 index: index.to_ref(),
405 hir::ExprKind::Unary(hir::UnOp::UnDeref, ref arg) => {
406 if cx.tables().is_method_call(expr) {
407 overloaded_place(cx, expr, expr_ty, None, vec![arg.to_ref()])
409 ExprKind::Deref { arg: arg.to_ref() }
413 hir::ExprKind::Unary(hir::UnOp::UnNot, ref arg) => {
414 if cx.tables().is_method_call(expr) {
415 overloaded_operator(cx, expr, vec![arg.to_ref()])
424 hir::ExprKind::Unary(hir::UnOp::UnNeg, ref arg) => {
425 if cx.tables().is_method_call(expr) {
426 overloaded_operator(cx, expr, vec![arg.to_ref()])
428 if let hir::ExprKind::Lit(ref lit) = arg.node {
430 literal: cx.const_eval_literal(&lit.node, expr_ty, lit.span, true),
442 hir::ExprKind::Struct(ref qpath, ref fields, ref base) => {
444 ty::Adt(adt, substs) => {
445 match adt.adt_kind() {
446 AdtKind::Struct | AdtKind::Union => {
447 let user_provided_types = cx.tables().user_provided_types();
448 let user_ty = user_provided_types.get(expr.hir_id).map(|u_ty| *u_ty);
449 debug!("make_mirror_unadjusted: (struct/union) user_ty={:?}", user_ty);
452 variant_index: VariantIdx::new(0),
455 fields: field_refs(cx, fields),
456 base: base.as_ref().map(|base| {
459 field_types: cx.tables()
460 .fru_field_types()[expr.hir_id]
467 let res = cx.tables().qpath_res(qpath, expr.hir_id);
469 Res::Def(DefKind::Variant, variant_id) => {
470 assert!(base.is_none());
472 let index = adt.variant_index_with_id(variant_id);
473 let user_provided_types = cx.tables().user_provided_types();
474 let user_ty = user_provided_types.get(expr.hir_id)
477 "make_mirror_unadjusted: (variant) user_ty={:?}",
482 variant_index: index,
485 fields: field_refs(cx, fields),
490 span_bug!(expr.span, "unexpected res: {:?}", res);
498 "unexpected type for struct literal: {:?}",
504 hir::ExprKind::Closure(..) => {
505 let closure_ty = cx.tables().expr_ty(expr);
506 let (def_id, substs, movability) = match closure_ty.sty {
507 ty::Closure(def_id, substs) => (def_id, UpvarSubsts::Closure(substs), None),
508 ty::Generator(def_id, substs, movability) => {
509 (def_id, UpvarSubsts::Generator(substs), Some(movability))
512 span_bug!(expr.span, "closure expr w/o closure type: {:?}", closure_ty);
515 let upvars = cx.tcx.upvars(def_id).iter()
516 .flat_map(|upvars| upvars.iter())
517 .zip(substs.upvar_tys(def_id, cx.tcx))
518 .map(|(upvar, ty)| capture_upvar(cx, expr, upvar, ty))
528 hir::ExprKind::Path(ref qpath) => {
529 let res = cx.tables().qpath_res(qpath, expr.hir_id);
530 convert_path_expr(cx, expr, res)
533 hir::ExprKind::InlineAsm(ref asm, ref outputs, ref inputs) => {
534 ExprKind::InlineAsm {
536 outputs: outputs.to_ref(),
537 inputs: inputs.to_ref(),
541 // Now comes the rote stuff:
542 hir::ExprKind::Repeat(ref v, ref count) => {
543 let def_id = cx.tcx.hir().local_def_id_from_hir_id(count.hir_id);
544 let substs = InternalSubsts::identity_for_item(cx.tcx.global_tcx(), def_id);
545 let instance = ty::Instance::resolve(
551 let global_id = GlobalId {
555 let span = cx.tcx.def_span(def_id);
556 let count = match cx.tcx.at(span).const_eval(cx.param_env.and(global_id)) {
557 Ok(cv) => cv.unwrap_usize(cx.tcx),
558 Err(ErrorHandled::Reported) => 0,
559 Err(ErrorHandled::TooGeneric) => {
560 cx.tcx.sess.span_err(span, "array lengths can't depend on generic parameters");
570 hir::ExprKind::Ret(ref v) => ExprKind::Return { value: v.to_ref() },
571 hir::ExprKind::Break(dest, ref value) => {
572 match dest.target_id {
573 Ok(target_id) => ExprKind::Break {
574 label: region::Scope {
575 id: target_id.local_id,
576 data: region::ScopeData::Node
578 value: value.to_ref(),
580 Err(err) => bug!("invalid loop id for break: {}", err)
583 hir::ExprKind::Continue(dest) => {
584 match dest.target_id {
585 Ok(loop_id) => ExprKind::Continue {
586 label: region::Scope {
587 id: loop_id.local_id,
588 data: region::ScopeData::Node
591 Err(err) => bug!("invalid loop id for continue: {}", err)
594 hir::ExprKind::Match(ref discr, ref arms, _) => {
596 scrutinee: discr.to_ref(),
597 arms: arms.iter().map(|a| convert_arm(cx, a)).collect(),
600 hir::ExprKind::While(ref cond, ref body, _) => {
602 condition: Some(cond.to_ref()),
603 body: block::to_expr_ref(cx, body),
606 hir::ExprKind::Loop(ref body, _, _) => {
609 body: block::to_expr_ref(cx, body),
612 hir::ExprKind::Field(ref source, ..) => {
614 lhs: source.to_ref(),
615 name: Field::new(cx.tcx.field_index(expr.hir_id, cx.tables)),
618 hir::ExprKind::Cast(ref source, ref cast_ty) => {
619 // Check for a user-given type annotation on this `cast`
620 let user_provided_types = cx.tables.user_provided_types();
621 let user_ty = user_provided_types.get(cast_ty.hir_id);
624 "cast({:?}) has ty w/ hir_id {:?} and user provided ty {:?}",
630 // Check to see if this cast is a "coercion cast", where the cast is actually done
631 // using a coercion (or is a no-op).
632 let cast = if cx.tables().is_coercion_cast(source.hir_id) {
633 // Convert the lexpr to a vexpr.
634 ExprKind::Use { source: source.to_ref() }
636 // check whether this is casting an enum variant discriminant
637 // to prevent cycles, we refer to the discriminant initializer
638 // which is always an integer and thus doesn't need to know the
639 // enum's layout (or its tag type) to compute it during const eval
643 // B = A as isize + 4,
645 // The correct solution would be to add symbolic computations to miri,
646 // so we wouldn't have to compute and store the actual value
647 let var = if let hir::ExprKind::Path(ref qpath) = source.node {
648 let res = cx.tables().qpath_res(qpath, source.hir_id);
651 .node_type(source.hir_id)
653 .and_then(|adt_def| {
656 DefKind::Ctor(CtorOf::Variant, CtorKind::Const),
659 let idx = adt_def.variant_index_with_ctor_id(variant_ctor_id);
660 let (d, o) = adt_def.discriminant_def_for_variant(idx);
661 use rustc::ty::util::IntTypeExt;
662 let ty = adt_def.repr.discr_type();
663 let ty = ty.to_ty(cx.tcx());
673 let source = if let Some((did, offset, var_ty)) = var {
674 let mk_const = |literal| Expr {
678 kind: ExprKind::Literal {
683 let offset = mk_const(ty::Const::from_bits(
686 cx.param_env.and(var_ty),
690 // in case we are offsetting from a computed discriminant
691 // and not the beginning of discriminants (which is always `0`)
692 let substs = InternalSubsts::identity_for_item(cx.tcx(), did);
693 let lhs = mk_const(cx.tcx().mk_const(ty::Const {
694 val: ConstValue::Unevaluated(did, substs),
697 let bin = ExprKind::Binary {
715 ExprKind::Cast { source }
718 if let Some(user_ty) = user_ty {
719 // NOTE: Creating a new Expr and wrapping a Cast inside of it may be
720 // inefficient, revisit this when performance becomes an issue.
721 let cast_expr = Expr {
727 debug!("make_mirror_unadjusted: (cast) user_ty={:?}", user_ty);
729 ExprKind::ValueTypeAscription {
730 source: cast_expr.to_ref(),
731 user_ty: Some(*user_ty),
737 hir::ExprKind::Type(ref source, ref ty) => {
738 let user_provided_types = cx.tables.user_provided_types();
739 let user_ty = user_provided_types.get(ty.hir_id).map(|u_ty| *u_ty);
740 debug!("make_mirror_unadjusted: (type) user_ty={:?}", user_ty);
741 if source.is_place_expr() {
742 ExprKind::PlaceTypeAscription {
743 source: source.to_ref(),
747 ExprKind::ValueTypeAscription {
748 source: source.to_ref(),
753 hir::ExprKind::DropTemps(ref source) => {
754 ExprKind::Use { source: source.to_ref() }
756 hir::ExprKind::Box(ref value) => {
758 value: value.to_ref(),
761 hir::ExprKind::Array(ref fields) => ExprKind::Array { fields: fields.to_ref() },
762 hir::ExprKind::Tup(ref fields) => ExprKind::Tuple { fields: fields.to_ref() },
764 hir::ExprKind::Yield(ref v) => ExprKind::Yield { value: v.to_ref() },
765 hir::ExprKind::Err => unreachable!(),
776 fn user_substs_applied_to_res(
777 cx: &mut Cx<'a, 'gcx, 'tcx>,
780 ) -> Option<ty::CanonicalUserType<'tcx>> {
781 debug!("user_substs_applied_to_res: res={:?}", res);
782 let user_provided_type = match res {
783 // A reference to something callable -- e.g., a fn, method, or
784 // a tuple-struct or tuple-variant. This has the type of a
785 // `Fn` but with the user-given substitutions.
786 Res::Def(DefKind::Fn, _) |
787 Res::Def(DefKind::Method, _) |
788 Res::Def(DefKind::Ctor(_, CtorKind::Fn), _) |
789 Res::Def(DefKind::Const, _) |
790 Res::Def(DefKind::AssocConst, _) =>
791 cx.tables().user_provided_types().get(hir_id).map(|u_ty| *u_ty),
793 // A unit struct/variant which is used as a value (e.g.,
794 // `None`). This has the type of the enum/struct that defines
795 // this variant -- but with the substitutions given by the
797 Res::Def(DefKind::Ctor(_, CtorKind::Const), _) =>
798 cx.user_substs_applied_to_ty_of_hir_id(hir_id),
800 // `Self` is used in expression as a tuple struct constructor or an unit struct constructor
802 cx.user_substs_applied_to_ty_of_hir_id(hir_id),
805 bug!("user_substs_applied_to_res: unexpected res {:?} at {:?}", res, hir_id)
807 debug!("user_substs_applied_to_res: user_provided_type={:?}", user_provided_type);
811 fn method_callee<'a, 'gcx, 'tcx>(
812 cx: &mut Cx<'a, 'gcx, 'tcx>,
815 overloaded_callee: Option<(DefId, SubstsRef<'tcx>)>,
817 let temp_lifetime = cx.region_scope_tree.temporary_scope(expr.hir_id.local_id);
818 let (def_id, substs, user_ty) = match overloaded_callee {
819 Some((def_id, substs)) => (def_id, substs, None),
821 let (kind, def_id) = cx.tables().type_dependent_def(expr.hir_id)
823 span_bug!(expr.span, "no type-dependent def for method callee")
825 let user_ty = user_substs_applied_to_res(cx, expr.hir_id, Res::Def(kind, def_id));
826 debug!("method_callee: user_ty={:?}", user_ty);
827 (def_id, cx.tables().node_substs(expr.hir_id), user_ty)
830 let ty = cx.tcx().mk_fn_def(def_id, substs);
835 kind: ExprKind::Literal {
836 literal: ty::Const::zero_sized(cx.tcx(), ty),
842 trait ToBorrowKind { fn to_borrow_kind(&self) -> BorrowKind; }
844 impl ToBorrowKind for AutoBorrowMutability {
845 fn to_borrow_kind(&self) -> BorrowKind {
846 use rustc::ty::adjustment::AllowTwoPhase;
848 AutoBorrowMutability::Mutable { allow_two_phase_borrow } =>
849 BorrowKind::Mut { allow_two_phase_borrow: match allow_two_phase_borrow {
850 AllowTwoPhase::Yes => true,
851 AllowTwoPhase::No => false
853 AutoBorrowMutability::Immutable =>
859 impl ToBorrowKind for hir::Mutability {
860 fn to_borrow_kind(&self) -> BorrowKind {
862 hir::MutMutable => BorrowKind::Mut { allow_two_phase_borrow: false },
863 hir::MutImmutable => BorrowKind::Shared,
868 fn convert_arm<'a, 'gcx, 'tcx>(cx: &mut Cx<'a, 'gcx, 'tcx>, arm: &'tcx hir::Arm) -> Arm<'tcx> {
870 patterns: arm.pats.iter().map(|p| cx.pattern_from_hir(p)).collect(),
871 guard: match arm.guard {
872 Some(hir::Guard::If(ref e)) => Some(Guard::If(e.to_ref())),
875 body: arm.body.to_ref(),
876 lint_level: LintLevel::Explicit(arm.hir_id),
877 scope: region::Scope {
878 id: arm.hir_id.local_id,
879 data: region::ScopeData::Node
885 fn convert_path_expr<'a, 'gcx, 'tcx>(cx: &mut Cx<'a, 'gcx, 'tcx>,
886 expr: &'tcx hir::Expr,
889 let substs = cx.tables().node_substs(expr.hir_id);
891 // A regular function, constructor function or a constant.
892 Res::Def(DefKind::Fn, _) |
893 Res::Def(DefKind::Method, _) |
894 Res::Def(DefKind::Ctor(_, CtorKind::Fn), _) |
895 Res::SelfCtor(..) => {
896 let user_ty = user_substs_applied_to_res(cx, expr.hir_id, res);
897 debug!("convert_path_expr: user_ty={:?}", user_ty);
899 literal: ty::Const::zero_sized(
901 cx.tables().node_type(expr.hir_id),
907 Res::Def(DefKind::ConstParam, def_id) => {
908 let node_id = cx.tcx.hir().as_local_node_id(def_id).unwrap();
909 let item_id = cx.tcx.hir().get_parent_node(node_id);
910 let item_def_id = cx.tcx.hir().local_def_id(item_id);
911 let generics = cx.tcx.generics_of(item_def_id);
912 let index = generics.param_def_id_to_index[&cx.tcx.hir().local_def_id(node_id)];
913 let name = cx.tcx.hir().name(node_id).as_interned_str();
914 let val = ConstValue::Param(ty::ParamConst::new(index, name));
916 literal: cx.tcx.mk_const(
919 ty: cx.tables().node_type(expr.hir_id),
926 Res::Def(DefKind::Const, def_id) |
927 Res::Def(DefKind::AssocConst, def_id) => {
928 let user_ty = user_substs_applied_to_res(cx, expr.hir_id, res);
929 debug!("convert_path_expr: (const) user_ty={:?}", user_ty);
931 literal: cx.tcx.mk_const(ty::Const {
932 val: ConstValue::Unevaluated(def_id, substs),
933 ty: cx.tcx.type_of(def_id),
939 Res::Def(DefKind::Ctor(_, CtorKind::Const), def_id) => {
940 let user_provided_types = cx.tables.user_provided_types();
941 let user_provided_type = user_provided_types.get(expr.hir_id).map(|u_ty| *u_ty);
942 debug!("convert_path_expr: user_provided_type={:?}", user_provided_type);
943 let ty = cx.tables().node_type(expr.hir_id);
945 // A unit struct/variant which is used as a value.
946 // We return a completely different ExprKind here to account for this special case.
947 ty::Adt(adt_def, substs) => {
950 variant_index: adt_def.variant_index_with_ctor_id(def_id),
952 user_ty: user_provided_type,
957 _ => bug!("unexpected ty: {:?}", ty),
961 Res::Def(DefKind::Static, id) => ExprKind::StaticRef { id },
963 Res::Local(..) | Res::Upvar(..) => convert_var(cx, expr, res),
965 _ => span_bug!(expr.span, "res `{:?}` not yet implemented", res),
969 fn convert_var<'a, 'gcx, 'tcx>(cx: &mut Cx<'a, 'gcx, 'tcx>,
970 expr: &'tcx hir::Expr,
973 let temp_lifetime = cx.region_scope_tree.temporary_scope(expr.hir_id.local_id);
976 Res::Local(id) => ExprKind::VarRef { id },
978 Res::Upvar(var_hir_id, index, closure_expr_id) => {
979 debug!("convert_var(upvar({:?}, {:?}, {:?}))",
983 let var_ty = cx.tables().node_type(var_hir_id);
985 // FIXME free regions in closures are not right
986 let closure_ty = cx.tables()
987 .node_type(cx.tcx.hir().node_to_hir_id(closure_expr_id));
989 // FIXME we're just hard-coding the idea that the
990 // signature will be &self or &mut self and hence will
991 // have a bound region with number 0
992 let closure_def_id = cx.tcx.hir().local_def_id(closure_expr_id);
993 let region = ty::ReFree(ty::FreeRegion {
994 scope: closure_def_id,
995 bound_region: ty::BoundRegion::BrAnon(0),
997 let region = cx.tcx.mk_region(region);
999 let self_expr = if let ty::Closure(_, closure_substs) = closure_ty.sty {
1000 match cx.infcx.closure_kind(closure_def_id, closure_substs).unwrap() {
1001 ty::ClosureKind::Fn => {
1002 let ref_closure_ty = cx.tcx.mk_ref(region,
1005 mutbl: hir::MutImmutable,
1009 temp_lifetime: temp_lifetime,
1011 kind: ExprKind::Deref {
1016 kind: ExprKind::SelfRef,
1022 ty::ClosureKind::FnMut => {
1023 let ref_closure_ty = cx.tcx.mk_ref(region,
1026 mutbl: hir::MutMutable,
1032 kind: ExprKind::Deref {
1037 kind: ExprKind::SelfRef,
1042 ty::ClosureKind::FnOnce => {
1047 kind: ExprKind::SelfRef,
1056 kind: ExprKind::SelfRef,
1060 // at this point we have `self.n`, which loads up the upvar
1061 let field_kind = ExprKind::Field {
1062 lhs: self_expr.to_ref(),
1063 name: Field::new(index),
1066 // ...but the upvar might be an `&T` or `&mut T` capture, at which
1067 // point we need an implicit deref
1068 let upvar_id = ty::UpvarId {
1069 var_path: ty::UpvarPath {hir_id: var_hir_id},
1070 closure_expr_id: LocalDefId::from_def_id(closure_def_id),
1072 match cx.tables().upvar_capture(upvar_id) {
1073 ty::UpvarCapture::ByValue => field_kind,
1074 ty::UpvarCapture::ByRef(borrow) => {
1078 ty: cx.tcx.mk_ref(borrow.region,
1081 mutbl: borrow.kind.to_mutbl_lossy(),
1091 _ => span_bug!(expr.span, "type of & not region"),
1096 fn bin_op(op: hir::BinOpKind) -> BinOp {
1098 hir::BinOpKind::Add => BinOp::Add,
1099 hir::BinOpKind::Sub => BinOp::Sub,
1100 hir::BinOpKind::Mul => BinOp::Mul,
1101 hir::BinOpKind::Div => BinOp::Div,
1102 hir::BinOpKind::Rem => BinOp::Rem,
1103 hir::BinOpKind::BitXor => BinOp::BitXor,
1104 hir::BinOpKind::BitAnd => BinOp::BitAnd,
1105 hir::BinOpKind::BitOr => BinOp::BitOr,
1106 hir::BinOpKind::Shl => BinOp::Shl,
1107 hir::BinOpKind::Shr => BinOp::Shr,
1108 hir::BinOpKind::Eq => BinOp::Eq,
1109 hir::BinOpKind::Lt => BinOp::Lt,
1110 hir::BinOpKind::Le => BinOp::Le,
1111 hir::BinOpKind::Ne => BinOp::Ne,
1112 hir::BinOpKind::Ge => BinOp::Ge,
1113 hir::BinOpKind::Gt => BinOp::Gt,
1114 _ => bug!("no equivalent for ast binop {:?}", op),
1118 fn overloaded_operator<'a, 'gcx, 'tcx>(cx: &mut Cx<'a, 'gcx, 'tcx>,
1119 expr: &'tcx hir::Expr,
1120 args: Vec<ExprRef<'tcx>>)
1122 let fun = method_callee(cx, expr, expr.span, None);
1127 from_hir_call: false,
1131 fn overloaded_place<'a, 'gcx, 'tcx>(
1132 cx: &mut Cx<'a, 'gcx, 'tcx>,
1133 expr: &'tcx hir::Expr,
1135 overloaded_callee: Option<(DefId, SubstsRef<'tcx>)>,
1136 args: Vec<ExprRef<'tcx>>,
1137 ) -> ExprKind<'tcx> {
1138 // For an overloaded *x or x[y] expression of type T, the method
1139 // call returns an &T and we must add the deref so that the types
1140 // line up (this is because `*x` and `x[y]` represent places):
1142 let recv_ty = match args[0] {
1143 ExprRef::Hair(e) => cx.tables().expr_ty_adjusted(e),
1144 ExprRef::Mirror(ref e) => e.ty
1147 // Reconstruct the output assuming it's a reference with the
1148 // same region and mutability as the receiver. This holds for
1149 // `Deref(Mut)::Deref(_mut)` and `Index(Mut)::index(_mut)`.
1150 let (region, mutbl) = match recv_ty.sty {
1151 ty::Ref(region, _, mutbl) => (region, mutbl),
1152 _ => span_bug!(expr.span, "overloaded_place: receiver is not a reference"),
1154 let ref_ty = cx.tcx.mk_ref(region, ty::TypeAndMut {
1159 // construct the complete expression `foo()` for the overloaded call,
1160 // which will yield the &T type
1161 let temp_lifetime = cx.region_scope_tree.temporary_scope(expr.hir_id.local_id);
1162 let fun = method_callee(cx, expr, expr.span, overloaded_callee);
1163 let ref_expr = Expr {
1167 kind: ExprKind::Call {
1171 from_hir_call: false,
1175 // construct and return a deref wrapper `*foo()`
1176 ExprKind::Deref { arg: ref_expr.to_ref() }
1179 fn capture_upvar<'a, 'gcx, 'tcx>(cx: &mut Cx<'a, 'gcx, 'tcx>,
1180 closure_expr: &'tcx hir::Expr,
1184 let var_hir_id = upvar.var_id();
1185 let upvar_id = ty::UpvarId {
1186 var_path: ty::UpvarPath { hir_id: var_hir_id },
1187 closure_expr_id: cx.tcx.hir().local_def_id_from_hir_id(closure_expr.hir_id).to_local(),
1189 let upvar_capture = cx.tables().upvar_capture(upvar_id);
1190 let temp_lifetime = cx.region_scope_tree.temporary_scope(closure_expr.hir_id.local_id);
1191 let var_ty = cx.tables().node_type(var_hir_id);
1192 let captured_var = Expr {
1195 span: closure_expr.span,
1196 kind: convert_var(cx, closure_expr, upvar.res),
1198 match upvar_capture {
1199 ty::UpvarCapture::ByValue => captured_var.to_ref(),
1200 ty::UpvarCapture::ByRef(upvar_borrow) => {
1201 let borrow_kind = match upvar_borrow.kind {
1202 ty::BorrowKind::ImmBorrow => BorrowKind::Shared,
1203 ty::BorrowKind::UniqueImmBorrow => BorrowKind::Unique,
1204 ty::BorrowKind::MutBorrow => BorrowKind::Mut { allow_two_phase_borrow: false }
1209 span: closure_expr.span,
1210 kind: ExprKind::Borrow {
1212 arg: captured_var.to_ref(),
1219 /// Converts a list of named fields (i.e., for struct-like struct/enum ADTs) into FieldExprRef.
1220 fn field_refs<'a, 'gcx, 'tcx>(cx: &mut Cx<'a, 'gcx, 'tcx>,
1221 fields: &'tcx [hir::Field])
1222 -> Vec<FieldExprRef<'tcx>> {
1226 name: Field::new(cx.tcx.field_index(field.hir_id, cx.tables)),
1227 expr: field.expr.to_ref(),